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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3de2fd07a4e2afff8c25f5ccec376b7d5a6d24c1 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /WinsockLab/TcpServer/TcpServerSrc.cpp | 8be7afa146dfe16e6dc455c9e5382e4f19f30b62 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,978 | cpp | #include <winsock2.h>
#include <stdio.h>
int main(void)
{
WSADATA wsaData;
SOCKET ListeningSocket;
SOCKET NewConnection;
SOCKADDR_IN ServerAddr;
int Port = 5150;
// Initialize Winsock version 2.2
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0)
{
// MSDN: An application can call the WSAGetLastError() function to determine the
// extended error code for other Windows sockets functions as is normally
// done in Windows Sockets even if the WSAStartup function fails or the WSAStartup
// function was not called to properly initialize Windows Sockets before calling a
// Windows Sockets function. The WSAGetLastError() function is one of the only functions
// in the Winsock 2.2 DLL that can be called in the case of a WSAStartup failure
printf("Server: WSAStartup failed with error %ld\n", WSAGetLastError());
// Exit with error
return -1;
}
else
{
printf("Server: The Winsock dll found!\n");
printf("Server: The current status is %s.\n", wsaData.szSystemStatus);
}
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 )
{
//Tell the user that we could not find a usable WinSock DLL
printf("Server: The dll do not support the Winsock version %u.%u!\n",
LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
// Do the clean up
WSACleanup();
// and exit with error
return -1;
}
else
{
printf("Server: The dll supports the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),
HIBYTE(wsaData.wVersion));
printf("Server: The highest version this dll can support is %u.%u\n",
LOBYTE(wsaData.wHighVersion), HIBYTE(wsaData.wHighVersion));
}
// Create a new socket to listen for client connections.
ListeningSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// Check for errors to ensure that the socket is a valid socket.
if (ListeningSocket == INVALID_SOCKET)
{
printf("Server: Error at socket(), error code: %ld\n", WSAGetLastError());
// Clean up
WSACleanup();
// and exit with error
return -1;
}
else
printf("Server: socket() is OK!\n");
// Set up a SOCKADDR_IN structure that will tell bind that we
// want to listen for connections on all interfaces using port 5150.
// The IPv4 family
ServerAddr.sin_family = AF_INET;
// host-to-network byte order
ServerAddr.sin_port = htons(Port);
// Listen on all interface, host-to-network byte order
ServerAddr.sin_addr.s_addr = htonl(INADDR_ANY);
// Associate the address information with the socket using bind.
// Call the bind function, passing the created socket and the sockaddr_in
// structure as parameters. Check for general errors.
if (bind(ListeningSocket, (SOCKADDR *)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR)
{
printf("Server: bind() failed! Error code: %ld.\n", WSAGetLastError());
// Close the socket
closesocket(ListeningSocket);
// Do the clean up
WSACleanup();
// and exit with error
return -1;
}
else
printf("Server: bind() is OK!\n");
// Listen for client connections. We used a backlog of 5, which
// is normal for many applications.
if (listen(ListeningSocket, 5) == SOCKET_ERROR)
{
printf("Server: listen(): Error listening on socket %ld.\n", WSAGetLastError());
// Close the socket
closesocket(ListeningSocket);
// Do the clean up
WSACleanup();
// Exit with error
return -1;
}
else
printf("Server: listen() is OK, I'm waiting for connections...\n");
printf("Server: accept() is ready...\n");
// Accept a new connection when one arrives.
while(1)
{
NewConnection = SOCKET_ERROR;
while(NewConnection == SOCKET_ERROR)
{
NewConnection = accept(ListeningSocket, NULL, NULL);
}
printf("Server: accept() is OK...\n");
printf("Server: Client connected, ready for receiving and sending data...\n");
// Transfer the connected socket to the listening socket
ListeningSocket = NewConnection;
break;
}
// At this point you can do two things with these sockets. Wait
// for more connections by calling accept again on ListeningSocket
// and start sending or receiving data on NewConnection (need a loop). We will
// describe how to send and receive data later in the chapter.
// When you are finished sending and receiving data on the
// NewConnection socket and are finished accepting new connections
// on ListeningSocket, you should close the sockets using the closesocket API.
if(closesocket(NewConnection) != 0)
printf("Server: Cannot close \"NewConnection\" socket. Error code: %ld\n", WSAGetLastError());
else
printf("Server: Closing \"NewConnection\" socket...\n");
// When your application is finished handling the connections,
// call WSACleanup.
if(WSACleanup() != 0)
printf("Server: WSACleanup() failed! Error code: %ld\n", WSAGetLastError());
else
printf("Server: WSACleanup() is OK...\n");
return 0;
} | [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
142
]
]
]
|
f6c28eaccf7129f97f83c1eccfa0f7bdb0ad2e12 | ad6a37b326227901f75bad781f2cbf357b42544f | /Effects/SimpleBlur.h | 9c9b4f32e268ea7ed897a84946e902154068f1b4 | []
| no_license | OpenEngineDK/branches-PostProcessingEffects | 83b4e1dc1a390b66357bed6bc94d4cab16ef756a | c4f4585cbdbb905d382499bf12fd8bfe7d27812c | refs/heads/master | 2021-01-01T05:43:32.564360 | 2009-04-20T14:50:03 | 2009-04-20T14:50:03 | 58,077,144 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | #ifndef __SIMPLEBLUR_H__
#define __SIMPLEBLUR_H__
#include <PostProcessing/OpenGL/PostProcessingEffect.h>
#include <PostProcessing/IPostProcessingPass.h>
#include <Display/Viewport.h>
#include <Core/IEngine.h>
#include <vector>
#include <stdio.h>
using namespace OpenEngine::PostProcessing;
class SimpleBlur : public PostProcessingEffect {
private:
IPostProcessingPass* pass1;
vector<float> offset;
public:
SimpleBlur(Viewport* viewport, IEngine& engine);
void Setup();
void PerFrame(const float deltaTime);
};
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
22
],
[
24,
28
]
],
[
[
7,
7
],
[
23,
23
]
]
]
|
ff198393f71b4f7be41a7d75050dfe2c1c914407 | cac9d7127b80c67223135204095e80f7869c1502 | /src/ClientSocket.h | 740f46a6fdf9f04a05ea2f2cc89ebf226d98cae6 | []
| no_license | perepechaev/xmud | d26bef482ebd7df23487b4479de236d483609af7 | 9841842b44d7237b4a4c17e40437dc700cad08bc | refs/heads/master | 2020-05-18T02:49:15.102595 | 2011-03-21T09:39:40 | 2011-03-21T09:39:40 | 1,505,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 400 | h | // Definition of the ClientSocket class
#ifndef ClientSocket_class
#define ClientSocket_class
#include "Socket.h"
class ClientSocket : private Socket
{
public:
ClientSocket ( std::string host, int port );
virtual ~ClientSocket(){};
const ClientSocket& operator << ( const std::string& ) const;
const ClientSocket& operator >> ( std::string& ) const;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
22a51c67b254fbf8352ca28d91b71e7e39d3eac4 | 841e58a0ee1393ddd5053245793319c0069655ef | /Karma/Headers/GuiHandler.h | 0e863d0b507e24fff5632f219f033b5239033b4a | []
| no_license | dremerbuik/projectkarma | 425169d06dc00f867187839618c2d45865da8aaa | faf42e22b855fc76ed15347501dd817c57ec3630 | refs/heads/master | 2016-08-11T10:02:06.537467 | 2010-06-09T07:06:59 | 2010-06-09T07:06:59 | 35,989,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,351 | h | /*---------------------------------------------------------------------------------*/
/* File: GuiHandler.h */
/* Author: Per Karlsson, [email protected] */
/* */
/* Description: GuiHandler is a class takes care of all the in-game GUI */
/* (and the cursor). */
/*---------------------------------------------------------------------------------*/
#ifndef GUIHANDLER_H
#define GUIHANDLER_H
#include <Ogre.h>
#include "Debug.h"
#include "GameEnums.h"
class GuiHandler
{
public:
/* renderWnd = the current OGRE render window. */
GuiHandler(Ogre::RenderWindow* renderWnd);
/* A struct containing pointers to all overlay elements in an actionbar slot. */
struct ActionBarElements
{
Ogre::OverlayElement *PowerUp,*PowerUpLocked,*Active;
};
/* Changes the cursor. Following cursors are available:
Game::Cursor_Normal
Game::Cursor_MoveBox
Game::Cursor_MoveBoxGrab
Game::Cursor_Aim */
void changeCursor(int cursor);
/* Either shows or hide the First Person gun. If the First Person gun is to be showed,
then the cursor is placed in the middle of the screen.*/
void firstPerson(bool state);
/* Hides the casting bar. */
void hideCastingBar();
/* Hides the cursor. */
void hideCursor();
/* Initiate the GUI. Following components are loaded here:
Action bar, Casting Bar, MiniMap, First Person Gun, HP-meter.*/
void initGui();
/* If a PowerUp is loaded, this returns true, else false. A PowerUp is loaded
once the player has intersected with the representive barrel in game.*/
bool isLoaded(int powerUp);
/* Loads the casting bar for PowerUps that requires once. TotalTime is how long (seconds)
the bar will be shown. */
void loadCastingBar(int powerUp, float totalTime);
/* Shows the cursor. */
void showCursor();
/* Either shows or hides Muzzle Fire in First Person mode. */
void showMuzzleFire(bool state);
/* Either shows or hides the In-Game Gui. Used when switching from Menu and game and vice versa. */
void toggleGameGUI(bool state);
/* Updates an action bar slot. Avaiable action bar modes are:
Game::ActionBar_Normal
Game::ActionBar_Locked
Game::ActionBar_Active */
void updateActionBarElement(int powerUp,int ActionBarMode);
/* Updates the casting bar (making it smaller). */
void updateCastingBar(float curTime);
/* Updates the position of the cursor on the screen. */
void updateCursorPos(const int x,const int y);
/* Update the HP-meter. hp is a postive value. */
void updateHP(float hp);
/* Updates the position on the MiniMap. GlobalX and GlobalZ are the OGRE world
position coordinates of the player.*/
void updateMiniMap(double globalX, double globalZ);
private:
bool mvFirstPerson,mvCastBar;
int mvMouseX,mvMouseY;
float mvCastingBarTotalTime;
Ogre::RenderWindow *mvpRenderWnd;
Ogre::Overlay *mvpCursorLayer,*mvpMiniMapLayer,*mvpMuzzleFireFirstPerson,*mvpFirstPersonLayer,
*mvpHPLayer,*mvpCastingBarLayer,*mvpActionBar;
Ogre::OverlayElement *mvpCursorNormal,*mvpCursorMoveBox, *mvpCursorMoveBoxGrab,*mvpCursorAim,*mvpCurCursor,
*mvpMiniMap,*mvpCastingBar,*mvpCastingBarCur,*mvpCastingBarText,*mvpHPText,*mvpCastingBarTextTime,
*mvpCastingBarSuperSpeed,*mvpCastingBarMoveBox,*mvpCastingBarRocketBoots,*mvpCurrCastingBarIcon;
ActionBarElements mvpActionBarSuperJump,mvpActionBarSuperSpeed,mvpActionBarMoveBox,mvpActionBarPistol,mvpActionBarMachineGun,
mvpActionBarRocketBoots;
/* Initiates the HP-meter. */
void initHP();
/* Initiates the Action Bar. */
void initActionBar();
/* Initiates the First Person Shooter GUI. Starts hidden. */
void initFirstPersonShooter();
/* Initiates the MiniMap */
void initMiniMap();
/* Initiates the Casting Bar. */
void initCastingBar();
/* Changes an action bar element. See ::updateActionBarElement for available Action Bar modes. */
void changeActionBarElement(ActionBarElements& ae, int ActionBarMode);
#ifdef DEBUG
public:
void initDebugGui();
void updateDebugFPS(Ogre::String&);
void updateDebugCharXYZ(Ogre::Vector3&);
void updateDebugCamXYZ(Ogre::Vector3&);
void updateDebugDirXYZ(Ogre::Vector3&);
void updateDebugTriangles(Ogre::String& s);
void updateDebugCursorPos(const int x,const int y);
void updateCurChunk(const int x, const int y);
void updateDebugHP(float x);
private:
Ogre::Overlay* mtpDebugLayer;
Ogre::OverlayElement* debugFPS;
Ogre::OverlayElement* debugCharX;
Ogre::OverlayElement* debugCharY;
Ogre::OverlayElement* debugCharZ;
Ogre::OverlayElement* debugCamX;
Ogre::OverlayElement* debugCamY;
Ogre::OverlayElement* debugCamZ;
Ogre::OverlayElement* debugDirX;
Ogre::OverlayElement* debugDirY;
Ogre::OverlayElement* debugDirZ;
Ogre::OverlayElement* debugMouseX;
Ogre::OverlayElement* debugMouseY;
Ogre::OverlayElement* debugTriangles;
Ogre::OverlayElement* debugChunkX;
Ogre::OverlayElement* debugChunkY;
Ogre::OverlayElement* debugHP;
#endif
};
#endif#ifndef GUIHANDLER_H
#define GUIHANDLER_H
#include <Ogre.h>
#include "Debug.h"
#include "GameEnums.h"
class GuiHandler
{
public:
GuiHandler(Ogre::RenderWindow* renderWnd);
void initGui();
struct ActionBarElements
{
Ogre::OverlayElement *PowerUp,*PowerUpLocked,*Active;
};
void toggleGameGUI(bool state);
void updateActionBarElement(int powerUp,int ActionBarMode);
bool isLoaded(int powerUp);
void loadCastingBar(int powerUp, float totalTime);
void updateCastingBar(float curTime);
void hideCastingBar();
void showMuzzleFire(bool state);
void firstPerson(bool state);
void updateHP(float hp);
void updateMiniMap(double globalX, double globalZ);
void showCursor();
void changeCursor(int cursor);
void hideCursor();
void updateCursorPos(const int x,const int y);
private:
bool mvFirstPerson,mvCastBar;
int mvMouseX,mvMouseY;
Ogre::OverlayElement *mtpCursorNormal,*mtpCursorMoveBox, *mtpCursorMoveBoxGrab,*mtpCursorAim,*mtpCurCursor;
Ogre::Overlay* mtpCursorLayer;
Ogre::Overlay* mtpMiniMapLayer;
Ogre::Overlay* mtpMuzzleFireFirstPerson;
Ogre::Overlay* mtpFirstPersonLayer;
Ogre::Overlay* mtpHPLayer;
Ogre::RenderWindow* mvpRenderWnd;
Ogre::Overlay* mtpCastingBarLayer;
Ogre::OverlayElement* mtpMiniMap;
Ogre::OverlayElement* mtpCastingBar;
Ogre::OverlayElement* mtpCastingBarCur;
Ogre::OverlayElement* mtpCastingBarText;
Ogre::OverlayElement* mtpHPText;
Ogre::OverlayElement* mtpCastingBarTextTime;
Ogre::OverlayElement* mtpCastingBarSuperSpeed,*mtpCastingBarMoveBox,*mtpCastingBarRocketBoots;
Ogre::OverlayElement* mtpCurrCastingBarIcon;
float mtCastingBarTotalTime;
//Action Bar
Ogre::Overlay* mvActionBar;
ActionBarElements mvActionBarSuperJump;
ActionBarElements mvActionBarSuperSpeed;
ActionBarElements mvActionBarMoveBox;
ActionBarElements mvActionBarPistol;
ActionBarElements mvActionBarMachineGun;
ActionBarElements mvActionBarRocketBoots;
void initHP();
void initActionBar();
void initFirstPersonShooter();
void initMiniMap();
void initCastingBar();
void changeActionBarElement(ActionBarElements& ae, int ActionBarMode);
#ifdef DEBUG
public:
void initDebugGui();
void updateDebugFPS(Ogre::String&);
void updateDebugCharXYZ(Ogre::Vector3&);
void updateDebugCamXYZ(Ogre::Vector3&);
void updateDebugDirXYZ(Ogre::Vector3&);
void updateDebugTriangles(Ogre::String& s);
void updateDebugCursorPos(const int x,const int y);
void updateCurChunk(const int x, const int y);
void updateDebugHP(float x);
private:
Ogre::Overlay* mtpDebugLayer;
Ogre::OverlayElement* debugFPS;
Ogre::OverlayElement* debugCharX;
Ogre::OverlayElement* debugCharY;
Ogre::OverlayElement* debugCharZ;
Ogre::OverlayElement* debugCamX;
Ogre::OverlayElement* debugCamY;
Ogre::OverlayElement* debugCamZ;
Ogre::OverlayElement* debugDirX;
Ogre::OverlayElement* debugDirY;
Ogre::OverlayElement* debugDirZ;
Ogre::OverlayElement* debugMouseX;
Ogre::OverlayElement* debugMouseY;
Ogre::OverlayElement* debugTriangles;
Ogre::OverlayElement* debugChunkX;
Ogre::OverlayElement* debugChunkY;
Ogre::OverlayElement* debugHP;
#endif
};
#endif | [
"perkarlsson89@0a7da93c-2c89-6d21-fed9-0a9a637d9411"
]
| [
[
[
1,
264
]
]
]
|
ebe090cc1c4b18a3a09be3f58a6b77400d3a92af | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/statechart/test/TransitionTest.cpp | 2a224d7164b61be0bd75447f8a9ed08a7c72ad50 | [
"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 | 24,077 | cpp | //////////////////////////////////////////////////////////////////////////////
// Copyright 2004-2007 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////
#include "OuterOrthogonal.hpp"
#include "InnermostDefault.hpp"
#include <boost/statechart/state_machine.hpp>
#include <boost/statechart/null_exception_translator.hpp>
#include <boost/statechart/exception_translator.hpp>
#include <boost/statechart/event.hpp>
#include <boost/statechart/transition.hpp>
#include <boost/statechart/custom_reaction.hpp>
#include <boost/mpl/list.hpp>
#include <boost/test/test_tools.hpp>
#include <typeinfo>
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdexcept>
namespace sc = boost::statechart;
namespace mpl = boost::mpl;
typedef std::string ActionDescription();
typedef ActionDescription * ActionDescriptionPtr;
typedef std::vector< ActionDescriptionPtr > ActionDescriptionSequence;
typedef ActionDescriptionSequence::const_iterator SequenceIterator;
typedef void Action( ActionDescriptionSequence & );
typedef Action * ActionPtr;
template< class State >
std::string EntryDescription()
{
static const std::string entry = "Entry: ";
return entry + typeid( State ).name() + "\n";
}
template< class State >
std::string ExitFnDescription()
{
static const std::string exitFunction = "exit(): ";
return exitFunction + typeid( State ).name() + "\n";
}
template< class State >
std::string DtorDescription()
{
static const std::string destructor = "Destructor: ";
return destructor + typeid( State ).name() + "\n";
}
template< class Context, class Event >
std::string TransDescription()
{
static const std::string transition = "Transition: ";
static const std::string event = " with Event: ";
return transition + typeid( Context ).name() +
event + typeid( Event ).name() + "\n";
}
template< ActionPtr pAction >
std::string ThrowDescription()
{
static const std::string throwing = "Throwing exception in ";
ActionDescriptionSequence sequence;
pAction( sequence );
return throwing + sequence.front()();
}
template< class State >
void Entry( ActionDescriptionSequence & sequence )
{
sequence.push_back( &::EntryDescription< State > );
}
template< class State >
void ExitFn( ActionDescriptionSequence & sequence )
{
sequence.push_back( &::ExitFnDescription< State > );
}
template< class State >
void Dtor( ActionDescriptionSequence & sequence )
{
sequence.push_back( &::DtorDescription< State > );
}
template< class State >
void Exit( ActionDescriptionSequence & sequence )
{
ExitFn< State >( sequence );
Dtor< State >( sequence );
}
template< class Context, class Event >
void Trans( ActionDescriptionSequence & sequence )
{
sequence.push_back( &::TransDescription< Context, Event > );
}
template< ActionPtr pAction >
void Throw( ActionDescriptionSequence & sequence )
{
sequence.push_back( &::ThrowDescription< pAction > );
}
const int arrayLength = 30;
typedef ActionPtr ActionArray[ arrayLength ];
class TransitionTestException : public std::runtime_error
{
public:
TransitionTestException() : std::runtime_error( "Oh la la!" ) {}
};
// This test state machine is a beefed-up version of the one presented in
// "Practical Statecharts in C/C++" by Miro Samek, CMP Books 2002
struct A : sc::event< A > {};
struct B : sc::event< B > {};
struct C : sc::event< C > {};
struct D : sc::event< D > {};
struct E : sc::event< E > {};
struct F : sc::event< F > {};
struct G : sc::event< G > {};
struct H : sc::event< H > {};
template< class M > struct S0;
template< class Translator >
struct TransitionTest : sc::state_machine<
TransitionTest< Translator >, S0< TransitionTest< Translator > >,
std::allocator< void >, Translator >
{
public:
//////////////////////////////////////////////////////////////////////////
TransitionTest() : pThrowAction_( 0 ), unconsumedEventCount_( 0 ) {}
~TransitionTest()
{
// Since state destructors access the state machine object, we need to
// make sure that all states are destructed before this subtype
// portion is destructed.
this->terminate();
}
void CompareToExpectedActionSequence( ActionArray & actions )
{
expectedSequence_.clear();
// Copy all non-null pointers in actions into expectedSequence_
for ( ActionPtr * pCurrent = &actions[ 0 ];
( pCurrent != &actions[ arrayLength ] ) && ( *pCurrent != 0 );
++pCurrent )
{
( *pCurrent )( expectedSequence_ );
}
if ( ( expectedSequence_.size() != actualSequence_.size() ) ||
!std::equal( expectedSequence_.begin(),
expectedSequence_.end(), actualSequence_.begin() ) )
{
std::string message = "\nExpected action sequence:\n";
for ( SequenceIterator pExpected = expectedSequence_.begin();
pExpected != expectedSequence_.end(); ++pExpected )
{
message += ( *pExpected )();
}
message += "\nActual action sequence:\n";
for ( SequenceIterator pActual = actualSequence_.begin();
pActual != actualSequence_.end(); ++pActual )
{
message += ( *pActual )();
}
BOOST_FAIL( message.c_str() );
}
actualSequence_.clear();
}
void ClearActualSequence()
{
actualSequence_.clear();
}
void ThrowAction( ActionPtr pThrowAction )
{
pThrowAction_ = pThrowAction;
}
template< class State >
void ActualEntry()
{
StoreActualAction< &::Entry< State > >();
}
template< class State >
void ActualExitFunction()
{
StoreActualAction< &::ExitFn< State > >();
}
template< class State >
void ActualDestructor()
{
StoreActualAction< &::Dtor< State > >();
}
template< class Context, class Event >
void ActualTransition()
{
StoreActualAction< &::Trans< Context, Event > >();
}
void unconsumed_event( const sc::event_base & )
{
++unconsumedEventCount_;
}
unsigned int GetUnconsumedEventCount() const
{
return unconsumedEventCount_;
}
private:
//////////////////////////////////////////////////////////////////////////
template< ActionPtr pAction >
void StoreActualAction()
{
if ( pAction == pThrowAction_ )
{
Throw< pAction >( actualSequence_ );
throw TransitionTestException();
}
else
{
pAction( actualSequence_ );
}
}
ActionPtr pThrowAction_;
ActionDescriptionSequence actualSequence_;
ActionDescriptionSequence expectedSequence_;
unsigned int unconsumedEventCount_;
};
template< class M > struct S1;
template< class M > struct S211;
template< class M >
struct S0 : Orthogonal0< S0< M >, M, S1< M > >
{
typedef Orthogonal0< S0< M >, M, S1< M > > my_base;
public:
typedef sc::transition< E, S211< M > > reactions;
S0( typename my_base::my_context ctx ) : my_base( ctx ) {}
void Transit( const A & evt ) { TransitImpl( evt ); }
void Transit( const B & evt ) { TransitImpl( evt ); }
void Transit( const C & evt ) { TransitImpl( evt ); }
void Transit( const D & evt ) { TransitImpl( evt ); }
void Transit( const F & evt ) { TransitImpl( evt ); }
void Transit( const G & evt ) { TransitImpl( evt ); }
void Transit( const H & evt ) { TransitImpl( evt ); }
private:
template< class Event >
void TransitImpl( const Event & )
{
this->outermost_context().template ActualTransition< S0< M >, Event >();
}
};
template< class M > struct S11;
template< class M > struct S21;
template< class M >
struct S2 : Orthogonal2< S2< M >, S0< M >, S21< M > >
{
typedef Orthogonal2< S2< M >, S0< M >, S21< M > > my_base;
typedef mpl::list<
sc::transition< C, S1< M >, S0< M >, &S0< M >::Transit >,
sc::transition< F, S11< M >, S0< M >, &S0< M >::Transit >
> reactions;
S2( typename my_base::my_context ctx ) : my_base( ctx ) {}
};
template< class M >
struct S21 : Orthogonal1<
S21< M >, typename S2< M >::template orthogonal< 2 >, S211< M > >
{
typedef Orthogonal1<
S21< M >, typename S2< M >::template orthogonal< 2 >, S211< M >
> my_base;
typedef mpl::list<
sc::transition< H, S21< M >, S0< M >, &S0< M >::Transit >,
sc::transition< B, S211< M >, S0< M >, &S0< M >::Transit >
> reactions;
S21( typename my_base::my_context ctx ) : my_base( ctx ) {}
};
template< class M >
struct S211 : InnermostDefault<
S211< M >, typename S21< M >::template orthogonal< 1 > >
{
typedef InnermostDefault<
S211< M >, typename S21< M >::template orthogonal< 1 > > my_base;
typedef mpl::list<
sc::transition< D, S21< M >, S0< M >, &S0< M >::Transit >,
sc::transition< G, S0< M > >
> reactions;
S211( typename my_base::my_context ctx ) : my_base( ctx ) {}
};
template< class M >
struct S1 : Orthogonal1< S1< M >, S0< M >, S11< M > >
{
typedef Orthogonal1< S1< M >, S0< M >, S11< M > > my_base;
typedef mpl::list<
sc::transition< A, S1< M >, S0< M >, &S0< M >::Transit >,
sc::transition< B, S11< M >, S0< M >, &S0< M >::Transit >,
sc::transition< C, S2< M >, S0< M >, &S0< M >::Transit >,
sc::transition< D, S0< M > >,
sc::transition< F, S211< M >, S0< M >, &S0< M >::Transit >
> reactions;
S1( typename my_base::my_context ctx ) : my_base( ctx ) {}
};
template< class M >
struct S11 : InnermostDefault<
S11< M >, typename S1< M >::template orthogonal< 1 > >
{
typedef InnermostDefault<
S11< M >, typename S1< M >::template orthogonal< 1 > > my_base;
typedef mpl::list<
sc::transition< G, S211< M >, S0< M >, &S0< M >::Transit >,
sc::custom_reaction< H >
> reactions;
S11( typename my_base::my_context ctx ) : my_base( ctx ) {}
sc::result react( const H & )
{
this->outermost_context().template ActualTransition< S11< M >, H >();
return this->discard_event();
}
};
struct X1;
struct TransitionEventBaseTest :
sc::state_machine< TransitionEventBaseTest, X1 >
{
public:
TransitionEventBaseTest() : actionCallCounter_( 0 ) {}
void Transit( const sc::event_base & eventBase )
{
BOOST_REQUIRE(
( dynamic_cast< const B * >( &eventBase ) != 0 ) ||
( dynamic_cast< const D * >( &eventBase ) != 0 ) );
++actionCallCounter_;
}
unsigned int GetActionCallCounter() const
{
return actionCallCounter_;
}
private:
unsigned int actionCallCounter_;
};
struct X2 : sc::simple_state< X2, TransitionEventBaseTest >
{
typedef sc::transition< sc::event_base, X1,
TransitionEventBaseTest, &TransitionEventBaseTest::Transit > reactions;
};
struct X1 : sc::simple_state< X1, TransitionEventBaseTest >
{
typedef sc::transition< sc::event_base, X2 > reactions;
};
template< class M >
void TestTransitions( M & machine )
{
machine.initiate();
ActionArray init =
{
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >
};
machine.CompareToExpectedActionSequence( init );
machine.process_event( A() );
ActionArray a1 =
{
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, A >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >
};
machine.CompareToExpectedActionSequence( a1 );
machine.process_event( B() );
ActionArray b1 =
{
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, B >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >
};
machine.CompareToExpectedActionSequence( b1 );
machine.process_event( C() );
ActionArray c1 =
{
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, C >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( c1 );
machine.process_event( D() );
ActionArray d2 =
{
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Trans< S0< M >, D >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( d2 );
machine.process_event( E() );
ActionArray e2 =
{
Exit< Default2< S0< M > > >,
Exit< Default1< S0< M > > >,
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Exit< Default1< S2< M > > >,
Exit< Default0< S2< M > > >,
Exit< S2< M > >,
Exit< S0< M > >,
Entry< S0< M > >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >
};
machine.CompareToExpectedActionSequence( e2 );
machine.process_event( F() );
ActionArray f2 =
{
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Exit< Default1< S2< M > > >,
Exit< Default0< S2< M > > >,
Exit< S2< M > >,
Trans< S0< M >, F >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >
};
machine.CompareToExpectedActionSequence( f2 );
machine.process_event( G() );
ActionArray g1 =
{
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, G >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( g1 );
machine.process_event( H() );
ActionArray h2 =
{
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Trans< S0< M >, H >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( h2 );
BOOST_REQUIRE( machine.GetUnconsumedEventCount() == 0 );
machine.process_event( A() );
BOOST_REQUIRE( machine.GetUnconsumedEventCount() == 1 );
ActionArray a2 =
{
};
machine.CompareToExpectedActionSequence( a2 );
machine.process_event( B() );
ActionArray b2 =
{
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Trans< S0< M >, B >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( b2 );
machine.process_event( C() );
ActionArray c2 =
{
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Exit< Default1< S2< M > > >,
Exit< Default0< S2< M > > >,
Exit< S2< M > >,
Trans< S0< M >, C >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >
};
machine.CompareToExpectedActionSequence( c2 );
machine.process_event( D() );
ActionArray d1 =
{
Exit< Default2< S0< M > > >,
Exit< Default1< S0< M > > >,
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Exit< S0< M > >,
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >
};
machine.CompareToExpectedActionSequence( d1 );
machine.process_event( F() );
ActionArray f1 =
{
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, F >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >
};
machine.CompareToExpectedActionSequence( f1 );
machine.process_event( G() );
ActionArray g2 =
{
Exit< Default2< S0< M > > >,
Exit< Default1< S0< M > > >,
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Exit< Default1< S2< M > > >,
Exit< Default0< S2< M > > >,
Exit< S2< M > >,
Exit< S0< M > >,
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >
};
machine.CompareToExpectedActionSequence( g2 );
machine.process_event( H() );
ActionArray h1 =
{
Trans< S11< M >, H >
};
machine.CompareToExpectedActionSequence( h1 );
machine.process_event( E() );
ActionArray e1 =
{
Exit< Default2< S0< M > > >,
Exit< Default1< S0< M > > >,
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Exit< S0< M > >,
Entry< S0< M > >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Entry< S211< M > >,
Entry< Default2< S21< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >
};
machine.CompareToExpectedActionSequence( e1 );
machine.terminate();
ActionArray term =
{
Exit< Default2< S0< M > > >,
Exit< Default1< S0< M > > >,
Exit< Default2< S21< M > > >,
Exit< S211< M > >,
Exit< Default0< S21< M > > >,
Exit< S21< M > >,
Exit< Default1< S2< M > > >,
Exit< Default0< S2< M > > >,
Exit< S2< M > >,
Exit< S0< M > >
};
machine.CompareToExpectedActionSequence( term );
machine.ThrowAction( Entry< Default0< S1< M > > > );
BOOST_REQUIRE_THROW( machine.initiate(), TransitionTestException );
ActionArray initThrow1 =
{
Entry< S0< M > >,
Entry< S1< M > >,
Throw< Entry< Default0< S1< M > > > >,
Dtor< S1< M > >,
Dtor< S0< M > >
};
machine.CompareToExpectedActionSequence( initThrow1 );
BOOST_REQUIRE( machine.terminated() );
machine.ThrowAction( Entry< S11< M > > );
BOOST_REQUIRE_THROW( machine.initiate(), TransitionTestException );
ActionArray initThrow2 =
{
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Throw< Entry< S11< M > > >,
Dtor< Default0< S1< M > > >,
Dtor< S1< M > >,
Dtor< S0< M > >
};
machine.CompareToExpectedActionSequence( initThrow2 );
BOOST_REQUIRE( machine.terminated() );
machine.ThrowAction( Trans< S0< M >, A > );
machine.initiate();
BOOST_REQUIRE_THROW( machine.process_event( A() ), TransitionTestException );
ActionArray a1Throw1 =
{
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >,
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Throw< Trans< S0< M >, A > >,
Dtor< Default2< S0< M > > >,
Dtor< Default1< S0< M > > >,
Dtor< S0< M > >
};
machine.CompareToExpectedActionSequence( a1Throw1 );
BOOST_REQUIRE( machine.terminated() );
machine.ThrowAction( Entry< S211< M > > );
machine.initiate();
BOOST_REQUIRE_THROW( machine.process_event( C() ), TransitionTestException );
ActionArray c1Throw1 =
{
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >,
Exit< Default2< S1< M > > >,
Exit< S11< M > >,
Exit< Default0< S1< M > > >,
Exit< S1< M > >,
Trans< S0< M >, C >,
Entry< S2< M > >,
Entry< Default0< S2< M > > >,
Entry< Default1< S2< M > > >,
Entry< S21< M > >,
Entry< Default0< S21< M > > >,
Throw< Entry< S211< M > > >,
Dtor< Default2< S0< M > > >,
Dtor< Default1< S0< M > > >,
Dtor< Default0< S21< M > > >,
Dtor< S21< M > >,
Dtor< Default1< S2< M > > >,
Dtor< Default0< S2< M > > >,
Dtor< S2< M > >,
Dtor< S0< M > >
};
machine.CompareToExpectedActionSequence( c1Throw1 );
BOOST_REQUIRE( machine.terminated() );
machine.ThrowAction( ExitFn< S11< M > > );
machine.initiate();
BOOST_REQUIRE_THROW( machine.process_event( C() ), TransitionTestException );
ActionArray c1Throw2 =
{
Entry< S0< M > >,
Entry< S1< M > >,
Entry< Default0< S1< M > > >,
Entry< S11< M > >,
Entry< Default2< S1< M > > >,
Entry< Default1< S0< M > > >,
Entry< Default2< S0< M > > >,
Exit< Default2< S1< M > > >,
Throw< ExitFn< S11< M > > >,
Dtor< S11< M > >,
Dtor< Default2< S0< M > > >,
Dtor< Default1< S0< M > > >,
Dtor< Default0< S1< M > > >,
Dtor< S1< M > >,
Dtor< S0< M > >
};
machine.CompareToExpectedActionSequence( c1Throw2 );
BOOST_REQUIRE( machine.terminated() );
BOOST_REQUIRE( machine.GetUnconsumedEventCount() == 1 );
}
int test_main( int, char* [] )
{
TransitionTest< sc::null_exception_translator > null_machine;
TestTransitions( null_machine );
TransitionTest< sc::exception_translator<> > machine;
TestTransitions( machine );
TransitionEventBaseTest eventBaseMachine;
eventBaseMachine.initiate();
BOOST_REQUIRE_NO_THROW( eventBaseMachine.state_cast< const X1 & >() );
eventBaseMachine.process_event( A() );
BOOST_REQUIRE_NO_THROW( eventBaseMachine.state_cast< const X2 & >() );
BOOST_REQUIRE( eventBaseMachine.GetActionCallCounter() == 0 );
eventBaseMachine.process_event( B() );
BOOST_REQUIRE_NO_THROW( eventBaseMachine.state_cast< const X1 & >() );
BOOST_REQUIRE( eventBaseMachine.GetActionCallCounter() == 1 );
eventBaseMachine.process_event( C() );
BOOST_REQUIRE_NO_THROW( eventBaseMachine.state_cast< const X2 & >() );
BOOST_REQUIRE( eventBaseMachine.GetActionCallCounter() == 1 );
eventBaseMachine.process_event( D() );
BOOST_REQUIRE_NO_THROW( eventBaseMachine.state_cast< const X1 & >() );
BOOST_REQUIRE( eventBaseMachine.GetActionCallCounter() == 2 );
return 0;
}
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
849
]
]
]
|
49436052a8a5a301cdc16aea949ca3fa8d81491e | 6fd162d2cade2db745e68f11d7e9722a3855f033 | /Source/Common/S3UT/Console.cpp | c046fab758a44e3bfc687832c7b9c48748c91324 | []
| no_license | SenichiFSeiei/oursavsm | 8f418325bc9883bcb245e139dbd0249e72c18d78 | 379e77cab67b3b1423a4c6f480b664f79b03afa9 | refs/heads/master | 2021-01-10T21:00:52.797565 | 2010-04-27T13:18:19 | 2010-04-27T13:18:19 | 41,737,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,369 | cpp | #include "DXUT.h"
#include <windows.h>
#include <process.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
//#include <iostream.h>
#include <iostream>
//#include <fstream.h>
#include <fstream>
#include "Console.h"
#ifdef PLATFORM_ENABLE_CONSOLE
#define MAX_CONSOLE_LINES 2000;
HANDLE g_hConsoleOut; // Handle to debug console
void RedirectIOToConsole(const wchar_t title[]);
// This function dynamically creates a "Console" window and points stdout and stderr to it.
// It also hooks stdin to the window
// You must free it later with FreeConsole
void RedirectIOToConsole(const wchar_t title[])
{
int hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
// How many lines do you want to have in the console buffer
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
// redirect unbuffered STDOUT to the console
g_hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE);
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
// setvbuf( stdout, NULL, _IONBF, 0 );
// // redirect unbuffered STDIN to the console
// lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
// hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
// fp = _fdopen( hConHandle, "r" );
// *stdin = *fp;
// setvbuf( stdin, NULL, _IONBF, 0 );
// // redirect unbuffered STDERR to the console
// lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
// hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
// fp = _fdopen( hConHandle, "w" );
// *stderr = *fp;
// setvbuf( stderr, NULL, _IONBF, 0 );
SetConsoleTitle(title);
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well
// Uncomment the next line if you are using c++ cio or comment if you don't file://ios::sync_with_stdio();
}
#endif // PLATFORM_ENABLE_CONSOLE
////////////////////////////////////////////////////////////////////////////
//
// end of console.cpp
//
//////////////////////////////////////////////////////////////////////////// | [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
6460bc37a630e53fa1fe68ec35ea1d4accb95912 | d826e0dcc5b51f57101f2579d65ce8e010f084ec | /pre/FSketch.cpp | ff2becfb15ac7d974600b041fd932419ebe1deb1 | []
| no_license | crazyhedgehog/macro-parametric | 308d9253b96978537a26ade55c9c235e0442d2c4 | 9c98d25e148f894b45f69094a4031b8ad938bcc9 | refs/heads/master | 2020-05-18T06:01:30.426388 | 2009-06-26T15:00:02 | 2009-06-26T15:00:02 | 38,305,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,910 | cpp | #include ".\FSketch.h"
#include <iostream>
#include <uf_modl.h>
#include <uf_sket.h>
#include <uf_obj.h>
#include "Part.h"
#include "FSKETCHCreate2DLIne2Points.h"
#include "FSKETCHCreate2DCircleCenterPoint.h"
#include "FSKETCHcreate2DArcCenterEnds.h"
//#include "FSKETCHCreate2DArc3Points.h"
using namespace std;
int FSketch::_nSketCnt = 0;
FSketch::FSketch(Part * part, tag_t fTag) :
Feature(part,fTag)
{
//---------- Get sketchTag of fTag----------//
uf_list_p_t object_list;
// Returns all sketchTags associated with fTag
UF_CALL(UF_SKET_ask_feature_sketches( fTag, &object_list));
// set the first to _sketTag
UF_CALL(UF_MODL_ask_list_item (object_list, 0, &_sketTag ));
UF_MODL_delete_list(&object_list);
// get Sketch Info from _sketTag
UF_CALL(UF_SKET_ask_sketch_info (_sketTag, &_ugSketInfo));
for (int i=0 ; i < 12 ; i++ )
_sketInfo[i] = ValRnd(_ugSketInfo.csys[i]);
}
FSketch::~FSketch(void)
{
Clear();
}
void FSketch::Clear()
{
std::vector<Feature*>::iterator i = _sketObjList.begin();
while ( i != _sketObjList.end() ) {delete *i; i++;}
_sketObjList.clear();
}
Feature * FSketch::GetCLine()
{
for (size_t i=0; i < GetSketObjSize() ; i++)
{
Feature * pFeature = GetSketObj((int)i);
if ( pFeature->GetFType() == SKETCH_Create_2D_Centerline )
return pFeature;
}
return 0;
}
void FSketch::SetCLine(Feature* pFeature)
{
if (GetCLine()) return;
_sketObjList.insert(_sketObjList.begin(), pFeature);
}
Feature * FSketch::CreateSketObj(tag_t objectTag)
{
Feature * pSketchObjectFeature = 0;
int curve_type;
int curve_subtype;
UF_CALL(UF_OBJ_ask_type_and_subtype (objectTag, &curve_type, &curve_subtype));
//DEBUG
cout << " " << (unsigned int)(this->GetSketObjSize()) << " : CurveType=" << curve_type << ", SubType=" << curve_subtype;
cout << " --> ";
switch (curve_type) {
case 3 : // Line
pSketchObjectFeature = new FSKETCHCreate2DLine2Points(GetPart(), objectTag, this);
cout << "SKETCHCreate2DLine2Points Constructed" << endl;
break;
case 5 : // Arc, Circle
UF_CURVE_arc_t ugArc;
UF_CALL(UF_CURVE_ask_arc_data( objectTag, &ugArc ) );
//---------- Circle : SKETCHCreate2DCircleCenterPoint ----------//
if ( (ugArc.end_angle - ugArc.start_angle) >= (2*PI) )
{
pSketchObjectFeature = new FSKETCHCreate2DCircleCenterPoint(GetPart(), objectTag, this);
cout << "SKETCHCreate2DCircleCenterPoint Constructed" << endl;
}
//---------- Arc : SKETCHcreate2DArcCenterEnds ----------//
else
{
pSketchObjectFeature = new FSKETCHCreate2DArcCenterEnds(GetPart(), objectTag, this);
cout << "FSKETCHcreate2DArcCenterEnds Constructed" << endl;
}
break;
default : // curve_type unknown
cout << "Unknown Sketch curve type : " << curve_type << endl;
break;
}
if(pSketchObjectFeature) _sketObjList.push_back(pSketchObjectFeature);
return pSketchObjectFeature;
}
void FSketch::GetUGInfo()
{
Feature * pFSketchObject;
int objectsNum; // sketch objects number
tag_t * objectTags; // sketch objects tags list
UF_CALL(UF_SKET_ask_geoms_of_sketch( GetSketTag(), &objectsNum, &objectTags)); // UF_free(objectTags)
//DEBUG
cout << " " << "[[[ Constructing Sketch objects... ]]]" << endl;
//------- Loop to create sketch object features list in objectTag --------//
for (int k=0; k < objectsNum ; k++)
{
tag_t objectTag = objectTags[k];
// Create a sketch object feature class
pFSketchObject = CreateSketObj(objectTag);
if(!pFSketchObject)
cerr << " " << "****** Cannot support the sketch object! ******" << endl;
}
UF_free(objectTags);
//DEBUG
cout << " " << "[[[ Translating Sketch objects... ]]]" << endl;
//------- Loop to translate sketch object features in list --------//
for ( size_t i=0 ; i < GetSketObjSize(); ++i )
{
GetSketObj((unsigned int)i)->GetUGInfo();
//DEBUG
cout << " " << (unsigned int)i << " : " << GetSketObj((unsigned int)i)->GetName() << " translated" << endl;
}
//---------- Set Result_Object_Name ----------//
char buffer[20];
_itoa(_nSketCnt ++ , buffer, 10 );
SetName("sketch" + (string)buffer);
}
TransCAD::ISketchEditorPtr FSketch::GetSketchEditorPtr()
{
return _spSketEditor;
}
void FSketch::ToTransCAD()
{
static int k = 0;
k++;
Point3D origin = GetOrigin();
Direct3D xdir = GetX();
Direct3D ydir = GetY();
//DEBUG
Direct3D zdir = GetZ();
cout << " " << origin.X() << " " << origin.Y() << " " << origin.Z() << endl;
cout << " " << xdir.X() << " " << xdir.Y() << " " << xdir.Z() << endl;
cout << " " << ydir.X() << " " << ydir.Y() << " " << ydir.Z() << endl;
cout << " " << zdir.X() << " " << zdir.Y() << " " << zdir.Z() << endl;
// Select Reference Plane for sketch
//TransCAD::IReferencePtr spSelectedPlane;
//if (k==4) spSelectedPlane = GetPart()->_spPart->SelectObjectByName("proExtrude0,sketch0,line2D2,0,0,0,ExtrudeFeature:0,0:0;0");
TransCAD::IReferencePtr spSelectedPlane = GetPart()->_spPart->SelectPlaneByAxis(origin.X(), origin.Y(), origin.Z(),
xdir.X(), xdir.Y(), xdir.Z(), ydir.X(), ydir.Y(), ydir.Z());
// Add new StdSketchFeature to TransCAD
TransCAD::IStdSketchFeaturePtr spSketch = GetPart()->_spFeatures->AddNewSketchFeature(GetName().c_str(), spSelectedPlane);
// Set Coordinate system of Sketch
spSketch->SetCoordinateSystem(origin.X(), origin.Y(), origin.Z(), xdir.X(), xdir.Y(), xdir.Z(), ydir.X(), ydir.Y(), ydir.Z());
// TransCAD Sketch Open
_spSketEditor = spSketch->OpenEditorEx(VARIANT_FALSE);
//---------- Sketch Objects : ToTransCAD() ----------//
for ( size_t i=0 ; i < GetSketObjSize() ; ++i )
GetSketObj((unsigned int)i)->ToTransCAD();
// TransCAD Sketch Close
_spSketEditor->Close();
} | [
"surplusz@2d8c97fe-2f4b-11de-8e0c-53a27eea117e"
]
| [
[
[
1,
195
]
]
]
|
62d30666cb93420b43837fa5349d6c1c81bd2f1c | 50c10c208dc64d362a02d680388a944f7da16cbc | /Principal/interfazRMN2/instruction.h | 80149a188325489ae32af2ecaa15b1be73635e23 | []
| no_license | raulmonti/generador-de-pulsos-2011 | c18e9938f9f28651a995677414ebc8d29f0c2dcc | 3634a47bcf2fb01cba4d9f8c84928ca2eb60646c | refs/heads/master | 2020-04-14T15:09:01.914839 | 2011-03-23T22:03:20 | 2011-03-23T22:03:20 | 33,492,955 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | h | #ifndef INSTRUCTION_H
#define INSTRUCTION_H
#define LOOP_INST_CODE 0
#define ACQUIRE_INST_CODE 1
#define PULSE_INST_CODE 2
#define DELAY_INST_CODE 3
#define ENDLOOP_INST_CODE 4
#define END_INST_CODE 5
class instruction{
private:
unsigned int id;
unsigned int type;
int data;
unsigned int duration;
unsigned int number;
unsigned int phase_shift;
public:
instruction(unsigned int i, int t, int d);
void set_duration(unsigned int d);
unsigned int get_duration(void);
void std_out_print(void);
int get_data(void);
unsigned int get_type(void);
unsigned int get_id(void);
bool is_phase_shifted(void);
void phase_add_shift(int shift);
void set_phase_shift(bool shifted);
int phase_get_shift(void);
unsigned int get_number(void);
void set_number(unsigned int n);
instruction *clone(void);
void set_data(unsigned int n);
unsigned int get_instruction_code(void);
};
#endif
| [
"[email protected]@d9bf8441-58a9-7046-d6f0-32bbd92d4940"
]
| [
[
[
1,
54
]
]
]
|
bcd4b6368720366efdbcf9e922220d32fd3a13ae | d7320c9c1f155e2499afa066d159bfa6aa94b432 | /ghostgproxy/pluginmgr.cpp | 3e8f20d067bde568d94b8cb537e4c6fe1aa13bb9 | []
| no_license | HOST-PYLOS/ghostnordicleague | c44c804cb1b912584db3dc4bb811f29f3761a458 | 9cb262d8005dda0150b75d34b95961d664b1b100 | refs/heads/master | 2016-09-05T10:06:54.279724 | 2011-02-23T08:02:50 | 2011-02-23T08:02:50 | 32,241,503 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,130 | cpp | #include <dlfcn.h>
#include "ghost.h"
#include "util.h"
#include "game_base.h"
#include "pluginmgr.h"
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
using namespace boost :: filesystem;
typedef void* (*arbitrary)();
CPlugin :: CPlugin(string nName, void *nHandle)
{
CONSOLE_Print("[PLUGIN] Loaded plugin [" + nName + "]" );
m_Name = nName;
m_Handle = nHandle;
}
CPlugin :: ~CPlugin()
{
dlclose(m_Handle);
CONSOLE_Print("[PLUGIN] Unloading [" + m_Name + "]" );
}
void CPlugin :: Execute(string function)
{
if (!m_Handle)
{
CONSOLE_Print("[PLUGIN: " + m_Name + "] Execute aborted, called [" + function + "] but we have no handle!" );
return;
}
char *error;
typedef void (*function_t)();
function_t PluginFunction = (function_t) dlsym(m_Handle, function.c_str());
if ((error = dlerror()) != NULL)
{
CONSOLE_Print("[PLUGIN: " + m_Name + "] Can not finding symbol for [" + function + "]" );
dlclose(m_Handle);
return;
}
(*PluginFunction)();
}
CPluginMgr :: CPluginMgr()
{
ReloadPlugins( );
}
CPluginMgr :: ~CPluginMgr()
{
UnloadPlugins( );
}
void CPluginMgr :: ReloadPlugins( )
{
if (!m_LoadedPlugins.empty())
UnloadPlugins();
CONSOLE_Print("[PLUGINMGR] Searching for plugins...");
FindPlugins(path("./plugins"), true);
CONSOLE_Print("[PLUGINMGR] Loaded " + UTIL_ToString( m_LoadedPlugins.size() ) + " plugins." );
}
void CPluginMgr :: FindPlugins( const path & directory, bool recurse_into_subdirs )
{
if( exists( directory ) )
{
directory_iterator end;
for( directory_iterator iter(directory) ; iter != end ; ++iter )
{
if ( is_directory( *iter ) )
{
if ( recurse_into_subdirs )
FindPlugins(*iter);
}
else
{
CONSOLE_Print(iter->leaf());
boost::regex expression("^.*(so)$");
if (boost::regex_match(iter->leaf(),expression))
LoadPlugin( iter->string() );
}
}
}
}
void CPluginMgr :: LoadPlugin( string filename )
{
char *error;
void* handle = dlopen(filename.c_str(), RTLD_LAZY);
CONSOLE_Print("[PLUGINMGR] Trying to load: " + filename);
if (!handle)
{
CONSOLE_Print( "[PLUGINMGR] Error loading plugin: " + filename );
return;
}
typedef string (*getname_t)();
getname_t GetName = (getname_t) dlsym(handle, "GetName");
if ((error = dlerror()) != NULL)
{
CONSOLE_Print("[PLUGINMGR] Error finding symbol [GetName]" );
dlclose(handle);
return;
}
string PluginName = (*GetName)();
m_LoadedPlugins.push_back(new CPlugin(PluginName, handle));
}
void CPluginMgr :: UnloadPlugins( )
{
CONSOLE_Print("[PLUGINMGR] Unloading " + UTIL_ToString( m_LoadedPlugins.size() ) + " plugins." );
for( vector<CPlugin *> :: iterator i = m_LoadedPlugins.begin( ); i != m_LoadedPlugins.end( ); )
{
delete *i;
i = m_LoadedPlugins.erase( i );
}
}
void CPluginMgr :: Execute(string function)
{
for( vector<CPlugin *> :: iterator i = m_LoadedPlugins.begin( ); i != m_LoadedPlugins.end( ); )
{
(*i)->Execute(function);
}
}
//vector<CPlugin *> m_LoadedPlugins;
| [
"[email protected]@4a4c9648-eef2-11de-9456-cf00f3bddd4e"
]
| [
[
[
1,
139
]
]
]
|
c5a91c39e1ebbaeed7ed02618cfc7a302b3dc148 | a705a17ff1b502ec269b9f5e3dc3f873bd2d3b9c | /src/bg_layer.cpp | 8628b650253a406949b90f1f8d01784f9dae336e | []
| no_license | cantidio/ChicolinusQuest | 82431a36516d17271685716590fe7aaba18226a0 | 9b77adabed9325bba23c4d99a3815e7f47456a4d | refs/heads/master | 2021-01-25T07:27:54.263356 | 2011-08-09T11:17:53 | 2011-08-09T11:17:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,507 | cpp | #include "bg_layer.hpp"
#include "lua.hpp"
using namespace Gorgon::Script;
BGLayer::BGLayer(const std::string& pImage, const Point& pScrollingVelocity)
{
mImage = al_load_bitmap( pImage.c_str() );
al_convert_mask_to_alpha(mImage, al_map_rgb(255,0,255));
mScrollingVelocity.x = pScrollingVelocity.x;
mScrollingVelocity.y = pScrollingVelocity.y;
}
BGLayer::~BGLayer()
{
al_destroy_bitmap( mImage );
}
/*
-lallegro
-lallegro_color
-lallegro_image
-lallegro_primitives
-lallegro_memfile
-lallegro_audio
-lallegro_acodec
*/
void BGLayer::addObject(Object* pObject)
{
mObjects.push_back(pObject);
}
void BGLayer::draw(const Point& pPosition) const
{
const float base_x = pPosition.x * mScrollingVelocity.x;
const float base_y = pPosition.y * mScrollingVelocity.y;
const int init_x1= (int)base_x % al_get_bitmap_width(mImage);
//const double init_x1 = base_x - base_x/al_get_bitmap_width(mImage) ;
const int end_x1 = al_get_bitmap_width(mImage) - init_x1;
al_draw_bitmap_region
(
mImage,
init_x1,
0,
al_get_bitmap_width(mImage) - init_x1,
al_get_bitmap_height(mImage),
0, 0,
0
);
al_draw_bitmap_region
(
mImage,
0,0,
init_x1,
al_get_bitmap_height(mImage),
end_x1,
0,
0
);
//draw objects
for(register unsigned int i = 0; i < mObjects.size(); ++i)
{
mObjects[i]->draw( Point( -base_x,base_y ) );
}
}
void BGLayer::logic()
{
for(register unsigned int i = 0; i < mObjects.size(); ++i)
{
mObjects[i]->logic();
}
}
| [
"[email protected]"
]
| [
[
[
1,
75
]
]
]
|
1fee82a9da6876e4ed54044f10432228d77b8749 | 1d415fdfabd9db522a4c3bca4ba66877ec5b8ef4 | /mpeg2decoder/ttmpeg2decoder.h | 9e9e99e665212a01e22f128d775a6a24c620e8c6 | []
| no_license | panjinan333/ttcut | 61b160c0c38c2ea6c8785ba258c2fa4b6d18ae1a | fc13ec3289ae4dbce6a888d83c25fbc9c3d21c1a | refs/heads/master | 2022-03-23T21:55:36.535233 | 2010-12-23T20:58:13 | 2010-12-23T20:58:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,075 | h | /*----------------------------------------------------------------------------*/
/* COPYRIGHT: TriTime (c) 2003/2010 / www.tritime.org */
/*----------------------------------------------------------------------------*/
/* PROJEKT : TTCUT 2008 */
/* FILE : ttmpeg2decoder.h */
/*----------------------------------------------------------------------------*/
/* AUTHOR : b. altendorf (E-Mail: [email protected]) DATE: 02/23/2005 */
/* MODIFIED: b. altendorf DATE: 03/01/2005 */
/* MODIFIED: b. altendorf DATE: 03/31/2005 */
/* MODIFIED: b. altendorf DATE: 04/30/2005 */
/*----------------------------------------------------------------------------*/
// ----------------------------------------------------------------------------
// TTMPEG2DECODER
// ----------------------------------------------------------------------------
/*----------------------------------------------------------------------------*/
/* This program is free software; you can redistribute it and/or modify it */
/* under the terms of the GNU General Public License as published by the Free */
/* Software Foundation; */
/* either version 2 of the License, or (at your option) any later version. */
/* */
/* This program is distributed in the hope that it will be useful, but WITHOUT*/
/* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */
/* FITNESS FOR A PARTICULAR PURPOSE. */
/* See the GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License along */
/* with this program; if not, write to the Free Software Foundation, */
/* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */
/*----------------------------------------------------------------------------*/
#ifndef TTMPEG2DECODER_H
#define TTMPEG2DECODER_H
#include "../common/ttcut.h"
// standard C header files
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
// libmpeg2-dec header files
extern "C"
{
#include <mpeg2dec/mpeg2.h>
#include <mpeg2dec/mpeg2convert.h>
}
// Qt header files
#include <qstring.h>
#include "../avstream/ttavheader.h"
#include "../avstream/ttvideoheaderlist.h"
#include "../avstream/ttvideoindexlist.h"
#include "../avstream/ttmpeg2videoheader.h"
/* /////////////////////////////////////////////////////////////////////////////
* constants for mpeg2 pixel format
*/
enum TPixelFormat
{
formatRGB24 = 1, // RGB interleaved; default
formatRGB32 = 2,
formatRGB8 = 3,
formatYV12 = 4,
formatYUV24 = 5 // YUV planes
};
/* /////////////////////////////////////////////////////////////////////////////
* Frame info struct
*/
typedef struct
{
quint8* Y;
quint8* U;
quint8* V;
int width;
int height;
int size;
int type;
int chroma_width;
int chroma_height;
int chroma_size;
} TFrameInfo;
/* /////////////////////////////////////////////////////////////////////////////
* Sequence properties struct
*/
typedef struct
{
int width;
int height;
unsigned int byte_rate;
unsigned int vbv_buffer_size;
unsigned int frame_period;
} TSequenceInfo;
/* /////////////////////////////////////////////////////////////////////////////
* Stream properties struct
*/
typedef struct
{
quint64 size;
quint64 position;
int frame;
int videoPTS;
} TStreamInfo;
/* /////////////////////////////////////////////////////////////////////////////
* Initial buffer size
*/
const int initialStreamBufferSize = 65536;
const int initialDecoderBufferSize = 5129;
/* /////////////////////////////////////////////////////////////////////////////
* TTMpeg2Decoder class declaration
*/
class TTMpeg2Decoder
{
public:
TTMpeg2Decoder(QString cFName,
TTVideoIndexList* viIndex, TTVideoHeaderList* viHeader,
TPixelFormat pixelFormat=formatRGB32);
~TTMpeg2Decoder();
void openMPEG2File(QString cFName);
quint64 fileSize();
QString fileName();
int moveToFrameIndex(int iFramePos);
TFrameInfo* decodeFirstMPEG2Frame(TPixelFormat pixelFormat=formatRGB32);
TFrameInfo* decodeMPEG2Frame(TPixelFormat pixelFormat=formatRGB32);
int gotoNextFrame();
void getCurrentFrameData(quint8* data);
TFrameInfo* getFrameInfo();
int desiredFrameType;
int desiredFramePos;
protected:
void initDecoder(TPixelFormat pixelFormat=formatRGB32);
int decodeNextFrame();
int skipFrames(int count);
int seek(quint64 seqHeaderOffset);
private:
QFile* mpeg2Stream;
mpeg2dec_t* mpeg2Decoder;
mpeg2_state_t state;
quint8* streamBuffer;
quint8* decoderBuffer;
int streamBufferSize;
int decoderBufferSize;
const mpeg2_info_t* mpeg2Info;
quint8* sliceData;
TTVideoHeaderList* videoHeaderList;
TTVideoIndexList* videoIndexList;
TPixelFormat convType;
TFrameInfo* t_frame_info;
};
/* /////////////////////////////////////////////////////////////////////////////
* Decoder exception class
*/
class TTMpeg2DecoderException
{
public:
enum ExceptionType
{
ArgumentNull,
DecoderInit,
StreamOpen
};
TTMpeg2DecoderException(ExceptionType type);
QString message();
protected:
ExceptionType ex_type;
};
#endif //TTMPEG2DECODER_H
| [
"[email protected]"
]
| [
[
[
1,
184
]
]
]
|
e140637121bce96c8fba1ef169d21acb4401a9b0 | c1b7571589975476405feab2e8b72cdd2a592f8f | /chopshop10/LiftCan166.cpp | 4ba9cbc81f9c9df475bde5d71210e53ee2c05a70 | []
| no_license | chopshop-166/frc-2010 | ea9cd83f85c9eb86cc44156f21894410a9a4b0b5 | e15ceff05536768c29fad54fdefe65dba9a5fab5 | refs/heads/master | 2021-01-21T11:40:07.493930 | 2010-12-10T02:04:05 | 2010-12-10T02:04:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,274 | cpp | /*******************************************************************************
* Project : chopshop10 - 2010 Chopshop Robot Controller Code
* File Name : Lift166.cpp
* Owner : Software Group (FIRST Chopshop Team 166)
* Creation Date : January 18, 2010
* Revision History : From Explorer with TortoiseSVN, Use "Show log" menu item
* File Description : Robot code which controls the hanging lift
*******************************************************************************/
/*----------------------------------------------------------------------------*/
/* Copyright (c) MHS Chopshop Team 166, 2010. All Rights Reserved. */
/*----------------------------------------------------------------------------*/
#include "WPILib.h"
#include "LiftCan166.h"
// To locally enable debug printing: set true, to disable false
#define DPRINTF if(false)dprintf
// Sample in memory buffer
struct abuf166
{
struct timespec tp; // Time of snapshot
bool deployed; // Deployed already?
bool button; // Whether the lift button is pressed
float current;
};
// Memory Log
class LiftCanLog : public MemoryLog166
{
public:
LiftCanLog() : MemoryLog166(
sizeof(struct abuf166), LIFT_CYCLE_TIME, "lift",
"Seconds,Nanoseconds,Elapsed Time,Deployed?,Button State,Lift Motor Current\n"
) {
return;
};
~LiftCanLog() {return;};
unsigned int DumpBuffer( // Dump the next buffer into the file
char *nptr, // Buffer that needs to be formatted
FILE *outputFile); // and then stored in this file
unsigned int PutOne(bool deployed, bool button, float current); // Log the lift's state
};
// Write one buffer into memory
unsigned int LiftCanLog::PutOne(bool deployed, bool button, float current)
{
struct abuf166 *ob; // Output buffer
// Get output buffer
if ((ob = (struct abuf166 *)GetNextBuffer(sizeof(struct abuf166)))) {
// Fill it in.
clock_gettime(CLOCK_REALTIME, &ob->tp);
ob->deployed = button;
ob->button = button;
ob->current = current;
return (sizeof(struct abuf166));
}
// Did not get a buffer. Return a zero length
return (0);
}
// Format the next buffer for file output
unsigned int LiftCanLog::DumpBuffer(char *nptr, FILE *ofile)
{
struct abuf166 *ab = (struct abuf166 *)nptr;
// Output the data into the file
fprintf(ofile, "%u,%u,%4.5f,%d,%d,%4.5f\n",
ab->tp.tv_sec, ab->tp.tv_nsec,
((ab->tp.tv_sec - starttime.tv_sec) + ((ab->tp.tv_nsec-starttime.tv_nsec)/1000000000.)),
ab->deployed, ab->button, ab->current);
// Done
return (sizeof(struct abuf166));
}
// task constructor
Team166LiftCan::Team166LiftCan(void):
liftJag(T166_LIFT_MOTOR_CAN),
LiftLatch_Solenoid(T166_LIFT_PISTON),
LiftUnlatch_Solenoid(T166_UNLIFT_PISTON)
{
Start((char *)"166LiftCanTask", LIFT_CYCLE_TIME);
return;
};
// task destructor
Team166LiftCan::~Team166LiftCan(void)
{
return;
};
// Main function of the task
int Team166LiftCan::Main(int a2, int a3, int a4, int a5,
int a6, int a7, int a8, int a9, int a10)
{
Robot166 *lHandle; // Local handle
LiftCanLog sl; // log
Proxy166 *proxy;
bool deployed = false; // Whether the button was pressed
bool button = false; // Whether the button is a new press or not
unsigned valuethrottle = 0; // Only let the current update every once in a while
float liftCurrent = 0; // Current for the lift jag
// Let the world know we're in
DPRINTF(LOG_DEBUG,"In the 166 Lift task\n");
// Wait for Robot go-ahead (e.g. entering Autonomous or Tele-operated mode)
WaitForGoAhead();
// Register our logger
lHandle = Robot166::getInstance();
lHandle->RegisterLogger(&sl);
proxy=Proxy166::getInstance();
// Prepare the solenoids-these don't have to be constantly pulsed
LiftUnlatch_Solenoid.Set(false);
LiftLatch_Solenoid.Set(true);
// General main loop (while in Autonomous or Tele mode)
while ((lHandle->RobotMode == T166_AUTONOMOUS) ||
(lHandle->RobotMode == T166_OPERATOR)) {
if(deployed) {
// Set motor to retract or expand the arm
liftJag.Set(
proxy->GetButton(T166_COPILOT_STICK,T166_LIFT_UP_BUTTON) -
proxy->GetButton(T166_COPILOT_STICK,T166_LIFT_DOWN_BUTTON)
);
} else { // Not deployed
button = (
proxy->GetButton(T166_COPILOT_STICK, T166_LIFT_RELEASE_BUTTON) &
proxy->GetButton(T166_DRIVER_STICK_LEFT, T166_AUTOBALANCE_BUTTON, false) &
proxy->GetButton(T166_DRIVER_STICK_RIGHT, T166_AUTOBALANCE_BUTTON, false)
);
if(button) {
deployed = true;
LiftLatch_Solenoid.Set(false);
LiftUnlatch_Solenoid.Set(true);
}
}
if ((++valuethrottle) % (1000/LIFT_CYCLE_TIME) == 0)
{
// Get Current from each jaguar
liftCurrent = liftJag.GetOutputCurrent();
// Put current values into proxy
proxy->SetCurrent(T166_LIFT_MOTOR_CAN, liftCurrent);
// Print debug to console
DPRINTF(LOG_DEBUG, "Lift Jag Current: %f", liftCurrent);
}
// Should we log this value?
sl.PutOne(deployed, button, liftCurrent);
// Wait for our next lap
WaitForNextLoop();
}
return (0);
};
| [
"[email protected]",
"[email protected]",
""
]
| [
[
[
1,
24
],
[
26,
26
],
[
28,
33
],
[
40,
43
],
[
45,
47
],
[
49,
56
],
[
60,
71
],
[
76,
82
],
[
87,
106
],
[
111,
119
],
[
121,
123
],
[
128,
130
],
[
147,
148
],
[
160,
166
]
],
[
[
25,
25
],
[
27,
27
],
[
34,
39
],
[
44,
44
],
[
48,
48
],
[
57,
59
],
[
72,
75
],
[
83,
86
],
[
107,
110
],
[
120,
120
],
[
124,
127
],
[
131,
146
],
[
149,
156
],
[
159,
159
]
],
[
[
157,
158
]
]
]
|
5c87dcea407dfad4b06f13c2d11103eab9b305ed | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Utilities/VisualDebugger/Viewer/Collide/hkpContactPointViewer.h | 06e67e6a4cbf685cbde92f68a371e3fb6e5d0679 | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | 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-2008 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_UTILITIES2_CONTACT_POINT_VIEWER_H
#define HK_UTILITIES2_CONTACT_POINT_VIEWER_H
#include <Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldViewerBase.h>
#include <Physics/Dynamics/World/Listener/hkpWorldPostSimulationListener.h>
class hkDebugDisplayHandler;
class hkpWorld;
class hkListener;
/// An abstract base class for the contact viewers
/// (hkActiveContactPointviewer and hkpInactiveContactPointViewer).
class hkpContactPointViewer : public hkpWorldViewerBase, public hkpWorldPostSimulationListener
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VDB);
virtual void init();
void postSimulationCallback(hkpWorld* world);
protected:
/// Draw all of the contact points in the given simulation island.
void drawAllContactPointsInIsland(const class hkpSimulationIsland* island);
/// Get the array of simulation islands that this viewer will draw.
virtual const hkArray<class hkpSimulationIsland*>& getIslands(class hkpWorld* world) const = 0;
hkpContactPointViewer(const hkArray<hkProcessContext*>& contexts, const int color);
virtual ~hkpContactPointViewer();
virtual void worldAddedCallback( hkpWorld* world );
virtual void worldRemovedCallback( hkpWorld* world );
const int m_color;
};
#endif // HK_UTILITIES2_CONTACT_POINT_VIEWER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* 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
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
64
]
]
]
|
8d4e5163e1ddcb5569c1b7e873973138630325b5 | 814b49df11675ac3664ac0198048961b5306e1c5 | /Code/Engine/Graphics/StaticMeshManager.cpp | 602df552ba8aac73f4ac5eba865f5a829355a782 | []
| no_license | Atridas/biogame | f6cb24d0c0b208316990e5bb0b52ef3fb8e83042 | 3b8e95b215da4d51ab856b4701c12e077cbd2587 | refs/heads/master | 2021-01-13T00:55:50.502395 | 2011-10-31T12:58:53 | 2011-10-31T12:58:53 | 43,897,729 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,379 | cpp | #include "StaticMeshManager.h"
#include <XML/XMLTreeNode.h>
bool CStaticMeshManager::Load(const string &_szFileName)
{
return Load(_szFileName, false);
}
bool CStaticMeshManager::Load(const string &_szFileName, bool _bReload)
{
LOGGER->AddNewLog(ELL_INFORMATION, "CStaticMeshManager::Load");
m_vXMLFiles.insert( _szFileName );
CXMLTreeNode l_XMLMeshes;
if(!l_XMLMeshes.LoadFile(_szFileName.c_str()))
{
LOGGER->AddNewLog(ELL_WARNING,"CStaticMeshManager:: No s'ha trobat el XML \"%s\"", _szFileName.c_str());
return false;
}
int l_iNumMeshes = l_XMLMeshes.GetNumChildren();
for(int i = 0; i < l_iNumMeshes; i++)
{
string l_szName;
string l_szPath;
CStaticMesh* l_pStaticMesh = 0;
CXMLTreeNode l_XMLMesh = l_XMLMeshes(i);
l_szName = l_XMLMesh.GetPszISOProperty("name" ,"");
l_szPath = l_XMLMesh.GetPszISOProperty("path" ,"");
if(!GetResource(l_szName))
{
l_pStaticMesh = new CStaticMesh();
if(l_pStaticMesh->Load(l_XMLMesh))
{
LOGGER->AddNewLog(ELL_INFORMATION,"CStaticMeshManager:: Adding mesh: \"%s\"", l_szName.c_str());
AddResource(l_szName,l_pStaticMesh);
}else{
CHECKED_DELETE(l_pStaticMesh);
}
}else{
if(!_bReload)
LOGGER->AddNewLog(ELL_WARNING,"CStaticMeshManager:: Mesh \"%s\" repetit", l_szName.c_str());
}
}
SetOk(true);
return true;
}
bool CStaticMeshManager::Load(const SStaticMeshManagerParams& _params)
{
LOGGER->AddNewLog(ELL_INFORMATION, "CStaticMeshManager::Load (Multi)");
bool l_res = true;
vector<string>::const_iterator l_end = _params.vRenderableMeshes.cend();
for(vector<string>::const_iterator l_it = _params.vRenderableMeshes.cbegin(); l_it != l_end; ++l_it)
{
if(!Load(*l_it, false))
{
l_res = false;
}
}
return l_res;
}
bool CStaticMeshManager::Reload()
{
LOGGER->AddNewLog(ELL_INFORMATION, "CStaticMeshManager::Reload");
bool l_res = true;
set<string>::iterator l_end = m_vXMLFiles.end();
for(set<string>::iterator l_it = m_vXMLFiles.begin(); l_it != l_end; ++l_it)
{
if(!Load(*l_it, true))
{
l_res = false;
}
}
return l_res;
}
void CStaticMeshManager::Release()
{
CMapManager<CStaticMesh>::Release();
m_vXMLFiles.clear();
}
| [
"sergivalls@576ee6d0-068d-96d9-bff2-16229cd70485",
"Atridas87@576ee6d0-068d-96d9-bff2-16229cd70485",
"mudarra@576ee6d0-068d-96d9-bff2-16229cd70485",
"atridas87@576ee6d0-068d-96d9-bff2-16229cd70485"
]
| [
[
[
1,
12
],
[
14,
15
],
[
17,
17
],
[
19,
29
],
[
32,
36
],
[
38,
48
],
[
51,
53
],
[
55,
55
],
[
61,
62
],
[
72,
75
]
],
[
[
13,
13
],
[
16,
16
],
[
18,
18
],
[
30,
31
],
[
54,
54
],
[
56,
60
],
[
63,
71
],
[
76,
86
]
],
[
[
37,
37
]
],
[
[
49,
50
],
[
87,
94
]
]
]
|
a50281b138a9cdcef0cdbfc268065b2e4d35dc44 | 8aa65aef3daa1a52966b287ffa33a3155e48cc84 | /Source/World/CompoundEntity.h | 35e94a257d6be97d04e0bf32aa1d5170f415dbb5 | []
| no_license | jitrc/p3d | da2e63ef4c52ccb70023d64316cbd473f3bd77d9 | b9943c5ee533ddc3a5afa6b92bad15a864e40e1e | refs/heads/master | 2020-04-15T09:09:16.192788 | 2009-06-29T04:45:02 | 2009-06-29T04:45:02 | 37,063,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,154 | h | #pragma once
#include "Entity.h"
namespace P3D
{
namespace World
{
/*
Compound entity can contain entities inside.
These entities is located in CompoundEntitys object space.
*/
class CompoundEntity : public Entity
{
public:
CompoundEntity(World* world);
virtual ~CompoundEntity();
/*
Return entity class.
*/
override EntityClass GetClass() const { return Entity_Compound; }
/*
Add entity to the childs list.
Ignore it if it is already there.
Removes it from former parent list.
Do not AddRefs it but takes ownership.
*/
virtual void AddEntity(Entity* entity);
/*
Remove entity from the childs list (releasing it).
*/
virtual void RemoveEntity(Entity* entity);
/*
Remove all entities from the list calling RemoveEntity method.
*/
void RemoveAllEntities();
/*
Return true in case the entity is among childs.
*/
bool Contains(Entity* entity) const;
/*
Simulate physics, do thinking etc.
*/
override bool Update();
/*
Called after world has been build before first update.
*/
override void Prepare();
protected:
/*
Render all entites one by one in order they were added.
*/
override void DoRender(const RendererContext& params);
/*
Says that entity should recalculate transform to world space.
*/
override void InvalidatTransformToWorldSpace();
/*
Recalculate bounding box.
*/
override void RecalculateBoundingBox(AABB& box);
protected:
typedef std::list<Entity*> ChildsContainer;
ChildsContainer _childs;
};
}
} | [
"vadun87@6320d0be-1f75-11de-b650-e715bd6d7cf1"
]
| [
[
[
1,
78
]
]
]
|
2cc23287e89fc01c5f66a63a27691cceddfd7905 | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/ground_detection/NormalizedHomographyBasedGPD.cpp | e0f31124df29bc666c76ade462343d1936498327 | []
| no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 47 | cpp | #include ".\normalizedhomographybasedgpd.h"
| [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
2
]
]
]
|
9f497121db5701e8a88beb706349ae375a9053ff | df7f75e3289b4eee692438c627b21a5563d66db1 | /prufuthattari.cpp | 4024433899aee0109e5f468bedaccc075d8d6855 | []
| no_license | arnar/falskur_fjolnir | 3ec6c9bd11c6faf8c902de0569ad38bd02825285 | 23f69832bebf8843dd9aa910f99b4644520ae82c | refs/heads/master | 2016-09-10T19:03:03.558066 | 2010-06-03T11:20:26 | 2010-06-03T11:20:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,387 | cpp | #if 0
#include <iostream>
#include <fstream>
#pragma warning(push)
#pragma warning( disable : 4251 4267 4101 4267 )
#include "FjolnirForritLexer.hpp"
#include "FjolnirEiningLexer.hpp"
#include "FjolnirParser.hpp"
#include "FjolnirTransformer.hpp"
#include <antlr/AST.hpp>
#include <antlr/CommonAST.hpp>
#include <antlr/TokenStreamSelector.hpp>
#pragma warning(pop)
int eeemain_lex(int argc, char** args);
void eeeprintTree(antlr::RefAST tree, std::ostream& out, antlr::Parser& p, int indent = 0);
int eeeprintDotTree(antlr::RefAST tree, std::ostream& out, antlr::Parser& p);
int eeemain_parse(int argc, char** args)
{
using namespace std;
using namespace antlr;
using namespace ff;
try {
istream* input;
if (argc > 1) {
input = new ifstream(args[1], ios::in);
} else {
input = &cin;
}
TokenStreamSelector selector;
FjolnirForritLexer forritLexer(*input);
forritLexer.initialize(&selector);
FjolnirEiningLexer einingLexer(forritLexer.getInputState());
einingLexer.initialize(&selector);
selector.addInputStream(&forritLexer, "forritlexer");
selector.addInputStream(&einingLexer, "eininglexer");
selector.select("forritlexer");
ASTFactory my_factory;
FjolnirParser parser(selector);
parser.initializeASTFactory(my_factory);
parser.setASTFactory(&my_factory);
parser.forrit();
RefAST ast = RefAST(parser.getAST());
// cout << "Fyrir transformation:" << endl;
if (ast) {
// printTree(ast, cout, parser);
} else {
cout << "null AST" << endl;
}
FjolnirTransformer tparser;
tparser.initializeASTFactory(my_factory);
tparser.setASTFactory(&my_factory);
tparser.forrit(ast);
RefAST transformed = RefAST(tparser.getAST());
// cout << endl << "Eftir fasa 2:" << endl;
if (ast) {
// printTree(transformed, cout, parser);
cout << "digraph G {" << endl;
cout << "edge [fontname=\"Helvetica\",fontsize=10,labelfontname=\"Helvetica\",labelfontsize=10];" << endl;
cout << "node [fontname=\"Helvetica\",fontsize=10,shape=box];" << endl;
printDotTree(transformed, cout, parser);
cout << "}" << endl;
} else {
cout << "null AST" << endl;
}
} catch(exception& e) {
cerr << "exception: " << e.what() << endl;
}
return 0;
}
void eeeprintTree(antlr::RefAST tree, std::ostream& out, antlr::Parser& p, int indent) {
int j = indent;
std::string i = ""; while (j-- > 0) i += " ";
if (tree->getFirstChild()) {
out << i << "( " << tree->toString() << " <" <<
p.getTokenName(tree->getType()) << ">" << std::endl;
printTree(tree->getFirstChild(), out, p, indent+1);
out << i << ")" << std::endl;
} else {
out << i << tree->toString() << " <" <<
p.getTokenName(tree->getType()) << ">" << std::endl;
}
if (tree->getNextSibling()) {
printTree(tree->getNextSibling(), out, p, indent);
}
}
static int eee_dot_node = 0;
int eeeprintDotTree(antlr::RefAST tree, std::ostream& out, antlr::Parser& p) {
int me = ++_dot_node;
out << me << " [label=\"" << p.getTokenName(tree->getType())
<< "\\n" << tree->getText() << "\"];" << std::endl;
antlr::RefAST c = tree->getFirstChild();
while (antlr::nullAST != c) {
int child = printDotTree(c, out, p);
out << me << " -> " << child << ";" << std::endl;
c = c->getNextSibling();
}
return me;
}
#endif | [
"[email protected]"
]
| [
[
[
1,
122
]
]
]
|
71e0257f9daafeded30aec2900859cb553c52fa9 | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-18/gerbview/rs274d.cpp | a2a1c44b1d000254b0e5528af9d808fe7ba59c78 | []
| 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 | 19,865 | cpp | /********************************************************/
/**** Routine de lecture et visu d'un fichier GERBER ****/
/********************************************************/
#include "fctsys.h"
#include "common.h"
#include "gerbview.h"
#include "pcbplot.h"
#include "protos.h"
#define IsNumber(x) ( ( ((x) >= '0') && ((x) <='9') ) ||\
((x) == '-') || ((x) == '+') || ((x) == '.'))
/* Format Gerber : NOTES :
Fonctions preparatoires:
Gn =
G01 interpolation lineaire ( trace de droites )
G02,G20,G21 Interpolation circulaire , sens trigo < 0
G03,G30,G31 Interpolation circulaire , sens trigo > 0
G04 commentaire
G06 Interpolation parabolique
G07 Interpolation cubique
G10 interpolation lineaire ( echelle 10x )
G11 interpolation lineaire ( echelle 0.1x )
G12 interpolation lineaire ( echelle 0.01x )
G52 plot symbole reference par Dnn code
G53 plot symbole reference par Dnn ; symbole tourne de -90 degres
G54 Selection d'outil
G55 Mode exposition photo
G56 plot symbole reference par Dnn A code
G57 affiche le symbole reference sur la console
G58 plot et affiche le symbole reference sur la console
G60 interpolation lineaire ( echelle 100x )
G70 Unites = Inches
G71 Unites = Millimetres
G74 supprime interpolation circulaire sur 360 degre, revient a G01
G75 Active interpolation circulaire sur 360 degre
G90 Mode Coordonnees absolues
G91 Mode Coordonnees Relatives
Coordonnees X,Y
X,Y sont suivies de + ou - et de m+n chiffres (non separes)
m = partie entiere
n = partie apres la virgule
formats classiques : m = 2, n = 3 (format 2.3)
m = 3, n = 4 (format 3.4)
ex:
G__ X00345Y-06123 D__*
Outils et D_CODES
numero d'outil ( identification des formes )
1 a 99 (classique)
1 a 999
D_CODES:
D01 ... D9 = codes d'action:
D01 = activation de lumiere (baisser de plume) lors du déplacement
D02 = extinction de lumiere (lever de plume) lors du déplacement
D03 = Flash
D09 = VAPE Flash
D51 = precede par G54 -> Select VAPE
D10 ... D255 = Indentification d'outils ( d'ouvertures )
Ne sont pas tj dans l'ordre ( voir tableau dans PCBPLOT.H)
*/
// Type d'action du phototraceur:
#define GERB_ACTIVE_DRAW 1 // activation de lumiere ( baisser de plume)
#define GERB_STOP_DRAW 2 // extinction de lumiere ( lever de plume)
#define GERB_FLASH 3 // Flash
#define NEGATE(nb) (nb) = -(nb)
/* Variables locales : */
static wxPoint LastPosition;
/* Routines Locales */
static void Append_1_Line_GERBER(int Dcode_index, WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & startpoint,const wxPoint & endpoint,
int largeur);
static void Append_1_Flash_GERBER(int Dcode_index, WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & pos,const wxSize & size, int forme);
static void Append_1_Flash_ROND_GERBER(int Dcode_index, WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & pos, int diametre);
static void Append_1_SEG_ARC_GERBER(int Dcode_index,
WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & startpoint, const wxPoint & endpoint,
const wxPoint & rel_center, int largeur,
bool trigo_sens, bool multiquadrant);
/****************************************************************/
static void Append_1_Flash_ROND_GERBER(int Dcode_tool,
WinEDA_GerberFrame * frame,
wxDC * DC, const wxPoint & pos,int diametre)
/****************************************************************/
/* Trace 1 flash ROND en position pos
*/
{
TRACK * track;
track = new TRACK(frame->m_Pcb);
track->Insert(frame->m_Pcb, NULL);
track->m_Layer = frame->GetScreen()->m_Active_Layer;
track->m_Width = diametre ;
track->m_Start = track->m_End = pos;
NEGATE(track->m_Start.y);
NEGATE(track->m_End.y);
track->m_NetCode = Dcode_tool;
track->m_Shape = S_SPOT_CIRCLE;
Trace_Segment(frame->DrawPanel, DC, track, GR_OR) ;
}
/**********************************************************************/
static void Append_1_Flash_GERBER(int Dcode_index,
WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & pos,const wxSize & size,int forme)
/*********************************************************************/
/*
Trace 1 flash rectangulaire ou ovale vertical ou horizontal
donne par son centre et ses dimensions X et Y
*/
{
TRACK * track;
int width, len;
width = min( size.x, size.y );
len = max( size.x, size.y ) - width;
track = new TRACK(frame->m_Pcb);
track->Insert(frame->m_Pcb, NULL);
track->m_Layer = frame->GetScreen()->m_Active_Layer;
track->m_Width = width;
track->m_Start = track->m_End = pos;
NEGATE(track->m_Start.y);
NEGATE(track->m_End.y);
track->m_NetCode = Dcode_index;
if ( forme == OVALE )
track->m_Shape = S_SPOT_OVALE;
else
track->m_Shape = S_SPOT_RECT; // donc rectangle ou carré
len >>= 1;
if ( size.x > size.y ) // ovale / rect horizontal
{
track->m_Start.x -= len ;
track->m_End.x += len;
}
else // ovale / rect vertical
{
track->m_Start.y -= len;
track->m_End.y += len;
}
Trace_Segment(frame->DrawPanel, DC, track, GR_OR) ;
}
/******************************************************************/
static void Append_1_Line_GERBER(int Dcode_index,
WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & startpoint, const wxPoint & endpoint,
int largeur)
/********************************************************************/
{
TRACK * track;
track = new TRACK( frame->m_Pcb );
track->Insert(frame->m_Pcb, NULL);
track->m_Layer = frame->GetScreen()->m_Active_Layer ;
track->m_Width = largeur ;
track->m_Start = startpoint;
NEGATE(track->m_Start.y);
track->m_End = endpoint;
NEGATE(track->m_End.y);
track->m_NetCode = Dcode_index;
Trace_Segment(frame->DrawPanel, DC, track,GR_OR) ;
}
/*****************************************************************/
static void Append_1_SEG_ARC_GERBER(int Dcode_index,
WinEDA_GerberFrame * frame, wxDC * DC,
const wxPoint & startpoint, const wxPoint & endpoint,
const wxPoint & rel_center, int largeur,
bool trigo_sens, bool multiquadrant)
/*****************************************************************/
/* creation d'un arc:
si multiquadrant == TRUE arc de 0 a 360 degres
et rel_center est la coordonnée du centre relativement au startpoint
si multiquadrant == FALSE arc de 0 à 90 entierement contenu dans le meme quadrant
et rel_center est la coordonnée du centre relativement au startpoint,
mais en VALEUR ABSOLUE et le signe des valeurs x et y de rel_center doit
etre deduit de cette limite de 90 degres
*/
{
TRACK * track;
wxPoint center, delta;
track = new TRACK( frame->m_Pcb );
track->Insert(frame->m_Pcb, NULL);
track->m_Shape = S_ARC;
track->m_Layer = frame->GetScreen()->m_Active_Layer ;
track->m_Width = largeur ;
if ( multiquadrant )
{
center.x = startpoint.x + rel_center.x;
center.y = startpoint.y - rel_center.y;
if ( !trigo_sens )
{
track->m_Start = startpoint;
track->m_End = endpoint;
}
else
{
track->m_Start = endpoint;
track->m_End = startpoint;
}
}
else
{
center = rel_center;
delta.x = endpoint.x - startpoint.x;
delta.y = endpoint.y - startpoint.y;
// il faut corriger de signe de rel_center.x et rel_center.y
// selon le quadrant ou on se trouve
if ( (delta.x >= 0) && (delta.y >= 0) ) // 1er quadrant
{
center.x = - center.x;
}
else if ( (delta.x < 0) && (delta.y >= 0) ) // 2eme quadrant
{
center.x = - center.x;
center.y = - center.y;
}
else if ( (delta.x < 0) && (delta.y < 0) ) // 3eme quadrant
{
center.y = - center.y;
}
else // 4eme qadrant: les 2 coord sont >= 0!
{
}
center.x += startpoint.x;
center.y = startpoint.y + center.y ;
if ( trigo_sens )
{
track->m_Start = startpoint;
track->m_End = endpoint;
}
else
{
track->m_Start = endpoint;
track->m_End = startpoint;
}
}
track->m_NetCode = Dcode_index;
track->m_Param = center.x;
track->m_Sous_Netcode = center.y;
NEGATE(track->m_Start.y);
NEGATE(track->m_End.y);
NEGATE(track->m_Sous_Netcode);
Trace_Segment(frame->DrawPanel, DC, track,GR_OR);
}
/**************************************************/
/* Routines utilisées en lecture de ficher gerber */
/**************************************************/
/* ces routines lisent la chaine de texte pointée par Text.
Apres appel, Text pointe le debut de la sequence non lue
*/
/***********************************************/
wxPoint GERBER_Descr::ReadXYCoord(char * &Text)
/***********************************************/
/* Retourne la coord courante pointee par Text (XnnnnYmmmm)
*/
{
wxPoint pos = m_CurrentPos;
int type_coord = 0, current_coord, nbchar;
bool is_float = FALSE;
char * text;
char line[256];
if ( m_Relative ) pos.x = pos.y = 0;
else pos = m_CurrentPos;
if ( Text == NULL ) return pos;
text = line;
while ( * Text )
{
if ( (* Text == 'X') || (* Text == 'Y') )
{
type_coord = * Text;
Text++;
text = line; nbchar = 0;
while( IsNumber(*Text) )
{
if ( *Text == '.' ) is_float = TRUE;
*(text++) = *(Text++);
if ( (*Text >= '0') && (*Text <='9') ) nbchar++;
}
*text = 0;
if ( is_float )
{
if ( m_GerbMetric )
current_coord = (int) round(atof(line) / 0.00254);
else
current_coord = (int) round(atof(line) * PCB_INTERNAL_UNIT);
}
else
{
int fmt_scale = (type_coord == 'X') ? m_FmtScale.x : m_FmtScale.y;
if ( m_NoTrailingZeros )
{
int min_digit = (type_coord == 'X') ? m_FmtLen.x : m_FmtLen.y;
while (nbchar < min_digit) { *(text++) ='0'; nbchar++; }
*text=0;
}
current_coord = atoi(line);
double real_scale = 1.0;
switch( fmt_scale)
{
case 0: real_scale = 10000.0;
break;
case 1: real_scale = 1000.0;
break;
case 2: real_scale = 100.0;
break;
case 3: real_scale = 10.0;
break;
case 4:
break;
case 5: real_scale = 0.1;
break;
case 6: real_scale = 0.01;
break;
case 7: real_scale = 0.001;
break;
case 8: real_scale = 0.0001;
break;
case 9: real_scale = 0.00001;
break;
}
if ( m_GerbMetric ) real_scale = real_scale / 25.4;
current_coord = (int) round(current_coord * real_scale);
}
if ( type_coord == 'X' ) pos.x = current_coord;
else if ( type_coord == 'Y' ) pos.y = current_coord;
continue;
}
else break;
}
if ( m_Relative )
{
pos.x += m_CurrentPos.x;
pos.y += m_CurrentPos.y;
}
m_CurrentPos = pos;
return pos;
}
/************************************************/
wxPoint GERBER_Descr::ReadIJCoord(char * &Text)
/************************************************/
/* Retourne la coord type InnJnn courante pointee par Text (InnnnJmmmm)
Ces coordonnées sont relatives, donc si une coord est absente, sa valeur
par defaut est 0
*/
{
wxPoint pos(0,0);
int type_coord = 0, current_coord, nbchar;
bool is_float = FALSE;
char * text;
char line[256];
if ( Text == NULL ) return pos;
text = line;
while ( * Text )
{
if ( (* Text == 'I') || (* Text == 'J') )
{
type_coord = * Text;
Text++;
text = line; nbchar = 0;
while( IsNumber(*Text) )
{
if ( *Text == '.' ) is_float = TRUE;
*(text++) = *(Text++);
if ( (*Text >= '0') && (*Text <='9') ) nbchar++;
}
*text = 0;
if ( is_float )
{
if ( m_GerbMetric )
current_coord = (int) round(atof(line) / 0.00254);
else
current_coord = (int) round(atof(line) * PCB_INTERNAL_UNIT);
}
else
{
int fmt_scale = (type_coord == 'I') ? m_FmtScale.x : m_FmtScale.y;
if ( m_NoTrailingZeros )
{
int min_digit = (type_coord == 'I') ? m_FmtLen.x : m_FmtLen.y;
while (nbchar < min_digit) { *(text++) ='0'; nbchar++; }
*text=0;
}
current_coord = atoi(line);
double real_scale = 1.0;
switch( fmt_scale)
{
case 0: real_scale = 10000.0;
break;
case 1: real_scale = 1000.0;
break;
case 2: real_scale = 100.0;
break;
case 3: real_scale = 10.0;
break;
case 4:
break;
case 5: real_scale = 0.1;
break;
case 6: real_scale = 0.01;
break;
case 7: real_scale = 0.001;
break;
case 8: real_scale = 0.0001;
break;
case 9: real_scale = 0.00001;
break;
}
if ( m_GerbMetric ) real_scale = real_scale / 25.4;
current_coord = (int) round(current_coord * real_scale);
}
if ( type_coord == 'I' ) pos.x = current_coord;
else if ( type_coord == 'J' ) pos.y = current_coord;
continue;
}
else break;
}
m_IJPos = pos;
return pos;
}
/*****************************************************/
int GERBER_Descr::ReturnGCodeNumber(char * &Text)
/*****************************************************/
/* Lit la sequence Gnn et retourne la valeur nn
*/
{
int ii = 0;
char * text;
char line[1024];
if ( Text == NULL ) return 0;
Text++;
text = line;
while( IsNumber(*Text) )
{
*(text++) = *(Text++);
}
*text = 0;
ii = atoi(line);
return ii;
}
/**************************************************/
int GERBER_Descr::ReturnDCodeNumber(char * &Text)
/**************************************************/
/* Lit la sequence Dnn et retourne la valeur nn
*/
{
int ii = 0;
char * text;
char line[1024];
if ( Text == NULL ) return 0;
Text ++;
text = line;
while( IsNumber(*Text) ) *(text++) = *(Text++);
*text = 0;
ii = atoi(line);
return ii;
}
/******************************************************************/
bool GERBER_Descr::Execute_G_Command(char * &text, int G_commande)
/******************************************************************/
{
switch (G_commande)
{
case GC_LINEAR_INTERPOL_1X:
m_Iterpolation = GERB_INTERPOL_LINEAR_1X;
break;
case GC_CIRCLE_NEG_INTERPOL:
m_Iterpolation = GERB_INTERPOL_ARC_NEG;
break;
case GC_CIRCLE_POS_INTERPOL:
m_Iterpolation = GERB_INTERPOL_ARC_POS;
break;
case GC_COMMENT:
text = NULL;
break ;
case GC_LINEAR_INTERPOL_10X:
m_Iterpolation = GERB_INTERPOL_LINEAR_10X;
break;
case GC_LINEAR_INTERPOL_0P1X:
m_Iterpolation = GERB_INTERPOL_LINEAR_01X;
break;
case GC_LINEAR_INTERPOL_0P01X:
m_Iterpolation = GERB_INTERPOL_LINEAR_001X;
break;
case GC_SELECT_TOOL:
{
int D_commande = ReturnDCodeNumber(text);
if ( D_commande < FIRST_DCODE) return FALSE;
if (D_commande > (MAX_TOOLS-1)) D_commande = MAX_TOOLS-1;
m_Current_Tool = D_commande;
D_CODE * pt_Dcode = ReturnToolDescr(m_Layer, D_commande);
if ( pt_Dcode ) pt_Dcode->m_InUse = TRUE;
break;
}
case GC_SPECIFY_INCHES:
m_GerbMetric = FALSE; // FALSE = Inches, TRUE = metric
break;
case GC_SPECIFY_MILLIMETERS:
m_GerbMetric = TRUE; // FALSE = Inches, TRUE = metric
break;
case GC_TURN_OFF_360_INTERPOL:
m_360Arc_enbl = FALSE;
break;
case GC_TURN_ON_360_INTERPOL:
m_360Arc_enbl = TRUE;
break;
case GC_SPECIFY_ABSOLUES_COORD:
m_Relative = FALSE; // FALSE = absolute Coord, RUE = relative Coord
break;
case GC_SPECIFY_RELATIVEES_COORD:
m_Relative = TRUE; // FALSE = absolute Coord, RUE = relative Coord
break;
case GC_TURN_ON_POLY_FILL:
m_PolygonFillMode = TRUE;
break;
case GC_TURN_OFF_POLY_FILL:
m_PolygonFillMode = FALSE;
m_PolygonFillModeState = 0;
break;
case GC_MOVE: // Non existant
default:
{
wxString msg; msg.Printf( wxT("G%.2d command not handled"),G_commande);
DisplayError(NULL, msg);
return FALSE;
}
}
return TRUE;
}
/*****************************************************************************/
bool GERBER_Descr::Execute_DCODE_Command(WinEDA_GerberFrame * frame, wxDC * DC,
char * &text, int D_commande)
/*****************************************************************************/
{
wxSize size(15, 15);
int shape = 1, dcode = 0;
D_CODE * pt_Tool = NULL;
wxString msg;
if(D_commande >= FIRST_DCODE )
{
if (D_commande > (MAX_TOOLS-1)) D_commande = MAX_TOOLS-1;
m_Current_Tool = D_commande;
D_CODE * pt_Dcode = ReturnToolDescr(m_Layer, D_commande);
if ( pt_Dcode ) pt_Dcode->m_InUse = TRUE;
return TRUE;
}
if ( m_PolygonFillMode ) // Enter a plygon description:
{
switch ( D_commande )
{
case 1: //code D01 Draw line, exposure ON
{
SEGZONE * edge_poly, *last;
edge_poly = new SEGZONE( frame->m_Pcb );
last = (SEGZONE*)frame->m_Pcb->m_Zone;
if ( last ) while (last->Pnext ) last = (SEGZONE*)last->Pnext;
edge_poly->Insert(frame->m_Pcb, last);
edge_poly->m_Layer = frame->GetScreen()->m_Active_Layer ;
edge_poly->m_Width = 1;
edge_poly->m_Start = m_PreviousPos;
NEGATE(edge_poly->m_Start.y);
edge_poly->m_End = m_CurrentPos;
NEGATE(edge_poly->m_End.y);
edge_poly->m_NetCode = m_PolygonFillModeState;
m_PreviousPos = m_CurrentPos;
m_PolygonFillModeState = 1;
break;
}
case 2: //code D2: exposure OFF (i.e. "move to")
m_PreviousPos = m_CurrentPos;
m_PolygonFillModeState = 0;
break;
default:
return FALSE;
}
}
else switch ( D_commande )
{
case 1: //code D01 Draw line, exposure ON
pt_Tool = ReturnToolDescr(m_Layer, m_Current_Tool);
if ( pt_Tool )
{
size = pt_Tool->m_Size;
dcode = pt_Tool->m_Num_Dcode;
shape = pt_Tool->m_Shape;
}
switch ( m_Iterpolation )
{
case GERB_INTERPOL_LINEAR_1X:
Append_1_Line_GERBER(dcode,
frame, DC,
m_PreviousPos, m_CurrentPos,
size.x);
break;
case GERB_INTERPOL_LINEAR_01X:
case GERB_INTERPOL_LINEAR_001X:
case GERB_INTERPOL_LINEAR_10X:
wxBell();
break;
case GERB_INTERPOL_ARC_NEG:
Append_1_SEG_ARC_GERBER(dcode,
frame, DC,
m_PreviousPos, m_CurrentPos, m_IJPos,
size.x, FALSE, m_360Arc_enbl);
break;
case GERB_INTERPOL_ARC_POS:
Append_1_SEG_ARC_GERBER(dcode,
frame, DC,
m_PreviousPos, m_CurrentPos, m_IJPos,
size.x, TRUE, m_360Arc_enbl);
break;
default:
msg.Printf( wxT("Execute_DCODE_Command: interpol error (type %X)"),
m_Iterpolation);
DisplayError(frame, msg);
break;
}
m_PreviousPos = m_CurrentPos;
break;
case 2: //code D2: exposure OFF (i.e. "move to")
m_PreviousPos = m_CurrentPos;
break;
case 3: // code D3: flash aperture
pt_Tool = ReturnToolDescr(m_Layer, m_Current_Tool);
if ( pt_Tool )
{
size = pt_Tool->m_Size;
dcode = pt_Tool->m_Num_Dcode;
shape = pt_Tool->m_Shape;
}
switch (shape)
{
case GERB_LINE:
case GERB_CIRCLE :
Append_1_Flash_ROND_GERBER(dcode,
frame, DC,
m_CurrentPos,
size.x);
break ;
case GERB_OVALE :
Append_1_Flash_GERBER( dcode,
frame, DC, m_CurrentPos,
size,
OVALE);
break ;
case GERB_RECT:
Append_1_Flash_GERBER( dcode,
frame, DC, m_CurrentPos,
size,
RECT);
break ;
default: // Special (Macro) : Non implanté
break;
}
m_PreviousPos = m_CurrentPos;
break;
default:
return FALSE;
}
return TRUE;
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
762
]
]
]
|
0601e74e25c52f630d3141df875429fc3de47955 | 3542f5e57819d534f02876fb775e64b072332598 | /cardClass.cpp | cbb1c62916534181eaa33c336d0c000fef3b7d95 | []
| no_license | sjdurfey/uno | 5728a69574c90afbd8b6ae057010dedc6f37f952 | cf0e6c8f85f674358bd46b5a3aedd8992ff2fc4f | refs/heads/master | 2021-03-12T19:43:47.925442 | 2008-12-29T07:43:35 | 2008-12-29T07:43:35 | 97,812 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | cpp | #include "cardClass.h"
using namespace std;
unoCard::unoCard(short cNum, string cColor)
{
cardNumber = cNum;
cardColor = cColor;
next = NULL;
}
short unoCard::getCardNumber()
{
return cardNumber;
}
string unoCard::getCardColor()
{
return cardColor;
}
void unoCard::setCardColor(string cColor)
{
cardColor = cColor;
}
void unoCard::setCardNumber(short cNum)
{
cardNumber = cNum;
}
| [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
b5a456d3897e5dac124276f6c3a7fcf8eb7e7c62 | 698f3c3f0e590424f194a4c138ed9706eb28b34f | /Classes/PauseScene.h | e3e23a2f5b8ee9bf86b033124759ed50ce7a30a9 | []
| no_license | nghepop/super-fashion-puzzle-cocos2d-x | 16b3a86072a6758fc2547b9e177bbfeebed82681 | 5e8d8637e3cf70b4ec45256347ccf7b350c11bce | refs/heads/master | 2021-01-10T06:28:10.028735 | 2011-12-03T23:49:16 | 2011-12-03T23:49:16 | 44,685,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | h |
#ifndef __pausescene_h__
#define __pausescene_h__
#include "cocos2d.h"
using namespace cocos2d;
class PauseScene :
public CCScene
{
public:
PauseScene(void){};
~PauseScene(void);
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommand to return the exactly class pointer
static cocos2d::CCScene* scene();
// implement the "static node()" method manually
LAYER_NODE_FUNC(PauseScene);
// button callbacks
void resumeButtonPressed(CCObject* pSender);
void optionsButtonPressed(CCObject* pSender);
void menuButtonPressed(CCObject* pSender);
void howToPlayButtonPressed(CCObject* pSender);
void onEnter(void);
void onExit(void);
void onEnterTransitionDidFinish(void);
PlayingScene* m_playingScene; // used to inform it that pause is going to be resumed just before finishing this object
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
760c5fda75255c6340d40760053c90b282cda4f5 | 58943f35c5f6659879f41317666416c1216dbc28 | /Student_beforech9.cpp | 600dda65ccdb08ef27f919310abb47e39a781eac | []
| no_license | abzaremba/nauka_cpp | 37c82a20acb98b62ae4bf01eb6f70c576b9aa3a4 | 1461647b3e4864bc219567e93134849029ff5cb5 | refs/heads/master | 2021-01-13T02:31:37.111733 | 2011-10-05T12:03:06 | 2011-10-05T12:03:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,220 | cpp | // source file for Student_infoted functions
#include "Student_info.h"
#include "grade.h"
#include <list>
#include <algorithm>
#include <iterator>
using std::istream;
using std::vector;
using std::list;
bool compare(const Student_info& x, const Student_info& y)
{
return x.name < y.name;
}
istream& read (istream& is, Student_info& s)
{
//read and store student's name and midterm and final exam grades
is >> s.name >> s.midterm >> s.final;
read_hw (is, s.homework); // read and store all the student's homework grades
return is;
}
istream& read_hw (istream& in, vector<double>& hw)
{
//read homework grades from an input stream into a vector<double>
if (in) {
// get rid of previous contents
hw.clear();
//read homework grades
double x;
while (in >> x)
hw.push_back(x);
//clear the stream so that input will work for the next student
in.clear();
}
return in;
}
bool pgrade(const Student_info& s)
{
return !fgrade(s);
}
//// version 5 with vectors and faster way of dealing with them
//vector<Student_info> extract_fails(vector<Student_info>& students)
//{
// vector<Student_info> fail;
// remove_copy_if(students.begin(), students.end(), back_inserter(fail), pgrade);
// students.erase(remove_if(students.begin(), students.end(), fgrade), students.end());
//
// return fail;
//}
// version 6 using stable_partition
vector<Student_info> extract_fails(vector<Student_info>& students)
{
vector<Student_info>::iterator iter = stable_partition(students.begin(),students.end(), pgrade);
vector<Student_info> fail(iter, students.end());
students.erase(iter,students.end());
return fail;
}
bool did_all_hw(const Student_info& s)
{
return ((find(s.homework.begin(), s.homework.end(), 0)) == s.homework.end());
}
//// version 4: use list instead of vector
//list<Student_info> extract_fails(list<Student_info>& students)
//{
// list<Student_info> fail;
// list<Student_info>::iterator iter = students.begin();
//
// while (iter != students.end())
// {
// if (fgrade(*iter)){
// fail.push_back(*iter);
// iter = students.erase(iter);
// }else
// ++iter;
// }
// return fail;
//}
| [
"[email protected]"
]
| [
[
[
1,
93
]
]
]
|
37b8f9b6a88a427ccdea49c4b95a894349f04594 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/addons/pa/ParticleUniverse/include/Externs/ParticleUniverseSphereColliderExtern.h | 1c8afec3720c88484087140f3377d85115b6b8ad | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,754 | h | /*
-----------------------------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2010 Henry van Merode
Usage of this program is licensed under the terms of the Particle Universe Commercial License.
You can find a copy of the Commercial License in the Particle Universe package.
-----------------------------------------------------------------------------------------------
*/
#ifndef __PU_SPHERE_COLLIDER_EXTERN_H__
#define __PU_SPHERE_COLLIDER_EXTERN_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleAffectors/ParticleUniverseSphereCollider.h"
#include "ParticleUniverseAttachable.h"
namespace ParticleUniverse
{
/** The SphereColliderExtern is a wrapper of the SphereCollider, adding the functionality of a MovableObject.
This makes it possible to let particles collide with a SphereCollider that is attached to a different
SceneNode, than the ParticleSystem with which particles it collides.
*/
class _ParticleUniverseExport SphereColliderExtern : public Attachable, public SphereCollider
{
public:
SphereColliderExtern(void) :
Attachable(),
SphereCollider() {};
virtual ~SphereColliderExtern(void) {};
/** see Extern::_preProcessParticles */
virtual void _preProcessParticles(ParticleTechnique* technique, Ogre::Real timeElapsed);
/** see Extern::_interface */
virtual void _interface(ParticleTechnique* technique,
Particle* particle,
Ogre::Real timeElapsed);
/** Copy both the Extern and the derived SphereCollider properties.
*/
virtual void copyAttributesTo (Extern* externObject);
protected:
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
24732520a84e2b9b7a00d22092275460f8994e76 | 3643bb671f78a0669c8e08935476551a297ce996 | /JK_Parse.cpp | 5b1d102e140ef61e6f39681962292fbb87af5973 | []
| no_license | mattfischer/3dportal | 44b3b9fb2331650fc406596b941f6228f37ff14b | e00f7d601138f5cf72aac35f4d15bdf230c518d9 | refs/heads/master | 2020-12-25T10:36:51.991814 | 2010-08-29T22:53:06 | 2010-08-29T22:53:06 | 65,869,788 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,358 | cpp | #include <windows.h>
#include "JK_Parse.h"
namespace Jk
{
Parser::Parser(const string &input)
{
data = input;
p = 0;
}
static string getRawLine( const string& input, int& start )
{
int i;
string newdata;
i = start;
while( input[i] != '\n' && input[i] != '\r' && i < input.length()) i++;
i++;
newdata = input.substr( start, i - start - 1 );
start = i + 1;
if( start > input.size() ) start = input.length();
return newdata;
}
static string removeComments( const string& input )
{
int i = 0;
string newdata;
while( i < input.length() && input[i] != '#') i++;
newdata = input.substr( 0, i );
return newdata;
}
Parser::Line Parser::getLine(bool &error)
{
string newdata;
bool empty;
int i;
error = false;
while( 1 )
{
if( p == data.length() )
{
error = true;
return Line("");
}
newdata = getRawLine( data, p );
newdata = removeComments( newdata );
empty = true;
i = 0;
while( i < newdata.length() )
{
if( newdata[i] != ' ' && newdata[i] != '\t')
{
empty = false;
break;
}
i++;
}
if( !empty ) break;
}
return Line(newdata);
}
void Parser::findString( const string& match, bool& error )
{
error = false;
while( 1 )
{
Line line = getLine( error );
if( error ) break;
if( line.line() == match) break;
}
}
void Parser::reset()
{
p = 0;
}
Parser::Line::Line(const string &input)
{
data = input;
p = 0;
}
Parser::Line::Line()
{
p = 0;
}
int Parser::Line::getInt(bool &error)
{
int retval;
int i = p;
int i2;
string newdata;
error = false;
if( i >= data.length() )
{
error = true;
return 0;
}
if( data[i] == ' ' || data[i] == ':' || data[i] == ',' || data[i] == '\t' )
{
while( i < data.length() && ( data[i] == ' ' || data[i] == ':' || data[i] == ',' || data[i] == '\t') ) i++;
if( i >= data.length() )
{
error = true;
return 0;
}
}
i2 = i;
while( i2 < data.length() && data[i2] != ' ' && data[i2] != ':' && data[i2] != ',' && data[i2] != '\t' ) i2++;
newdata = data.substr( i, i2 - i );
p = i2;
retval = atoi( newdata.c_str() );
return retval;
}
float Parser::Line::getFloat(bool &error)
{
float retval;
int i = p;
int i2;
string newdata;
error = false;
if( i >= data.length() )
{
error = true;
return 0;
}
if( data[i] == ' ' || data[i] == ':' || data[i] == ',' || data[i] == '\t' )
{
while( ( data[i] == ' ' || data[i] == ':' || data[i] == ',' || data[i] == '\t' ) && data[i] != '\0' ) i++;
if( i >= data.length() )
{
error = true;
return 0;
}
}
i2 = i;
while( i2 < data.length() && data[i2] != ' ' && data[i2] != ':' && data[i2] != ',' && data[i2] != '\t' ) i2++;
newdata = data.substr( i, i2 - i );
p = i2;
retval = atof( newdata.c_str() );
return retval;
}
string Parser::Line::getString(bool &error)
{
int i = p;
int i2;
string newdata;
error = false;
if( i >= data.length() )
{
error = true;
return "";
}
if( data[i] == ' ' || data[i] == '\t' || data[i] == ':' )
{
while( i < data.length() && (data[i] == ' ' || data[i] == '\t' || data[i] == ':' ) ) i++;
if( i == data.length() )
{
error = true;
return "";
}
}
i2 = i;
while( i2 < data.length() && data[i2] != ' ' && data[i2] != '\t')// && data[i2]!=':')
i2++;
newdata = data.substr( i, i2 - i );
p = i2;
return newdata;
}
int Parser::Line::getHex(bool &error)
{
string hexString;
int retVal;
int placeVal;
int i;
error = false;
hexString = getString( error );
if( error ) return 0;
retVal = 0;
placeVal = 1;
for( i = hexString.length() - 1 ; i >= 2 ; i-- )
{
if( hexString[i] >= '0' && hexString[i] <= '9' )
retVal += placeVal * ( hexString[i] - '0' );
else if( hexString[i] >= 'A' && hexString[i] <= 'F' )
retVal += placeVal * ( hexString[i] - 'A' + 10 );
else if( hexString[i] >= 'a' && hexString[i] <= 'f' )
retVal += placeVal * ( hexString[i] - 'a' + 10 );
placeVal *= 16;
}
return retVal;
}
void Parser::Line::matchString(const string &match, bool &error)
{
error = false;
if( data.substr( p, match.length() ) == match ) p += match.length();
else error = true;
}
const string &Parser::Line::line()
{
return data;
}
string Parser::Line::rest()
{
return data.substr(p);
}
} | [
"devnull@localhost"
]
| [
[
[
1,
243
]
]
]
|
9143b30e0085b0460c988b74354876c217b5f382 | 43626054205d6048ec98c76db5641ce8e42b8237 | /source/CHackOrb.cpp | da0ac8dd3450be5056bb962cc2058e5f3c60c491 | []
| no_license | Wazoobi/whitewings | b700da98b855a64442ad7b7c4b0be23427b0ee23 | a53fdb832cfb1ce8605209c9af47f36b01c44727 | refs/heads/master | 2021-01-10T19:33:22.924792 | 2009-08-05T18:30:07 | 2009-08-05T18:30:07 | 32,119,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,577 | cpp | ////////////////////////////////////////////////////////////////////////
// File Name : "CBase.cpp"
//
// Author : Juno Madden (JM)
//
// Purpose : To contain all the shared data and functionaly of
// our game objects.
////////////////////////////////////////////////////////////////////////
#include "CHackOrb.h"
#include "SGD Wrappers/CSGD_TextureManager.h"
#include "CMessageManager.h"
CHackOrb::CHackOrb(void)
{
m_nImageID = CSGD_TextureManager::GetInstance()->LoadTexture("resource/graphics/HackOrb.bmp");
m_nDisplayDepth = 1; // Z-sorting
m_uiRefCount = 1; // Always start with a reference to yourself
m_uiType = OBJ_HACKORB;
SetPosX(0.0f);
SetPosY(0.0f);
SetVelX(0.0f);
SetVelY(0.0f);
}
CHackOrb::~CHackOrb(void)
{
}
void CHackOrb::Update(float fElapsedTime)
{
// Using the elapsed time
}
void CHackOrb::Render(void)
{
// TODO: Render the current frames image
CSGD_TextureManager::GetInstance()->Draw(m_nImageID, GetPosX(), GetPosY());
}
bool CHackOrb::CheckCollision(CBase* pBase)
{
// TODO: Use the current frame of the animation instance to grab the collision rect and
// compare it to the collision rect of the passed in CBase pointer's animation instance's
// current frame's collision rect.
// TODO: Clean up collecting hack orbs. Currently just adds to your hack orb count and deletes the orb.
if(CBase::CheckCollision(pBase) && pBase->GetObjectType() == OBJ_PLAYER)
{
CMessageManager::GetInstance()->SendMsg(new CDestroyHackOrbMessage(this));
}
return false;
} | [
"Juno05@1cfc0206-7002-11de-8585-3f51e31374b7"
]
| [
[
[
1,
57
]
]
]
|
9bf81d6304a5d5070feec9457b9ff0ca8e6a916f | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_ExpParserFile.cpp | 7d922a532875469aa4805d00fbf38761e44fbe29 | []
| no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 96,772 | cpp | // Aipi_ExpParserFile.cpp: implementation of the CAipi_ExpParserFileFile class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "AIPI.h"
#include "Aipi_ExpParserFile.h"
#include "../MainFrm.h"
#include "../ChildFrm.h"
#include "../OutputTabView.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAipi_ExpParserFile::CAipi_ExpParserFile()
:m_query(GetSession())
{
m_index = 0;
//Data Base
m_bFlagConnDlg = false; //Database is needed
g_iDBProvider = UNDEFINE;
m_dbProvider = _T("");
m_dbDNS = _T("");
m_dbUser = _T("");
m_dbPassword = _T("");
m_dbName = _T("");
g_bStopFlag = false; //Stop interpreter flag
//g_currentVarLoc = UNDEFINE;
g_currentParserClass = EXP_PARSER_FILE;
}
CAipi_ExpParserFile::~CAipi_ExpParserFile()
{
}
void CAipi_ExpParserFile::ExecCmdSearch(long pm, int i1, int i2)
{
CString str;
str.Format(_T("Cmd Search PM...%d " ), pm);
AfxMessageBox(str);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CMainFrame::g_mmCmdLocation::iterator iterCmd;
pair <CMainFrame::g_mmCmdLocation::iterator, CMainFrame::g_mmCmdLocation::iterator> pCmd;
//Search for Commands in the production
pCmd = pMainFrame->gmmCmdLocation.equal_range(pm);
for(iterCmd = pCmd.first; iterCmd != pCmd.second; ++iterCmd)
{
AfxMessageBox(_T("Exp Parser File: Entro a buscar command"));
CAipi_CmdLocation cloc = (CAipi_CmdLocation)iterCmd->second;
long index1 = cloc.getStartIndex();
long index2 = cloc.getEndIndex();
if( i2 > index1 )
{
continue;
}
m_index = index1;
m_endIndex = index2;
callExpParserFile();
}
//AfxMessageBox(_T("END ExpParserFILE CONFLIC_SET"));
}
CString CAipi_ExpParserFile::LiteralVarSearch(long iform, CString strToken )
{
//Search global literal variables first
CAipi_STableGlobalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f == NOT_FOUND )
{
//Search local literal variables
CAipi_STableLocalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f == NOT_FOUND )
{
return _T("NOT_FOUND");
}
else
{
g_currentVarLoc = VAR_LOCAL;
CString str = lit.m_STLitValue.data();
AfxMessageBox(str);
return str;
}
}
else
{
g_currentVarLoc = VAR_GLOBAL;
CString str = lit.m_STGLitValue.data();
AfxMessageBox(str);
return str;
}
return _T("NOT_FOUND");
}
double CAipi_ExpParserFile::NumericVarSearch(long iform, CString strToken)
{
//Search global numeric variables first
CAipi_STableGlobalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f == NOT_FOUND )
{
//Search local numeric variables
CAipi_STableLocalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f == NOT_FOUND )
{
return NOT_FOUND;
}
else
{
AfxMessageBox(_T("Encontro Variable"));
g_currentVarLoc = VAR_LOCAL;
double val = num.m_STLNumValue;
CString str;
str.Format(_T("%f"), val);
AfxMessageBox(str);
return val;
}
}
else
{
AfxMessageBox(_T("Encontro Variable"));
g_currentVarLoc = VAR_GLOBAL;
double val = num.m_STGNumValue;
CString str;
str.Format(_T("%f"), val);
AfxMessageBox(str);
return val;
}
return NOT_FOUND;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//// Script ////
///////////////////////////////////////////////////////////////////////////////////////////////
void CAipi_ExpParserFile::ScriptSearch(long iform, tstring sId)
{
CAipi_ScriptCode script;
int f = script.findScriptMembers(iform);
if( f != NOT_FOUND )
{
CString lang = script.m_ScriptLanguage;
CString code = script.m_ScriptDefinition;
tstring name = script.m_ScriptName;
CString strName = name.data();
if( lang == _T("JScript") || lang == _T("VBScript") )
{
AfxMessageBox(_T("EXECUTE SCRIPT"));
long index1 = script.m_StartIndex;
long pos1 = script.m_StartPos;
int nParam = script.m_nParameters;
/*
CString str;
str.Format(_T("m_index %d"), m_index);
AfxMessageBox(str);
str.Format(_T("m_endIndex %d"), m_endIndex);
AfxMessageBox(str);
*/
long indexEndScript = ScriptSaveParam(m_index, m_endIndex);
if( indexEndScript != P_UNSUCCESS )
{
//CString str;
//str.Format(_T("End call Script %d"), indexEndScript);
//AfxMessageBox(str);
CString szResult = ScriptExecute(pos1, index1, nParam, strName, lang, code);
double result = isDigitOpt(szResult);
if( result != 0 )
{
m_stackNumeric.push(result);
}
else
{
tstring strResult = (LPCTSTR)szResult;
m_stackLiteral.push(strResult);
}
m_vParameters.clear();
m_index = indexEndScript;
}
else
{
CAipi_Error err;
err.displayFileError(JSCRIPT_PARAM, JSCRIPT_ERROR, _T("The function parameters syntax is incorrect or not permited."));
return;
}
}
else if ( lang == _T("SQL") )
{
AfxMessageBox(_T("Encontro Script SQL"));
AfxMessageBox(code);
CString szResult = _T("");
int nParam = script.m_nParameters;
if( nParam == 0 )
{
m_query << code;
if( !m_query.ExecuteSQL())
{
return;
}
int nCol = m_query.GetColumnsCount();
int nRow = m_query.GetDataCount();
/*
CString str;
str.Format(_T("nCol... %d"), nCol);
AfxMessageBox(str);
str.Format(_T("nRow... %d"), nRow);
AfxMessageBox(str);
*/
if( nCol == 1 && nRow == 1 )
{
m_query > szResult;
double result = isDigitOpt(szResult);
if( result != 0 )
{
m_stackNumeric.push(result);
}
else
{
tstring strResult = (LPCTSTR)szResult;
m_stackLiteral.push(strResult);
}
}
else
{
SqlRunQuery(code);
}
}
else
{
long index1 = script.m_StartIndex;
long index2 = script.m_EndIndex;
SqlRunQueryVars(code, index1, index2);
}
}
}
else
{
CAipi_Error err;
CString strId = sId.data();
CString strDesc = _T("No type was found for script identifier [") + strId + _T("].");
err.displayFileError(UNKNOW_TYPE, SEMANT_ERROR, strDesc);
}
}
long CAipi_ExpParserFile::ScriptSaveParam(long i1, long i2)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CAipi_Tokenizer tkz;
int nParam = 0;
long pos = 0;
long posOpenParenthesis = pMainFrame->gvTokenizer[i2].getPos1();
long posCloseParenthesis = pMainFrame->gvTokenizer[i2].getPos1();
long indexCloseParenthesis = 0;
long iForm = 0;
tstring sToken = _T("");
CString str;
str.Format(_T("Index1...%d " ), i1);
AfxMessageBox(str);
str.Format(_T("Index2...%d " ), i2);
AfxMessageBox(str);
for( long i = i1; i< i2; ++i )
{
sToken = pMainFrame->gvTokenizer[i].getToken();
iForm = pMainFrame->gvTokenizer[i].getIntForm();
pos = pMainFrame->gvTokenizer[i].getPos1();
//Open parenthesis after the script function name
if( iForm == OPEN_PARENTHESIS )
{
posOpenParenthesis = pMainFrame->gvTokenizer[i].getPos1();
/*
CString str;
str.Format(_T("pos open parenthesis...%d " ), pos);
AfxMessageBox(str);
*/
}
//Close parenthesis after the script function name
if( iForm == CLOSE_PARENTHESIS )
{
posCloseParenthesis = pMainFrame->gvTokenizer[i].getPos1();
/*
CString str;
str.Format(_T("pos close parenthesis...%d " ), pos);
AfxMessageBox(str);
*/
}
/*
CString str;
str.Format(_T("pos...%d " ), pos);
AfxMessageBox(str);
AfxMessageBox(sToken.data());
*/
if( pos > posOpenParenthesis && pos < posCloseParenthesis )
{
//AfxMessageBox(_T("GetIn"));
if( iForm != COMMA )
{
CString strParam = sToken.data();
m_vParameters.push_back(strParam);
++nParam;
/*
CString str;
str.Format(_T("nParam %d"), nParam);
AfxMessageBox(str);
AfxMessageBox(strParam);
*/
}
}
if( pos > posCloseParenthesis )
{
indexCloseParenthesis = i;
return indexCloseParenthesis;
}
}
return P_UNSUCCESS;
}
CString CAipi_ExpParserFile::ScriptExecute(long pos1, long index1, int nParam, CString name, CString lang, CString code)
{
m_ScriptObj.Reset();
m_ScriptObj.SetLanguage(lang);
if (!m_ScriptObj.AddScript( code ))
{
AfxMessageBox(_T("Error Sale"));
CAipi_Tokenizer tkz;
int line = tkz.v_getLineByIndex(index1);
ScriptDisplayError(pos1, line, name);
return _T("ERROR");;
}
else
{
AfxMessageBox(code);
}
CString sResult = _T("");
CSafeArrayHelper sfHelper;
try
{
_variant_t var;
sfHelper.Create(VT_VARIANT, 1, 0, nParam);
int v_size = m_vParameters.size();
CString str;
str.Format(_T("nElements %d"), v_size);
AfxMessageBox(str);
for(int i=0; i< nParam; ++i)
{
CString sParam = m_vParameters.at(i);
AfxMessageBox(sParam);
var = _bstr_t(sParam);
sfHelper.PutElement(i, (void*)&var);
}
AfxMessageBox(_T("Try"));
LPSAFEARRAY sa = sfHelper.GetArray();
_variant_t varRet;
if( m_ScriptObj.RunProcedure(name, &sa, &varRet))
{
AfxMessageBox(_T("Run"));
sResult = (LPCTSTR)_bstr_t(varRet);
AfxMessageBox(_T("SCRIP RESULT"));
AfxMessageBox(sResult);
}
else
{
AfxMessageBox(_T("Error"));
CAipi_Tokenizer tkz;
int line = tkz.v_getLineByIndex(index1);
CString str;
str.Format(_T("line %d"), line);
AfxMessageBox(str);
str.Format(_T("position1 %d"), pos1);
AfxMessageBox(str);
ScriptDisplayError(pos1, line, name);
sResult = _T("ERROR");
//CString sError = m_ScriptObj.GetErrorString();
//ScriptDisplayError(posStartProc);
//AfxMessageBox(sError);
}
}
catch(...)
{
AfxMessageBox(_T("Catch"));
CAipi_Tokenizer tkz;
int line = tkz.v_getLineByIndex(index1);
ScriptDisplayError(pos1, line, name);
sResult = _T("ERROR");
//ScriptDisplayError(pos1, line, strName);
//CString sError = m_ScriptObj.GetErrorString();
//AfxMessageBox(sError);
}
return sResult;
}
void CAipi_ExpParserFile::ScriptDisplayError(long nStartSel, int line, CString name)
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
//_bstr_t line = _T("");
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd;
CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive();
CScintillaView* pView = (CScintillaView*) pChild->GetActiveView();
ASSERT(pView);
CScintillaCtrl& rCtrl = pView->GetCtrl();
LPTSTR lpsErrLine =_T("0");
//LPTSTR lpsLine =_T("0");
LPTSTR lpsErrPos = _T("0");
LPTSTR lpsErrCode = _T("0");
LPTSTR lpsErrDesc = _T("No description has found for this error");
LPTSTR lpsErrFile = _T("");
int type = JSCRIPT_ERROR;
//Handle Internationational
LANGID dwLanguageID = GetSystemLanguagePrimaryID();
switch( dwLanguageID)
{
case LANG_SPANISH:
//errLine = _bstr_t(_T("Línea: ")) + _itot( g_currentLine, buff, 10 );
//errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10);
break;
default:
//errLine = _bstr_t(_T("Line: ")) + _itot( g_currentLine, buff, 10 );
//errPos = _bstr_t(_T("Pos. ")) + _itot(g_currentPos, buff, 10);
break;
}
//LPTSTR strErrorLineNumber = (LPTSTR)line;
CString strErrScriptLine = m_ScriptObj.GetErrorLineNumber();
int nErrScriptLine = _ttoi(strErrScriptLine);
int nStartScriptLine = rCtrl.LineFromPosition(nStartSel);
int nErrLine = nStartScriptLine + nErrScriptLine + 1;
TCHAR buffer[8];
CString strErrLine = _itot( nErrLine, buffer, 10 );
lpsErrLine = strErrLine.GetBuffer(0);
strErrLine.ReleaseBuffer();
/*
CString strLine = _itot( line, buffer, 10 );
lpsLine = strErrLine.GetBuffer(0);
strLine.ReleaseBuffer();
*/
//AfxMessageBox(strErrLine);
//AfxMessageBox(strLine);
CString strErrCode = m_ScriptObj.GetErrorNumber();
lpsErrCode = strErrCode.GetBuffer(0);
strErrCode.ReleaseBuffer();
CString strErrDesc = m_ScriptObj.GetErrorDescription();
strErrDesc += _T(" Method: ") + name + _T(".");
lpsErrDesc = strErrDesc.GetBuffer(0);
strErrDesc.ReleaseBuffer();
CString strErrScriptCol = m_ScriptObj.GetErrorColumn();
int nErrScriptCol = _ttoi(strErrScriptCol);
int nStartScriptPos = rCtrl.PositionFromLine(nErrLine -1);
int nErrCol = nErrScriptCol + nStartScriptPos;
CString strErrCol = _itot( nErrCol, buffer, 10 );
lpsErrPos = strErrCol.GetBuffer(0);
strErrCol.ReleaseBuffer();
CString strErrFile = g_currentFile;
lpsErrFile = strErrFile.GetBuffer(0);
strErrFile.ReleaseBuffer();
/*
AfxMessageBox(strErrScriptLine);
AfxMessageBox(strErrCode);
AfxMessageBox(strErrDesc);
AfxMessageBox(strErrScriptCol);
*/
if ( pMainFrame->m_wndOutputTabView.IsVisible())
{
pMainFrame->m_wndOutputTabView.m_TabViewContainer.SetActivePageIndex(1);
LVITEM Item = pMainFrame->m_wndOutputTabView.AddListItem2(0, 0, _T(""), type);
pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 1, lpsErrLine);
pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 2, lpsErrPos);
pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 3, lpsErrDesc);
pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 4, lpsErrFile);
pMainFrame->m_wndOutputTabView.AddListSubItem2(Item, 0, 5, lpsErrCode);
}
m_ScriptObj.ClearError();
}
////////////////////////////////////////////////////////////////////////////////////
//// SQL OleDB DataBase /////
///////////////////////////////////////////////////////////////////////////////////
int CAipi_ExpParserFile::SqlSelectDB(tstring db)
{
if( db == _T("Ms_Access") || db == _T("MS_ACCESS") )
{
//m_idbProvider = MS_ACCESS;
g_iDBProvider = MS_ACCESS;
return g_iDBProvider;
}
else if ( db == _T("Ms_SqlServer") || db == _T("MS_SQLSERVER") )
{
//m_idbProvider = MS_SQLSERVER;
g_iDBProvider = MS_SQLSERVER;
return g_iDBProvider;
}
else if ( m_dbProvider == _T("Ms_Oracle") || _T("MS_ORACLE") )
{
//m_idbProvider = MS_ORACLE;
g_iDBProvider = MS_ORACLE;
return g_iDBProvider;
}
else if( m_dbProvider == _T("Oracle") || _T("MS_ORACLE") )
{
//m_idbProvider = ORACLE;
g_iDBProvider = ORACLE;
return g_iDBProvider;
}
else if( m_dbProvider == _T("MySql") || _T("MYSQL") )
{
//m_idbProvider = MYSQL;
g_iDBProvider = MYSQL;
return g_iDBProvider;
}
else if( m_dbProvider == _T("db2") || _T("DB2") )
{
//m_idbProvider = DB2;
g_iDBProvider = DB2;
return g_iDBProvider;
}
else
{
g_iDBProvider = UNDEFINE;
//WARNNING Provider incorrect not idnetifcated
//CAipi_Error err;
//err.displayGUIError();
}
return g_iDBProvider;
}
void CAipi_ExpParserFile::SqlShowDBDlg()
{
if( g_iDBProvider != UNDEFINE && m_dbName == _T("") && m_dbUser == _T("") && m_dbPassword == _T("") && m_dbDNS == _T("") )
{
SqlOpenConnectionDlg();
}
else if ( g_iDBProvider == UNDEFINE && m_dbName == _T("") && m_dbUser == _T("") && m_dbPassword == _T("") && m_dbDNS == _T("") )
{
//If no provider is reconized then select MsAccess by default
g_iDBProvider = MS_ACCESS;
SqlOpenConnectionDlg();
}
else
{
//SqlOpenConnectionDlg();
AfxMessageBox(_T("OPEN OLE CTRL"));
SqlOpenOleDB();
}
}
void CAipi_ExpParserFile::SqlOpenConnectionDlg()
{
//AfxMessageBox(_T("SqlOpen"));
if( g_iDBProvider != UNDEFINE )
{
AfxMessageBox(_T("Open Connection Dlg"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOleDBDlg.OnOpenDatabaseConnection(g_iDBProvider);
if ( !pMainFrame->m_wndOleDBDlg.IsVisible())
{
pMainFrame->ShowControlBar(&pMainFrame->m_wndOleDBDlg, !pMainFrame->m_wndOleDBDlg.IsVisible(), FALSE);
}
}
}
void CAipi_ExpParserFile::SqlOpenOleDB()
{
//AfxMessageBox(_T("OPEN DB"));
if( g_iDBProvider != UNDEFINE )
{
AfxMessageBox(_T("Open Connection Dlg"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOleDBDlg.OnOpenDatabase(g_iDBProvider);
if ( !pMainFrame->m_wndOleDBDlg.IsVisible())
{
pMainFrame->ShowControlBar(&pMainFrame->m_wndOleDBDlg, !pMainFrame->m_wndOleDBDlg.IsVisible(), FALSE);
}
}
/*
if( g_iDBProvider != UNDEFINE )
{
COleDBConnectionProp m_props;
m_props.Connect(g_iDBProvider);
m_props.m_strServerName = g_sDBDNS;
m_props.m_strDSN = g_sDBDNS;
m_props.m_strPassword = g_sDBPassword;
m_props.m_strLoginName = g_sDBUser;
m_props.m_strDatabaseName = g_sDBName;
m_props.LoadSettings();
m_props.SaveSettings();
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->ShowControlBar(&pMainFrame->m_wndOleDBDlg, !pMainFrame->m_wndOleDBDlg.IsVisible(), FALSE);
}
*/
}
void CAipi_ExpParserFile::SqlRunQuery(CString query)
{
AfxMessageBox(_T("SQL Run Query"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOleDBDlg.m_strQuery = query;
pMainFrame->m_wndOleDBDlg.RunQuery();
pMainFrame->m_wndOleDBDlg.m_wndQueryEdit.SetWindowText(query);
}
void CAipi_ExpParserFile::SqlRunQueryVars(CString query, long index1, long index2)
{
AfxMessageBox(_T("SQL Run Query VARIABLES"));
AfxMessageBox(query);
CString strToken = _T("");
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
for(long i = index1+1; i<index2; ++i)
{
tstring sToken = pMainFrame->gvTokenizer[i].getToken();
int categ = pMainFrame->gvTokenizer[i].getCategory();
if( categ == AIPI_VAR )
{
AfxMessageBox(_T("Aipi Var"));
int iform = pMainFrame->gvTokenizer[i].getIntForm();
CAipi_STableGlobalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f == NOT_FOUND )
{
CAipi_STableLocalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f == NOT_FOUND )
{
CAipi_STableGlobalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f == NOT_FOUND )
{
CAipi_STableLocalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f == NOT_FOUND )
{
g_currentVarLoc = UNDEFINE;
CAipi_Error er;
CString strDesc = _T("Identifier [") + strToken + _T("] was not found.");
er.displayGUIError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
else
{
g_currentVarLoc = VAR_LOCAL;
CString str = lit.m_STLitValue.data();
AfxMessageBox(str);
strToken += str + _T(" ");
}
}
else
{
g_currentVarLoc = VAR_GLOBAL;
CString str = lit.m_STGLitValue.data();
AfxMessageBox(str);
strToken += str + _T(" ");
}
}
else
{
AfxMessageBox(_T("Encontro Variable"));
g_currentVarLoc = VAR_LOCAL;
double val = num.m_STLNumValue;
CString str;
str.Format(_T("%f"), val);
AfxMessageBox(str);
strToken += str + _T(" ");
}
}
else
{
AfxMessageBox(_T("Encontro Variable"));
g_currentVarLoc = VAR_GLOBAL;
double val = num.m_STGNumValue;
CString str;
str.Format(_T("%f"), val);
AfxMessageBox(str);
strToken += str + _T(" ");
}
}
else
{
strToken += sToken.data();
strToken += _T(" ");
AfxMessageBox(strToken);
}
}
pMainFrame->m_wndOleDBDlg.m_strQuery = strToken;
pMainFrame->m_wndOleDBDlg.RunQuery();
pMainFrame->m_wndOleDBDlg.m_wndQueryEdit.SetWindowText(strToken);
}
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
//// Lexer /////
////////////////////////////////////////////////////////////////////////
bool CAipi_ExpParserFile::isDigit(CString t)
{
CString first = t[0];
if( first == _T("0") || first == _T("1") || first == _T("2") || first == _T("3") ||
first == _T("4") || first == _T("5") || first == _T("6") || first == _T("7") ||
first == _T("8") || first == _T("9")
)
{
return true;
}
return false;
}
double CAipi_ExpParserFile::isDigitOpt(CString t)
{
double digit = _tcstod(t, NULL);
if( digit == 0 )
{
//Can not convert to double
return 0;
}
if( digit == HUGE_VAL || digit == -HUGE_VAL )
{
//Error value is to long
return HUGE_VAL;
}
return digit;
}
bool CAipi_ExpParserFile::isAlphabetic(CString t)
{
t.MakeLower();
if( t == _T("a") || t == _T("b") || t == _T("c") || t == _T("d") || t == _T("e") || t == _T("f") ||
t == _T("g") || t == _T("h") || t == _T("i") || t == _T("j") || t == _T("k") || t == _T("l") ||
t == _T("m") || t == _T("n") || t == _T("o") || t == _T("p") || t == _T("q") || t == _T("r") ||
t == _T("s") || t == _T("t") || t == _T("u") || t == _T("v") || t == _T("w") || t == _T("x") ||
t == _T("y") || t == _T("z") )
{
return true;
}
return false;
}
////////////////////////////////////////////////////////////////////////
//// Expression parser ////
//////////////////////////////////////////////////////////////////////////
void CAipi_ExpParserFile::initExpParserFile()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndStatusBar.SetBarProgress(1, TRUE, 0, 0);
pMainFrame->m_wndStatusBar.SetUpBar(1, TRUE, TRUE);
pMainFrame->m_wndStatusBar.SetPaneText( 0, _T("Syntax analyzer..."), RGB(0,0,0), TRUE);
CAipi_Lexer lex;
CAipi_Tokenizer tkz;
g_currentId_IForm = 1000;
m_index = 0;
m_endIndex = tkz.v_sizeTokenizer();
m_fendPos = g_currentDocEndPos;
AfxMessageBox(_T("Expression Parser TOKEN"));
getTokenizer();
AfxMessageBox(_T("Empieza ExParserFile "));
translation_unit();
AfxMessageBox(_T("Termina ExParserFile "));
pMainFrame->m_wndStatusBar.ResetBar(1, TRUE);
pMainFrame->m_wndStatusBar.SetPaneText( 0, _T("Process finished"), RGB(0,0,0), TRUE);
}
void CAipi_ExpParserFile::callExpParserFile()
{
AfxMessageBox(_T("****Entro EXP PARSER FILE****"));
getTokenizer();
translation_unit();
AfxMessageBox(_T("****Entro EXP PARSER FILE****"));
}
void CAipi_ExpParserFile::initTokenizer()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndStatusBar.SetBarProgress(1, TRUE, 0, 0);
pMainFrame->m_wndStatusBar.SetUpBar(1, TRUE, TRUE);
pMainFrame->m_wndStatusBar.SetPaneText( 0, _T("Syntax analyzer..."), RGB(0,0,0), TRUE);
if( pMainFrame->gvTokenizer.empty() )
{
AfxMessageBox(_T("vacio"));
return;
}
if( m_index < pMainFrame->gvTokenizer.size() )
{
getTokenizer();
}
if( m_lookahead == COMMENT )
{
AfxMessageBox(_T("Comments"));
do
{
getTokenizer();
}while (m_lookahead == COMMENT || m_lookahead == _TEOF );
}
translation_unit();
}
void CAipi_ExpParserFile::getToken()
{
CAipi_Lexer lex;
TCHAR symbol = _gettc(g_fp);
m_lookahead = lex.getTokenFile(symbol);
m_sToken = lex.m_sToken;
if( m_lookahead == COMMENT )
{
do
{
TCHAR symbol = _gettc(g_fp);
m_lookahead = lex.getTokenFile(symbol);
m_sToken = lex.m_sToken;
}while (m_lookahead == COMMENT || m_lookahead == _TEOF );
}
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndStatusBar.SetBarProgress(1, TRUE, 100, g_fcurrentPos*100/m_fendPos);
/*
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
//str.Format(_T("pos...%d " ), g_fcurrentPos);
//AfxMessageBox(str);
m_sToken = lex.m_sToken;
AfxMessageBox(m_sToken);
*/
}
long CAipi_ExpParserFile::getTokenizer()
{
//AfxMessageBox(_T("Tokenizer"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
//CString str;
//str.Format(_T("TOKENIZER SIZE...%d " ), tkzSize);
//AfxMessageBox(str);
CString str;
str.Format(_T("Index1...%d " ), m_index);
AfxMessageBox(str);
str.Format(_T("Index2...%d " ), m_endIndex);
AfxMessageBox(str);
if( m_index > m_endIndex )
{
longjmp(e_buf, 1);
}
else if( m_index < m_endIndex )
{
m_lookahead = pMainFrame->gvTokenizer[m_index].getCategory();
m_sToken = pMainFrame->gvTokenizer[m_index].getToken().data();
pMainFrame->m_wndStatusBar.SetBarProgress(1, TRUE, 100, m_index*100/m_endIndex);
++m_index;
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
AfxMessageBox(m_sToken);
//str.Format(_T("index...%d " ), m_index);
//AfxMessageBox(str);
}
else
{
m_lookahead = _TEOF;
}
if( m_lookahead == COMMENT )
{
AfxMessageBox(_T("COMENTARIO ENCONTRADO"));
do
{
if( m_index < m_endIndex )
{
m_lookahead = pMainFrame->gvTokenizer[m_index].getCategory();
m_sToken = pMainFrame->gvTokenizer[m_index].getToken().data();
pMainFrame->m_wndStatusBar.SetBarProgress(1, TRUE, 100, m_index*100/m_endIndex);
++m_index;
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
AfxMessageBox(m_sToken);
//str.Format(_T("index...%d " ), m_index);
//AfxMessageBox(str);
}
else
{
m_lookahead = _TEOF;
break;
}
}while (m_lookahead == COMMENT );
}
return m_lookahead;
}
void CAipi_ExpParserFile::printStack()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOutputTabView.AddMsg1(_T("******* Parser Stack *******"));
CString str = _T("");
int size = m_stackNumeric.size();
for( int i = 0; i< size; ++i )
{
double element = m_stackNumeric.top();
str.Format(_T("Element...%d , %f " ), i, element);
pMainFrame->m_wndOutputTabView.AddMsg1(str);
}
}
void CAipi_ExpParserFile::emit_declaration(int tk)
{
if ( tk == IDENTIFIER )
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
double id = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring tk = pMainFrame->gvTokenizer[m_index-4].getToken();
AfxMessageBox(tk.data());
m_sCurrentId = tk;
m_dCurrentId = id;
/*
CAipi_Symbol sym;
long iform = sym.findId_IntForm(tk);
if( iform != NOT_FOUND )
{
id = iform;
}
*/
if( m_currentType == AIPI_STRING || m_currentType == AIPI_CHAR )
{
tstring sToken = (LPCTSTR)m_sToken;
//Checking repeated identifiers declarations
CAipi_STableLocalLiteral lit;
int found = lit.findSTableLiteralMembers(id);
if( found == NOT_FOUND )
{
CAipi_STableLocalLiteral lt;
lt.addSymbol(id, sToken, m_currentType, _T(""));
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was already declare.");
er.displayFileError(DUP_VAR, SEMANT_ERROR, strDesc);
}
}
else
{
tstring sToken = (LPCTSTR)m_sToken;
//AfxMessageBox(m_sToken);
//Checking repeated identifiers declarations
CAipi_STableLocalNumeric num;
int found = num.findSTableNumericMembers(id);
/*
CString str;
str.Format(_T("idSymbol...%d " ), idSymbol);
AfxMessageBox(str);
str.Format(_T("id...%d " ), id);
AfxMessageBox(str);
*/
//Check if ID were previously declare
if( found == NOT_FOUND )
{
//The ID was not previously declare
CAipi_STableLocalNumeric st;
st.addSymbol(id, sToken, m_currentType, 0);
//AfxMessageBox("Add Numeric Table");
//AfxMessageBox(sToken.data());
}
else
{
//Check if identifier was used in a script definition
CAipi_ScriptCode script;
long idsearch = script.findId_Into_ScriptCode(id);
if(idsearch != NOT_FOUND )
{
//The id was used in a script definition, but was not previously declare
CAipi_STableLocalNumeric st;
st.addSymbol(id, sToken, m_currentType, 0);
//AfxMessageBox("Add Numeric Table");
//AfxMessageBox(sToken.data());
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was already declare.");
er.displayFileError(DUP_VAR, SEMANT_ERROR, strDesc);
AfxMessageBox(_T("ERROR"));
}
}
}
/*
CString str;
AfxMessageBox(m_sToken);
str.Format(_T("ID...%d " ), id);
AfxMessageBox(str);
str.Format(_T("Type...%d " ), type);
AfxMessageBox(str);
*/
}
if( tk == EQUAL )
{
AfxMessageBox(_T("EMIT DECLARATION EQUAL"));
CString str;
str.Format(_T("Current Type...%d " ), m_currentType);
AfxMessageBox(str);
/*
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
long id = pMainFrame->gvTokenizer[m_index-4].getIntForm();
string tk = pMainFrame->gvTokenizer[m_index-4].getToken();
AfxMessageBox(tk.data());
*/
AfxMessageBox(m_sCurrentId.data());
CAipi_Symbol sym;
double id = m_dCurrentId;
if( m_currentType == AIPI_STRING || m_currentType == AIPI_CHAR )
{
if( !m_stackLiteral.empty() )
{
tstring value = m_stackLiteral.top();
m_stackLiteral.pop();
CAipi_STableLocalLiteral lt;
lt.editSTableLiteralValue(id, value);
/*
AfxMessageBox(value.data());
AfxMessageBox(m_sToken);
*/
}
}
else
{
if( !m_stackNumeric.empty() )
{
double value = m_stackNumeric.top();
m_stackNumeric.pop();
CAipi_STableLocalNumeric st;
st.editSTableNumericValue(id, value);
/*
CString str;
str.Format(_T("TOP...%f " ), result);
AfxMessageBox(str);
AfxMessageBox(m_sToken);
*/
}
}
}
}
void CAipi_ExpParserFile::emit_expression(int tk)
{
CAipi_Lexer lex;
if( tk == IDENTIFIER )
{
AfxMessageBox(_T("EMIT IDENTIFIER"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
tstring sId = pMainFrame->gvTokenizer[m_index-1].getToken();
long iform = pMainFrame->gvTokenizer[m_index-1].getIntForm();
AfxMessageBox(_T("TOKEN"));
AfxMessageBox(sId.data());
/*
CAipi_Symbol sym;
long iform = sym.findId_IntForm(sId);
*/
CString str;
str.Format(_T("ID...%d " ), iform);
AfxMessageBox(str);
//AfxMessageBox(_T("FOUND"));
CAipi_STableGlobalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f != NOT_FOUND )
{
AfxMessageBox(_T("PUSH DIGIT"));
m_stackNumeric.push(num.m_STNumValue);
m_currentType = num.m_STGNumType;
}
else
{
CAipi_STableLocalNumeric num;
double f = num.findSTableNumericMembers(iform);
if( f != NOT_FOUND )
{
AfxMessageBox(_T("PUSH DIGIT"));
m_stackNumeric.push(num.m_STNumValue);
m_currentType = num.m_STLNumType;
}
else
{
CAipi_STableGlobalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f != NOT_FOUND )
{
AfxMessageBox(_T("PUSH LITERAL"));
m_stackLiteral.push(lit.m_STLitValue);
m_currentType = lit.m_STGLitType;
}
else
{
CAipi_STableLocalLiteral lit;
int f = lit.findSTableLiteralMembers( iform);
if( f != NOT_FOUND )
{
AfxMessageBox(_T("PUSH LITERAL"));
m_stackLiteral.push(lit.m_STLitValue);
m_currentType = lit.m_STLLitType;
}
else
{
ScriptSearch(iform, sId);
}
}
}
}
}
if( tk == LITERAL )
{
AfxMessageBox(_T("EMIT LITERAL"));
m_sToken.TrimLeft('"');
m_sToken.TrimRight('"');
m_stackLiteral.push((LPCTSTR)m_sToken);
AfxMessageBox(m_sToken);
}
if( tk == DIGIT )
{
AfxMessageBox(_T("EMIT DIGIT"));
//AfxMessageBox(m_sToken);
double tk = _tcstod(m_sToken, NULL);
m_stackNumeric.push(tk);
CString str;
str.Format(_T("Number...%f " ), tk);
AfxMessageBox(str);
}
//Assignation
if( tk == EQUAL )
{
AfxMessageBox(_T("EMIT EQUAL"));
CString str;
str.Format(_T("Current Type...%d " ), m_currentType);
AfxMessageBox(str);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
long id = pMainFrame->gvTokenizer[m_index-4].getIntForm();
tstring tk = pMainFrame->gvTokenizer[m_index-4].getToken();
AfxMessageBox(tk.data());
/*
CAipi_Symbol sym;
long iform = sym.findId_IntForm(tk);
if( iform != NOT_FOUND )
{
id = iform;
}
*/
if( m_currentType == AIPI_STRING || m_currentType == AIPI_CHAR )
{
if( !m_stackLiteral.empty() )
{
tstring value = m_stackLiteral.top();
m_stackLiteral.pop();
CAipi_STableLocalLiteral lt;
lt.editSTableLiteralValue(id, value);
/*
AfxMessageBox(value.data());
AfxMessageBox(m_sToken);
*/
}
}
else
{
if( !m_stackNumeric.empty() )
{
double value = m_stackNumeric.top();
m_stackNumeric.pop();
CAipi_STableLocalNumeric st;
st.editSTableNumericValue(id, value);
/*
CString str;
str.Format(_T("TOP...%f " ), result);
AfxMessageBox(str);
AfxMessageBox(m_sToken);
*/
}
}
}
//Add operation
if( tk == PLUS_SIGN )
{
AfxMessageBox(_T("SIGNO MAS"));
CString str;
str.Format(_T("Current Type...%d " ), m_currentType);
AfxMessageBox(str);
if( m_currentType == AIPI_INT
|| m_currentType == AIPI_LONG
|| m_currentType == AIPI_SHORT
|| m_currentType == AIPI_FLOAT
|| m_currentType == AIPI_DOUBLE
)
{
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
AfxMessageBox(_T("EMIT SUMA"));
//AfxMessageBox(m_sToken);
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = left_op + right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
else if( m_currentType == AIPI_STRING || m_currentType == AIPI_CHAR )
{
tstring left_op = _T("");
tstring right_op = _T("");
tstring result = _T("");
if( !m_stackLiteral.empty() )
{
AfxMessageBox(_T("EMIT SUMA CADENAS"));
//AfxMessageBox(m_sToken);
right_op = m_stackLiteral.top();
m_stackLiteral.pop();
left_op = m_stackLiteral.top();
m_stackLiteral.pop();
result = left_op + right_op;
m_stackLiteral.push(result);
AfxMessageBox(result.data());
}
}
else
{
return;
}
}
if( tk == MINUS_SIGN )
{
AfxMessageBox(_T("EMIT RESTA"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = left_op - right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == ASTERIC )
{
AfxMessageBox(_T("EMIT MULTIPLICATION"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = left_op * right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == SLASH )
{
AfxMessageBox(_T("EMIT DIVISION"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = left_op / right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == PERCENT )
{
AfxMessageBox(_T("EMIT MOD"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = (int)left_op % (int)right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == UNARY_MINUS )
{
AfxMessageBox(_T("ADD UNARY MINUS"));
m_stackNumeric.push(-1);
}
if ( tk == UNARY_PLUS )
{
AfxMessageBox(_T("ADD UNARY PLUS"));
m_stackNumeric.push(1);
}
if( tk == UNARY_OP )
{
AfxMessageBox(_T("EMIT UNARY"));
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
result = left_op * right_op;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == INC_OP )
{
AfxMessageBox(_T("EMIT INC OP"));
double result = 0;
if( !m_stackNumeric.empty() )
{
result = m_stackNumeric.top();
m_stackNumeric.pop();
++result;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == DEC_OP )
{
AfxMessageBox(_T("EMIT DEC OP"));
double result = 0;
if( !m_stackNumeric.empty() )
{
result = m_stackNumeric.top();
m_stackNumeric.pop();
--result;
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == LT )
{
AfxMessageBox(_T("EMIT LESS THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op < right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == GT )
{
AfxMessageBox(_T("EMIT GREATER THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op > right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == LE )
{
AfxMessageBox(_T("EMIT LESS-EQUAL THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op <= right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == GE )
{
AfxMessageBox(_T("EMIT GREATER-EQUAL THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op >= right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == ET )
{
AfxMessageBox(_T("EMIT EQUAL THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op == right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == NE )
{
AfxMessageBox(_T("EMIT NO-EQUAL THAN"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op != right_op )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == AND_OP )
{
AfxMessageBox(_T("EMIT AND"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op == 1 && right_op == 1 )
{
result = 1;
}
else
{
result = 0;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
if( tk == OR_OP )
{
AfxMessageBox(_T("EMIT OR"));
//AfxMessageBox(m_sToken);
double left_op = 0;
double right_op = 0;
double result = 0;
if( !m_stackNumeric.empty() )
{
right_op = m_stackNumeric.top();
m_stackNumeric.pop();
left_op = m_stackNumeric.top();
m_stackNumeric.pop();
if( left_op == 0 && right_op == 0 )
{
result = 0;
}
else
{
result = 1;
}
m_stackNumeric.push(result);
CString str;
str.Format(_T("Result...%f " ), result);
AfxMessageBox(str);
}
}
/*
int size = m_stackNumeric.size();
CString str;
str.Format(_T("Size...%d" ), size);
AfxMessageBox(str);
*/
}
////////////////////////////////////////////////
/// PARSER ////
///////////////////////////////////////////////
void CAipi_ExpParserFile::translation_unit()
{
if( m_lookahead != _TEOF )
{
if( m_lookahead == COMMENT )
{
getTokenizer();
}
if( m_lookahead == AIPI_VOID
|| m_lookahead == AIPI_CHAR
|| m_lookahead == AIPI_STRING
|| m_lookahead == AIPI_SHORT
|| m_lookahead == AIPI_INT
|| m_lookahead == AIPI_LONG
|| m_lookahead == AIPI_FLOAT
|| m_lookahead == AIPI_DOUBLE
)
{
//AfxMessageBox(_T("Entro a declaration"));
declaration();
//AfxMessageBox(_T("Salio de declaration"));
translation_unit();
}
else if ( m_lookahead == IDENTIFIER
|| m_lookahead == DIGIT
)
{
//AfxMessageBox(_T("Entro a expresion"));
expression_statement();
/*
AfxMessageBox(_T("Salio de expresion"));
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
*/
translation_unit();
}
else if( m_lookahead == AIPI_OUTPUT )
{
cmd_output();
translation_unit();
}
else if( m_lookahead == AIPI_INPUT )
{
int r = cmd_input();
if( r == AIPI_STOP )
{
g_bStopFlag = true;
return;
}
translation_unit();
}
else if( m_lookahead == AIPI_DISPLAYCTRL )
{
int r = UNDEFINE;
//matchToken(AIPI_DISPLAYCTRL);
getTokenizer();
switch( m_lookahead)
{
case AIPI_CTRL_MEDIAPLAYER :
ctrl_mediaplayer();
break;
case AIPI_CTRL_JUKEBOX:
ctrl_jukebox();
break;
case AIPI_CTRL_IMAGEFILTER:
ctrl_imagefilter();
break;
case AIPI_CTRL_LISTOPTION:
r = ctrl_listoption();
if( r == AIPI_STOP )
{
g_bStopFlag = true;
return;
}
break;
case AIPI_CTRL_OLEDB:
ctrl_oledb();
break;
}
translation_unit();
}
else if ( m_lookahead == AIPI_DB_OPEN ||
m_lookahead == AIPI_DB_CLOSE
)
{
AfxMessageBox(_T("Entro a OPEN DB"));
cmd_db_open();
translation_unit();
}
else
{
AfxMessageBox(_T("Sale de ExpParserFile"));
if( g_bExecuteFlag )
{
CAipi_Main main;
main.execute_continue();
}
else
{
CAipi_ParserFile file;
file.m_lookahead = m_lookahead;
file.translation_unit();
file.endParser();
}
/*
CString str;
str.Format(_T("ERROR FINAL::: Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
CAipi_Error err;
err.displayFileError(ABNORMAL_STOP, WARNING_ERROR, _T("The parser was not able to finish the depuration process. The initialization sintax is incorrect.") );
*/
}
}
else
{
/*
TCHAR buffer[8];
unsigned int nError = g_LexError + g_SintaxError + g_SemantError;
unsigned int nWarning = g_WarningError + g_QuestionError;
CString str_nError = _itot( nError, buffer, 10 );
CString str_nWarning = _itot( nWarning, buffer, 10 );
CString strLex = _itot( g_LexError, buffer, 10 );
CString strSintax = _itot( g_SintaxError, buffer, 10 );
CString strSemant = _itot( g_SemantError, buffer, 10 );
CString strWarning = _itot( g_WarningError, buffer, 10);
CString strQuestion = _itot( g_QuestionError, buffer, 10);
//CString strInfo = _itot( g_InfoError, buffer, 10);
//CString strStop = _itot( g_SintaxError, buffer, 10 );
CAipi_Error err;
err.displayFileError(EMPTY_MSG, -1, _T(" *************************************************************************************************************"));
err.displayFileError(ERROR_COUNT, INFO_ERROR, _T(" Lexical errors:...") + strLex + _T(" Sintax errors:...") + strSintax + _T(" Semantic errors:...") + strSemant + _T(" *Total errors:...") + str_nError );
err.displayFileError(WARNING_COUNT, INFO_ERROR, _T(" Warnings:...") + strWarning + _T(" Warning questions:...") + strQuestion + _T(" *Total warnings:...") + str_nWarning );
err.displayFileError(FINISH, INFO_ERROR, _T(" **** Debug Summary:- ") + str_nError + _T(" error(s), ") + str_nWarning + _T(" warning(s). ****" ));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndOutputTabView.AddMsg1(_T("Debug Summary:- ") + str_nError + _T(" error(s), ") + str_nWarning + _T(" warning(s). ****" ));
*/
}
//Save place to jump
int jump = setjmp(e_buf);
if( jump == 1 )
{
AfxMessageBox(_T("JUMP"));
return;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////
/// Declaration Parser ////
//////////////////////////////////////////////////////////////////////////////////////////////////
void CAipi_ExpParserFile::declaration_specifiers()
{
if( m_lookahead == AIPI_VOID
|| m_lookahead == AIPI_STRING
|| m_lookahead == AIPI_CHAR
|| m_lookahead == AIPI_SHORT
|| m_lookahead == AIPI_INT
|| m_lookahead == AIPI_LONG
|| m_lookahead == AIPI_FLOAT
|| m_lookahead == AIPI_DOUBLE
)
{
m_currentType = m_lookahead;
getTokenizer();
declaration_specifiers();
}
}
void CAipi_ExpParserFile::declaration()
{
declaration_specifiers();
if( m_lookahead == SEMICOLON)
{
getTokenizer();
//AfxMessageBox(_T("SEMICOLON"));
return;
}
declarator_list_init();
getTokenizer();
}
void CAipi_ExpParserFile::declarator_list_init()
{
declarator_init();
if( m_lookahead == COMMA )
{
while ( m_lookahead == COMMA )
{
getTokenizer();
declarator_init();
}
}
//Multidimensional arrays
if( m_lookahead == OPEN_BRACKET )
{
declarator_init();
}
}
void CAipi_ExpParserFile::declarator_init()
{
declarator_direct();
if( m_lookahead == EQUAL )
{
getTokenizer();
initializer();
emit_declaration(EQUAL);
}
}
void CAipi_ExpParserFile::initializer()
{
expression_assignment();
//initialize an array
//Example: int a[] = { 6, 8 }
if( m_lookahead == OPEN_BRACE )
{
//AfxMessageBox(_T("OPEN BRACE"));
getTokenizer();
initializer_list();
getTokenizer();
if( m_lookahead == COMMA)
{
//AfxMessageBox(_T("Entro a COMA"));
getTokenizer();
initializer_list();
//AfxMessageBox(_T("FIN initializer"));
}
}
}
void CAipi_ExpParserFile::initializer_list()
{
initializer();
//getTokenizer();
//AfxMessageBox(_T("CLOSE BRACE"));
//AfxMessageBox(_T("antes de coma"));
//CString str;
//str.Format(_T("Antes de coma Look Ahead...%d " ), m_lookahead);
//AfxMessageBox(str);
if( m_lookahead == COMMA )
{
//AfxMessageBox(_T("Entro de coma"));
while ( m_lookahead == COMMA )
{
//AfxMessageBox(_T("while coma"));
getTokenizer();
initializer_list();
}
}
}
void CAipi_ExpParserFile::declarator_direct()
{
if( m_lookahead == IDENTIFIER )
{
emit_declaration(IDENTIFIER);
getTokenizer();
}
//Function declaration
if( m_lookahead == OPEN_PARENTHESIS )
{
//while( m_lookahead == OPEN_PARENTHESIS)
//{
getTokenizer();
if( m_lookahead == IDENTIFIER
|| m_lookahead == OPEN_PARENTHESIS
|| m_lookahead == OPEN_BRACKET
)
{
declarator_direct();
}
if( m_lookahead == AIPI_VOID
|| m_lookahead == AIPI_CHAR
|| m_lookahead == AIPI_SHORT
|| m_lookahead == AIPI_INT
|| m_lookahead == AIPI_LONG
|| m_lookahead == AIPI_FLOAT
|| m_lookahead == AIPI_DOUBLE
)
{
parameter_list();
}
getTokenizer();
//}
}
//CString str;
//str.Format(_T("Look Ahead...%d " ), m_lookahead);
//AfxMessageBox(str);
//Array declaration
if( m_lookahead == OPEN_BRACKET )
{
getTokenizer();
//matchToken(OPEN_BRACKET);
if( m_lookahead == DIGIT )
{
expression_atom_constant();
}
getTokenizer();
//matchToken(CLOSE_BRACKET);
}
}
void CAipi_ExpParserFile::parameter_declaration()
{
declaration_specifiers();
if( m_lookahead == IDENTIFIER || m_lookahead == OPEN_PARENTHESIS || m_lookahead == OPEN_BRACKET)
{
declarator_direct();
}
}
void CAipi_ExpParserFile::parameter_list()
{
parameter_declaration();
if( m_lookahead == COMMA)
{
while(m_lookahead == COMMA)
{
getTokenizer();
//matchToken(COMMA);
parameter_declaration();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
///// Expression Parser /////
/////////////////////////////////////////////////////////////////////////////////////////////
void CAipi_ExpParserFile::expression_statement()
{
if( m_lookahead == SEMICOLON )
{
getTokenizer();
}
expression();
getTokenizer();
}
void CAipi_ExpParserFile::expression()
{
expression_logical_or();
expression_assignment();
}
void CAipi_ExpParserFile::expression_assignment()
{
/*
if( m_lookahead == IDENTIFIER )
{
AfxMessageBox(_T("IDENTIFICADOR"));
expression_atom_identifier();
}
*/
if( m_lookahead == EQUAL)
{
getTokenizer();
expression_logical_or();
emit_expression(EQUAL);
}
expression_logical_or();
}
void CAipi_ExpParserFile::expression_logical_or()
{
expression_logical_and();
while(true)
{
if( m_lookahead == OR_OP )
{
getTokenizer();
expression_logical_and();
emit_expression(OR_OP);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_logical_and()
{
expression_equality();
while(true)
{
if( m_lookahead == AND_OP )
{
getTokenizer();
expression_equality();
emit_expression(AND_OP);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_equality()
{
expression_relational();
while(true)
{
if( m_lookahead == ET || m_lookahead == NE )
{
int tk = m_lookahead;
getTokenizer();
expression_relational();
emit_expression(tk);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_relational()
{
expression_aritmetic();
while(true)
{
if( m_lookahead == LT || m_lookahead == LE || m_lookahead == GT || m_lookahead == GE )
{
int tk = m_lookahead;
getTokenizer();
expression_aritmetic();
emit_expression(tk);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_aritmetic()
{
expression_term();
while(true)
{
if( m_lookahead == PLUS_SIGN || m_lookahead == MINUS_SIGN )
{
int tk = m_lookahead;
//AfxMessageBox(_T("Arit get Token"));
getTokenizer();
//AfxMessageBox(_T("Arit get Term"));
expression_term();
//AfxMessageBox(_T("Arit emit_expression"));
//CString str;
//str.Format(_T("Look Ahead...%d " ), m_lookahead);
//AfxMessageBox(str);
emit_expression(tk);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_term()
{
expression_factor();
while(true)
{
if( m_lookahead == ASTERIC || m_lookahead == SLASH || m_lookahead == PERCENT )
{
int tk = m_lookahead;
getTokenizer();
expression_factor();
emit_expression(tk);
}
else
{
return;
}
}
}
void CAipi_ExpParserFile::expression_unary_plus()
{
AfxMessageBox(_T("CASE UNARY"));
emit_expression(UNARY_PLUS);
getTokenizer();
expression_factor();
emit_expression(UNARY_OP);
}
void CAipi_ExpParserFile::expression_unary_minus()
{
AfxMessageBox(_T("UNARY MINUS"));
emit_expression(UNARY_MINUS);
getTokenizer();
expression_factor();
emit_expression(UNARY_OP);
}
void CAipi_ExpParserFile::expression_unary_increment()
{
AfxMessageBox(_T("INCREMENT OPERATOR"));
getTokenizer();
//It just apply to identifiers
if( m_lookahead == IDENTIFIER )
{
expression_factor();
emit_expression(INC_OP);
}
}
void CAipi_ExpParserFile::expression_unary_decrement()
{
AfxMessageBox(_T("DECREMENT OPERATOR"));
getTokenizer();
//It just apply to identifiers
if( m_lookahead = IDENTIFIER )
{
expression_factor();
emit_expression(DEC_OP);
}
}
/*
void CAipi_ExpParserFile::expression_factor()
{
switch(m_lookahead)
{
case IDENTIFIER:
emit_expression(IDENTIFIER);
getTokenizer();
if( m_lookahead == INC_OP )
{
expression_unary_increment();
}
if( m_lookahead == DEC_OP )
{
expression_unary_decrement();
}
break;
case DIGIT:
emit_expression(DIGIT);
getTokenizer();
break;
case LITERAL:
emit_expression(LITERAL);
getTokenizer();
break;
case OPEN_PARENTHESIS:
getTokenizer();
expression();
getTokenizer();
break;
case MINUS_SIGN:
expression_unary_minus();
break;
case PLUS_SIGN:
expression_unary_plus();
break;
case INC_OP:
expression_unary_increment();
break;
case DEC_OP:
expression_unary_decrement();
break;
}
}
*/
void CAipi_ExpParserFile::expression_factor()
{
switch(m_lookahead)
{
case IDENTIFIER:
expression_atom_identifier();
break;
case DIGIT:
expression_atom_constant();
break;
case LITERAL:
expression_atom_literal();
break;
case OPEN_PARENTHESIS:
getTokenizer();
expression();
getTokenizer();
break;
case MINUS_SIGN:
expression_unary_minus();
break;
case PLUS_SIGN:
expression_unary_plus();
break;
case INC_OP:
expression_unary_increment();
break;
case DEC_OP:
expression_unary_decrement();
break;
}
}
void CAipi_ExpParserFile::expression_atom_identifier()
{
emit_expression(IDENTIFIER);
getTokenizer();
if( m_lookahead == INC_OP )
{
expression_unary_increment();
}
if( m_lookahead == DEC_OP )
{
expression_unary_decrement();
}
//Detect function call
if( m_lookahead == OPEN_PARENTHESIS )
{
getTokenizer();
expression_argument_list();
getTokenizer();
//emit_expression(IDENTIFIER_SCRIPT);
}
}
void CAipi_ExpParserFile::expression_argument_list()
{
expression_assignment();
if( m_lookahead == COMMA )
{
while ( m_lookahead == COMMA )
{
getTokenizer();
expression_assignment();
}
}
}
void CAipi_ExpParserFile::expression_atom_constant()
{
emit_expression(DIGIT);
getTokenizer();
}
void CAipi_ExpParserFile::expression_atom_literal()
{
emit_expression(LITERAL);
getTokenizer();
}
void CAipi_ExpParserFile::type_name()
{
//CString str;
//str.Format(_T("SPECIFIER_QUALIFIER_LIST...%d " ), m_lookahead);
//AfxMessageBox(str);
switch(m_lookahead)
{
case AIPI_CHAR:
emit_expression(AIPI_CHAR);
break;
case AIPI_SHORT:
emit_expression(AIPI_SHORT);
break;
case AIPI_INT:
emit_expression(AIPI_INT);
break;
case AIPI_LONG:
emit_expression(AIPI_LONG);
break;
case AIPI_FLOAT:
emit_expression(AIPI_FLOAT);
break;
case AIPI_DOUBLE:
emit_expression(AIPI_DOUBLE);
break;
}
}
void CAipi_ExpParserFile::operator_unary()
{
switch(m_lookahead)
{
case PLUS_SIGN:
emit_expression(PLUS_SIGN);
break;
case MINUS_SIGN:
emit_expression(MINUS_SIGN);
break;
}
}
void CAipi_ExpParserFile::operator_assigment()
{
switch(m_lookahead)
{
case EQUAL:
emit_expression(EQUAL);
break;
case MUL_ASSIGN:
emit_expression(MUL_ASSIGN);
break;
case DIV_ASSIGN:
emit_expression(DIV_ASSIGN);
break;
case ADD_ASSIGN:
emit_expression(ADD_ASSIGN);
break;
case SUB_ASSIGN:
emit_expression(SUB_ASSIGN);
break;
}
}
//////////////////////////////////////////////////////////////////////////
//// AIPI Commands ////
////////////////////////////////////////////////////////////////////////////
void CAipi_ExpParserFile::cmd_db_open()
{
getTokenizer();
//matchToken(AIPI_DB_OPEN);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
cmd_db_open_parameter_list();
getTokenizer();
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
//matchToken(SEMICOLON);
m_bFlagConnDlg = true;
}
void CAipi_ExpParserFile::cmd_db_open_parameter()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CString sProvider = _T("");
switch( m_lookahead )
{
case AIPI_DB_DNS:
getTokenizer();
getTokenizer();
//matchToken(AIPI_DB_DNS);
//matchToken(EQUAL);
if( m_lookahead == LITERAL )
{
m_dbDNS = pMainFrame->gvTokenizer[m_index-1].getToken();
g_sDBDNS = m_dbDNS.data();
AfxMessageBox(_T("DB_DNS"));
AfxMessageBox(m_dbDNS.data());
g_sDBDNS = m_dbDNS.data();
getTokenizer();
//matchToken(LITERAL);
}
else if ( m_lookahead == IDENTIFIER )
{
long dns = pMainFrame->gvTokenizer[m_index-1].getIntForm();
//Search in global variables
CAipi_STableGlobalLiteral lit;
m_dbDNS = lit.findIdValue(dns);
AfxMessageBox(_T("DB_DNS"));
AfxMessageBox(m_dbDNS.data());
if( m_dbDNS != _T("NOT_FOUND") )
{
g_sDBDNS = m_dbDNS.data();
}
else
{
//Search in local variables
CAipi_STableLocalLiteral lit;
m_dbDNS = lit.findIdValue(dns);
AfxMessageBox(_T("DB_DNS"));
AfxMessageBox(m_dbDNS.data());
if( m_dbDNS != _T("NOT_FOUND") )
{
g_sDBDNS = m_dbDNS.data();
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
getTokenizer();
//matchToken(IDENTIFIER);
}
break;
case AIPI_DB_USER:
getTokenizer();
getTokenizer();
//matchToken(AIPI_DB_USER);
//matchToken(EQUAL);
if( m_lookahead == LITERAL )
{
m_dbUser = pMainFrame->gvTokenizer[m_index-1].getToken();
g_sDBUser = m_dbUser.data();
AfxMessageBox(_T("DB_USER"));
AfxMessageBox(m_dbUser.data());
g_sDBUser = m_dbUser.data();
getTokenizer();
//matchToken(LITERAL);
}
else if ( m_lookahead == IDENTIFIER )
{
long user = pMainFrame->gvTokenizer[m_index-1].getIntForm();
//Search in global variables
CAipi_STableGlobalLiteral lit;
m_dbUser = lit.findIdValue(user);
AfxMessageBox(_T("DB_USER"));
AfxMessageBox(m_dbUser.data());
if( m_dbUser != _T("NOT_FOUND") )
{
g_sDBUser = m_dbUser.data();
}
else
{
//Search in local variables
CAipi_STableLocalLiteral lit;
m_dbUser = lit.findIdValue(user);
AfxMessageBox(_T("DB_USER"));
AfxMessageBox(m_dbUser.data());
if( m_dbUser != _T("NOT_FOUND") )
{
g_sDBUser = m_dbUser.data();
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
getTokenizer();
//matchToken(IDENTIFIER);
}
break;
case AIPI_DB_PASSWORD:
getTokenizer();
getTokenizer();
//matchToken(AIPI_DB_PASSWORD);
//matchToken(EQUAL);
if( m_lookahead == LITERAL )
{
m_dbPassword = pMainFrame->gvTokenizer[m_index-1].getToken();
g_sDBPassword = m_dbPassword.data();
AfxMessageBox(_T("DB_PASSWORD"));
AfxMessageBox(m_dbPassword.data());
g_sDBPassword = m_dbPassword.data();
getTokenizer();
//matchToken(LITERAL);
}
else if ( m_lookahead == IDENTIFIER )
{
long password = pMainFrame->gvTokenizer[m_index-1].getIntForm();
//Search in global variables
CAipi_STableGlobalLiteral lit;
m_dbPassword = lit.findIdValue(password);
AfxMessageBox(_T("DB_PASSWORD"));
AfxMessageBox(m_dbPassword.data());
if( m_dbPassword != _T("NOT_FOUND") )
{
g_sDBPassword = m_dbPassword.data();
}
else
{
//Search in local variables
CAipi_STableLocalLiteral lit;
m_dbPassword = lit.findIdValue(password);
AfxMessageBox(_T("DB_PASSWORD"));
AfxMessageBox(m_dbPassword.data());
if( m_dbPassword != _T("NOT_FOUND") )
{
g_sDBPassword = m_dbPassword.data();
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
getTokenizer();
//matchToken(IDENTIFIER);
}
break;
case AIPI_DB_NAME:
getTokenizer();
getTokenizer();
//matchToken(AIPI_DB_NAME);
//matchToken(EQUAL);
if( m_lookahead == LITERAL )
{
m_dbName = pMainFrame->gvTokenizer[m_index-1].getToken();
g_sDBName = m_dbName.data();
AfxMessageBox(_T("DB_NAME"));
AfxMessageBox(m_dbName.data());
getTokenizer();
//matchToken(LITERAL);
}
else if ( m_lookahead == IDENTIFIER )
{
long name = pMainFrame->gvTokenizer[m_index-1].getIntForm();
//Search in global variables
CAipi_STableGlobalLiteral lit;
m_dbName = lit.findIdValue(name);
AfxMessageBox(_T("DB_NAME"));
AfxMessageBox(m_dbName.data());
if( m_dbName != _T("NOT_FOUND") )
{
g_sDBName = m_dbName.data();
}
else
{
//Search in local variables
CAipi_STableLocalLiteral lit;
m_dbName = lit.findIdValue(name);
AfxMessageBox(_T("DB_NAME"));
AfxMessageBox(m_dbName.data());
if( m_dbName != _T("NOT_FOUND") )
{
g_sDBName = m_dbName.data();
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
getTokenizer();
//matchToken(IDENTIFIER);
}
break;
case AIPI_DB_PROVIDER:
getTokenizer();
getTokenizer();
//matchToken(AIPI_DB_PROVIDER);
//matchToken(EQUAL);
if( m_lookahead == LITERAL )
{
m_dbProvider = pMainFrame->gvTokenizer[m_index-1].getToken();
g_iDBProvider = SqlSelectDB(m_dbProvider);
AfxMessageBox(_T("DB_PROVIDER"));
AfxMessageBox(m_dbProvider.data());
getTokenizer();
//matchToken(LITERAL);
}
else if ( m_lookahead == IDENTIFIER )
{
long provider = pMainFrame->gvTokenizer[m_index-1].getIntForm();
//Search in global variables
CAipi_STableGlobalLiteral lit;
m_dbProvider = lit.findIdValue(provider);
AfxMessageBox(_T("DB_PROVIDER"));
AfxMessageBox(m_dbProvider.data());
if( m_dbProvider != _T("NOT_FOUND") )
{
g_iDBProvider = SqlSelectDB(m_dbProvider);
}
else
{
//Search in local variables
CAipi_STableGlobalLiteral lit;
m_dbProvider = lit.findIdValue(provider);
AfxMessageBox(_T("DB_PROVIDER"));
AfxMessageBox(m_dbProvider.data());
if( m_dbProvider != _T("NOT_FOUND") )
{
g_iDBProvider = SqlSelectDB(m_dbProvider);
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + m_sToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
getTokenizer();
//matchToken(IDENTIFIER);
}
break;
}
}
void CAipi_ExpParserFile::cmd_output()
{
CString currentDocView = _T("");
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
getTokenizer();
//matchToken(AIPI_OUTPUT);
AfxMessageBox(_T("EXP PARSER FILE OUTPUT"));
if ( m_lookahead == LEFT_OP )
{
while( m_lookahead != SEMICOLON && m_lookahead != _TEOF)
{
getTokenizer();
//matchToken(LEFT_OP);
if( m_lookahead == LITERAL )
{
long if_lit = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring s_lit = pMainFrame->gvTokenizer[m_index-1].getToken();
CString strLit = s_lit.data();
//matchToken(LITERAL);
getTokenizer();
//AfxMessageBox(_T("Antes de escribir"));
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd;
CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive();
CRichEditView* pView = (CRichEditView*) pChild->GetActiveView();
ASSERT(pView);
//Set output to current document
pView->GetRichEditCtrl().GetWindowText(currentDocView);
currentDocView = currentDocView + _T("\r\n") + strLit;
pView->GetRichEditCtrl().SetWindowText(currentDocView);
}
else if( m_lookahead == IDENTIFIER )
{
long if_ident = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring s_ident = pMainFrame->gvTokenizer[m_index-1].getToken();
CString strToken = s_ident.data();
//AfxMessageBox(_T("OUTPUT ID.............................VAR"));
//CString str;
//str.Format(_T("ID IFORM...%d " ), if_ident);
//AfxMessageBox(str);
//AfxMessageBox(strToken);
//Search in global variables
double dId = NumericVarSearch(if_ident, strToken);
if( dId == NOT_FOUND )
{
CString strLit = LiteralVarSearch( if_ident, strToken);
if( strLit != _T("NOT_FOUND") )
{
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd;
CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive();
CRichEditView* pView = (CRichEditView*) pChild->GetActiveView();
ASSERT(pView);
//Set output to current document
pView->GetRichEditCtrl().GetWindowText(currentDocView);
currentDocView = currentDocView + _T("\r\n") + strLit;
pView->GetRichEditCtrl().SetWindowText(currentDocView);
}
else
{
g_currentVarLoc = UNDEFINE;
CAipi_Error er;
CString strDesc = _T("Identifier [") + strToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
else
{
CString strNum;
strNum.Format(_T("%f"), dId);
CMDIFrameWnd* pFrame = (CMDIFrameWnd*)::AfxGetApp()->m_pMainWnd;
CMDIChildWnd* pChild = (CMDIChildWnd*) pFrame->MDIGetActive();
CRichEditView* pView = (CRichEditView*) pChild->GetActiveView();
ASSERT(pView);
//Set output to current document
pView->GetRichEditCtrl().GetWindowText(currentDocView);
currentDocView = currentDocView + _T("\r\n") + strNum;
pView->GetRichEditCtrl().SetWindowText(currentDocView);
}
//matchToken(IDENTIFIER);
getTokenizer();
}
else if( m_lookahead == _TEOF )
{
return;
}
else
{
break;
}
}
//matchToken(SEMICOLON);
}
}
int CAipi_ExpParserFile::cmd_input()
{
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
//matchToken(AIPI_INPUT);
getTokenizer();
if ( m_lookahead == RIGHT_OP )
{
while( m_lookahead != SEMICOLON && m_lookahead != _TEOF)
{
getTokenizer();
//matchToken(RIGHT_OP);
if( m_lookahead == IDENTIFIER )
{
long if_ident = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring s_ident = pMainFrame->gvTokenizer[m_index-1].getToken();
long pos = pMainFrame->gvTokenizer[m_index-1].getPos1();
CString strToken = s_ident.data();
//AfxMessageBox(_T("OUTPUT ID.............................VAR"));
//CString str;
//str.Format(_T("ID IFORM...%d " ), if_ident);
//AfxMessageBox(str);
//AfxMessageBox(strToken);
//Search in numeric variables
double dId = NumericVarSearch(if_ident, strToken);
if( dId == NOT_FOUND )
{
//Search in literal variables
CString strLit = LiteralVarSearch( if_ident, strToken);
if( strLit != _T("NOT_FOUND") )
{
pMainFrame->Cmd_OpenCommandDlgBar();
g_currentDataCateg = LITERAL;
g_currentId_IForm = if_ident;
g_currentLookahead = m_lookahead;
g_fcurrentPos = pos;
return AIPI_STOP;
}
else
{
g_currentVarLoc = UNDEFINE;
CAipi_Error er;
CString strDesc = _T("Identifier [") + strToken + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
else
{
pMainFrame->Cmd_OpenCommandDlgBar();
g_currentDataCateg = DIGIT;
g_currentId_IForm = if_ident;
g_currentLookahead = m_lookahead;
g_fcurrentPos = pos;
return AIPI_STOP;
}
getTokenizer();
//matchToken(IDENTIFIER);
}
else if( m_lookahead == _TEOF )
{
return _TEOF;
}
else
{
break;
}
}
//matchToken(SEMICOLON);
//Update current index
}
return P_SUCCESS;
}
void CAipi_ExpParserFile::cmd_input_continue()
{
AfxMessageBox(_T("Input Val"));
AfxMessageBox(g_currentCmdInput);
CString s;
s.Format(_T("Data Categ...%d " ), g_currentDataCateg);
AfxMessageBox(s);
s.Format(_T("Var Localization...%d " ), g_currentVarLoc);
AfxMessageBox(s);
if(g_currentDataCateg == LITERAL )
{
m_sCurrentId = g_currentCmdInput;
if( g_currentVarLoc == VAR_GLOBAL )
{
CAipi_STableGlobalLiteral lt;
lt.editSTableLiteralValue(g_currentId_IForm, m_sCurrentId);
lt.printSTableLiteral();
}
if( g_currentVarLoc == VAR_LOCAL )
{
CAipi_STableLocalLiteral lt;
lt.editSTableLiteralValue(g_currentId_IForm, m_sCurrentId);
lt.printSTableLiteral();
}
}
if( g_currentDataCateg == DIGIT )
{
AfxMessageBox(_T("DIGIT"));
m_dCurrentId = _tcstod(g_currentCmdInput, NULL);
if( g_currentVarLoc == VAR_GLOBAL )
{
AfxMessageBox(_T("EDIT DATA GLOBAL"));
CAipi_STableGlobalNumeric nt;
nt.editSTableNumericValue(g_currentId_IForm, m_dCurrentId);
nt.printSTableNumeric();
}
if( g_currentVarLoc == VAR_LOCAL )
{
AfxMessageBox(_T("EDIT DATA LOCAL"));
CAipi_STableLocalNumeric nt;
nt.editSTableNumericValue(g_currentId_IForm, m_dCurrentId);
nt.printSTableNumeric();
}
}
m_lookahead = g_currentLookahead;
if( m_lookahead == _TEOF )
{
return;
}
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
m_index = g_TkzIndex1 + 1;
m_endIndex = g_TkzIndex2;
getTokenizer();
//matchToken(IDENTIFIER);
getTokenizer();
//matchToken(SEMICOLON);
AfxMessageBox(_T("Out of Cmd Input Continue"));
ExecCmdSearch(g_currentFiredPM, m_index, m_endIndex);
CAipi_RETE_PNode pnode;
pnode.conflictResolution(g_CRStrategy);
//translation_unit();
/*
if( g_bStopFlag != true )
{
fclose(g_fp);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndStatusBar.ResetBar(1, TRUE);
pMainFrame->m_wndStatusBar.SetPaneText( 0, _T("Process finished"), RGB(0,0,0), TRUE);
}
*/
}
void CAipi_ExpParserFile::ctrl_jukebox()
{
AfxMessageBox(_T("ENTRO JUKEBOXDLG"));
bool bPlayVideo = false;
bool bShowWnd = false;
bool bInput = false;
bool bPath = false;
CString szPath = _T("");
getTokenizer();
//matchToken(AIPI_CTRL_JUKEBOX);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
while( m_lookahead != CLOSE_PARENTHESIS && m_lookahead != _TEOF )
{
if ( m_lookahead == AIPI_SHOWCTRL
|| m_lookahead == AIPI_PLAY
|| m_lookahead == AIPI_INPUTVAR
|| m_lookahead == AIPI_PATH
)
{
if(m_lookahead == AIPI_SHOWCTRL )
{
getTokenizer();
//matchToken(AIPI_SHOWCTRL);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bShowWnd = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bShowWnd = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_PLAY )
{
getTokenizer();
//matchToken(AIPI_PLAY);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bPlayVideo = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bPlayVideo = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_INPUTVAR )
{
getTokenizer();
//matchToken(AIPI_INPUTVAR);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bInput = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bInput = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_PATH )
{
getTokenizer();
//matchToken(AIPI_PATH);
getTokenizer();
//matchToken(EQUAL);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
tstring strPath = pMainFrame->gvTokenizer[m_index-1].getToken();
szPath = strPath.data();
if( szPath != _T("") )
{
bPath = true;
}
getTokenizer();
//matchToken(LITERAL);
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else
{
break;
}
}
getTokenizer();
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
//matchToken(SEMICOLON);
CString str;
str.Format(_T("ShowWnd...%d " ), bShowWnd);
AfxMessageBox(str);
if( bShowWnd )
{
AfxMessageBox(_T("LOOK CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_OpenJukeBoxDlg();
if( bPath )
{
pMainFrame->Cmd_PathJukeBoxDlg(szPath);
if( bPlayVideo )
{
pMainFrame->Cmd_PlayJukeBoxDlg();
AfxMessageBox(_T("PLAY CTRL"));
if( bInput)
{
pMainFrame->Cmd_OpenCommandDlgBar();
}
}
}
}
else
{
AfxMessageBox(_T("CLOSE CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_CloseJukeBoxDlg();
}
}
void CAipi_ExpParserFile::ctrl_mediaplayer()
{
AfxMessageBox(_T("ENTRO MEDIAPLAYERDLG"));
bool bPlayVideo = false;
bool bShowWnd = false;
bool bInput = false;
bool bPath = false;
CString szPath = _T("");
//matchToken(AIPI_CTRL_MEDIAPLAYER);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
getTokenizer();
while( m_lookahead != CLOSE_PARENTHESIS && m_lookahead != _TEOF )
{
if ( m_lookahead == AIPI_SHOWCTRL
|| m_lookahead == AIPI_PLAY
|| m_lookahead == AIPI_INPUTVAR
|| m_lookahead == AIPI_PATH
)
{
if(m_lookahead == AIPI_SHOWCTRL )
{
//matchToken(AIPI_SHOWCTRL);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
bShowWnd = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
bShowWnd = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else if( m_lookahead == AIPI_PLAY )
{
//matchToken(AIPI_PLAY);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
bPlayVideo = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
bPlayVideo = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else if( m_lookahead == AIPI_INPUTVAR )
{
//matchToken(AIPI_INPUTVAR);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
bInput = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
bInput = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else if( m_lookahead == AIPI_PATH )
{
//matchToken(AIPI_PATH);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
tstring strPath = pMainFrame->gvTokenizer[m_index-1].getToken();
szPath = strPath.data();
if( szPath != _T("") )
{
bPath = true;
}
//matchToken(LITERAL);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else
{
break;
}
}
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
//matchToken(SEMICOLON);
getTokenizer();
if( bShowWnd )
{
AfxMessageBox(_T("LOOK CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_OpenMediaPlayerDlg();
if( bPath )
{
pMainFrame->Cmd_PathMediaPlayerDlg(szPath);
if( bPlayVideo )
{
pMainFrame->Cmd_PlayMediaPlayerDlg();
AfxMessageBox(_T("PLAY CTRL"));
if( bInput)
{
pMainFrame->Cmd_OpenCommandDlgBar();
}
}
}
}
else
{
AfxMessageBox(_T("CLOSE CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_CloseMediaPlayerDlg();
}
}
void CAipi_ExpParserFile::ctrl_imagefilter()
{
AfxMessageBox(_T("ENTRO IMAGEFILTERDLG"));
bool bShowWnd = false;
bool bInput = false;
bool bPath = false;
CString szPath = _T("");
getTokenizer();
//matchToken(AIPI_CTRL_IMAGEFILTER);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
while( m_lookahead != CLOSE_PARENTHESIS && m_lookahead != NUL )
{
if ( m_lookahead == AIPI_SHOWCTRL
|| m_lookahead == AIPI_INPUTVAR
|| m_lookahead == AIPI_PATH
)
{
if(m_lookahead == AIPI_SHOWCTRL )
{
getTokenizer();
//matchToken(AIPI_SHOWCTRL);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bShowWnd = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bShowWnd = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_INPUTVAR )
{
getTokenizer();
//matchToken(AIPI_INPUTVAR);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bInput = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bInput = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_PATH )
{
getTokenizer();
//matchToken(AIPI_PATH);
getTokenizer();
//matchToken(EQUAL);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
tstring strPath = pMainFrame->gvTokenizer[m_index-1].getToken();
szPath = strPath.data();
if( szPath != _T("") )
{
bPath = true;
}
getTokenizer();
//matchToken(LITERAL);
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else
{
break;
}
}
getTokenizer();
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
//matchToken(SEMICOLON);
if( bShowWnd )
{
AfxMessageBox(_T("LOOK CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_OpenImageFilterDlg();
if( bPath )
{
pMainFrame->Cmd_PathImageFilterDlg(szPath);
if( bInput)
{
pMainFrame->Cmd_OpenCommandDlgBar();
}
}
}
else
{
AfxMessageBox(_T("CLOSE CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_CloseImageFilterDlg();
}
}
int CAipi_ExpParserFile::ctrl_listoption()
{
AfxMessageBox(_T("ENTRO LISTOPTION CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
CAipi_Tokenizer tkz;
bool bShowWnd = false;
bool bInput = false;
bool bInsert = false;
long posTk = 0;
long iformTk = UNDEFINE;
tstring strTk = _T("");
CString szTk = _T("");
CString szItem = _T("");
CString szTip = _T("");
std::vector <CString> vListItems;
std::vector <CString> vListTips;
vListItems.clear();
vListTips.clear();
getTokenizer();
//matchToken(AIPI_CTRL_LISTOPTION);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
while( m_lookahead != CLOSE_PARENTHESIS && m_lookahead != _TEOF )
{
if ( m_lookahead == AIPI_SHOWCTRL
|| m_lookahead == AIPI_INSERT
|| m_lookahead == AIPI_INPUTVAR
)
{
if(m_lookahead == AIPI_SHOWCTRL )
{
getTokenizer();
//matchToken(AIPI_SHOWCTRL);
getTokenizer();
//matchToken(EQUAL);
if( m_lookahead == AIPI_TRUE )
{
getTokenizer();
//matchToken(AIPI_TRUE);
bShowWnd = true;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
else if ( m_lookahead == AIPI_FALSE)
{
getTokenizer();
//matchToken(AIPI_FALSE);
bShowWnd = false;
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else if( m_lookahead == AIPI_INPUTVAR )
{
getTokenizer();
//matchToken(AIPI_INPUTVAR);
getTokenizer();
//matchToken(EQUAL);
iformTk = pMainFrame->gvTokenizer[m_index-1].getIntForm();
strTk = pMainFrame->gvTokenizer[m_index-1].getToken();
szTk = strTk.data();
posTk = pMainFrame->gvTokenizer[m_index-1].getPos1();
if( szTk != _T("") )
{
bInput = true;
}
AfxMessageBox(_T("INPUT ID.............................VAR"));
CString str;
str.Format(_T("ID IFORM...%d " ), iformTk);
AfxMessageBox(str);
AfxMessageBox(szTk);
getTokenizer();
//matchToken(IDENTIFIER);
}
else if( m_lookahead == AIPI_INSERT )
{
bInsert = true;
getTokenizer();
//matchToken(AIPI_INSERT);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
//matchToken(OPEN_BRACE);
while( m_lookahead != CLOSE_BRACE )
{
if( m_lookahead == OPEN_PARENTHESIS )
{
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
iformTk = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring strItem = pMainFrame->gvTokenizer[m_index-1].getToken();
szItem = strItem.data();
posTk = pMainFrame->gvTokenizer[m_index-1].getPos1();
//AfxMessageBox(_T("AIPI INSERT ITEM:::::::::::::::"));
//AfxMessageBox(szItem);
if( szItem != _T("") )
{
vListItems.push_back(szItem);
}
getTokenizer();
//matchToken(LITERAL);
getTokenizer();
//matchToken(COMMA);
iformTk = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring strTip = pMainFrame->gvTokenizer[m_index-1].getToken();
szTip = strTip.data();
posTk = pMainFrame->gvTokenizer[m_index-1].getPos1();
//AfxMessageBox(_T("AIPI INSERT TIP:::::::::::::::"));
//AfxMessageBox(szItem);
if( szTip != _T("") )
{
vListTips.push_back(szTip);
}
else
{
vListTips.push_back(_T(""));
}
getTokenizer();
//matchToken(LITERAL);
getTokenizer();
//matchToken(CLOSE_PARENTHESIS);
if( m_lookahead != CLOSE_BRACE)
{
getTokenizer();
//matchToken(COMMA);
}
}
else
{
iformTk = pMainFrame->gvTokenizer[m_index-1].getIntForm();
tstring strItem = pMainFrame->gvTokenizer[m_index-1].getToken();
szItem = strItem.data();
posTk = pMainFrame->gvTokenizer[m_index-1].getPos1();
//AfxMessageBox(_T("AIPI INSERT ITEM:::::::::::::::"));
//AfxMessageBox(szItem);
if( szItem != _T("") )
{
vListItems.push_back(szItem);
}
getTokenizer();
//matchToken(LITERAL);
if( m_lookahead != CLOSE_BRACE)
{
getTokenizer();
//matchToken(COMMA);
}
}
}
getTokenizer();
//matchToken(CLOSE_BRACE);
if( m_lookahead != CLOSE_PARENTHESIS )
{
getTokenizer();
//matchToken(COMMA);
}
}
}
else
{
break;
}
}
getTokenizer();
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
//matchToken(SEMICOLON);
pMainFrame->m_wndListOptionCtrl.ResetListBox();
//Check if CImageList was already created
if( g_ImageListFlag != true )
{
pMainFrame->m_wndListOptionCtrl.SetImageList();
g_ImageListFlag = true;
}
/*
//print vector
for(int i = 0; i<vListItems.size(); ++i )
{
CString sItem = vListItems.at(i);
pMainFrame->m_wndOutputTabView.AddMsg1(sItem);
}
*/
if( bShowWnd )
{
AfxMessageBox(_T("LOOK CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_OpenListOptionCtrl();
if( bInsert )
{
CString sItem;
CString sTip;
for(int i = 0; i<vListItems.size(); ++i )
{
sItem = vListItems.at(i);
//AfxMessageBox(_T("ITEM:::::::::::::::"));
//AfxMessageBox(sItem);
if( !vListTips.empty() )
{
sTip = vListTips.at(i);
}
LPCTSTR lpcItem = (LPCTSTR)sItem;
LPCTSTR lpcTip = (LPCTSTR)sTip;
pMainFrame->Cmd_InsertListOptionCtrl(lpcItem, lpcTip);
}
if( bInput)
{
//Search in numeric variables
double dId = NumericVarSearch(iformTk, szTk);
if( dId == NOT_FOUND )
{
//Search in literal variables
CString szLit = LiteralVarSearch( iformTk, szTk);
if( szLit != _T("NOT_FOUND") )
{
AfxMessageBox(_T("Found var Literal"));
g_currentDataCateg = LITERAL;
g_currentId_IForm = iformTk;
//g_currentLookahead = IDENTIFIER;
g_currentLookahead = m_lookahead;
g_fcurrentPos = posTk;
return AIPI_STOP;
}
else
{
CAipi_Error er;
CString strDesc = _T("Identifier [") + szTk + _T("] was not found.");
er.displayFileError(NOT_DECLARE, SEMANT_ERROR, strDesc);
}
}
else
{
AfxMessageBox(_T("Found var Numeric"));
g_currentDataCateg = DIGIT;
g_currentId_IForm = iformTk;
//g_currentLookahead = IDENTIFIER;
g_currentLookahead = m_lookahead;
g_fcurrentPos = posTk;
return AIPI_STOP;
}
}
}
}
else
{
AfxMessageBox(_T("CLOSE CTRL"));
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->Cmd_CloseListOptionCtrl();
}
return P_SUCCESS;
}
void CAipi_ExpParserFile::ctrl_listoption_continue()
{
AfxMessageBox(_T("Input Val"));
AfxMessageBox(g_currentCmdInput);
CString s;
s.Format(_T("Data Categ...%d " ), g_currentDataCateg);
AfxMessageBox(s);
s.Format(_T("Var Localization...%d " ), g_currentVarLoc);
AfxMessageBox(s);
if(g_currentDataCateg == LITERAL )
{
m_sCurrentId = g_currentCmdInput;
if( g_currentVarLoc == VAR_GLOBAL )
{
CAipi_STableGlobalLiteral lt;
lt.editSTableLiteralValue(g_currentId_IForm, m_sCurrentId);
lt.printSTableLiteral();
}
if( g_currentVarLoc == VAR_LOCAL )
{
CAipi_STableLocalLiteral lt;
lt.editSTableLiteralValue(g_currentId_IForm, m_sCurrentId);
lt.printSTableLiteral();
}
}
if( g_currentDataCateg == DIGIT )
{
AfxMessageBox(_T("DIGIT"));
m_dCurrentId = _tcstod(g_currentCmdInput, NULL);
if( g_currentVarLoc == VAR_GLOBAL )
{
AfxMessageBox(_T("EDIT DATA GLOBAL"));
CAipi_STableGlobalNumeric nt;
nt.editSTableNumericValue(g_currentId_IForm, m_dCurrentId);
nt.printSTableNumeric();
}
if( g_currentVarLoc == VAR_LOCAL )
{
AfxMessageBox(_T("EDIT DATA LOCAL"));
CAipi_STableLocalNumeric nt;
nt.editSTableNumericValue(g_currentId_IForm, m_dCurrentId);
nt.printSTableNumeric();
}
}
m_lookahead = g_currentLookahead;
if( m_lookahead == _TEOF )
{
return;
}
CString str;
str.Format(_T("Look Ahead...%d " ), m_lookahead);
AfxMessageBox(str);
m_index = g_TkzIndex1 + 1;
m_endIndex = g_TkzIndex2;
AfxMessageBox(_T("Out of List Option Input Continue"));
ExecCmdSearch(g_currentFiredPM, m_index, m_endIndex);
CAipi_RETE_PNode pnode;
pnode.conflictResolution(g_CRStrategy);
//translation_unit();
/*
if( g_bStopFlag != true )
{
fclose(g_fp);
CMainFrame* pMainFrame = (CMainFrame*)::AfxGetMainWnd();
pMainFrame->m_wndStatusBar.ResetBar(1, TRUE);
pMainFrame->m_wndStatusBar.SetPaneText( 0, _T("Process finished"), RGB(0,0,0), TRUE);
}
*/
}
void CAipi_ExpParserFile::ctrl_oledb()
{
//matchToken(AIPI_CTRL_OLEDB);
getTokenizer();
//matchToken(OPEN_PARENTHESIS);
getTokenizer();
while( m_lookahead != CLOSE_PARENTHESIS && m_lookahead != NUL )
{
if ( m_lookahead == AIPI_SHOWCTRL
|| m_lookahead == AIPI_INPUTVAR
|| m_lookahead == AIPI_SHOWTABLES
)
{
if(m_lookahead == AIPI_SHOWCTRL )
{
//matchToken(AIPI_SHOWCTRL);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else if( m_lookahead == AIPI_SHOWTABLES )
{
//matchToken(AIPI_SHOWTABLES);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
else if( m_lookahead == AIPI_INPUTVAR )
{
//matchToken(AIPI_INPUTVAR);
getTokenizer();
//matchToken(EQUAL);
getTokenizer();
if( m_lookahead == AIPI_TRUE )
{
//matchToken(AIPI_TRUE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
else if ( m_lookahead == AIPI_FALSE)
{
//matchToken(AIPI_FALSE);
getTokenizer();
if( m_lookahead != CLOSE_PARENTHESIS )
{
//matchToken(COMMA);
getTokenizer();
}
}
}
}
else
{
break;
}
}
//matchToken(CLOSE_PARENTHESIS);
getTokenizer();
}
void CAipi_ExpParserFile::cmd_db_open_parameter_list()
{
cmd_db_open_parameter();
if( m_lookahead == COMMA )
{
while ( m_lookahead == COMMA )
{
getTokenizer();
//matchToken(COMMA);
cmd_db_open_parameter();
}
}
}
void CAipi_ExpParserFile::cmd_db_close()
{
getTokenizer();
//matchToken(AIPI_DB_CLOSE);
}
| [
"[email protected]"
]
| [
[
[
1,
4529
]
]
]
|
af3cca2e464331b10b78fe03acd6787388ba5e14 | 40b507c2dde13d14bb75ee1b3c16b4f3f82912d1 | /core/smn_bitbuffer.cpp | 949717e222f07bd812a23305b4d6336058dd4b4b | []
| no_license | Nephyrin/-furry-octo-nemesis | 5da2ef75883ebc4040e359a6679da64ad8848020 | dd441c39bd74eda2b9857540dcac1d98706de1de | refs/heads/master | 2016-09-06T01:12:49.611637 | 2008-09-14T08:42:28 | 2008-09-14T08:42:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,776 | cpp | /**
* vim: set ts=4 :
* =============================================================================
* SourceMod
* Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved.
* =============================================================================
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, version 3.0, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, AlliedModders LLC gives you permission to link the
* code of this program (as well as its derivative works) to "Half-Life 2," the
* "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software
* by the Valve Corporation. You must obey the GNU General Public License in
* all respects for all other code used. Additionally, AlliedModders LLC grants
* this exception to all derivative works. AlliedModders LLC defines further
* exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007),
* or <http://www.sourcemod.net/license.php>.
*
* Version: $Id$
*/
#include "sourcemod.h"
#include "HandleSys.h"
#include <bitbuf.h>
#include <vector.h>
static cell_t smn_BfWriteBool(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteOneBit(params[2]);
return 1;
}
static cell_t smn_BfWriteByte(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteByte(params[2]);
return 1;
}
static cell_t smn_BfWriteChar(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteChar(params[2]);
return 1;
}
static cell_t smn_BfWriteShort(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteShort(params[2]);
return 1;
}
static cell_t smn_BfWriteWord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteWord(params[2]);
return 1;
}
static cell_t smn_BfWriteNum(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteLong(static_cast<long>(params[2]));
return 1;
}
static cell_t smn_BfWriteFloat(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteFloat(sp_ctof(params[2]));
return 1;
}
static cell_t smn_BfWriteString(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
int err;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
char *str;
if ((err=pCtx->LocalToString(params[2], &str)) != SP_ERROR_NONE)
{
pCtx->ThrowNativeErrorEx(err, NULL);
return 0;
}
pBitBuf->WriteString(str);
return 1;
}
static cell_t smn_BfWriteEntity(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteShort(params[2]);
return 1;
}
static cell_t smn_BfWriteAngle(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteBitAngle(sp_ctof(params[2]), params[3]);
return 1;
}
static cell_t smn_BfWriteCoord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pBitBuf->WriteBitCoord(sp_ctof(params[2]));
return 1;
}
static cell_t smn_BfWriteVecCoord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pVec;
pCtx->LocalToPhysAddr(params[2], &pVec);
Vector vec(sp_ctof(pVec[0]), sp_ctof(pVec[1]), sp_ctof(pVec[2]));
pBitBuf->WriteBitVec3Coord(vec);
return 1;
}
static cell_t smn_BfWriteVecNormal(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pVec;
pCtx->LocalToPhysAddr(params[2], &pVec);
Vector vec(sp_ctof(pVec[0]), sp_ctof(pVec[1]), sp_ctof(pVec[2]));
pBitBuf->WriteBitVec3Normal(vec);
return 1;
}
static cell_t smn_BfWriteAngles(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_write *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_WrBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pAng;
pCtx->LocalToPhysAddr(params[2], &pAng);
QAngle ang(sp_ctof(pAng[0]), sp_ctof(pAng[1]), sp_ctof(pAng[2]));
pBitBuf->WriteBitAngles(ang);
return 1;
}
static cell_t smn_BfReadBool(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadOneBit() ? 1 : 0;
}
static cell_t smn_BfReadByte(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadByte();
}
static cell_t smn_BfReadChar(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadChar();
}
static cell_t smn_BfReadShort(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadShort();
}
static cell_t smn_BfReadWord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadWord();
}
static cell_t smn_BfReadNum(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return static_cast<cell_t>(pBitBuf->ReadLong());
}
static cell_t smn_BfReadFloat(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return sp_ftoc(pBitBuf->ReadFloat());
}
static cell_t smn_BfReadString(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
int numChars = 0;
char *buf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
pCtx->LocalToPhysAddr(params[2], (cell_t **)&buf);
pBitBuf->ReadString(buf, params[3], params[4] ? true : false, &numChars);
if (pBitBuf->IsOverflowed())
{
return -numChars - 1;
}
return numChars;
}
static cell_t smn_BfReadEntity(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->ReadShort();
}
static cell_t smn_BfReadAngle(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return sp_ftoc(pBitBuf->ReadBitAngle(params[2]));
}
static cell_t smn_BfReadCoord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return sp_ftoc(pBitBuf->ReadBitCoord());
}
static cell_t smn_BfReadVecCoord(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pVec;
pCtx->LocalToPhysAddr(params[2], &pVec);
Vector vec;
pBitBuf->ReadBitVec3Coord(vec);
pVec[0] = sp_ftoc(vec.x);
pVec[1] = sp_ftoc(vec.y);
pVec[2] = sp_ftoc(vec.z);
return 1;
}
static cell_t smn_BfReadVecNormal(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pVec;
pCtx->LocalToPhysAddr(params[2], &pVec);
Vector vec;
pBitBuf->ReadBitVec3Normal(vec);
pVec[0] = sp_ftoc(vec.x);
pVec[1] = sp_ftoc(vec.y);
pVec[2] = sp_ftoc(vec.z);
return 1;
}
static cell_t smn_BfReadAngles(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
cell_t *pAng;
pCtx->LocalToPhysAddr(params[2], &pAng);
QAngle ang;
pBitBuf->ReadBitAngles(ang);
pAng[0] = sp_ftoc(ang.x);
pAng[1] = sp_ftoc(ang.y);
pAng[2] = sp_ftoc(ang.z);
return 1;
}
static cell_t smn_BfGetNumBytesLeft(IPluginContext *pCtx, const cell_t *params)
{
Handle_t hndl = static_cast<Handle_t>(params[1]);
HandleError herr;
HandleSecurity sec;
bf_read *pBitBuf;
sec.pOwner = NULL;
sec.pIdentity = g_pCoreIdent;
if ((herr=g_HandleSys.ReadHandle(hndl, g_RdBitBufType, &sec, (void **)&pBitBuf))
!= HandleError_None)
{
return pCtx->ThrowNativeError("Invalid bit buffer handle %x (error %d)", hndl, herr);
}
return pBitBuf->GetNumBitsLeft() >> 3;
}
REGISTER_NATIVES(bitbufnatives)
{
{"BfWriteBool", smn_BfWriteBool},
{"BfWriteByte", smn_BfWriteByte},
{"BfWriteChar", smn_BfWriteChar},
{"BfWriteShort", smn_BfWriteShort},
{"BfWriteWord", smn_BfWriteWord},
{"BfWriteNum", smn_BfWriteNum},
{"BfWriteFloat", smn_BfWriteFloat},
{"BfWriteString", smn_BfWriteString},
{"BfWriteEntity", smn_BfWriteEntity},
{"BfWriteAngle", smn_BfWriteAngle},
{"BfWriteCoord", smn_BfWriteCoord},
{"BfWriteVecCoord", smn_BfWriteVecCoord},
{"BfWriteVecNormal", smn_BfWriteVecNormal},
{"BfWriteAngles", smn_BfWriteAngles},
{"BfReadBool", smn_BfReadBool},
{"BfReadByte", smn_BfReadByte},
{"BfReadChar", smn_BfReadChar},
{"BfReadShort", smn_BfReadShort},
{"BfReadWord", smn_BfReadWord},
{"BfReadNum", smn_BfReadNum},
{"BfReadFloat", smn_BfReadFloat},
{"BfReadString", smn_BfReadString},
{"BfReadEntity", smn_BfReadEntity},
{"BfReadAngle", smn_BfReadAngle},
{"BfReadCoord", smn_BfReadCoord},
{"BfReadVecCoord", smn_BfReadVecCoord},
{"BfReadVecNormal", smn_BfReadVecNormal},
{"BfReadAngles", smn_BfReadAngles},
{"BfGetNumBytesLeft", smn_BfGetNumBytesLeft},
{NULL, NULL}
};
| [
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
1
],
[
31,
33
],
[
36,
486
],
[
488,
499
],
[
503,
503
],
[
505,
506
],
[
508,
653
],
[
673,
702
],
[
704,
705
]
],
[
[
2,
2
],
[
4,
5
],
[
7,
7
],
[
11,
11
],
[
16,
16
],
[
19,
19
],
[
28,
30
],
[
487,
487
],
[
500,
502
],
[
504,
504
],
[
507,
507
]
],
[
[
3,
3
],
[
6,
6
],
[
8,
10
],
[
12,
15
],
[
17,
18
],
[
20,
27
],
[
34,
35
]
],
[
[
654,
672
],
[
703,
703
]
]
]
|
ac8d2fed6abbfa015d117ab80c0d1bb0c420d356 | 016774685beb74919bb4245d4d626708228e745e | /lib/Collide/ozcollide/aabbtreeaabb_io.cpp | 6210ae89bec1e0c9e8b2058315cbf881a6f6ce61 | []
| no_license | sutuglon/Motor | 10ec08954d45565675c9b53f642f52f404cb5d4d | 16f667b181b1516dc83adc0710f8f5a63b00cc75 | refs/heads/master | 2020-12-24T16:59:23.348677 | 2011-12-20T20:44:19 | 2011-12-20T20:44:19 | 1,925,770 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,960 | cpp |
ENTER_NAMESPACE_OZCOLLIDE
ERR AABBTreeAABB::loadBinary(const char *_fileName, AABBTreeAABB **_tree)
{
DataIn file;
ERR err;
if (!file.open(_fileName))
return ERR_CANNOT_OPEN;
err = loadBinary(file, _tree);
if (err)
return err;
file.close();
return NOERR;
}
ERR AABBTreeAABB::loadBinary(DataIn &_file, AABBTreeAABB **_tree)
{
char chunk[4];
int chunkSize;
_file.read(chunk, 4);
if (MID(chunk[0], chunk[1],chunk[2], chunk[3]) != MID('A', 'A', 'B', 'B'))
return ERR_INVALID_FORMAT;
chunkSize = _file.readDword();
char leafType = _file.readByte();
if (leafType != 2)
return ERR_INVALID_FORMAT;
char leafDepth = _file.readByte();
int nbNodes = _file.readDword();
int nbLeafs = _file.readDword();
AABBTreeAABB *t;
t = new AABBTreeAABB(leafDepth);
t->leafs_ = new AABBTreeAABBLeaf[nbLeafs];
t->root_ = new AABBTreeNode[nbNodes];
while(chunkSize > 8) {
char id[4];
_file.read(id, 4);
int sc = MID(id[0], id[1], id[2], id[3]);
int scSize = _file.readDword();
int pos0 = _file.tell();
if (sc == MID('N','O','D','S'))
t->readNODSchunk(_file, scSize, nbNodes);
else if (sc == MID('L','E','F','S'))
t->readLEFSchunk(_file, scSize, nbLeafs);
else
_file.advance(scSize);
int pos1 = _file.tell();
if (pos1 - pos0 != scSize)
_file.seek(pos0 + scSize);
chunkSize -= scSize + 8;
}
*_tree = t;
return NOERR;
}
void AABBTreeAABB::readNODSchunk(DataIn &_file, int _chunkSize, int _nbNodes)
{
int i;
for (i = 0; i < _nbNodes; i++) {
AABBTreeNode &node = root_[i];
node.aabb.center.x = _file.readFloat();
node.aabb.center.y = _file.readFloat();
node.aabb.center.z = _file.readFloat();
node.aabb.extent.x = _file.readFloat();
node.aabb.extent.y = _file.readFloat();
node.aabb.extent.z = _file.readFloat();
int leftID = _file.readDword();
int rightID = _file.readDword();
if (leftID == -1)
node.left = NULL;
else {
int isLeaf = leftID >> 31;
int index = leftID & 0x7fffffff;
if (isLeaf)
node.left = &leafs_[index];
else
node.left = &root_[index];
}
if (rightID == -1)
node.right = NULL;
else {
int isLeaf = rightID >> 31;
int index = rightID & 0x7fffffff;
if (isLeaf)
node.right = &leafs_[index];
else
node.right = &root_[index];
}
}
}
void AABBTreeAABB::readLEFSchunk(DataIn &_file, int _chunkSize, int _nbLeafs)
{
int i, j;
for (i = 0; i < _nbLeafs; i++) {
AABBTreeAABBLeaf &leaf = leafs_[i];
leaf.aabb.center.x = _file.readFloat();
leaf.aabb.center.y = _file.readFloat();
leaf.aabb.center.z = _file.readFloat();
leaf.aabb.extent.x = _file.readFloat();
leaf.aabb.extent.y = _file.readFloat();
leaf.aabb.extent.z = _file.readFloat();
leaf.left = NULL;
leaf.right = NULL;
int nbBoxes = _file.readDword();
leaf.nbBoxes = nbBoxes;
leaf.boxes = new Box[nbBoxes];
for (j = 0; j < nbBoxes; j++) {
Box &b = (Box &) leaf.boxes[j];
b.center.x = _file.readFloat();
b.center.y = _file.readFloat();
b.center.z = _file.readFloat();
b.extent.x = _file.readFloat();
b.extent.y = _file.readFloat();
b.extent.z = _file.readFloat();
}
}
}
ERR AABBTreeAABB::saveBinary(const char *_fname)
{
DataOut file;
ERR err;
if (!file.open(_fname))
return ERR_CANNOT_OPEN;
err = saveBinary(file);
if (err)
return err;
file.close();
return NOERR;
}
ERR AABBTreeAABB::saveBinary(DataOut &_file)
{
int i, j;
_file.writeStr("AABB");
int posBBT = _file.tell();
_file.advance(4);
int size = 0;
size += _file.writeByte(2);
nbNodes_ = getNbNodes();
nbLeafs_ = getNbLeafs();
size += _file.writeByte(leafDepth_);
size += _file.writeDword(nbNodes_);
size += _file.writeDword(nbLeafs_);
size += _file.writeStr("NODS");
size += _file.writeDword((24 + 8) * nbNodes_);
for (i = 0; i < nbNodes_; i++) {
AABBTreeNode *node = &root_[i];
size += _file.writeFloat(node->aabb.center.x);
size += _file.writeFloat(node->aabb.center.y);
size += _file.writeFloat(node->aabb.center.z);
size += _file.writeFloat(node->aabb.extent.x);
size += _file.writeFloat(node->aabb.extent.y);
size += _file.writeFloat(node->aabb.extent.z);
const AABBTreeNode *left = node->left;
const AABBTreeNode *right = node->right;
if (left) {
int diff = left - root_;
if (diff < 0 || diff >= nbNodes_) {
diff = ((AABBTreeAABBLeaf*) left) - leafs_;
diff |= 0x80000000;
}
size += _file.writeDword(diff);
}
else
size += _file.writeDword(-1);
if (right) {
int diff = right - root_;
if (diff < 0 || diff >= nbNodes_) {
diff = ((AABBTreeAABBLeaf*) right) - leafs_;
diff |= 0x80000000;
}
size += _file.writeDword(diff);
}
else
size += _file.writeDword(-1);
}
size += _file.writeStr("LEFS");
int posLEFS = _file.tell();
_file.advance(4);
int sizeLEFS = 0;
for (i = 0; i < nbLeafs_; i++) {
AABBTreeAABBLeaf *leaf = &leafs_[i];
_file.writeFloat(leaf->aabb.center.x);
_file.writeFloat(leaf->aabb.center.y);
_file.writeFloat(leaf->aabb.center.z);
_file.writeFloat(leaf->aabb.extent.x);
_file.writeFloat(leaf->aabb.extent.y);
_file.writeFloat(leaf->aabb.extent.z);
size += 24; sizeLEFS += 24;
_file.writeDword(leaf->nbBoxes);
size += 4; sizeLEFS += 4;
int nbBoxes = leaf->nbBoxes;
for (j = 0; j < nbBoxes; j++) {
const Box &b = leaf->boxes[j];
_file.writeFloat(b.center.x);
_file.writeFloat(b.center.y);
_file.writeFloat(b.center.z);
_file.writeFloat(b.extent.x);
_file.writeFloat(b.extent.y);
_file.writeFloat(b.extent.z);
}
size += nbBoxes * 24;
sizeLEFS += nbBoxes * 24;
}
_file.seek(posLEFS);
_file.writeDword(sizeLEFS);
_file.seek(posBBT);
_file.writeDword(size);
return NOERR;
}
LEAVE_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
258
]
]
]
|
62c96a8d2a25ca5d242b803de986997e98d8d310 | 52f70251d04ca4f42ba3cb991727003a87d2c358 | /src/pragma/geometry/UnitTest.cpp | ffce5b64718fabbbf68e0e0c4522d16fd08aae04 | [
"MIT"
]
| permissive | vicutrinu/pragma-studios | 71a14e39d28013dfe009014cb0e0a9ca16feb077 | 181fd14d072ccbb169fa786648dd942a3195d65a | refs/heads/master | 2016-09-06T14:57:33.040762 | 2011-09-11T23:20:24 | 2011-09-11T23:20:24 | 2,151,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,262 | cpp | #include <pragma/geometry/types.h>
#include <pragma/geometry/intersection/ray_triangle.h>
#include <pragma/debug/debug.h>
namespace pragma
{
bool DoIntersectionTests()
{
vector3f lA(-1,0,0);
vector3f lB(0,1,0);
vector3f lC(1,0,0);
// Estos 3 puntos forman el triangulo:
// .
// / \
// / \
// / \
// / \
// .---------.
// alineado con el plano XY (Z = 0)
vector2f lOut;
float lDistanceOut;
bool lRetVal = true;
if(lRetVal)
{
vector3f lOrigin(0,0.5,-1);
vector3f lDir(0,0,1);
lRetVal = IntersectRayTriangle(lA, lB, lC, lOrigin, lDir, lOut, lDistanceOut);
vector3f lIntersection = lA + ( (lB-lA) * lOut.x +
(lC-lA) * lOut.y );
pragma_error_if(!lRetVal, "IntersectRayTriangle is not working properly");
}
if(lRetVal)
{
vector3f lOrigin(0.0001f,0,2);
vector3f lDir(0,0,-1);
IntersectRayTriangle(lA, lB, lC, lOrigin, lDir, float(1), lOut, lDistanceOut);
IntersectRayTriangle(lA, lB, lC, lOrigin, lDir);
IntersectRayTriangle_2Sided(lA, lB, lC, lOrigin, lDir, lOut, lDistanceOut);
IntersectRayTriangle_2Sided(lA, lB, lC, lOrigin, lDir, float(1), lOut, lDistanceOut);
}
return lRetVal;
}
}
| [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
e7501bcca95141625a4a2d778ced94e0d2a37727 | 7b6292601467a32ab84e3f2c35801226dedb1490 | /Timer/TimerApp.h | 66ac280bd6e09e37b12c5d9cfdac546bb6dd9531 | []
| no_license | mareqq/mareq-timer | b4bc9134573fec6d554b7da51dc5d9350cc73581 | 180a60d7e1d8190f80b05177a0270cc0309e7822 | refs/heads/master | 2021-01-21T07:39:46.790716 | 2008-09-02T13:56:09 | 2008-09-02T13:56:09 | 32,898,637 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | h | #pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "TimerWnd.h"
#define ELEMS(x) (sizeof(x)/sizeof(*x))
class CTimerApp : public CWinApp
{
public:
CTimerApp();
protected:
virtual BOOL InitInstance();
DECLARE_MESSAGE_MAP()
protected:
CTimerWnd m_TimerWnd;
};
extern CTimerApp theApp; | [
"mareqq@62a7fa73-be4e-0410-9e8d-e136552d7b79"
]
| [
[
[
1,
25
]
]
]
|
daebf6474e2e38d9ba0f690342a355d6a401c390 | 59f1959abb023c7e0a7ce2a347c250d799339fd8 | /Engine/Core/OutputDataStream.h | 242449a5f9c970a2c2f85b06b2719242a5850128 | []
| no_license | ghsoftco/scenegallery | 78580a8aaf02a0c7ccc2687bc4a40c1873da5715 | 965fabdb39cbdd7c9735aaa5daab9f617bf020cf | refs/heads/master | 2021-01-10T11:18:30.032732 | 2011-10-14T20:56:27 | 2011-10-14T20:56:27 | 47,763,913 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,871 | h | /*
OutputDataStream.h
Written by Matthew Fisher
OutputDataStream class. An ostream but for binary data.
*/
#pragma once
class OutputDataStream
{
public:
OutputDataStream();
~OutputDataStream();
void FreeMemory();
//
// Saves stream to a file
//
void SaveToFile(const String &Filename);
void SaveToFileNoHeader(const String &Filename);
//
// Writes data represented by T as binary data to the stream
//
template<class type> __forceinline void WriteData(const type &T)
{
const UINT ByteCount = sizeof(T);
const UINT StartLength = _Data.Length();
_Data.ReSize(StartLength + ByteCount);
BYTE *StreamOffset = _Data.CArray() + StartLength;
const BYTE *TOffset = (const BYTE *)&T;
for(UINT ByteIndex = 0; ByteIndex < ByteCount; ByteIndex++)
{
*StreamOffset = *TOffset;
StreamOffset++;
TOffset++;
}
}
//
// Writes raw binary data to the stream
//
void WriteData(const BYTE *Data, UINT BytesToWrite);
template<class type> void WriteSimpleVector(const Vector<type> &v)
{
const UINT length = v.Length();
*this << length;
WriteData((BYTE *)v.CArray(), length * sizeof(type));
}
__forceinline void InlineUnicodeString(const UnicodeString &S)
{
WriteData((const BYTE *)S.CString(), S.Length() * sizeof(UnicodeCharacter));
}
__forceinline const Vector<BYTE>& Data() const
{
return _Data;
}
protected:
Vector<BYTE> _Data;
};
//
// Output for several basic types
//
__forceinline OutputDataStream& operator << (OutputDataStream &S, UINT A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, int A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, float A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, double A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, char A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, unsigned short A)
{
S.WriteData(A);
return S;
}
__forceinline OutputDataStream& operator << (OutputDataStream &S, UnicodeCharacter A)
{
S.WriteData(A);
return S;
}
template<class type> OutputDataStream& operator << (OutputDataStream &S, const Vector<type> &V)
{
UINT Length = V.Length();
S << Length;
for(UINT Index = 0; Index < Length; Index++)
{
S << V[Index];
}
return S;
}
OutputDataStream& operator << (OutputDataStream &S, const String &V); | [
"[email protected]"
]
| [
[
[
1,
124
]
]
]
|
c98aa4f3649c41b3bc3e7ccbca3e2d53e29a7ab9 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/SupportWFLib/symbian/NewAudioServerTypes.cpp | af5cca089b6d794105a811a6e46d800599b08f24 | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,181 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "NewAudioServerTypes.h"
#include <badesca.h>
void ClipBuf::initEmpty( const TDesC& fileName )
{
// Copy the filename
m_array = NULL;
m_time = TTimeIntervalMicroSeconds(0);
m_fileName = fileName.Alloc();
m_des.Set( NULL, 0 );
m_realBuf = NULL;
m_numChannels = -1;
m_sampleRate = -1;
}
ClipBuf::ClipBuf(const TDesC& fileName )
{
initEmpty( fileName );
}
ClipBuf::ClipBuf(const class ClipBuf& other)
{
// Copy filename and set buffer to null.
initEmpty( other.m_fileName->Des() );
// Also copy the data.
if ( other.m_des.Length() != 0 ) {
// It was loaded.
setAudioData( other.m_des, other.m_time );
}
}
void ClipBuf::setAudioProperties( int numchannels,
int samplerate )
{
m_numChannels = numchannels;
m_sampleRate = samplerate;
}
void ClipBuf::handoverAudioData( TDes8& audioData,
const class TTimeIntervalMicroSeconds& timeMicro )
{
delete [] m_realBuf;
m_realBuf = NULL;
delete m_array;
m_array = NULL;
if ( audioData.Length() ) {
// Need an ordinary buffer, sice the HBufC8 does not
// work for audio playing.
// Blaarhhg. Need to const_cast it.
m_realBuf = const_cast<TUint8*>( audioData.Ptr() );
// But the API wants a TDes8
m_des.Set( reinterpret_cast<TUint8*>(m_realBuf), audioData.Length());
m_time = timeMicro;
#if 1
// Try splitting it into smaller buffers
#ifdef NAV2_CLIENT_UIQ3
const int dataPerBuf = 8192 / 2;
#else
const int dataPerBuf = 4096 / 2;
#endif
m_array =
new CPtrC8Array( (audioData.Length()+dataPerBuf-1) / dataPerBuf );
int curPos = 0;
int dataLeft = audioData.Length();
const TUint8* data = (TUint8*)m_realBuf;
while ( dataLeft > 0 ) {
int dataToAdd = MIN( dataPerBuf, dataLeft );
TPtrC8 tmp;
tmp.Set( data + curPos, dataToAdd );
m_array->AppendL( tmp );
dataLeft -= dataToAdd;
curPos += dataToAdd;
}
#else
m_array = new CPtrC8Array(1);
m_array->AppendL( m_des );
#endif
}
}
void ClipBuf::setAudioData(const TDesC8& audioData,
const class TTimeIntervalMicroSeconds& timeMicro )
{
// Delete these before allocing new data.
delete [] m_realBuf;
m_realBuf = NULL;
delete [] m_array;
m_array = NULL;
TPtr8 ptr( NULL, 0, 0 );
ptr.Set( NULL, 0, 0 );
if ( audioData.Length() ) {
TUint8* tmpBuf = new TUint8[ audioData.Length() ];
ptr.Set( tmpBuf, audioData.Length(), audioData.Length() );
ptr.Copy( audioData );
// Mem::Copy( tmpBuf, audioData.Ptr(),
// audioData.Length() );
}
handoverAudioData( ptr, timeMicro );
}
int ClipBuf::sampleRate() const
{
return m_sampleRate;
}
int ClipBuf::numChannels() const
{
return m_numChannels;
}
bool ClipBuf::isConverted() const
{
return m_realBuf != NULL;
}
int ClipBuf::getNbrBuffers() const
{
if ( isConverted() ) {
return m_array->MdcaCount();
} else {
return 0;
}
}
const TPtrC8& ClipBuf::getBuffer(int i )
{
return (*m_array)[i];
}
const TDesC& ClipBuf::getFileName() const
{
return *m_fileName;
}
ClipBuf::~ClipBuf()
{
delete [] m_realBuf;
delete m_fileName;
delete m_array;
}
ClipBufIterator::ClipBufIterator() :
m_clips(&m_emptyClips)
{
m_clipIt = m_clips->begin();
m_bufNbr = 0;
}
ClipBufIterator::ClipBufIterator(const TClips& clips) :
m_clips( &clips )
{
m_clipIt = m_clips->begin();
while ( m_clipIt != m_clips->end() &&
!(*m_clipIt)->isConverted() ) {
++m_clipIt;
}
m_bufNbr = 0;
}
class ClipBufIterator& ClipBufIterator::operator++()
{
m_bufNbr++;
if ( m_bufNbr >= (*m_clipIt)->getNbrBuffers() ) {
if ( m_clipIt != m_clips->end() ) {
++m_clipIt;
}
// Skip the unconverted ones.
while ( m_clipIt != m_clips->end() &&
!(*m_clipIt)->isConverted() ) {
++m_clipIt;
}
m_bufNbr = 0;
}
return *this;
}
const TDesC8* ClipBufIterator::operator*() const
{
if ( m_clipIt != m_clips->end() &&
m_bufNbr < (*m_clipIt)->getNbrBuffers() ) {
return &((*m_clipIt)->getBuffer(m_bufNbr));
} else {
return NULL;
}
}
| [
"[email protected]"
]
| [
[
[
1,
208
]
]
]
|
eac76ccf7eea3a250a1f4105259e8c45bdde9100 | fa134e5f64c51ccc1c2cac9b9cb0186036e41563 | /GT/RPM.h | 7f008ecb1defd0706261edd20c68799d958b7d65 | []
| no_license | dlsyaim/gradthes | 70b626f08c5d64a1d19edc46d67637d9766437a6 | db6ba305cca09f273e99febda4a8347816429700 | refs/heads/master | 2016-08-11T10:44:45.165199 | 2010-07-19T05:44:40 | 2010-07-19T05:44:40 | 36,058,688 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 433 | h | #pragma once
#include "Instrument.h"
// Instrument indicates revolutions per minutes(RPM).
class RPM :
public Instrument
{
public:
RPM(void);
~RPM(void);
void draw(void);
inline void setTurnAngle(double turnAngle){this->turnAngle = turnAngle;}
inline double getTurnAngle(void){return turnAngle;}
// Update the revolutions per minutes
void updateTurnAngle(double deltaAngle);
private:
double turnAngle;
};
| [
"[email protected]@3a95c3f6-2b41-11df-be6c-f52728ce0ce6"
]
| [
[
[
1,
18
]
]
]
|
a453d452035b84ef866ab695fe46545133ffbb9c | da48afcbd478f79d70767170da625b5f206baf9a | /tbmessage/websend/src/EditUserDlg.cpp | d503b8fbabe67c2e6807818e44d2f429b4d9dfbe | []
| no_license | haokeyy/fahister | 5ba50a99420dbaba2ad4e5ab5ee3ab0756563d04 | c71dc56a30b862cc4199126d78f928fce11b12e5 | refs/heads/master | 2021-01-10T19:09:22.227340 | 2010-05-06T13:17:35 | 2010-05-06T13:17:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 943 | cpp | // EditUserDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "BatchMessage.h"
#include "EditUserDlg.h"
#include ".\edituserdlg.h"
// CEditUserDlg 对话框
IMPLEMENT_DYNAMIC(CEditUserDlg, CDialog)
CEditUserDlg::CEditUserDlg(CWnd* pParent /*=NULL*/)
: CDialog(CEditUserDlg::IDD, pParent)
, m_UserId(_T(""))
, m_Password(_T(""))
{
}
CEditUserDlg::~CEditUserDlg()
{
}
void CEditUserDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_USERID, m_UserId);
DDX_Text(pDX, IDC_EDIT_PWD, m_Password);
}
BEGIN_MESSAGE_MAP(CEditUserDlg, CDialog)
ON_BN_CLICKED(IDOK, OnBnClickedOk)
END_MESSAGE_MAP()
// CEditUserDlg 消息处理程序
void CEditUserDlg::OnBnClickedOk()
{
UpdateData(TRUE);
if (m_UserId.IsEmpty())
{
MessageBox("用户名不能为空。", "错误");
return;
}
OnOK();
}
| [
"[email protected]@d41c10be-1f87-11de-a78b-a7aca27b2395"
]
| [
[
[
1,
49
]
]
]
|
ffba549fe4770f0f53f23e1a88e8b732cf88564a | 299a1b0fca9e1de3858a5ebeaf63be6dc3a02b48 | /tags/ic2005demo/dingus/dingus/gfx/skeleton/SkinMesh.cpp | dd0ea31d63d3f24b60ccc43d935ba6100cbd0fb2 | []
| no_license | BackupTheBerlios/dingus-svn | 331d7546a6e7a5a3cb38ffb106e57b224efbf5df | 1223efcf4c2079f58860d7fa685fa5ded8f24f32 | refs/heads/master | 2016-09-05T22:15:57.658243 | 2006-09-02T10:10:47 | 2006-09-02T10:10:47 | 40,673,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,314 | cpp | // --------------------------------------------------------------------------
// Dingus project - a collection of subsystems for game/graphics applications
// --------------------------------------------------------------------------
#include "stdafx.h"
#include "SkinMesh.h"
#include "../../kernel/D3DDevice.h"
using namespace dingus;
CSkinMesh::CSkinMesh()
: mMesh(0), mSkeleton(0),
mBonesPerVertex(0)
{
mMesh = new CMesh();
}
CSkinMesh::~CSkinMesh()
{
ASSERT_MSG( !isCreated(), "skin mesh not cleaned up" );
delete mMesh;
}
void CSkinMesh::createResource( const CMesh& srcMesh, const CSkeletonInfo& skelInfo )
{
ASSERT_MSG( !isCreated(), "skin mesh not cleaned up" );
mSkeleton = &skelInfo;
//
// calculate bone palette size
mPaletteSize = 25; // TBD: better calculation of this, based on VS constant count
if( skelInfo.getBoneCount() < mPaletteSize )
mPaletteSize = skelInfo.getBoneCount();
HRESULT hr;
int ngroups = srcMesh.getGroupCount();
//
// create ID3DXMesh from our mesh
ID3DXMesh* dxSrcMesh = 0;
DWORD meshOpts = D3DXMESH_SYSTEMMEM;
if( srcMesh.getIndexStride() == 4 )
meshOpts |= D3DXMESH_32BIT;
// get declaration
D3DVERTEXELEMENT9 decl[MAX_FVF_DECL_SIZE];
UINT numElements;
srcMesh.getVertexDecl().getObject()->GetDeclaration( decl, &numElements );
// re-cast d3dcolor in decl into ubyte4
D3DVERTEXELEMENT9* declP = decl;
while( declP->Stream != 0xFF ) {
if( declP->Usage == D3DDECLUSAGE_BLENDINDICES && declP->UsageIndex == 0 )
declP->Type = D3DDECLTYPE_UBYTE4;
++declP;
}
// create mesh
hr = D3DXCreateMesh(
srcMesh.getIndexCount()/3, srcMesh.getVertexCount(), meshOpts,
decl, &CD3DDevice::getInstance().getDevice(), &dxSrcMesh );
// copy VB
{
const void* srcVB = srcMesh.lockVBRead();
void* dxVB = 0;
hr = dxSrcMesh->LockVertexBuffer( 0, &dxVB );
memcpy( dxVB, srcVB, srcMesh.getVertexCount() * srcMesh.getVertexStride() );
hr = dxSrcMesh->UnlockVertexBuffer();
srcMesh.unlockVBRead();
}
// copy IB
{
const void* srcIB = srcMesh.lockIBRead();
void* dxIB = 0;
hr = dxSrcMesh->LockIndexBuffer( 0, &dxIB );
memcpy( dxIB, srcIB, srcMesh.getIndexCount() * srcMesh.getIndexStride() );
hr = dxSrcMesh->UnlockIndexBuffer();
srcMesh.unlockIBRead();
}
// copy groups and set up src bone combo table
D3DXBONECOMBINATION* srcBoneCombs = new D3DXBONECOMBINATION[ngroups];
DWORD* boneArray = new DWORD[skelInfo.getBoneCount()];
for( int b = 0; b < skelInfo.getBoneCount(); ++b )
boneArray[b] = b;
{
D3DXATTRIBUTERANGE* attrs = new D3DXATTRIBUTERANGE[ngroups];
DWORD* attrBuf = 0;
dxSrcMesh->LockAttributeBuffer( 0, &attrBuf );
for( int g = 0; g < ngroups; ++g ) {
attrs[g].AttribId = g;
const CMesh::CGroup& group = srcMesh.getGroup(g);
attrs[g].VertexStart = group.getFirstVertex();
attrs[g].VertexCount = group.getVertexCount();
attrs[g].FaceStart = group.getFirstPrim();
attrs[g].FaceCount = group.getPrimCount();
srcBoneCombs[g].AttribId = g;
srcBoneCombs[g].FaceStart = group.getFirstPrim();
srcBoneCombs[g].FaceCount = group.getPrimCount();
srcBoneCombs[g].VertexStart = group.getFirstVertex();
srcBoneCombs[g].VertexCount = group.getVertexCount();
srcBoneCombs[g].BoneId = boneArray;
for( int f = 0; f < group.getPrimCount(); ++f )
*attrBuf++ = g;
}
dxSrcMesh->UnlockAttributeBuffer();
hr = dxSrcMesh->SetAttributeTable( attrs, ngroups );
delete[] attrs;
}
//
// create ID3DXSkinInfo from the created mesh
ID3DXSkinInfo* dxSkin;
hr = D3DXCreateSkinInfoFromBlendedMesh( dxSrcMesh, skelInfo.getBoneCount(), srcBoneCombs, &dxSkin );
delete[] boneArray;
delete[] srcBoneCombs;
//
// convert to indexed blended mesh, with possibly multiple bone palettes
DWORD* srcMeshAdjacency = new DWORD[srcMesh.getIndexCount()/3*3];
hr = dxSrcMesh->GenerateAdjacency( 1.0e-6f, srcMeshAdjacency );
DWORD* resMeshAdjacency = new DWORD[srcMesh.getIndexCount()/3*3];
DWORD maxBonesPerVertUsed = 0;
DWORD boneComboCount = 0;
ID3DXBuffer* boneCombos = 0;
ID3DXMesh* dxResMesh = 0;
dxSkin->ConvertToIndexedBlendedMesh(
dxSrcMesh, /*meshOpts*/0, mPaletteSize,
srcMeshAdjacency, resMeshAdjacency, NULL, NULL,
&maxBonesPerVertUsed, &boneComboCount, &boneCombos, &dxResMesh );
mBonesPerVertex = maxBonesPerVertUsed;
delete[] srcMeshAdjacency;
// re-cast ubyte4 in decl into d3dcolor
hr = dxResMesh->GetDeclaration( decl );
declP = decl;
while( declP->Stream != 0xFF ) {
if( declP->Usage == D3DDECLUSAGE_BLENDINDICES && declP->UsageIndex == 0 )
declP->Type = D3DDECLTYPE_D3DCOLOR;
++declP;
}
hr = dxResMesh->UpdateSemantics( decl );
// TEST
DWORD strSrc = dxSrcMesh->GetNumBytesPerVertex();
DWORD strRes = dxResMesh->GetNumBytesPerVertex();
assert( dxSrcMesh->GetNumBytesPerVertex() == dxResMesh->GetNumBytesPerVertex() );
//
// optimize resulting dx mesh
hr = dxResMesh->OptimizeInplace( D3DXMESHOPT_COMPACT | D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_VERTEXCACHE,
resMeshAdjacency, NULL, NULL, NULL );
delete[] resMeshAdjacency;
//
// create partitioned mesh
mMesh->createResource( dxResMesh->GetNumVertices(), dxResMesh->GetNumFaces()*3,
srcMesh.getVertexFormat(), srcMesh.getIndexStride(), srcMesh.getVertexDecl(), CMesh::BUF_STATIC );
// copy VB
{
void* resVB = mMesh->lockVBWrite();
void* dxVB = 0;
hr = dxResMesh->LockVertexBuffer( D3DLOCK_READONLY, &dxVB );
memcpy( resVB, dxVB, mMesh->getVertexCount() * mMesh->getVertexStride() );
hr = dxResMesh->UnlockVertexBuffer();
mMesh->unlockVBWrite();
}
// copy IB
{
void* resIB = mMesh->lockIBWrite();
void* dxIB = 0;
hr = dxResMesh->LockIndexBuffer( D3DLOCK_READONLY, &dxIB );
memcpy( resIB, dxIB, mMesh->getIndexCount() * mMesh->getIndexStride() );
hr = dxResMesh->UnlockIndexBuffer();
mMesh->unlockIBWrite();
}
// copy groups
{
DWORD ngroups;
hr = dxResMesh->GetAttributeTable( NULL, &ngroups );
assert( ngroups == boneComboCount );
D3DXATTRIBUTERANGE* attrs = new D3DXATTRIBUTERANGE[ngroups];
hr = dxResMesh->GetAttributeTable( attrs, &ngroups );
for( int g = 0; g < ngroups; ++g ) {
const D3DXATTRIBUTERANGE& gr = attrs[g];
mMesh->addGroup( CMesh::CGroup(gr.VertexStart, gr.VertexCount, gr.FaceStart, gr.FaceCount) );
}
delete[] attrs;
}
mMesh->computeAABBs();
// copy palette infos
{
const D3DXBONECOMBINATION* boneComb = reinterpret_cast<const D3DXBONECOMBINATION*>( boneCombos->GetBufferPointer() );
for( int bc = 0; bc < boneComboCount; ++bc ) {
mPalettes.push_back( CSkinBonePalette() );
CSkinBonePalette& bpal = mPalettes.back();
bpal.beginPalette( boneComb->AttribId );
for( int b = 0; b < mPaletteSize; ++b )
bpal.setBone( b, boneComb->BoneId[b] );
bpal.endPalette();
++boneComb;
}
}
//
// release stuff
ULONG rc;
rc = dxSrcMesh->Release();
rc = dxSkin->Release();
rc = dxResMesh->Release();
rc = boneCombos->Release();
}
void CSkinMesh::deleteResource()
{
ASSERT_MSG( isCreated(), "skin mesh not created" );
mMesh->deleteResource();
mSkeleton = 0;
mBonesPerVertex = 0;
mPalettes.clear();
}
| [
"nearaz@73827abb-88f4-0310-91e6-a2b8c1a3e93d"
]
| [
[
[
1,
236
]
]
]
|
8af6b021a32e43a18c0d14dc1eeab76acfbb8f36 | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/Valkyrie/Moteur/ModelEau.h | 139eee3a69e52997f38566b15107fed8da8041a4 | []
| 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 | ISO-8859-1 | C++ | false | false | 2,403 | h |
// Classe pour la gestion de l'eau
#pragma once
#include "..\Moteur\VariableGlobale.h"
#include "..\Moteur\Scene.h"
#include "..\Moteur\EnvMiroir.h"
const int NB_VERTEX_EAU = 4; // nombre de vertex pour une zone d'eau
const int NB_INDICE_EAU = 6; // nombre d'indice pour une zone d'eau
const int NB_TRIANGLE_EAU = 2; // nombre de triangle pour une zone d'eau
const int NB_ZONE_EAU = 11; // nombre de zone d'eau
const float COEF_TEXTURE_X = 0.5f; // répétition de la texture
const float COEF_TEXTURE_Y = 2.0f; // répétition de la texture
const float VITESSE_EAU = -60.0f; // vitesse de déplacement de l'eau
// Nom des fichiers utilisé pour l'eau
static char FcihierTxBump[] = "..\\Donnees\\Terrain\\Composites\\EauBump.dds";
class CModelEau
{
// Type de vertex utilisé pour le model
struct CUSTOMVERTEX
{
D3DXVECTOR3 p; // position
D3DXVECTOR2 t; // coordonnées de texture
};
#define D3DFVF_CUSTOMVERTEX_EAUX (D3DFVF_XYZ|D3DFVF_TEX1)
public:
CScene* m_pScene; // pointeur sur la scène 3D
LPDIRECT3DDEVICE9 m_pD3DDevice; // pointeur sur le périphérique 3D
LPDIRECT3DINDEXBUFFER9 m_pIB; // pointeur sur l'index buffer du model
LPDIRECT3DVERTEXBUFFER9 m_pVB; // pointeur sur le vertex buffer du model
LPDIRECT3DTEXTURE9 m_pTexBump; // pointeur sur la texture de bump mapping
CUSTOMVERTEX Donnee[NB_VERTEX_EAU]; // tableau pour stocker les données du vertex buffer
D3DXMATRIXA16 m_Matrice[NB_ZONE_EAU];// matrice de trasformation du modèle
D3DXPLANE m_Plan; // plan du sol utilisé pour la réflexion
CEnvMiroir* m_pEnvMiroir; // pointeur sur un objet pour le rendu de l'environement
bool m_RenduMiroir; // permet de savoir si la réflexion est en cour de rendu
D3DXMATRIXA16 m_MatriceReflection; // matrice de réflexion
D3DXMATRIXA16 m_MatTransEau; // matrice de transformation de l'eau
float m_fLargeur;
float m_fLongeur;
float m_fPosition_Eau_X;
float m_fPosition_Eaux_Y;
float m_fPosition_Eau_Z;
CModelEau(CScene* pScene);
~CModelEau();
bool ChargerEau();
bool CreationEau(float fPositionX, float fPositionY, float fPositionZ, float fLongeur, float fLargeur);
void Release();
void RenduEau();
void MiseAJourDonnees(double TempsEcouler);
void RenduEnvMiroir();
D3DXMATRIXA16 GetMatriceReflection(){return m_MatriceReflection;}
}; | [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
66
]
]
]
|
3b65c329a091bf4788d356d47d76dc629438399b | 0d32d7cd4fb22b60c4173b970bdf2851808c0d71 | /src/hancock/hancock/FindSigsDlg.cpp | 1f52c0f491c55a2643cb3902605c535a92de9ef0 | []
| no_license | kanakb/cs130-hancock | a6eaef9a44955846d486ee2330bec61046cb91bd | d1f77798d90c42074c7a26b03eb9d13925c6e9d7 | refs/heads/master | 2021-01-18T13:04:25.582562 | 2009-06-12T03:49:56 | 2009-06-12T03:49:56 | 32,226,524 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,128 | cpp | // FindSigsDlg.cpp : implementation file
//
#include "stdafx.h"
#include "hancock.h"
#include "FindSigsDlg.h"
#include "EditCFGDlg.h"
#include "Action.h"
#include "Scheduler.h"
#include "ScheduleUI.h"
#include <iostream>
#include <fstream>
#include <string>
#include <list>
using namespace std;
// FindSigsDlg dialog
IMPLEMENT_DYNAMIC(FindSigsDlg, CDialog)
FindSigsDlg::FindSigsDlg(Scheduler *sched, CWnd* pParent /*=NULL*/)
: CDialog(FindSigsDlg::IDD, pParent), m_sched(sched)
{
}
FindSigsDlg::~FindSigsDlg()
{
}
void FindSigsDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_EDIT1, m_inpStubMap);
DDX_Control(pDX, IDC_EDIT9, m_inpClst1);
DDX_Control(pDX, IDC_EDIT10, m_inpInd1);
DDX_Control(pDX, IDC_EDIT_SMIM2, m_inpInd2);
DDX_Control(pDX, IDC_EDIT7, m_inpClst2);
DDX_Control(pDX, IDC_EDIT3, m_mode);
DDX_Control(pDX, IDC_EDIT4, m_output);
DDX_Control(pDX, IDC_BTN_ECFG, m_eCFG);
DDX_Control(pDX, IDOK, m_start);
DDX_Control(pDX, IDC_CHECK1, m_selI2);
DDX_Control(pDX, IDC_CHECK2, m_selC2);
DDX_Control(pDX, IDC_BTN_SELINP4, m_browseI2);
DDX_Control(pDX, IDC_SELDEP5, m_depI2);
DDX_Control(pDX, IDC_BTN_SELINP5, m_browseC2);
DDX_Control(pDX, IDC_SELDEP6, m_depC2);
DDX_Control(pDX, IDC_EDIT11, m_minCov);
}
BEGIN_MESSAGE_MAP(FindSigsDlg, CDialog)
ON_BN_CLICKED(IDC_BTN_CRCFG, &FindSigsDlg::OnBnClickedBtnCrcfg)
ON_BN_CLICKED(IDC_BTN_ECFG, &FindSigsDlg::OnBnClickedBtnEcfg)
ON_BN_CLICKED(IDOK, &FindSigsDlg::OnBnClickedOk)
ON_BN_CLICKED(IDC_BTN_SELINP1, &FindSigsDlg::OnBnClickedBtnSelinp1)
ON_BN_CLICKED(IDC_SELDEP1, &FindSigsDlg::OnBnClickedSeldep1)
ON_BN_CLICKED(IDC_BTN_SELINP2, &FindSigsDlg::OnBnClickedBtnSelinp2)
ON_BN_CLICKED(IDC_SELDEP3, &FindSigsDlg::OnBnClickedSeldep2)
ON_BN_CLICKED(IDC_BTN_SELINP3, &FindSigsDlg::OnBnClickedBtnSelinp3)
ON_BN_CLICKED(IDC_SELDEP4, &FindSigsDlg::OnBnClickedSeldep3)
ON_BN_CLICKED(IDC_BTN_SELINP4, &FindSigsDlg::OnBnClickedBtnSelinp4)
ON_BN_CLICKED(IDC_SELDEP5, &FindSigsDlg::OnBnClickedSeldep4)
ON_BN_CLICKED(IDC_BTN_SELINP5, &FindSigsDlg::OnBnClickedBtnSelinp5)
ON_BN_CLICKED(IDC_SELDEP6, &FindSigsDlg::OnBnClickedSeldep5)
ON_BN_CLICKED(IDC_BTN_SELFSOUT, &FindSigsDlg::OnBnClickedBtnSelfsout)
ON_BN_CLICKED(IDC_CHECK1, &FindSigsDlg::OnBnClickedCheck1)
ON_BN_CLICKED(IDC_CHECK2, &FindSigsDlg::OnBnClickedCheck2)
END_MESSAGE_MAP()
// FindSigsDlg message handlers
void FindSigsDlg::OnBnClickedBtnCrcfg()
{
// code for creating a cfg file
CFileDialog cfgBox(FALSE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("Configuration Files(*.cfg)|*.cfg|All Files(*.*)|*.*||"));
if (cfgBox.DoModal() == IDOK)
{
// Get file path from dialog
CString fullFilePath = cfgBox.GetPathName();
if (cfgBox.GetFileExt() == _T(""))
fullFilePath += _T(".cfg");
// Open file for writing
CT2CA asciiPath(fullFilePath);
string sPath(asciiPath);
m_cfgname = sPath;
ofstream fout(sPath.c_str());
// Write each parameter
CString param;
m_inpStubMap.GetWindowText(param);
CT2CA asciiParam(param);
string sParam(asciiParam);
fout << "stubMap = " << sParam << endl;
m_inpClst1.GetWindowText(param);
CT2CA asciiParam2(param);
sParam = asciiParam2;
fout << "fileGroupFile = " << sParam << endl;
fout << "#groupThresholdRatio = 0.1" << endl;
fout << "#groupCountThreshold = 4" << endl;
m_inpInd1.GetWindowText(param);
CT2CA asciiParam3(param);
sParam = asciiParam3;
fout << "fpIndexFile = " << sParam << endl;
if (m_selI2.GetCheck())
{
m_inpInd2.GetWindowText(param);
CT2CA asciiParam4(param);
sParam = asciiParam4;
fout << "fpIndexFile2 = " << sParam << endl;
}
else
fout << "#fpIndexFile2 = " << endl;
m_minCov.GetWindowText(param);
CT2CA asciiParam5(param);
sParam = asciiParam5;
fout << "sigMinCoverage = " << sParam << endl;
fout << "#StDevFileOffset = " << sParam << endl;
m_mode.GetWindowText(param);
CT2CA asciiParam7(param);
sParam = asciiParam7;
fout << "fileBufferMode = " << sParam << endl;
fout << "#dualSigs" << endl;
fout << "#triSigs" << endl;
fout << "#findRedundantSigs" << endl;
fout << "#queueSize = 10" << endl;
if (m_selC2.GetCheck())
{
m_inpClst2.GetWindowText(param);
CT2CA asciiParam8(param);
sParam = asciiParam8;
fout << "superGroupFile = " << sParam << endl;
}
else
fout << "#superGroupFile = " << endl;
fout << "#groupThresholdRatioOutsideSuperGroup = 0.5" << endl;
fout.close();
m_eCFG.EnableWindow(TRUE);
m_start.EnableWindow(TRUE);
}
}
void FindSigsDlg::OnBnClickedBtnEcfg()
{
// code for editing a cfg file
EditCFGDlg ecfg(m_cfgname);
ecfg.DoModal();
}
void FindSigsDlg::OnBnClickedOk()
{
// code for starting the action
std::list<string> inputs;
std::list<string> outputs;
// Process inputs
CString in;
m_inpStubMap.GetWindowText(in);
CT2CA asciiInp1(in);
inputs.push_back(string(asciiInp1));
m_inpClst1.GetWindowText(in);
CT2CA asciiInp2(in);
inputs.push_back(string(asciiInp2));
m_inpInd1.GetWindowText(in);
CT2CA asciiInp3(in);
inputs.push_back(string(asciiInp3));
m_inpInd2.GetWindowText(in);
BOOL checkState = m_selI2.GetCheck();
if (checkState)
{
CT2CA asciiInp4(in);
inputs.push_back(string(asciiInp4));
}
m_inpClst2.GetWindowText(in);
checkState = m_selC2.GetCheck();
if (checkState)
{
CT2CA asciiInp5(in);
inputs.push_back(string(asciiInp5));
}
//Process outputs
CString out;
m_output.GetWindowText(out);
CT2CA asciiOut(out);
string outfilename(asciiOut);
if (out != _T(""))
outputs.push_back(outfilename);
// Schedule action
Action *act = new Action("executables\\", "FindSigs.exe", m_cfgname, outfilename);
m_sched->addAction(act, m_deps, inputs, outputs);
OnOK();
}
void FindSigsDlg::OnBnClickedBtnSelinp1()
{
// code for picking an input stub map
CFileDialog inBox1(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("Stub Maps(*.bin)|*.bin|All Files(*.*)|*.*||"));
if (inBox1.DoModal() == IDOK)
{
CString fullFilePath = inBox1.GetPathName();
m_inpStubMap.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedSeldep1()
{
// code for dependencies for an input stub map (if applicable)
ScheduleUI depui(TRUE, m_sched);
if (depui.DoModal() == IDOK)
{
CString depName;
depui.getFileString(depName);
if (depName != _T(""))
{
m_deps.push_back(depui.getCurAct());
m_inpStubMap.SetWindowText(depName);
}
}
}
void FindSigsDlg::OnBnClickedBtnSelinp2()
{
// code for picking an input cluster (#1)
CFileDialog inBox2(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("Clusterings(*.txt)|*.txt|All Files(*.*)|*.*||"));
if (inBox2.DoModal() == IDOK)
{
CString fullFilePath = inBox2.GetPathName();
m_inpClst1.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedSeldep2()
{
// code for dependencies for an input cluster (#1) (if applicable)
ScheduleUI depui(TRUE, m_sched);
if (depui.DoModal() == IDOK)
{
CString depName;
depui.getFileString(depName);
if (depName != _T(""))
{
m_deps.push_back(depui.getCurAct());
m_inpClst1.SetWindowText(depName);
}
}
}
void FindSigsDlg::OnBnClickedBtnSelinp3()
{
// code for picking an input index (#1)
CFileDialog inBox3(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("All Files(*.*)|*.*||"));
if (inBox3.DoModal() == IDOK)
{
CString fullFilePath = inBox3.GetPathName();
m_inpInd1.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedSeldep3()
{
// code for dependencies for an input index (#1) (if applicable)
ScheduleUI depui(TRUE, m_sched);
if (depui.DoModal() == IDOK)
{
CString depName;
depui.getFileString(depName);
if (depName != _T(""))
{
m_deps.push_back(depui.getCurAct());
m_inpInd1.SetWindowText(depName);
}
}
}
void FindSigsDlg::OnBnClickedBtnSelinp4()
{
// code for picking an input index (#2)
CFileDialog inBox3(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("All Files(*.*)|*.*||"));
if (inBox3.DoModal() == IDOK)
{
CString fullFilePath = inBox3.GetPathName();
m_inpInd2.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedSeldep4()
{
// code for dependencies for an input index (#2) (if applicable)
ScheduleUI depui(TRUE, m_sched);
if (depui.DoModal() == IDOK)
{
CString depName;
depui.getFileString(depName);
if (depName != _T(""))
{
m_deps.push_back(depui.getCurAct());
m_inpInd2.SetWindowText(depName);
}
}
}
void FindSigsDlg::OnBnClickedBtnSelinp5()
{
// code for picking an input cluster (#2)
CFileDialog inBox2(TRUE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("Clusterings(*.txt)|*.txt|All Files(*.*)|*.*||"));
if (inBox2.DoModal() == IDOK)
{
CString fullFilePath = inBox2.GetPathName();
m_inpClst2.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedSeldep5()
{
// code for dependencies for an input cluster (#2) (if applicable)
ScheduleUI depui(TRUE, m_sched);
if (depui.DoModal() == IDOK)
{
CString depName;
depui.getFileString(depName);
if (depName != _T(""))
{
m_deps.push_back(depui.getCurAct());
m_inpClst2.SetWindowText(depName);
}
}
}
void FindSigsDlg::OnBnClickedBtnSelfsout()
{
// code for selecting output
CFileDialog outBox(FALSE, NULL, NULL, OFN_OVERWRITEPROMPT, _T("All Files(*.*)|*.*||"));
if (outBox.DoModal() == IDOK)
{
CString fullFilePath = outBox.GetPathName();
m_output.SetWindowText(fullFilePath);
}
}
void FindSigsDlg::OnBnClickedCheck1()
{
// code for enabling input index 2
BOOL checkState = m_selI2.GetCheck();
m_inpInd2.EnableWindow(checkState);
m_browseI2.EnableWindow(checkState);
m_depI2.EnableWindow(checkState);
}
void FindSigsDlg::OnBnClickedCheck2()
{
// code for enabling input cluster 2
BOOL checkState = m_selC2.GetCheck();
m_inpClst2.EnableWindow(checkState);
m_browseC2.EnableWindow(checkState);
m_depC2.EnableWindow(checkState);
}
| [
"kanakb@1f8f3222-2881-11de-bcab-dfcfbda92187"
]
| [
[
[
1,
374
]
]
]
|
fec632ecda41b771e9bd0915bc2b1ce4c8a1f712 | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/WarsongGulch.cpp | f8e2cb8e5b6e7a1abd3fa35acd32247d79346814 | [
"FSFUL"
]
| permissive | vata/solution | 4c6551b9253d8f23ad5e72f4a96fc80e55e583c9 | 774fca057d12a906128f9231831ae2e10a947da6 | refs/heads/master | 2021-01-10T02:08:50.032837 | 2007-11-13T22:01:17 | 2007-11-13T22:01:17 | 45,352,930 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 28,184 | cpp | // Copyright (C) 2004 WoW Daemon
// Copyright (C) 2006 Burlex
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "StdAfx.h"
#define BUFF_RESPAWN_TIME 90000
WarsongGulch::WarsongGulch()
{
FlagHolders[0] = 0;
FlagHolders[1] = 0;
FlagGuids[0] = 0;
FlagGuids[1] = 0;
pFlags[0] = pFlags[1] = NULL;
bSpawned = false;
bStarted = false;
m_BGTime = 0;
m_HordeGroup = m_AllianceGroup = NULL;
m_MaxScore = 3;
}
WarsongGulch::~WarsongGulch()
{
// Nothing
}
void WarsongGulch::Remove()
{
// remove some objects
// There's no need to remove the objects. mapmgr will take care of that when its deleted. :)
/*for(std::set<GameObject*>::iterator itr = m_Gates.begin(); itr!=m_Gates.end(); ++itr)
{
if( (*itr)->IsInWorld() )
(*itr)->RemoveFromWorld();
sObjHolder.Delete<GameObject>(*itr);
}
for(int i=0;i<2;i++)
if(pFlags[i])
{
if( pFlags[i]->IsInWorld() )
pFlags[i]->RemoveFromWorld();
sObjHolder.Delete<GameObject>(pFlags[i]);
}*/
}
void WarsongGulch::HandleBattlegroundAreaTrigger(Player *plr, uint32 TriggerID)
{
uint32 spellid=0;
int32 buffslot = -1;
switch(TriggerID)
{
case 3686: // Speed
buffslot = 0;
break;
case 3687: // Speed (Horde)
buffslot = 1;
break;
case 3706: // Restoration
buffslot = 2;
break;
case 3708: // Restoration (Horde)
buffslot = 3;
break;
case 3707: // Berserking
buffslot = 4;
break;
case 3709: // Berserking (Horde)
buffslot = 5;
break;
case 3669:
case 3671:
{
RemovePlayer(plr, true, true);
return;
}break;
case 3646:
case 3647:
{
// Flag capture points
if(plr->GetGUID() == FlagHolders[plr->m_bgTeam ? 0 : 1])
if(!((plr->m_bgTeam == 0 && TriggerID == 3647) || (plr->m_bgTeam == 1 && TriggerID == 3646)))
if(FlagInbase[plr->m_bgTeam])
HandleBattlegroundEvent(((Object*)plr), NULL, BGEVENT_WSG_SCORE_FLAG);
return;
}break;
default:
{
sLog.outString("WARNING: Unhandled AreaTrigger in Battleground: %d", TriggerID);
}break;
}
if(buffslot > -1 && gbuffs[buffslot])
{
spellid = gbuffs[buffslot]->GetInfo()->sound3;
gbuffs[buffslot]->Expire();
gbuffs[buffslot] = NULL;
sEventMgr.AddEvent(this, &WarsongGulch::SpawnBuff,(uint32)0,(uint32)buffslot, EVENT_BATTLEGROUND_SPAWN_BUFF1+buffslot, BUFF_RESPAWN_TIME, 1);
}
if(spellid)
{
SpellEntry *entry = sSpellStore.LookupEntry(spellid);
if(!entry)
sLog.outError("WARNING: Tried to add unknown spell id %d to plr.", spellid);
Spell *spell = new Spell(plr, entry, true,NULL);
SpellCastTargets targets;
targets.m_unitTarget = plr->GetGUID();
targets.m_targetMask = 0x2;
spell->prepare(&targets);
}
}
void WarsongGulch::HandleBattlegroundEvent(Object *src, Object *dst, uint16 EventID, uint32 params1, uint32 params2)
{
switch(EventID)
{
case BGEVENT_WSG_PLAYER_DEATH:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER) return;
if(Source->m_bgHasFlag)
HandleBattlegroundEvent(src, dst, BGEVENT_WSG_PLAYER_DIED_WITH_FLAG);
uint64 guid = Source->GetGUID();
std::map<uint64, BattlegroundScore>::iterator itr = m_PlayerScores.find(guid);
if(itr == m_PlayerScores.end())
{
SendMessageToPlayer(Source, "INTERNAL ERROR: Could not find in internal player score map!", true);
return;
}
itr->second.Deaths++;
UpdatePVPData();
}break;
case BGEVENT_WSG_PICKUP_FLAG:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER || Source->m_MountSpellId) return;
GameObject *flag = ((GameObject*)dst);
if(!flag || dst->GetTypeId() != TYPEID_GAMEOBJECT) return;
uint32 entry = flag->GetUInt32Value(OBJECT_FIELD_ENTRY);
if((Source->m_bgTeam == 1 && entry == 179831) || (Source->m_bgTeam == 0 && entry == 179830))
{
// nope.
return;
}
// Despawn flag
WorldPacket data(SMSG_GAMEOBJECT_DESPAWN_ANIM, 8);
data << flag->GetGUID();
Source->SendMessageToSet(&data, true);
bool returning = false;
// Remove from obj and map if it's a dropped flag.. we dont want to remove src flag
if(flag->GetUInt32Value(GAMEOBJECT_TYPE_ID) == 26)
{
if(flag->GetGUID() == FlagGuids[Source->m_bgTeam])
{
returning = true;
}
if(!returning)
{
uint32 flagteam = Source->m_bgTeam ? 0 : 1;
FlagGuids[flagteam] = 0;
}
}
uint64 flagguid = flag->GetGUID();
// Check if we're returning or capturing
if (!returning) HandleBattlegroundEvent(src, dst, BGEVENT_WSG_CAPTURE_FLAG);
else HandleBattlegroundEvent(src, dst, BGEVENT_WSG_RETURN_FLAG);
}
break;
case BGEVENT_WSG_DROP_FLAG:
{
char message[100];
Player *Source = (Player*)src;
sprintf(message, "The %s flag was dropped by $N!", Source->m_bgTeam ? "Horde" : "Alliance" );
WorldPacket * data = sChatHandler.FillMessageData(0x53, 0, message, Source->GetGUID());
SendPacketToAll(data);
delete data;
}
break;
case BGEVENT_WSG_CAPTURE_FLAG:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER || Source->m_MountSpellId) return;
// Check if it's been dropped somewhere or if someone else has it
GameObject *flag = ((GameObject*)dst);
if(!flag || dst->GetTypeId() != TYPEID_GAMEOBJECT) return;
uint32 entry = flag->GetUInt32Value(OBJECT_FIELD_ENTRY);
if((Source->m_bgTeam == 1 && entry == 179831) || (Source->m_bgTeam == 0 && entry == 179830))
{
// nope.
return;
}
if(flag->GetUInt32Value(GAMEOBJECT_TYPE_ID) != 26)
{
uint64 guid = Source->GetGUID();
std::map<uint64, BattlegroundScore>::iterator itr = m_PlayerScores.find(guid);
if(itr == m_PlayerScores.end())
{
SendMessageToPlayer(Source, "INTERNAL ERROR: Could not find in internal player score map!", true);
return;
}
itr->second.FlagCaptures++;
UpdatePVPData();
}
if(flag->IsInWorld())
{
flag->RemoveFromWorld();
}
sObjHolder.Delete<GameObject>(flag);
uint32 flagteam = Source->m_bgTeam ? 0 : 1;
if(FlagGuids[flagteam] != 0 || FlagHolders[flagteam] != 0)
{
// nope.
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 100);
data << uint32(0);
data << "Someone else on your team has the opponent's flag or it's been dropped.";
data << uint8(0);
Source->GetSession()->SendPacket(&data);
return;
}
SetWorldStateValue(Source->m_bgTeam ? WSG_ALLIANCE_FLAG_CAPTURED:WSG_HORDE_FLAG_CAPTURED,2);
char message[200];
sprintf(message, "The %s Flag was picked up by $n!", Source->m_bgTeam ? "Alliance" : "Horde");
WorldPacket *data2 = BuildMessageChat(0x54, 0x27, message,0, Source->GetGUID());
SendPacketToAll(data2);
delete data2;
// Update the worldstate
if(Source->m_bgTeam == 0)
SetWorldStateValue(0x60A,-1);
else
SetWorldStateValue(0x609,-1);
// Play sound
WorldPacket data(SMSG_PLAY_SOUND, 4);
data << uint32(Source->m_bgTeam ? SOUND_HORDE_CAPTURE : SOUND_ALLIANCE_CAPTURE);
SendPacketToAll(&data);
Source->m_bgHasFlag = true;
SpellEntry *proto = sSpellStore.LookupEntry(23333+(Source->m_bgTeam*2));
Spell *sp = new Spell(Source, proto, true, NULL);
SpellCastTargets targets;
targets.m_unitTarget = Source->GetGUID();
targets.m_targetMask = 0x2;
sp->prepare(&targets);
FlagInbase[flagteam] = false;
FlagHolders[flagteam] = Source->GetGUID();
pFlags[flagteam] = NULL;
}
break;
case BGEVENT_WSG_PLAYER_DIED_WITH_FLAG:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER) return;
char message[200];
sprintf(message, "The %s Flag was dropped by $n!", Source->m_bgTeam ? "Alliance" : "Horde");
WorldPacket *data2 = BuildMessageChat(0x53, 0x25, message, 0, Source->GetGUID());
SendPacketToAll(data2);
delete data2;
SetWorldStateValue(Source->m_bgTeam ? WSG_ALLIANCE_FLAG_CAPTURED:WSG_HORDE_FLAG_CAPTURED,1);
// Create dropped flag
GameObject *newflag = sObjHolder.Create<GameObject>();
newflag->SetInstanceID(GetInstanceID());
newflag->Create(this->GetMapId(),Source->GetPositionX(),Source->GetPositionY(),Source->GetPositionZ(),Source->GetOrientation());
newflag->SetUInt32Value(OBJECT_FIELD_TYPE,33);
newflag->SetUInt32Value(OBJECT_FIELD_ENTRY, (Source->m_bgTeam ? 179785 : 179786));
newflag->SetFloatValue(OBJECT_FIELD_SCALE_X,2.5f);
newflag->SetFloatValue(GAMEOBJECT_POS_X, Source->GetPositionX());
newflag->SetFloatValue(GAMEOBJECT_POS_Y, Source->GetPositionY());
newflag->SetFloatValue(GAMEOBJECT_POS_Z, Source->GetPositionZ());
newflag->SetFloatValue(GAMEOBJECT_FACING, Source->GetOrientation());
newflag->SetUInt32Value(GAMEOBJECT_DISPLAYID,(Source->m_bgTeam ? 5912 : 5913));
newflag->SetUInt32Value(GAMEOBJECT_STATE, 1);
newflag->SetUInt32Value(GAMEOBJECT_TYPE_ID,26);
newflag->SetUInt32Value(GAMEOBJECT_DYN_FLAGS,1);
newflag->AddToWorld();
uint32 flagteam = Source->m_bgTeam ? 0 : 1;
FlagGuids[flagteam] = newflag->GetGUID();
FlagHolders[flagteam] = 0; // no holder anymore..
Source->m_bgHasFlag = false;
// Remove aura from plr
Source->RemoveAura(23333+(Source->m_bgTeam*2));
HandleBattlegroundEvent(src, dst, BGEVENT_WSG_DROP_FLAG);
}
break;
case BGEVENT_WSG_SCORE_FLAG:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER) return;
// Remove aura from plr
Source->RemoveAura(23333+(Source->m_bgTeam*2));
// Remove flag
uint32 flagteam = Source->m_bgTeam ? 0 : 1;
FlagGuids[flagteam] = 0;
FlagHolders[flagteam] = 0;
// Spawn Flags again
if(flagteam)
{
// warsong flag - horde base
pFlags[flagteam] = SpawnGameObject(179831, 489, 915.367, 1433.78, 346.089, 3.17301, 0, 210, 2.5f);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
}
else
{
// silverwing flag - alliance base
pFlags[flagteam] = SpawnGameObject(179830, 489, 1540.29, 1481.34, 352.64, 3.17301, 0,1314, 2.5f);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
}
SetWorldStateValue(Source->m_bgTeam ? WSG_ALLIANCE_FLAG_CAPTURED:WSG_HORDE_FLAG_CAPTURED,1);
std::map<uint64, BattlegroundScore>::iterator itr;
for(itr = m_PlayerScores.begin(); itr != m_PlayerScores.end(); ++itr)
{
if(itr->second.teamid == Source->m_bgTeam)
itr->second.BonusHonor+=82;
}
SetWorldStateValue(Source->m_bgTeam ? WSG_ALLIANCE_FLAG_CAPTURED:WSG_HORDE_FLAG_CAPTURED,1);
WorldPacket data(SMSG_PLAY_SOUND, 4);
char message[100];
sprintf(message, "%s captured the %s flag!", Source->GetName(), Source->m_bgTeam ? "Horde" : "Alliance" );
WorldPacket * data4 = sChatHandler.FillMessageData(0x53, 0, message, Source->GetGUID());
SendPacketToAll(data4);
delete data4;
data << uint32(Source->m_bgTeam ? SOUND_HORDE_SCORES : SOUND_ALLIANCE_SCORES);
SendPacketToAll(&data);
Source->m_bgHasFlag = false; // oops.. forgot this lawl
// Update teh worldstate
if(Source->m_bgTeam == 0) {
SetWorldStateValue(0x60A,0x00);
SetAllianceScore(GetAllianceScore()+1);
}
else
{
SetWorldStateValue(0x609,0x00);
SetHordeScore(GetHordeScore()+1);
}
}break;
case BGEVENT_WSG_RETURN_FLAG:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER) return;
GameObject *flag = ((GameObject*)dst);
if(flag->IsInWorld())
{
flag->RemoveFromWorld();
}
sObjHolder.Delete<GameObject>(flag);
char message[200];
sprintf(message, "The %s Flag was returned to its base by $n!", Source->m_bgTeam ? "Horde" : "Alliance");
WorldPacket *data2 = BuildMessageChat(0x53, 0x32, message, 0, Source->GetGUID());
SendPacketToAll(data2);
delete data2;
WorldPacket *data3 = sChatHandler.FillMessageData(0x53, 0, message, Source->GetGUID());
SendPacketToAll(data3);
delete data3;
WorldPacket data(SMSG_PLAY_SOUND, 4);
data << uint32(0x00002000);
SendPacketToAll(&data);
GameObject *pFlag = NULL;
uint32 flagteam = Source->m_bgTeam;
SetWorldStateValue(Source->m_bgTeam ? WSG_HORDE_FLAG_CAPTURED:WSG_ALLIANCE_FLAG_CAPTURED,1);
// Spawn Flags again
if(flagteam)
{
// warsong flag - horde base
pFlags[flagteam] = SpawnGameObject(179831, 489, 915.367, 1433.78, 346.089, 3.17301, 0, 210, 2.5f);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
}
else
{
// silverwing flag - alliance base
pFlags[flagteam] = SpawnGameObject(179830, 489, 1540.29, 1481.34, 352.64, 3.17301, 0,1314, 2.5f);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[flagteam]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
}
uint64 guid = Source->GetGUID();
std::map<uint64, BattlegroundScore>::iterator itr = m_PlayerScores.find(guid);
if(itr == m_PlayerScores.end())
{
SendMessageToPlayer(Source, "INTERNAL ERROR: Could not find in internal player score map!", true);
return;
}
itr->second.FlagReturns++;
UpdatePVPData();
Source->m_bgHasFlag = false;
flagteam = Source->m_bgTeam;
FlagInbase[flagteam] = true;
FlagGuids[flagteam] = 0;
FlagHolders[flagteam] = 0;
}break;
case BGEVENT_WSG_PLAYER_KILL:
{
Player *Source = ((Player*)src);
if(!Source || src->GetTypeId() != TYPEID_PLAYER) return;
uint64 guid = Source->GetGUID();
std::map<uint64, BattlegroundScore>::iterator itr = m_PlayerScores.find(guid);
if(itr == m_PlayerScores.end())
{
SendMessageToPlayer(Source, "INTERNAL ERROR: Could not find in internal player score map!", true);
return;
}
itr->second.KillingBlows++;
UpdatePVPData();
}break;
default:
{
sLog.outString("WARNING: Unhandled battleground event: %d", EventID);
return;
}break;
}
}
void WarsongGulch::SetupBattleground()
{
// global world state's
WorldStateVars[0x8D8] = uint32(0x00);
WorldStateVars[0x8D7] = uint32(0x00);
WorldStateVars[0x8D6] = uint32(0x00);
WorldStateVars[0x8D5] = uint32(0x00);
WorldStateVars[0x8D4] = uint32(0x00);
WorldStateVars[0x8D3] = uint32(0x00);
// battleground world state's
WorldStateVars[WSG_ALLIANCE_FLAG_CAPTURED] = uint32(0x01);
WorldStateVars[WSG_HORDE_FLAG_CAPTURED] = uint32(0x01);
WorldStateVars[0x60B] = uint32(0x00); // unk
WorldStateVars[WSG_MAX_SCORE] = uint32(m_MaxScore);
WorldStateVars[WSG_CURRENT_HORDE_SCORE] = uint32(0x00);
WorldStateVars[WSG_CURRENT_ALLIANCE_SCORE] = uint32(0x00);
WorldStateVars[0x60A] = uint32(0x00);
WorldStateVars[0x609] = uint32(0x00);
//sLog.outString("BATTLEGROUND: Warsong Gulch Battleground Setup! %d WorldState Variables Set, 2 Spirit Guides Spawned.", WorldStateVars.size());
}
void WarsongGulch::SpawnBuff(uint32 typeentry,uint32 bannerslot)
{
switch(bannerslot)
{
case 0:
gbuffs[bannerslot] = SpawnGameObject(179871, 489, 1449.9296875, 1470.70971679688, 342.634552001953, -1.64060950279236, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.73135370016098);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,-0.681998312473297);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
case 1:
gbuffs[bannerslot] = SpawnGameObject(179899, 489, 1005.17071533203, 1447.94567871094, 335.903228759766, 1.64060950279236, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.73135370016098);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,0.681998372077942);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
case 2:
gbuffs[bannerslot] = SpawnGameObject(179904, 489, 1317.50573730469, 1550.85070800781, 313.234375, -0.26179963350296, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.130526319146156);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,-0.991444826126099);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
case 3:
gbuffs[bannerslot] = SpawnGameObject(179906, 489, 1110.45129394531, 1353.65563964844, 316.518096923828, -0.68067866563797, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.333806991577148);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,-0.94264143705368);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
case 4:
gbuffs[bannerslot] = SpawnGameObject(179905, 489, 1320.09375, 1378.78967285156, 314.753234863281, 1.18682384490967, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.559192895889282);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,0.829037606716156);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
case 5:
gbuffs[bannerslot] = SpawnGameObject(179907, 489, 1139.68774414063, 1560.28771972656, 306.843170166016, -2.4434609413147, 0, 114, 1);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_02,0.939692616462708);
gbuffs[bannerslot]->SetFloatValue(GAMEOBJECT_ROTATION_03,-0.342020124197006);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_STATE, 1);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 6);
gbuffs[bannerslot]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
break;
}
}
void WarsongGulch::SpawnBattleground()
{
for(int i=0;i<6;i++)
SpawnBuff(0,i);
// Alliance Gates
/*GameObject *gate = SpawnGameObject(179921, 489, 1471.554688, 1458.778076, 362.633240, 0, 33, 114, 2.33271);
m_Gates.insert(gate);
gate = SpawnGameObject(179919, 489, 1492.477783, 1457.912354, 342.968933, 0, 33, 114, 2.68149);
m_Gates.insert(gate);
gate = SpawnGameObject(179918, 489, 1503.335327, 1493.465820, 352.188843, 0, 33, 114, 2.26);
m_Gates.insert(gate);
// Horde Gates
gate = SpawnGameObject(179916, 489, 949.1663208, 1423.7717285, 345.6241455, -0.5756807, 32, 114, 0.900901);
gate->SetFloatValue(GAMEOBJECT_ROTATION,-0.0167336);
gate->SetFloatValue(GAMEOBJECT_ROTATION_01,-0.004956);
gate->SetFloatValue(GAMEOBJECT_ROTATION_02,-0.283972);
gate->SetFloatValue(GAMEOBJECT_ROTATION_03,0.9586736);
m_Gates.insert(gate);
gate = SpawnGameObject(179917, 489, 953.0507202, 1459.8424072, 340.6525573, -1.9966197, 32, 114, 0.854700);
gate->SetFloatValue(GAMEOBJECT_ROTATION,-0.1971825);
gate->SetFloatValue(GAMEOBJECT_ROTATION_01,0.1575096);
gate->SetFloatValue(GAMEOBJECT_ROTATION_02,-0.8239487);
gate->SetFloatValue(GAMEOBJECT_ROTATION_03,0.5073640);
m_Gates.insert(gate);*/
// Flags
// warsong flag - horde base
pFlags[1] = SpawnGameObject(179831, 489, 915.367, 1433.78, 346.089, 3.17301, 0, 210, 2.5f);
pFlags[1]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[1]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[1]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
// silverwing flag - alliance base
pFlags[0] = SpawnGameObject(179830, 489, 1540.29, 1481.34, 352.64, 3.17301, 0,1314, 2.5f);
pFlags[0]->SetUInt32Value(GAMEOBJECT_STATE, 1);
pFlags[0]->SetUInt32Value(GAMEOBJECT_TYPE_ID, 24);
pFlags[0]->SetUInt32Value(GAMEOBJECT_ANIMPROGRESS, 100);
SpawnSpiritGuides();
FlagInbase[0] = true;
FlagInbase[1] = true;
bSpawned = true;
}
void WarsongGulch::Start()
{
// Open all the doors
for(std::set<GameObject*>::iterator itr = m_Gates.begin(); itr!=m_Gates.end(); ++itr)
{
(*itr)->SetUInt32Value(GAMEOBJECT_FLAGS, 64);
(*itr)->SetUInt32Value(GAMEOBJECT_STATE, 0);
}
// Send message packet
WorldPacket *data = BuildMessageChat(0x52, 0x29, "Let the battle for Warsong Gulch begin!", 0);
SendPacketToAll(data);
delete data;
data = BuildMessageChat(0x52, 0x29, "The flags are now placed at their bases.", 0);
SendPacketToAll(data);
delete data;
WorldPacket pkt;
pkt.Initialize(SMSG_PLAY_SOUND);
pkt << uint32(SOUND_BATTLEGROUND_BEGIN); // Battleground Sound Begin
SendPacketToAll(&pkt);
}
void WarsongGulch::SetAllianceScore(uint32 score)
{
SetWorldStateValue(WSG_CURRENT_ALLIANCE_SCORE,score);
if(WorldStateVars[WSG_CURRENT_ALLIANCE_SCORE] == m_MaxScore)
{
// set battleground End
SetBattleGroundStatus(true);
// alliance wins
SetBattleGameWin(true);
// Team wins.
WorldPacket *data2 = BuildMessageChat(0x53, 0x13, "The Alliance wins!", 0);
SendPacketToAll(data2);
delete data2;
UpdatePVPData();
WorldPacket data(SMSG_PLAY_SOUND, 4);
data << uint32(SOUND_ALLIANCEWINS);
SendPacketToAll(&data);
}
}
void WarsongGulch::SetHordeScore(uint32 score)
{
SetWorldStateValue(WSG_CURRENT_HORDE_SCORE,score);
if(WorldStateVars[WSG_CURRENT_HORDE_SCORE] == m_MaxScore)
{
// set battleground win
SetBattleGroundStatus(true);
// horde wins
SetBattleGameWin(false);
// Team wins.
WorldPacket *data2 = BuildMessageChat(0x53, 0x13, "The Horde wins!", 0);
SendPacketToAll(data2);
delete data2;
UpdatePVPData();
WorldPacket data(SMSG_PLAY_SOUND, 4);
data << uint32(SOUND_HORDEWINS);
SendPacketToAll(&data);
}
}
uint32 WarsongGulch::GetAllianceScore()
{
return WorldStateVars[WSG_CURRENT_ALLIANCE_SCORE];
}
uint32 WarsongGulch::GetHordeScore()
{
return WorldStateVars[WSG_CURRENT_HORDE_SCORE];
}
void WarsongGulch::SpawnSpiritGuides()
{
// Alliance Spirit Guide
SpawnSpiritGuide(1423.218872f, 1554.663574f, 342.833801f, 3.124139f, 0);
// Horde Spirit Guide
SpawnSpiritGuide(1032.644775f, 1388.316040f, 340.559937f, 0.043200f, 1);
} | [
"[email protected]"
]
| [
[
[
1,
691
]
]
]
|
af269568254f7905d8d5f68b89330e05fe00d0c2 | 3ea8b8900d21d0113209fd02bd462310bd0fce83 | /pm_tasofro.h | f1d54c25a1b56866f052b9c701bbacfe5c0e56c8 | []
| no_license | LazurasLong/bgmlib | 56958b7dffd98d78f99466ce37c4abaddc7da5b1 | a9d557ea76a383fae54dc3729aaea455c258777a | refs/heads/master | 2022-12-04T02:58:36.450986 | 2011-08-16T17:44:46 | 2011-08-16T17:44:46 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,646 | h | // Music Room BGM Library
// ----------------------
// pm_tasofro.h - Twilight Frontier's Pack Methods
// ----------------------
// "©" Nmlgc, 2010
#ifndef BGMLIB_PM_TASOFRO_H
#define BGMLIB_PM_TASOFRO_H
// Pack Methods
#define BMWAV 0x3 // wave files in a single archive with header (only th075)
#define BMOGG 0x4 // Vorbis files and SFL loop info in a single archive with header (other Tasofro games)
// Encryptions
// -----------
#define CR_NONE 0x0 // No encryption
// Tasofro
#define CR_SUIKA 0x1 // Simple progressive XOR-encrypted header with lots of junk data, unencrypted files (th075, MegaMari)
#define CR_TENSHI 0x2 // Mersenne Twister pseudorandom encrypted header with an optional progressive XOR layer, static XOR-encrypted files (th105, th123, PatchCon)
// -----------
class PM_Tasofro : public PackMethod
{
private:
ulong HeaderSizeV2(FX::FXFile& In);
bool IsValidHeader(char* hdr, const FXuint& hdrSize, const FXushort& Files);
void DecryptHeaderV1(char* hdr, const FXuint& hdrSize);
void DecryptHeaderV2(char* hdr, const FXuint& hdrSize, const FXushort& Files);
protected:
virtual void GetPosData(GameInfo* GI, FX::FXFile& In, FXushort& Files, char* hdr, FXuint& hdrSize) = 0;
ulong HeaderSize(GameInfo* GI, FX::FXFile& In, const FXushort& Files);
bool DecryptHeader(GameInfo* GI, char* hdr, const FXuint& hdrSize, const FXushort& Files);
bool CheckCryptKind(ConfigFile& NewGame, const uchar& CRKind); // Checks if given encryption kind is valid
public:
virtual bool TrackData(GameInfo* GI);
};
// PM_BMWav
// --------
class PM_BMWav : public PM_Tasofro
{
protected:
PM_BMWav() {ID = BMWAV;}
void GetPosData(GameInfo* GI, FX::FXFile& In, FXushort& Files, char* hdr, FXuint& hdrSize);
public:
// Checks the track count from the first two bytes of [Target]'s BGM file
bool BGMFile_Check(GameInfo* Target);
#ifdef SUPPORT_VORBIS_PM
bool BGMFile_Check_Vorbis(GameInfo* GI, FXString& FN, FXString& Ext, FXString& LastVorbisFN, bool* TrgVorbis, OggVorbis_File* VF);
// Custom implementation for the Vorbis case
// Normal case defaults back to PM_Tasofro::TrackData
bool TrackData(GameInfo* GI);
#endif
bool ParseGameInfo(ConfigFile& NewGame, GameInfo* GI);
bool ParseTrackInfo(ConfigFile& NewGame, GameInfo* GI, ConfigParser* TS, TrackInfo* NewTrack); // return true if position data should be read from config file
GameInfo* Scan(const FXString& Path); // Scans [Path] for a game packed with this method
FXString DiskFN(GameInfo* GI, TrackInfo* TI);
SINGLETON(PM_BMWav);
};
// --------
// PM_BMOgg
// --------
class PM_BMOgg : public PM_Tasofro
{
protected:
PM_BMOgg() {ID = BMOGG;}
void MetaData(GameInfo* GI, FXFile& In, const ulong& Pos, const ulong& Size, TrackInfo* TI); // SFL Format
void GetPosData(GameInfo* GI, FX::FXFile& In, FXushort& Files, char* hdr, FXuint& hdrSize);
public:
bool ParseGameInfo(ConfigFile& NewGame, GameInfo* GI);
bool ParseTrackInfo(ConfigFile& NewGame, GameInfo* GI, ConfigParser* TS, TrackInfo* NewTrack); // return true if position data should be read from config file
inline ulong DecryptBuffer(const uchar& CryptKind, char* Out, const ulong& Pos, const ulong& Size); // Contains the decryption algorithm
ulong DecryptFile(GameInfo* GI, FXFile& In, char* Out, const ulong& Pos, const ulong& Size, volatile FXulong* p = NULL);
GameInfo* Scan(const FXString& Path); // Scans [Path] for a game packed with this method
FXString DiskFN(GameInfo* GI, TrackInfo* TI);
SINGLETON(PM_BMOgg);
};
// --------
#endif /* BGMLIB_PM_TASOFRO_H */ | [
"[email protected]"
]
| [
[
[
1,
100
]
]
]
|
65b15380b07619e3fb6a20fcd27f4834a033b55d | 58ef4939342d5253f6fcb372c56513055d589eb8 | /WallpaperChanger/WallpaperChange/source/SMS/src/SMSSendRecv.cpp | 24a9d5414fa42ccd28448259b4d08a141a38aaf6 | []
| no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 11,705 | cpp | // SMSSendRecv.cpp
//
// Copyright (c) 2003 Symbian Ltd. All rights reserved.
//
#include "SMSSendRecv.h"
//To get SMS service centre address
#include <SMUTSET.H>
#include <MSVAPI.H>
#include "OKCDebug.h"
#ifdef EKA2
#include <csmsaccount.h>
#else
//Observer class, required to get the service centre address before EKA2
class CObserver : public MMsvSessionObserver
{
public:
void HandleSessionEvent(TMsvSessionEvent aEvent, TAny* aArg1, TAny* aArg2, TAny* aArg3);
void HandleSessionEventL(TMsvSessionEvent aEvent, TAny* aArg1, TAny* aArg2, TAny* aArg3);
};
void CObserver::HandleSessionEvent(TMsvSessionEvent /*aEvent*/, TAny* /*aArg1*/, TAny* /*aArg2*/, TAny* /*aArg3*/) {}
void CObserver::HandleSessionEventL(TMsvSessionEvent /*aEvent*/, TAny* /*aArg1*/, TAny* /*aArg2*/, TAny* /*aArg3*/) {}
#endif
CSMSSender* CSMSSender::NewL()
/**
Intended Usage: Static factory constructor. Uses two phase
construction and leaves nothing on the CleanupStack.
@returns a new CSMSSender instance.
*/
{
CSMSSender* self = NewLC();
CleanupStack::Pop();
return self;
}
CSMSSender* CSMSSender::NewLC()
/**
Intended Usage: Static factory constructor. Uses two phase
construction and leaves a CSMSSender instance on the CleanupStack.
@returns a new CSMSSender instance.
*/
{
CSMSSender* self = new(ELeave) CSMSSender;
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
void CSMSSender::ConstructL()
/**
Second phase of construction, opens connections to the Socket Server and File server,
and opens an SMS socket.
*/
{
iSocketServer.Connect();
iFs.Connect();
User::LeaveIfError(iSocket.Open(iSocketServer, KSMSAddrFamily, KSockDatagram, KSMSDatagramProtocol));
}
CSMSSender::~CSMSSender()
/**
Close the connections to the Socket Server, Socket and File Server
*/
{
iSocket.Close();
iSocketServer.Close();
iFs.Close();
}
void CSMSSender::CreateSMSMessageL(const TDesC& aText, const TDesC& aAddress)
/**
Prepare SMS specific objects ready to send via ESOCK
@param aText buffer containing ascii contents of message to send
@param aAddress buffer with telephone number of SMS receiver
*/
{
TSmsAddr smsAddr;
smsAddr.SetSmsAddrFamily(ESmsAddrSendOnly);
smsAddr.SetPort(smsAddr.Port() + 1);//ycf
__LOGSTR_TOFILE("sockent bind");
iSocket.Bind(smsAddr);
CSmsBuffer* smsBuffer = CSmsBuffer::NewL();
//CleanupStack::PushL(smsBuffer) is NOT used because CSmsMessage takes ownership of our buffer :-)
CSmsMessage* smsMsg = CSmsMessage::NewL(iFs, CSmsPDU::ESmsSubmit, smsBuffer);
CleanupStack::PushL(smsMsg);
TSmsUserDataSettings smsSettings;
smsSettings.SetAlphabet(TSmsDataCodingScheme::ESmsAlphabetUCS2);
smsSettings.SetTextCompressed(EFalse);
smsMsg->SetUserDataSettingsL(smsSettings);
TBuf<KMaxAddressSize> toAddress;
toAddress.Copy(aAddress);
smsMsg->SetToFromAddressL(toAddress);
//Get service centre address.
// The method used here assumes the SMS settings are provisioned, which is true in known cases.
// There are alternative partner-only APIs, however this allow this source to be kept public
#ifdef EKA2
CSmsSettings* smsSCSettings = CSmsSettings::NewL();
CleanupStack::PushL(smsSCSettings);
CSmsAccount* smsAccount=CSmsAccount::NewLC();
smsAccount->LoadSettingsL(*smsSCSettings);
// index of the default service centre address for this service
TInt defIndex;
User::LeaveIfError(defIndex = smsSCSettings->DefaultServiceCenter());
// Get the service center address
CSmsServiceCenter& scAddr = smsSCSettings->GetServiceCenter(defIndex);
TPtrC theAddress=scAddr.Address();
HBufC* serviceCentreAddress=HBufC::NewLC(theAddress.Length());
*serviceCentreAddress=theAddress;
smsMsg->SmsPDU().SetServiceCenterAddressL(*serviceCentreAddress);
CleanupStack::PopAndDestroy(serviceCentreAddress);//
CleanupStack::PopAndDestroy(smsAccount);
CleanupStack::PopAndDestroy(smsSCSettings);
#else
TMsvId serviceId;
CObserver* pObserver = new (ELeave) CObserver();
CleanupStack::PushL(pObserver);
CMsvSession* pSession = CMsvSession::OpenSyncL(*pObserver);
CleanupStack::PushL(pSession);
TSmsUtilities::ServiceIdL(*pSession, serviceId, KUidMsgTypeSMS);
CMsvEntry* service = pSession->GetEntryL(serviceId);
CleanupStack::PushL(service);
CMsvStore* msvstore = service->ReadStoreL();
CleanupStack::PushL(msvstore);
CSmsSettings* smsSCSettings = CSmsSettings::NewL();
CleanupStack::PushL(smsSCSettings);
smsSCSettings->RestoreL(*msvstore);
TInt defIndex;
User::LeaveIfError(defIndex = smsSCSettings->DefaultSC());
defIndex = smsSCSettings->DefaultSC();
// Get the default service center address
CSmsNumber& scAddr = smsSCSettings->SCAddress(defIndex);
TPtrC theAddress=scAddr.Address();
HBufC* serviceCentreAddress=HBufC::NewLC(theAddress.Length());
*serviceCentreAddress=theAddress;
smsMsg->SmsPDU().SetServiceCenterAddressL(*serviceCentreAddress);
CleanupStack::PopAndDestroy(serviceCentreAddress);//
CleanupStack::PopAndDestroy(smsSCSettings); //smsSettings
CleanupStack::PopAndDestroy(msvstore);
CleanupStack::PopAndDestroy(service);
CleanupStack::PopAndDestroy(pSession);
CleanupStack::PopAndDestroy(pObserver);
#endif
//convert to wide
HBufC* payload = HBufC::NewL(aText.Length());
CleanupStack::PushL(payload);
TPtr pPayload=payload->Des();
pPayload.Copy(aText); //copy from narrow to wide and convert
smsBuffer->InsertL(0, pPayload); //copies payload
RSmsSocketWriteStream writeStream(iSocket);
CleanupClosePushL(writeStream);
writeStream << *smsMsg; // remember << operator _CAN_ leave
__LOGSTR_TOFILE("write stream commit");
writeStream.CommitL();
CleanupStack::PopAndDestroy(&writeStream);
CleanupStack::PopAndDestroy(2);//smsMsg, payload
}
void CSMSSender::SendSMSL(const TDesC& aText, const TDesC& aAddress, TRequestStatus& aStatus)
/**
Send an SMS message Asynchronously
@param aText buffer containing ascii contents of message to send
@param aAddress buffer with telephone number of SMS receiver
@param aStatus TRequestStatus which receives completion notification following a Send
@capability NetworkServices
@capability ReadUserData
*/
{
__LOGSTR_TOFILE("create message");
CreateSMSMessageL(aText, aAddress);
__LOGSTR_TOFILE("socket ioctl");
iSocket.Ioctl(KIoctlSendSmsMessage, aStatus, &iBuf, KSolSmsProv);
__LOGSTR_TOFILE("send sms end");
}
/*
CSMSReceiver
*/
// Construction functions
CSMSReceiver::CSMSReceiver() : CActive(EPriorityStandard)
/**
Standard priortiy active object.
*/
{
}
CSMSReceiver* CSMSReceiver::NewL()
/**
Intended Usage: Static factory constructor. Uses two phase
construction and leaves nothing on the CleanupStack.
@returns a new CSMSSender instance.
*/
{
CSMSReceiver* self = NewLC();
CleanupStack::Pop();
return self;
}
CSMSReceiver* CSMSReceiver::NewLC()
/**
Intended Usage: Static factory constructor. Uses two phase
construction and leaves an instance of CSMSReceiver on the CleanupStack.
@returns a new CSMSSender instance.
*/
{
CSMSReceiver* self = new(ELeave) CSMSReceiver;
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
void CSMSReceiver::ConstructL()
/**
Second phase of construction, opens connections to the Socket Server and File server,
and opens an SMS socket.
*/
{
iSocketServer.Connect();
iFs.Connect();
User::LeaveIfError(iSocket.Open(iSocketServer, KSMSAddrFamily, KSockDatagram, KSMSDatagramProtocol));
iReceiveStatus = EIdle;
CActiveScheduler::Add(this);
}
CSMSReceiver::~CSMSReceiver()
/**
Cancels any outstanding Receive, before closing sessions with the Socket and File Servers.
*/
{
Cancel(); //Cancel any outstanding Receiver
iSocket.Close();
iSocketServer.Close();
iFs.Close();
if(iSmsMsg)
{
delete iSmsMsg;
}
}
void CSMSReceiver::RunL()
/**
Handle asynchronous receive which is a two step process.
1. Accept and process an incoming SMS
2. Inform network that you received the message and not to try a resend.
Then we can complete the clients TRequestStatus we stored earlier
*/
{
switch (iReceiveStatus)
{
case EListening:
{
// Got an SMS, lets extract it
ExtractMessageL();
// And now let the network know that we received the message so that we
// do not receive another attempt
iSocket.Ioctl(KIoctlReadMessageSucceeded, iStatus, &iBuf, KSolSmsProv);
iReceiveStatus = EAcknowledging;
SetActive();
break;
}
case EAcknowledging:
// Finished Network acknowledgement. Client now needs to be informed
// of the outcome
User::RequestComplete(iClientStatus, iStatus.Int());
break;
default:
User::Panic(_L("Not Possible to be in RunL in Idle state"),KErrUnknown);
break;
}
}
void CSMSReceiver::DoCancel()
/**
Cancel any outstanding Ioctls.
*/
{
iSocket.CancelIoctl();
User::RequestComplete(iClientStatus, KErrCancel);
}
void CSMSReceiver::SetupSocketsL(const TDesC8& aPattern)
/**
Bind to socket and specify pattern match so that only incoming messages matching
the pattern are intercepted. Other messages will be caught by the messaging component.
@param aPattern buffer pattern match at beginning of incoming SMS message. Only SMS
messages containing this Pattern match will be intercepted.
*/
{
TSmsAddr smsAddr;
smsAddr.SetSmsAddrFamily(ESmsAddrMatchText);
smsAddr.SetTextMatch(aPattern);
// smsAddr.SetSmsAddrFamily(ESmsAddrApplication16BitPort);
// smsAddr.SetPort(111); //kjava»½ÐѶ˿Ú
User::LeaveIfError(iSocket.Bind(smsAddr));
}
void CSMSReceiver::ExtractMessageL()
/**
Following receive extract the contents of the message and store within CDatagram object.
*/
{
CSmsBuffer* buffer;
buffer=CSmsBuffer::NewL();
//CleanupStack::PushL(buffer) is NOT used because CSmsMessage takes ownership of our buffer :-)
iSmsMsg = CSmsMessage::NewL(iFs, CSmsPDU::ESmsSubmit, buffer);
RSmsSocketReadStream readStream(iSocket);
CleanupClosePushL(readStream);
readStream >> *iSmsMsg;
CleanupStack::PopAndDestroy(&readStream);
HBufC* dgram = HBufC::NewLC(KMaxSMSSize);
TPtr ptr = dgram->Des();
buffer->Extract(ptr, 0, buffer->Length());
// Convert from unicode data
TBuf<KMaxSMSSize> buf; // it is ok to do this on the stack because SMS size is small
buf.Copy(*dgram);
iDatagram->SetDataL(buf);
//ycf
TPtrC addr = iSmsMsg->ToFromAddress();
TBuf<KMaxSMSSize> bufAddr; // it is ok to do this on the stack because SMS size is small
bufAddr.Copy( addr );
iDatagram->SetAddressL( bufAddr );
//ycf
if (iSmsMsg)
{
delete iSmsMsg;
iSmsMsg=NULL;
}
// RLog::Log(*dgram);
CleanupStack::PopAndDestroy(); //dgram
}
void CSMSReceiver::ListenForSMSL(const TDesC8& aPattern, CDatagram* aDatagram, TRequestStatus& aStatus)
/**
Receive an SMS message Asynchronously
@param aPattern buffer pattern match at beginning of incoming SMS message. Only SMS
messages containing this Pattern match will be intercepted. Example: //MYPATTERN
@param aDatagram CDatagram to be populated during receive.
@param aStatus will receive completion notification following receive
*/
{
aStatus = KRequestPending;
iDatagram = aDatagram;
iClientStatus = &aStatus;
SetupSocketsL(aPattern);
iBuf()=KSockSelectRead;
iSocket.Ioctl(KIOctlSelect, iStatus, &iBuf,KSOLSocket);
iReceiveStatus = EListening;
SetActive();
}
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
389
]
]
]
|
3ff915c14c8a0a8f0cab21572bc46ced3d10a9b8 | 028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32 | /src/drivers/munchmo.cpp | d8199d173d4e1a86a88d25fe0fe5f8a5d4e95c8d | []
| 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 | 13,091 | cpp | #include "../vidhrdw/munchmo.cpp"
/***************************************************************************
Munch Mobile
(C) 1982 SNK
2 Z80s
2 AY-8910s
15 MHz crystal
Known Issues:
- sprite priority problems
- it's unclear if mirroring the videoram chunks is correct behavior
- several unmapped registers
- sustained sounds (when there should be silence)
***************************************************************************/
#include "driver.h"
#include "cpu/z80/z80.h"
#include "vidhrdw/generic.h"
extern UINT8 *mnchmobl_vreg;
extern UINT8 *mnchmobl_status_vram;
extern UINT8 *mnchmobl_sprite_xpos;
extern UINT8 *mnchmobl_sprite_attr;
extern UINT8 *mnchmobl_sprite_tile;
void mnchmobl_convert_color_prom(unsigned char *palette, unsigned short *colortable,const unsigned char *color_prom);
int mnchmobl_vh_start( void );
void mnchmobl_vh_stop( void );
WRITE_HANDLER( mnchmobl_palette_bank_w );
WRITE_HANDLER( mnchmobl_flipscreen_w );
READ_HANDLER( mnchmobl_sprite_xpos_r );
WRITE_HANDLER( mnchmobl_sprite_xpos_w );
READ_HANDLER( mnchmobl_sprite_attr_r );
WRITE_HANDLER( mnchmobl_sprite_attr_w );
READ_HANDLER( mnchmobl_sprite_tile_r );
WRITE_HANDLER( mnchmobl_sprite_tile_w );
READ_HANDLER( mnchmobl_videoram_r );
WRITE_HANDLER( mnchmobl_videoram_w );
void mnchmobl_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh);
/***************************************************************************/
static int mnchmobl_nmi_enable = 0;
static WRITE_HANDLER( mnchmobl_nmi_enable_w )
{
mnchmobl_nmi_enable = data;
}
static int mnchmobl_interrupt( void )
{
static int which;
which = !which;
if( which ) return interrupt();
if( mnchmobl_nmi_enable ) return nmi_interrupt();
return ignore_interrupt();
}
WRITE_HANDLER( mnchmobl_soundlatch_w )
{
soundlatch_w( offset, data );
cpu_cause_interrupt( 1, Z80_IRQ_INT );
}
static struct MemoryReadAddress readmem[] =
{
{ 0x0000, 0x3fff, MRA_ROM },
{ 0x8000, 0x83ff, MRA_RAM }, /* working RAM */
{ 0xa000, 0xa3ff, MRA_RAM },
{ 0xa400, 0xa7ff, mnchmobl_sprite_xpos_r }, /* mirrored */
{ 0xa800, 0xabff, MRA_RAM },
{ 0xac00, 0xafff, mnchmobl_sprite_tile_r }, /* mirrored */
{ 0xb000, 0xb3ff, MRA_RAM },
{ 0xb400, 0xb7ff, mnchmobl_sprite_attr_r }, /* mirrored */
{ 0xb800, 0xb8ff, MRA_RAM },
{ 0xb900, 0xb9ff, mnchmobl_videoram_r }, /* mirrored */
{ 0xbe02, 0xbe02, input_port_3_r }, /* DSW1 */
{ 0xbe03, 0xbe03, input_port_4_r }, /* DSW2 */
{ 0xbf01, 0xbf01, input_port_0_r }, /* coin, start */
{ 0xbf02, 0xbf02, input_port_1_r }, /* P1 controls */
{ 0xbf03, 0xbf03, input_port_2_r }, /* P2 controls */
{ -1 }
};
static struct MemoryWriteAddress writemem[] =
{
{ 0x0000, 0x3fff, MWA_ROM },
{ 0x8000, 0x83ff, MWA_RAM }, /* working RAM */
{ 0xa000, 0xa3ff, MWA_RAM, &mnchmobl_sprite_xpos },
{ 0xa400, 0xa7ff, mnchmobl_sprite_xpos_w },
{ 0xa800, 0xabff, MWA_RAM, &mnchmobl_sprite_tile },
{ 0xac00, 0xafff, mnchmobl_sprite_tile_w },
{ 0xb000, 0xb3ff, MWA_RAM, &mnchmobl_sprite_attr },
{ 0xb400, 0xb7ff, mnchmobl_sprite_attr_w },
{ 0xb800, 0xb9ff, mnchmobl_videoram_w, &videoram },
{ 0xba00, 0xbbff, MWA_RAM },
{ 0xbc00, 0xbc7f, MWA_RAM, &mnchmobl_status_vram },
{ 0xbe00, 0xbe00, mnchmobl_soundlatch_w },
{ 0xbe01, 0xbe01, mnchmobl_palette_bank_w },
{ 0xbe11, 0xbe11, MWA_RAM }, /* ? */
{ 0xbe21, 0xbe21, MWA_RAM }, /* ? */
{ 0xbe31, 0xbe31, MWA_RAM }, /* ? */
{ 0xbe41, 0xbe41, mnchmobl_flipscreen_w },
{ 0xbe61, 0xbe61, mnchmobl_nmi_enable_w }, /* ENI 1-10C */
{ 0xbf00, 0xbf07, MWA_RAM, &mnchmobl_vreg }, /* MY0 1-8C */
{ -1 }
};
static struct MemoryReadAddress readmem_sound[] =
{
{ 0x0000, 0x1fff, MRA_ROM },
{ 0x2000, 0x2000, soundlatch_r },
{ 0xe000, 0xe7ff, MRA_RAM },
{ -1 }
};
static struct MemoryWriteAddress writemem_sound[] =
{
{ 0x0000, 0x1fff, MWA_ROM },
{ 0x4000, 0x4000, AY8910_write_port_0_w },
{ 0x5000, 0x5000, AY8910_control_port_0_w },
{ 0x6000, 0x6000, AY8910_write_port_1_w },
{ 0x7000, 0x7000, AY8910_control_port_1_w },
{ 0x8000, 0x8000, MWA_NOP }, /* ? */
{ 0xa000, 0xa000, MWA_NOP }, /* ? */
{ 0xc000, 0xc000, MWA_NOP }, /* ? */
{ 0xe000, 0xe7ff, MWA_RAM },
{ -1 }
};
static struct AY8910interface ay8910_interface =
{
2, /* 2 chips */
1500000, /* 1.5 MHz? */
{ 50, 50 },
{ 0 },
{ 0 },
{ 0 },
{ 0 }
};
INPUT_PORTS_START( mnchmobl )
PORT_START
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_COIN1 )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_COIN2 ) /* service */
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_START1 )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_START2 )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_UNKNOWN )
PORT_START /* P1 controls */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_8WAY )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_8WAY )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_LEFT | IPF_8WAY )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_RIGHT | IPF_8WAY )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_LEFT | IPF_2WAY )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_RIGHT | IPF_2WAY )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* P2 controls */
PORT_BIT( 0x01, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_UP | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_DOWN | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_LEFT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICKLEFT_RIGHT | IPF_8WAY | IPF_COCKTAIL )
PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_LEFT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_JOYSTICKRIGHT_RIGHT | IPF_2WAY | IPF_COCKTAIL )
PORT_BIT( 0xc0, IP_ACTIVE_LOW, IPT_UNUSED )
PORT_START /* DSW1 0xbe02 */
PORT_DIPNAME( 0x01, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x01, DEF_STR( On ) )
PORT_DIPNAME( 0x1e, 0x00, DEF_STR( Coinage ) )
PORT_DIPSETTING( 0x14, DEF_STR( 3C_1C ) )
// PORT_DIPSETTING( 0x12, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x10, DEF_STR( 2C_1C ) )
PORT_DIPSETTING( 0x16, DEF_STR( 3C_2C ) )
PORT_DIPSETTING( 0x00, DEF_STR( 1C_1C ) )
// PORT_DIPSETTING( 0x1e, DEF_STR( 1C_1C ) )
// PORT_DIPSETTING( 0x1c, DEF_STR( 1C_1C ) )
// PORT_DIPSETTING( 0x1a, DEF_STR( 1C_1C ) )
// PORT_DIPSETTING( 0x18, DEF_STR( 1C_1C ) )
PORT_DIPSETTING( 0x02, DEF_STR( 1C_2C ) )
PORT_DIPSETTING( 0x04, DEF_STR( 1C_3C ) )
PORT_DIPSETTING( 0x06, DEF_STR( 1C_4C ) )
PORT_DIPSETTING( 0x08, DEF_STR( 1C_5C ) )
PORT_DIPSETTING( 0x0a, DEF_STR( 1C_6C ) )
PORT_DIPSETTING( 0x0c, DEF_STR( 1C_7C ) )
PORT_DIPSETTING( 0x0e, DEF_STR( 1C_8C ) )
PORT_DIPNAME( 0xe0, 0x00, DEF_STR( Bonus_Life ) )
PORT_DIPSETTING( 0x00, "No Bonus" )
PORT_DIPSETTING( 0x20, "70000" )
PORT_DIPSETTING( 0x40, "60000" )
PORT_DIPSETTING( 0x60, "50000" )
PORT_DIPSETTING( 0x80, "40000" )
PORT_DIPSETTING( 0xa0, "30000" )
PORT_DIPSETTING( 0xc0, "20000" )
PORT_DIPSETTING( 0xe0, "10000" )
PORT_START /* DSW2 0xbe03 */
PORT_DIPNAME( 0x03, 0x00, "Second Bonus Life" )
PORT_DIPSETTING( 0x00, "No Bonus?" )
PORT_DIPSETTING( 0x01, "100000?" )
PORT_DIPSETTING( 0x02, "40000?" )
PORT_DIPSETTING( 0x03, "30000?" )
PORT_DIPNAME( 0x0c, 0x0c, DEF_STR( Lives ) )
PORT_DIPSETTING( 0x00, "1" )
PORT_DIPSETTING( 0x04, "2" )
PORT_DIPSETTING( 0x08, "3" )
PORT_DIPSETTING( 0x0c, "5" )
PORT_DIPNAME( 0x10, 0x00, "Freeze" )
PORT_DIPSETTING( 0x00, DEF_STR( No ) )
PORT_DIPSETTING( 0x10, DEF_STR( Yes ) )
PORT_DIPNAME( 0x20, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x20, DEF_STR( On ) )
PORT_DIPNAME( 0x40, 0x00, DEF_STR( Cabinet ) )
PORT_DIPSETTING( 0x00, DEF_STR( Upright ) )
PORT_DIPSETTING( 0x40, DEF_STR( Cocktail ) )
PORT_DIPNAME( 0x80, 0x00, DEF_STR( Unknown ) )
PORT_DIPSETTING( 0x00, DEF_STR( Off ) )
PORT_DIPSETTING( 0x80, DEF_STR( On ) )
INPUT_PORTS_END
static struct GfxLayout char_layout =
{
8,8,
256,
4,
{ 0, 8, 256*128,256*128+8 },
{ 7,6,5,4,3,2,1,0 },
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 },
128
};
static struct GfxLayout tile_layout =
{
8,8,
0x100,
4,
{ 8,12,0,4 },
{ 0,0,1,1,2,2,3,3 },
{ 0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16 },
128
};
static struct GfxLayout sprite_layout1 =
{
32,32,
128,
3,
{ 0x4000*8,0x2000*8,0 },
{
7,7,6,6,5,5,4,4,3,3,2,2,1,1,0,0,
0x8000+7,0x8000+7,0x8000+6,0x8000+6,0x8000+5,0x8000+5,0x8000+4,0x8000+4,
0x8000+3,0x8000+3,0x8000+2,0x8000+2,0x8000+1,0x8000+1,0x8000+0,0x8000+0
},
{
0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8,10*8,11*8,12*8,13*8,14*8,15*8,
16*8,17*8,18*8,19*8,20*8,21*8,22*8,23*8,
24*8,25*8,26*8,27*8,28*8,29*8,30*8,31*8
},
256
};
static struct GfxLayout sprite_layout2 =
{
32,32,
128,
3,
{ 0,0,0 },
{
7,7,6,6,5,5,4,4,3,3,2,2,1,1,0,0,
0x8000+7,0x8000+7,0x8000+6,0x8000+6,0x8000+5,0x8000+5,0x8000+4,0x8000+4,
0x8000+3,0x8000+3,0x8000+2,0x8000+2,0x8000+1,0x8000+1,0x8000+0,0x8000+0
},
{
0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8,
8*8, 9*8,10*8,11*8,12*8,13*8,14*8,15*8,
16*8,17*8,18*8,19*8,20*8,21*8,22*8,23*8,
24*8,25*8,26*8,27*8,28*8,29*8,30*8,31*8
},
256
};
static struct GfxDecodeInfo gfxdecodeinfo[] =
{
{ REGION_GFX1, 0, &char_layout, 0, 4 }, /* colors 0- 63 */
{ REGION_GFX2, 0x1000, &tile_layout, 64, 4 }, /* colors 64-127 */
{ REGION_GFX3, 0, &sprite_layout1, 128, 16 }, /* colors 128-255 */
{ REGION_GFX4, 0, &sprite_layout2, 128, 16 }, /* colors 128-255 */
{ -1 }
};
static struct MachineDriver machine_driver_munchmo =
{
{
{
CPU_Z80,
3750000, /* ? */
readmem,writemem,0,0,
mnchmobl_interrupt,2
},
{
CPU_Z80 | CPU_AUDIO_CPU,
3750000, /* ? */
readmem_sound,writemem_sound,0,0,
nmi_interrupt,1
}
},
57, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */
1,
0,
/* video hardware */
256+32+32, 256, { 0, 255+32+32,0, 255-16 },
gfxdecodeinfo,
256,256,
mnchmobl_convert_color_prom,
VIDEO_TYPE_RASTER,
0,
mnchmobl_vh_start,
mnchmobl_vh_stop,
mnchmobl_vh_screenrefresh,
/* sound hardware */
0,0,0,0,
{
{
SOUND_AY8910,
&ay8910_interface
}
}
};
ROM_START( joyfulr )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for CPUA */
ROM_LOAD( "m1j.10e", 0x0000, 0x2000, 0x1fe86e25 )
ROM_LOAD( "m2j.10d", 0x2000, 0x2000, 0xb144b9a6 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound CPU */
ROM_LOAD( "mu.2j", 0x0000, 0x2000, 0x420adbd4 )
ROM_REGION( 0x2000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "s1.10a", 0x0000, 0x1000, 0xc0bcc301 ) /* characters */
ROM_LOAD( "s2.10b", 0x1000, 0x1000, 0x96aa11ca )
ROM_REGION( 0x2000, REGION_GFX2 )
ROM_LOAD( "b1.2c", 0x0000, 0x1000, 0x8ce3a403 ) /* tile layout */
ROM_LOAD( "b2.2b", 0x1000, 0x1000, 0x0df28913 ) /* 4x8 tiles */
ROM_REGION( 0x6000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "f1j.1g", 0x0000, 0x2000, 0x93c3c17e ) /* sprites */
ROM_LOAD( "f2j.3g", 0x2000, 0x2000, 0xb3fb5bd2 )
ROM_LOAD( "f3j.5g", 0x4000, 0x2000, 0x772a7527 )
ROM_REGION( 0x2000, REGION_GFX4 | REGIONFLAG_DISPOSE )
ROM_LOAD( "h", 0x0000, 0x2000, 0x332584de ) /* monochrome sprites */
ROM_REGION( 0x0100, REGION_PROMS )
ROM_LOAD( "a2001.clr", 0x0000, 0x0100, 0x1b16b907 ) /* color prom */
ROM_END
ROM_START( mnchmobl )
ROM_REGION( 0x10000, REGION_CPU1 ) /* 64k for CPUA */
ROM_LOAD( "m1.10e", 0x0000, 0x2000, 0xa4bebc6a )
ROM_LOAD( "m2.10d", 0x2000, 0x2000, 0xf502d466 )
ROM_REGION( 0x10000, REGION_CPU2 ) /* 64k for sound CPU */
ROM_LOAD( "mu.2j", 0x0000, 0x2000, 0x420adbd4 )
ROM_REGION( 0x2000, REGION_GFX1 | REGIONFLAG_DISPOSE )
ROM_LOAD( "s1.10a", 0x0000, 0x1000, 0xc0bcc301 ) /* characters */
ROM_LOAD( "s2.10b", 0x1000, 0x1000, 0x96aa11ca )
ROM_REGION( 0x2000, REGION_GFX2 )
ROM_LOAD( "b1.2c", 0x0000, 0x1000, 0x8ce3a403 ) /* tile layout */
ROM_LOAD( "b2.2b", 0x1000, 0x1000, 0x0df28913 ) /* 4x8 tiles */
ROM_REGION( 0x6000, REGION_GFX3 | REGIONFLAG_DISPOSE )
ROM_LOAD( "f1.1g", 0x0000, 0x2000, 0xb75411d4 ) /* sprites */
ROM_LOAD( "f2.3g", 0x2000, 0x2000, 0x539a43ba )
ROM_LOAD( "f3.5g", 0x4000, 0x2000, 0xec996706 )
ROM_REGION( 0x2000, REGION_GFX4 | REGIONFLAG_DISPOSE )
ROM_LOAD( "h", 0x0000, 0x2000, 0x332584de ) /* monochrome sprites */
ROM_REGION( 0x0100, REGION_PROMS )
ROM_LOAD( "a2001.clr", 0x0000, 0x0100, 0x1b16b907 ) /* color prom */
ROM_END
GAME( 1983, joyfulr, 0, munchmo, mnchmobl, 0, ROT270, "SNK", "Joyful Road (US)" )
GAME( 1983, mnchmobl, joyfulr, munchmo, mnchmobl, 0, ROT270, "SNK (Centuri license)", "Munch Mobile (Japan)" )
| [
"[email protected]"
]
| [
[
[
1,
403
]
]
]
|
1839d6a2005d885b9a975cd06467307bf1d2379f | 3ecc6321b39e2aedb14cb1834693feea24e0896f | /test/md2viewer.cpp | 841a7fab7a0333aba075cfbaba661806f4c440de | []
| no_license | weimingtom/forget3d | 8c1d03aa60ffd87910e340816d167c6eb537586c | 27894f5cf519ff597853c24c311d67c7ce0aaebb | refs/heads/master | 2021-01-10T02:14:36.699870 | 2011-06-24T06:21:14 | 2011-06-24T06:21:14 | 43,621,966 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,395 | cpp | /*****************************************************************************
* Copyright (C) 2009 The Forget3D Project by Martin Foo ([email protected])
* ALL RIGHTS RESERVED
*
* License I
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITHOUT a fee is granted under following requirements:
* - You make no money using this software.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* Licence II
* Permission to use, copy, modify, and distribute this software for
* any purpose and WITH a fee is granted under following requirements:
* - As soon as you make money using this software, you have to pay a
* licence fee. Until this point of time, you can use this software
* without a fee.
* Please contact Martin Foo ([email protected]) for further details.
* - The authors and/or this software is credited in your software or any
* work based on this software.
*
* THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
* AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
* FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL THE AUTHORS
* BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER,
* INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR
* REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT THE AUTHORS HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
* POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
*****************************************************************************/
#ifdef ANDROID
#include <sys/time.h>
#elif defined(_WIN32_WCE)
#include <aygshell.h>
#endif
#include "f3d.h"
#include "world.h"
#include "camera.h"
#include "image.h"
#include "model_md2.h"
#include "font.h"
#include "plane.h"
#include "skydome.h"
#include "fog.h"
using namespace F3D;
//F3D variables
World* world = NULL;
Camera* camera = NULL;
ModelMD2* model = NULL;
ModelMD2* weapon = NULL;
Font* font = NULL;
Plane* plane = NULL;
Skydome* skydome = NULL;
Fog* fog = NULL;
static char strFps[16];
static char strAction[32];
static int fps = 0;
static int is_done = 0;
static int action_idx = 0;
static int interval = 0;
static float angle = 0.0f;
#ifdef ANDROID
static int i_time = 0;
static int is_changed = false;
static struct timeval timeNow;
#elif (defined(WIN32) || defined(_WIN32_WCE))
static DWORD i_time = 0;
static int width = 480;
static int height = 640;
static int is_initialized = false;
static int is_foged = true;
static HWND hwnd;
#endif
#if (defined(WIN32) || defined(_WIN32_WCE))
static LRESULT CALLBACK WndProc(HWND wnd, UINT message,
WPARAM wParam, LPARAM lParam) {
RECT rc;
int useDefWindowProc = 0;
switch (message) {
case WM_CLOSE:
DestroyWindow(wnd);
is_done = 0;
break;
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
DestroyWindow(wnd);
is_done = 0;
break;
case WM_DESTROY:
PostQuitMessage(0);
is_done = 0;
break;
case WM_KEYDOWN:
#ifdef DEBUG
TCHAR szError[32];
wsprintf (szError, TEXT("WM_KEYDOWN: 0x%2x"), wParam);
MessageBox (hwnd, szError, TEXT("Debug"), MB_OK);
#endif
if (wParam == VK_ESCAPE || wParam == 0x51 || wParam == 0x86) { //press "ESC" or "Q" then exit
is_done = 0;
} else if (wParam == VK_UP) {
action_idx--;
if (action_idx < 0)
action_idx = model->getActionCount() - 1;
//go to prior action
model->setActionIndex(action_idx);
weapon->setActionIndex(action_idx);
} else if (wParam == VK_DOWN) {
action_idx++;
if (action_idx >= (int)model->getActionCount())
action_idx = 0;
//go to next action
model->setActionIndex(action_idx);
weapon->setActionIndex(action_idx);
} else if (wParam == 0x46) { //if press "F" then enable/disable fog
is_foged = !is_foged;
if (is_foged)
world->setFog(fog);
else
world->setFog(NULL);
}
break;
case WM_SIZE:
GetWindowRect(hwnd, &rc);
width = rc.right;
height = rc.bottom;
if (is_initialized) {
world->resize(width, height);
}
break;
default:
useDefWindowProc = 1;
}
if (useDefWindowProc)
return DefWindowProc(wnd, message, wParam, lParam);
return 0;
}
#endif
#if (defined(WIN32) || defined(_WIN32_WCE))
#define WINDOW_CLASS TEXT("F3D")
#define TITLE TEXT("Md2Viewer")
int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance,
LPTSTR cmdLine, int cmdShow) {
MSG msg;
WNDCLASS wc;
DWORD windowStyle;
int windowX, windowY;
// register class
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = instance;
wc.hIcon = NULL;
wc.hCursor = 0;
#ifdef WIN32
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
#else
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
#endif
wc.lpszMenuName = NULL;
wc.lpszClassName = WINDOW_CLASS;
if (!RegisterClass(&wc)) {
//GetLastError()
return FALSE;
}
// init instance
windowStyle = WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE;
#ifdef _WIN32_WCE
width = GetSystemMetrics(SM_CXSCREEN);
height = GetSystemMetrics(SM_CYSCREEN);
windowX = windowY = 0;
#else
windowStyle |= WS_OVERLAPPEDWINDOW;
windowX = CW_USEDEFAULT;
windowY = 0;
#endif
hwnd = CreateWindow(WINDOW_CLASS,
TITLE,
windowStyle,
windowX,
windowY,
width,
height,
NULL,
NULL,
instance,
NULL);
if (!hwnd)
return FALSE;
ShowWindow(hwnd, cmdShow);
#ifdef _WIN32_WCE
SHFullScreen(hwnd,
SHFS_HIDETASKBAR | SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);
MoveWindow(hwnd, 0, 0, width, height, TRUE);
#endif
UpdateWindow(hwnd);
#else
//android main entry
int main(int argc, char *argv[]) {
#endif
printf("world->init()...\n");
world = World::getInstance();
world->setBgColor(0.5f, 0.5f, 0.5f, 0.0f);
#if (defined(WIN32) || defined(_WIN32_WCE))
world->setSize(width, height);
if (!world->init(hwnd)) {
MessageBox(hwnd, TEXT("Init world error!"), TEXT("Error"), MB_OK);
return 0;
}
//after create world, set is_initialized to true
is_initialized = true;
#else
world->init();
#endif
camera = world->getActiveCamera();
camera->setEye(60.0f, 15.0f, 60.0f);
float fogColor[] = { 0.9f, 0.9f, 0.9f, 1.0f };
fog = new Fog();
fog->setFogColor(fogColor);
fog->setFogStart(-5.0f);
fog->setFogEnd(5.0f);
fog->setFogDensity(0.004f);
world->setFog(fog);
Texture* texture0 = Image::loadTexture("tris.bmp");
Texture* texture1 = Image::loadTexture("weapon.bmp");
Texture* texture2 = Image::loadTexture("floor.bmp");
Texture* texture3 = Image::loadTexture("clouds.bmp");
model = new ModelMD2();
model->loadModel("tris.md2");
model->setActionIndex(action_idx);
if (texture0 != NULL)
model->setTextureId(texture0->textureId);
weapon = new ModelMD2();
weapon->loadModel("weapon.md2");
weapon->setActionIndex(action_idx);
if (texture1 != NULL)
weapon->setTextureId(texture1->textureId);
plane = new Plane(4, 4, 128.0f);
if (texture2 != NULL)
plane->setTextureId(texture2->textureId);
plane->setPosition(-256.0f, -28.0f, -256.0f);
skydome = new Skydome(256, 30.0f, 10.0f);
if (texture3 != NULL)
skydome->setTextureId(texture3->textureId);
skydome->setPosition(0.0f, (float)(-256 * sinf(DTOR * 10.0f)) - 28.0f, 0.0f);
font = new Font(16, 16, 24, 36, "font.bmp");
printf("model->getActionName(%d): %s\n", action_idx, model->getActionName(action_idx));
printf("start loop...\n");
is_done = 1;
#ifdef ANDROID
gettimeofday(&timeNow, NULL);
i_time = CLOCK(timeNow);
#elif (defined(WIN32) || defined(_WIN32_WCE))
i_time = GetTickCount();
#endif
sprintf(strFps, "Fps:%.2f", 0.0f);
printf("strFps: %s\n", strFps);
sprintf(strAction, "Action[%d]:%s", action_idx, model->getActionName(action_idx));
printf("%s\n", strAction);
while (is_done) {
#if (defined(WIN32) || defined(_WIN32_WCE))
while (PeekMessage(&msg, hwnd, 0, 0, PM_NOREMOVE)) {
if (GetMessage(&msg, hwnd, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
is_done = 0;
break;
}
}
#endif
world->prepareRender();
skydome->setRotate(-90.0f, 0.0f, angle);
skydome->renderModel();
plane->renderModel();
model->renderModel();
weapon->renderModel();
//printf("strFps: %s\n", strFps);
font->drawString(4, 4, strFps);
//draw action info
int w_height = world->getHeight();
int f_height = font->getFonHeight();
font->drawString(4, w_height - f_height - 4, strAction);
world->finishRender();
fps++;
angle += 0.1f;
#ifdef ANDROID
gettimeofday(&timeNow, NULL);
interval = CLOCK(timeNow) - i_time;
if (interval >= 40000) {
is_done = 0;
printf("fps\t\t: %.2f\n", fps * 1.0f / 40);
} else if (interval >= 20000) {
if (!is_changed) {
action_idx++;
model->setActionIndex(action_idx);
weapon->setActionIndex(action_idx);
printf("model->getActionName(%d): %s\n", action_idx, model->getActionName(action_idx));
is_changed = true;
}
}
//refresh strFps per second
if (((CLOCK(timeNow) - i_time) / 1000) % 2 == 0 && interval > 0) {
sprintf(strFps, "Fps:%.2f", fps * 1000.0f / interval);
sprintf(strAction, "Action[%d]:%s", action_idx, model->getActionName(action_idx));
}
#elif (defined(WIN32) || defined(_WIN32_WCE))
interval = GetTickCount() - i_time;
//refresh strFps per 0.5 second
if (interval >= 500) {
sprintf(strFps, "Fps:%.2f", fps * 1000.0f / interval);
sprintf(strAction, "Action[%d]:%s", action_idx, model->getActionName(action_idx));
//reset all time variables after get strFps
interval = 0;
i_time = GetTickCount();
fps = 0;
}
#endif
}
delete model;
delete weapon;
delete font;
delete plane;
delete skydome;
World::release();
return 0;
}
| [
"i25ffz@8907dee8-4f14-11de-b25e-a75f7371a613"
]
| [
[
[
1,
380
]
]
]
|
235ae4b65452fa969a226e94e523ee262091df3b | 4fc6aeeaad470f83f05b62d685e543d58cd30bd4 | /src/game/server/player.cpp | d347cb5f0e4316708651138f14e513706d801a36 | [
"LicenseRef-scancode-other-permissive",
"Zlib"
]
| permissive | blacktrader/CCity | 97f5385fecbcd9e3d555ebe777383873a793c788 | c95a45c66c0b2d74197388cd56c547d72c9bdd97 | refs/heads/master | 2021-01-10T14:18:13.841894 | 2010-12-22T09:33:41 | 2010-12-22T09:33:41 | 1,186,784 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,015 | cpp | #include <string>
#include <engine/e_server_interface.h>
#include <engine/e_config.h>
#include "player.hpp"
#include "gamecontext.hpp"
#include "score.hpp"
MACRO_ALLOC_POOL_ID_IMPL(PLAYER, MAX_CLIENTS)
PLAYER::PLAYER(int client_id, int *args)
{
respawn_tick = server_tick();
character = 0;
this->client_id = client_id;
this->save_x = args[0];
this->save_y = args[1];
this->diff = args[2];
account = new PLAYER_ACCOUNT(this);
}
PLAYER::~PLAYER()
{
delete character;
character = 0;
delete account;
}
void PLAYER::tick()
{
server_setclientscore(client_id, score);
// do latency stuff
{
CLIENT_INFO info;
if(server_getclientinfo(client_id, &info))
{
latency.accum += info.latency;
latency.accum_max = max(latency.accum_max, info.latency);
latency.accum_min = min(latency.accum_min, info.latency);
}
if(server_tick()%server_tickspeed() == 0)
{
latency.avg = latency.accum/server_tickspeed();
latency.max = latency.accum_max;
latency.min = latency.accum_min;
latency.accum = 0;
latency.accum_min = 1000;
latency.accum_max = 0;
}
}
if(!character && die_tick+server_tickspeed()*3 <= server_tick())
spawning = true;
if(character)
{
if(character->alive)
{
view_pos = character->pos;
}
else
{
delete character;
character = 0;
}
}
else if(spawning && respawn_tick <= server_tick())
try_respawn();
if (muted>0)
muted--;
static int rainbow_color = 0;
rainbow_color = (rainbow_color + 1) % 256;
rbc = rainbow_color * 0x010000 + 0xff00;
}
void PLAYER::snap(int snapping_client)
{
NETOBJ_CLIENT_INFO *client_info = (NETOBJ_CLIENT_INFO *)snap_new_item(NETOBJTYPE_CLIENT_INFO, client_id, sizeof(NETOBJ_CLIENT_INFO));
str_to_ints(&client_info->name0, 6, server_clientname(client_id));
str_to_ints(&client_info->skin0, 6, skin_name);
client_info->use_custom_color = use_custom_color;
client_info->color_body = color_body;
client_info->color_feet = color_feet;
NETOBJ_PLAYER_INFO *info = (NETOBJ_PLAYER_INFO *)snap_new_item(NETOBJTYPE_PLAYER_INFO, client_id, sizeof(NETOBJ_PLAYER_INFO));
info->latency = latency.min;
info->latency_flux = latency.max-latency.min;
info->local = 0;
info->cid = client_id;
info->score = score;
info->team = team;
if(client_id == snapping_client)
info->local = 1;
if((config.sv_rainbow) || (config.sv_rainbow_admin && authed && rb==true))
{
game.players[client_id]->use_custom_color = true;
client_info->color_body = rbc;
client_info->color_feet = rbc;
}
}
void PLAYER::on_disconnect()
{
kill_character(WEAPON_GAME);
//game.controller->on_player_death(&game.players[client_id], 0, -1);
char buf[512];
str_format(buf, sizeof(buf), "%s has left the game", server_clientname(client_id));
game.send_chat(-1, GAMECONTEXT::CHAT_ALL, buf);
dbg_msg("game", "leave player='%d:%s'", client_id, server_clientname(client_id));
}
void PLAYER::on_predicted_input(NETOBJ_PLAYER_INPUT *new_input)
{
CHARACTER *chr = get_character();
if(chr)
chr->on_predicted_input(new_input);
}
void PLAYER::on_direct_input(NETOBJ_PLAYER_INPUT *new_input)
{
CHARACTER *chr = get_character();
if(chr)
chr->on_direct_input(new_input);
if(!chr && team >= 0 && (new_input->fire&1))
spawning = true;
if(!chr && team == -1)
view_pos = vec2(new_input->target_x, new_input->target_y);
}
CHARACTER *PLAYER::get_character()
{
if(character && character->alive)
return character;
return 0;
}
void PLAYER::kill_character(int weapon)
{
//CHARACTER *chr = get_character();
if(character)
{
character->die(client_id, weapon);
delete character;
character = 0;
}
}
void PLAYER::respawn()
{
if(team > -1)
spawning = true;
}
void PLAYER::set_team(int new_team)
{
if(!logged_in){
game.send_broadcast("You are not logged in! Type /account", client_id);
return;}
// clamp the team
new_team = game.controller->clampteam(new_team);
if(team == new_team)
return;
char buf[512];
str_format(buf, sizeof(buf), "%s joined the %s", server_clientname(client_id), game.controller->get_team_name(new_team));
game.send_chat(-1, GAMECONTEXT::CHAT_ALL, buf);
kill_character(WEAPON_GAME);
team = new_team;
dbg_msg("game", "team_join player='%d:%s' team=%d", client_id, server_clientname(client_id), team);
game.controller->on_player_info_change(game.players[client_id]);
}
void PLAYER::try_respawn()
{
vec2 spawnpos = vec2(100.0f, -60.0f);
if(!game.controller->can_spawn(this, &spawnpos))
return;
// check if the position is occupado
ENTITY *ents[2] = {0};
int num_ents = game.world.find_entities(spawnpos, 64, ents, 2, NETOBJTYPE_CHARACTER);
if(num_ents == 0 || game.controller->is_race())
{
spawning = false;
character = new(client_id) CHARACTER();
character->spawn(this, spawnpos, team);
game.create_playerspawn(spawnpos);
}
}
| [
"[email protected]"
]
| [
[
[
1,
207
]
]
]
|
bffe783e348fd9bd604c4a21a63038415d6fce0a | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /MyGUIEngine/include/MyGUI_SubSkin.h | 8d0bd8ae45fecb6148d85652434326cac61186f1 | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,711 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*/
#ifndef __MYGUI_SUB_SKIN_H__
#define __MYGUI_SUB_SKIN_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_SharedPanelAlphaOverlayElement.h"
#include "MyGUI_CroppedRectangleInterface.h"
namespace MyGUI
{
class _MyGUIExport SubSkin : public CroppedRectangleInterface
{
public:
SubSkin(const SubWidgetInfo &_info, const Ogre::String & _material, CroppedRectanglePtr _parent, size_t _id);
virtual ~SubSkin();
void setAlpha(float _alpha);
void show();
void hide();
void _updateView(); // обновления себя и детей
void _correctView();
void _setAlign(const IntSize& _size, bool _update);
void _setAlign(const IntCoord& _coord, bool _update);
void _setUVSet(const FloatRect& _rect);
void _attachChild(CroppedRectanglePtr _basis, bool _child);
Ogre::OverlayElement* _getOverlayElement();
inline static const Ogre::String & _getType() {static Ogre::String type("SubSkin"); return type;}
inline static bool _isSharedOverlay() {return true;}
bool _isText() {return false;}
Ogre::OverlayElement* _getSharedOverlayElement() {return (mId == 0) ? mOverlayContainer : null;}
protected:
inline void _setTransparent(bool _transparent)
{
if (mTransparent == _transparent) return;
mTransparent = _transparent;
mOverlayContainer->setTransparentInfo(mTransparent, mId);
}
protected:
SharedPanelAlphaOverlayElement * mOverlayContainer;
FloatRect mRectTexture;
size_t mId;
bool mTransparent;
}; // class _MyGUIExport SubSkin : public SubWidgetSkinInterface
} // namespace MyGUI
#endif // __MYGUI_SUB_SKIN_H__
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
12
],
[
14,
14
],
[
17,
17
],
[
21,
21
],
[
24,
27
],
[
29,
30
],
[
32,
33
],
[
35,
35
],
[
37,
38
],
[
40,
54
],
[
57,
60
],
[
62,
62
],
[
64,
64
],
[
66,
66
]
],
[
[
13,
13
],
[
15,
16
],
[
18,
20
],
[
22,
23
],
[
28,
28
],
[
31,
31
],
[
34,
34
],
[
36,
36
],
[
39,
39
],
[
55,
56
],
[
61,
61
],
[
63,
63
],
[
65,
65
]
]
]
|
150736bd49a0b5904ebfbb8a2faccbd83d5df990 | 619843aa55e023fe4eb40a3f1b59da6bcb993a54 | /reactor/reactor.cc | 5d948ca7b4839e2928a55e9e675950f24a7b2822 | []
| no_license | pengvan/xiao5geproject | 82271ceb18d2c9ea7abb960c41e883ad54a7e8c6 | 3e28c80f0af5d11eb1c03c569e040dda33966e4a | refs/heads/master | 2016-09-11T02:19:09.285543 | 2011-06-17T07:05:34 | 2011-06-17T07:05:34 | 38,201,768 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,927 | cc | #include <assert.h>
#include "reactor.h"
#include "event_demultiplexer.h"
/// @file reactor.cc
/// @brief Reactor类实现
/// @author zeshengwu<[email protected]>
/// @date 2011-03-20
namespace reactor
{
/// reactor的实现类
class ReactorImplementation
{
public:
/// 构造函数
ReactorImplementation();
/// 析构函数
~ReactorImplementation();
/// 向reactor中注册关注事件evt的handler
/// @param handler 要注册的事件处理器
/// @param evt 要关注的事件
/// @retval =0 注册成功
/// @retval <0 注册出错
int RegisterHandler(EventHandler * handler, event_t evt);
/// 从reactor中移除handler
/// @param handler 要移除的事件处理器
/// @retval =0 移除成功
/// @retval <0 移除出错
int RemoveHandler(EventHandler * handler);
/// 处理事件,回调注册的handler中相应的事件处理函数
/// @param timeout 超时时间
void HandleEvents(int timeout);
private:
EventDemultiplexer * m_demultiplexer; ///< 事件多路分发器
std::map<handle_t, EventHandler *> m_handlers; ///< 所有handler集合
};
///////////////////////////////////////////////////////////////////////////////
/// 构造函数
Reactor::Reactor()
{
m_reactor_impl = new ReactorImplementation();
}
/// 析构函数
Reactor::~Reactor()
{
delete m_reactor_impl;
}
/// 向reactor中注册关注事件evt的handler
/// @param handler 要注册的事件处理器
/// @param evt 要关注的事件
/// @retval =0 注册成功
/// @retval <0 注册出错
int Reactor::RegisterHandler(EventHandler * handler, event_t evt)
{
return m_reactor_impl->RegisterHandler(handler, evt);
}
/// 从reactor中移除handler
/// @param handler 要移除的事件处理器
/// @retval =0 移除成功
/// @retval <0 移除出错
int Reactor::RemoveHandler(EventHandler * handler)
{
return m_reactor_impl->RemoveHandler(handler);
}
/// 处理事件,回调注册的handler中相应的事件处理函数
/// @param timeout 超时时间
void Reactor::HandleEvents(int timeout)
{
m_reactor_impl->HandleEvents(timeout);
}
///////////////////////////////////////////////////////////////////////////////
/// 构造函数
ReactorImplementation::ReactorImplementation()
{
#if defined(_WIN32)
m_demultiplexer = new SelectDemultiplexer();
#elif defined(__linux__)
m_demultiplexer = new EpollDemultiplexer();
#else
#error "目前还不支持该平台"
#endif // _WIN32
}
/// 析构函数
ReactorImplementation::~ReactorImplementation()
{
delete m_demultiplexer;
}
/// 向reactor中注册关注事件evt的handler
/// @param handler 要注册的事件处理器
/// @param evt 要关注的事件
/// @retval =0 注册成功
/// @retval <0 注册出错
int ReactorImplementation::RegisterHandler(EventHandler * handler, event_t evt)
{
handle_t handle = handler->GetHandle();
std::map<handle_t, EventHandler *>::iterator it = m_handlers.find(handle);
if (it == m_handlers.end())
{
m_handlers[handle] = handler;
}
return m_demultiplexer->RequestEvent(handle, evt);
}
/// 从reactor中移除handler
/// @param handler 要移除的事件处理器
/// @retval =0 移除成功
/// @retval <0 移除出错
int ReactorImplementation::RemoveHandler(EventHandler * handler)
{
handle_t handle = handler->GetHandle();
m_handlers.erase(handle);
return m_demultiplexer->UnrequestEvent(handle);
}
/// 处理事件,回调注册的handler中相应的事件处理函数
/// @param timeout 超时时间
void ReactorImplementation::HandleEvents(int timeout)
{
m_demultiplexer->WaitEvents(&m_handlers);
}
} // namespace reactor
| [
"wuzesheng86@a907dffe-942c-7992-d486-e995bdc504d8"
]
| [
[
[
1,
139
]
]
]
|
2009af85d0ff6998fa6d52407dbaa6fdef979e97 | 368acbbc055ee3a84dd9ce30777ae3bbcecec610 | /project/jni/third_party/fcollada/FCollada_FREE_3.05B/FCollada/FCDocument/FCDExternalReferenceManager.cpp | 091357880895e0f33f7af04f12e9fe98ecd8b9df | [
"MIT",
"LicenseRef-scancode-x11-xconsortium-veillard"
]
| permissive | jcayzac/androido3d | 298559ebbe657482afe6b3b616561a1127320388 | 18e0a4cd4799b06543588cf7bea33f12500fb355 | HEAD | 2016-09-06T06:31:09.984535 | 2011-09-17T09:47:51 | 2011-09-17T09:47:51 | 1,816,466 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,075 | cpp | /*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
#include "StdAfx.h"
#include "FCDocument/FCDocument.h"
#include "FCDocument/FCDEntityReference.h"
#include "FCDocument/FCDExternalReferenceManager.h"
#include "FCDocument/FCDPlaceHolder.h"
#include "FUtils/FUFileManager.h"
#include "FCollada.h"
//
// FCDExternalReferenceManager
//
ImplementObjectType(FCDExternalReferenceManager);
FCDExternalReferenceManager::FCDExternalReferenceManager(FCDocument* document)
: FCDObject(document)
{
}
FCDExternalReferenceManager::~FCDExternalReferenceManager()
{
}
FCDPlaceHolder* FCDExternalReferenceManager::AddPlaceHolder(const fstring& _fileUrl)
{
fstring fileUrl = GetDocument()->GetFileManager()->GetCurrentUri().MakeAbsolute(_fileUrl);
FCDPlaceHolder* holder = placeHolders.Add(GetDocument());
holder->SetFileUrl(fileUrl);
SetNewChildFlag();
return holder;
}
const FCDPlaceHolder* FCDExternalReferenceManager::FindPlaceHolder(const fstring& _fileUrl) const
{
fstring fileUrl = GetDocument()->GetFileManager()->GetCurrentUri().MakeAbsolute(_fileUrl);
for (const FCDPlaceHolder** it = placeHolders.begin(); it != placeHolders.end(); ++it)
{
if ((*it)->GetFileUrl() == fileUrl) return *it;
}
return NULL;
}
FCDPlaceHolder* FCDExternalReferenceManager::AddPlaceHolder(FCDocument* document)
{
FCDPlaceHolder* placeHolder = placeHolders.Add(GetDocument(), document);
SetNewChildFlag();
return placeHolder;
}
const FCDPlaceHolder* FCDExternalReferenceManager::FindPlaceHolder(const FCDocument* document) const
{
for (const FCDPlaceHolder** it = placeHolders.begin(); it != placeHolders.end(); ++it)
{
if ((*it)->GetTarget() == document) return *it;
}
return NULL;
}
void FCDExternalReferenceManager::RegisterLoadedDocument(FCDocument* document)
{
fm::pvector<FCDocument> allDocuments;
FCollada::GetAllDocuments(allDocuments);
for (FCDocument** it = allDocuments.begin(); it != allDocuments.end(); ++it)
{
if ((*it) != document)
{
FCDExternalReferenceManager* xrefManager = (*it)->GetExternalReferenceManager();
for (FCDPlaceHolder** itP = xrefManager->placeHolders.begin(); itP != xrefManager->placeHolders.end(); ++itP)
{
// Set the document to the placeholders that targets it.
if ((*itP)->GetFileUrl() == document->GetFileUrl()) (*itP)->LoadTarget(document);
}
}
}
// On the newly-loaded document, there may be placeholders to process.
FCDExternalReferenceManager* xrefManager = document->GetExternalReferenceManager();
for (FCDPlaceHolder** itP = xrefManager->placeHolders.begin(); itP != xrefManager->placeHolders.end(); ++itP)
{
// Set the document to the placeholders that targets it.
for (FCDocument** itD = allDocuments.begin(); itD != allDocuments.end(); ++itD)
{
if ((*itP)->GetFileUrl() == (*itD)->GetFileUrl()) (*itP)->LoadTarget(*itD);
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
95
]
]
]
|
b67d6738b6ca85b8d2b113c53cd712a8a18997f3 | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /CamFighter/Math/Cameras/CameraSet.cpp | b004429dd057bc93711861e93edc3de90954c650 | []
| no_license | dogtwelve/fighter3d | 7bb099f0dc396e8224c573743ee28c54cdd3d5a2 | c073194989bc1589e4aa665714c5511f001e6400 | refs/heads/master | 2021-04-30T15:58:11.300681 | 2011-06-27T18:51:30 | 2011-06-27T18:51:30 | 33,675,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,916 | cpp | #include <fstream>
#include "../../Utils/Filesystem.h"
#include "../../Utils/Utils.h"
#include "CameraSet.h"
#include "CameraFree.h"
#include "CameraHuman.h"
using namespace Math::Cameras;
void CameraSet :: Load(const char *fileName)
{
Init();
std::ifstream in;
in.open(Filesystem::GetFullPath(fileName).c_str());
if (in.is_open())
{
std::string dir = Filesystem::GetParentDir(fileName);
char buffer[255];
int len;
Camera *camera = NULL;
ObjectTracker *tracker = NULL;
enum LoadMode
{
LoadMode_None,
LoadMode_CameraHuman,
LoadMode_CameraFree,
LoadMode_Tracking,
LoadMode_Viewport,
LoadMode_FOV,
} mode = LoadMode_None;
while (in.good())
{
in.getline(buffer, 255);
if (buffer[0] == 0 || buffer[0] == '#') continue;
len = strlen(buffer);
if (buffer[len - 1] == '\r') buffer[len - 1] = 0;
if (*buffer == '[')
{
if (StartsWith(buffer, "[camera human]"))
{
if (camera)
L_cameras.push_back(camera);
camera = new CameraHuman();
camera->Init();
camera->FOV.Projection = FieldOfView::PROJECT_ORTHOGONAL;
camera->FOV.FrontClip = 0.1f;
camera->FOV.BackClip = 1000.f;
mode = LoadMode_CameraHuman;
continue;
}
if (StartsWith(buffer, "[camera free]"))
{
if (camera)
L_cameras.push_back(camera);
camera = new CameraFree();
camera->Init();
camera->FOV.Projection = FieldOfView::PROJECT_ORTHOGONAL;
camera->FOV.FrontClip = 0.1f;
camera->FOV.BackClip = 1000.f;
mode = LoadMode_CameraFree;
continue;
}
mode = LoadMode_None;
continue;
}
if (camera)
{
if (StartsWith(buffer, "(track eye)"))
{
tracker = &camera->EyeTracker;
mode = LoadMode_Tracking;
continue;
}
if (StartsWith(buffer, "(track center)"))
{
tracker = &camera->CenterTracker;
mode = LoadMode_Tracking;
continue;
}
if (StartsWith(buffer, "(viewport)"))
{
mode = LoadMode_Viewport;
continue;
}
if (StartsWith(buffer, "(fov)"))
{
mode = LoadMode_FOV;
camera->FOV.Projection = FieldOfView::PROJECT_ORTHOGONAL;
continue;
}
if (StartsWith(buffer, "name"))
{
camera->SN_name = ReadSubstring(buffer+4);
continue;
}
if (StartsWith(buffer, "eye"))
{
sscanf(buffer+3, "%f\t%f\t%f", &camera->P_eye.x, &camera->P_eye.y, &camera->P_eye.z);
continue;
}
if (StartsWith(buffer, "center"))
{
sscanf(buffer+6, "%f\t%f\t%f", &camera->P_center.x, &camera->P_center.y, &camera->P_center.z);
continue;
}
if (StartsWith(buffer, "up"))
{
sscanf(buffer+2, "%f\t%f\t%f", &camera->NW_up.x, &camera->NW_up.y, &camera->NW_up.z);
continue;
}
if (StartsWith(buffer, "speedE"))
{
sscanf(buffer+5, "%f", &camera->W_TrackingSpeedEye);
continue;
}
if (StartsWith(buffer, "speedC"))
{
sscanf(buffer+5, "%f", &camera->W_TrackingSpeedCtr);
continue;
}
}
if (mode == LoadMode_Tracking)
{
if (StartsWith(buffer, "mode"))
{
const char *name = ReadSubstring(buffer+4);
if (StartsWith(name, "nothing")) tracker->Mode = ObjectTracker::TRACK_NOTHING;
else
if (StartsWith(name, "object")) tracker->Mode = ObjectTracker::TRACK_OBJECT;
else
if (StartsWith(name, "subobject")) tracker->Mode = ObjectTracker::TRACK_SUBOBJECT;
else
if (StartsWith(name, "all_center")) tracker->Mode = ObjectTracker::TRACK_ALL_CENTER;
else
{
tracker->Mode = ObjectTracker::TRACK_CUSTOM_SCRIPT;
tracker->ScriptName = name;
if (StartsWith(name, "EyeSeeAll_CenterTop"))
tracker->Script = Camera::SCRIPT_EyeSeeAll_CenterTop;
else
if (StartsWith(name, "EyeSeeAll_Center"))
tracker->Script = Camera::SCRIPT_EyeSeeAll_Center;
else
if (StartsWith(name, "EyeSeeAll_Radius"))
tracker->Script = Camera::SCRIPT_EyeSeeAll_Radius;
else
tracker->InitScript(name, Filesystem::GetFullPath(
"Data/scripts/cameras/" + tracker->ScriptName + ".lua"));
}
continue;
}
if (StartsWith(buffer, "object"))
{
int id;
sscanf(buffer+6, "%d", &id);
tracker->ID_object = id;
continue;
}
if (StartsWith(buffer, "subobj"))
{
int id;
sscanf(buffer+6, "%d", &id);
tracker->ID_subobject = id;
continue;
}
if (StartsWith(buffer, "shift"))
{
sscanf(buffer+5, "%f\t%f\t%f", &tracker->NW_destination_shift.x,
&tracker->NW_destination_shift.y, &tracker->NW_destination_shift.z);
continue;
}
}
if (mode == LoadMode_Viewport)
{
if (StartsWith(buffer, "left"))
{
int id;
sscanf(buffer+4, "%d", &id);
camera->FOV.ViewportLeftPercent = id * 0.01f;
continue;
}
if (StartsWith(buffer, "top"))
{
int id;
sscanf(buffer+3, "%d", &id);
camera->FOV.ViewportTopPercent = id * 0.01f;
continue;
}
if (StartsWith(buffer, "width"))
{
int id;
sscanf(buffer+5, "%d", &id);
camera->FOV.ViewportWidthPercent = id * 0.01f;
continue;
}
if (StartsWith(buffer, "height"))
{
int id;
sscanf(buffer+6, "%d", &id);
camera->FOV.ViewportHeightPercent = id * 0.01f;
continue;
}
}
if (mode == LoadMode_FOV)
{
if (StartsWith(buffer, "angle"))
{
xFLOAT angle;
sscanf(buffer+5, "%f", &angle);
camera->FOV.PerspAngle = angle;
camera->FOV.Projection = FieldOfView::PROJECT_PERSPECTIVE;
camera->FOV.BackClip = xFLOAT_HUGE_POSITIVE;
continue;
}
if (StartsWith(buffer, "front"))
{
xFLOAT clip;
sscanf(buffer+5, "%f", &clip);
camera->FOV.FrontClip = clip;
continue;
}
if (StartsWith(buffer, "back"))
{
xFLOAT clip;
sscanf(buffer+4, "%f", &clip);
camera->FOV.BackClip = clip;
continue;
}
}
}
if (camera)
L_cameras.push_back(camera);
in.close();
}
}
| [
"dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561",
"darekmac@f75eed02-8a0f-11dd-b20b-83d96e936561"
]
| [
[
[
1,
117
],
[
119,
119
],
[
126,
152
],
[
157,
245
]
],
[
[
118,
118
],
[
120,
125
],
[
153,
156
]
]
]
|
9040c54b88c31e86a91ea40c487450edc66da3e5 | 45229380094a0c2b603616e7505cbdc4d89dfaee | /OpenCV2.0/surfCLR/AssemblyInfo.cpp | c6af0bb21c6694f93b23362a4a198b3dff485f9c | []
| no_license | xcud/msrds | a71000cc096723272e5ada7229426dee5100406c | 04764859c88f5c36a757dbffc105309a27cd9c4d | refs/heads/master | 2021-01-10T01:19:35.834296 | 2011-11-04T09:26:01 | 2011-11-04T09:26:01 | 45,697,313 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,348 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly:AssemblyTitleAttribute("surfCLR")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("Microsoft")];
[assembly:AssemblyProductAttribute("surfCLR")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) Microsoft 2009")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the value or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"perpet99@cc61708c-8d4c-0410-8fce-b5b73d66a671"
]
| [
[
[
1,
40
]
]
]
|
2b8fd6e53bdcce3c0a33663fbf288aadbc445466 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/tools/NLS/Xlat/Xlat_Types.hpp | 549663ff1d88882b274529012de80590f69fa23e | [
"Apache-2.0"
]
| permissive | andyburke/bitflood | dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf | fca6c0b635d07da4e6c7fbfa032921c827a981d6 | refs/heads/master | 2016-09-10T02:14:35.564530 | 2011-11-17T09:51:49 | 2011-11-17T09:51:49 | 2,794,411 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,303 | hpp | /*
* Copyright 1999-2000,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Log: Xlat_Types.hpp,v $
* Revision 1.4 2004/09/08 13:57:07 peiyongz
* Apache License Version 2.0
*
* Revision 1.3 2000/03/02 19:55:54 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.2 2000/02/06 07:48:42 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:01:28 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:42:06 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Data types
//
// ErrReturns
// These are the values returned from main when an error occurs. It is
// also used to throw errors out to the main for return.
//
// OutFormts
// The available output formats. This is mapped to from the /OutFmt=
// command line parameter.
// ---------------------------------------------------------------------------
enum ErrReturns
{
ErrReturn_Success = 0
, ErrReturn_BadParameters = 1
, ErrReturn_OutFileOpenFailed = 4
, ErrReturn_ParserInit = 5
, ErrReturn_ParseErr = 6
, ErrReturn_LocaleErr = 7
, ErrReturn_NoTranscoder = 8
, ErrReturn_SrcFmtError = 9
, ErrReturn_UnknownDomain = 10
, ErrReturn_Internal = 9999
};
enum OutFormats
{
OutFormat_Unknown
, OutFormat_CppSrc
, OutFormat_ResBundle
, OutFormat_Win32RC
, OutFormat_MsgCatalog
};
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
5a61c5862d53274f835df05f6e168e3ea4035b2a | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Shared/src/ScreenOrWorldCoordinate.cpp | 4ed3083ca6590f8de55e79654b8fbbe5d67a8f9a | [
"BSD-3-Clause"
]
| permissive | ravustaja/Wayfinder-S60-Navigator | ef506c418b8c2e6498ece6dcae67e583fb8a4a95 | 14d1b729b2cea52f726874687e78f17492949585 | refs/heads/master | 2021-01-16T20:53:37.630909 | 2010-06-28T09:51:10 | 2010-06-28T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,973 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ScreenOrWorldCoordinate.h"
#include "MapMovingInterface.h"
// -- ScreenOrWorldCoordinate
const MC2Point&
ScreenOrWorldCoordinate::getScreenPoint(const MapMovingInterface& matrix)
{
if ( m_coord.isValid() ) {
matrix.transform( m_point, m_coord );
}
return m_point;
}
const MC2Coordinate&
ScreenOrWorldCoordinate::getWorldCoord() const
{
return m_coord;
}
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
1f1ccc32e9c7174385187892412a69127db15ace | 6a69593bdd78c65cbaeb731155c44d1ccb134802 | /programchallenge/common_permutation/common_permutation2.cpp | 42e44d6f07692a0b7472ccf6b7363a891b1f63e2 | []
| no_license | fannix/poj | 2ccf77e5ed0c1ea54602015026e17fda8107dd71 | 49b8c49a48fb67cba38bd72d7d12c103545a4511 | refs/heads/master | 2016-09-06T01:35:49.157774 | 2011-05-10T06:04:30 | 2011-05-10T06:04:30 | 1,726,476 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,579 | cpp | /*
* =====================================================================================
*
* Filename: common_permutation2.cpp
*
* Description:
*
* Version: 1.0
* Created: 2009-5-5 21:29:58 中国标准时间
* Revision: none
* Compiler: gcc
*
* Author: first_name last_name (fl), [email protected]
* Company: my-company
*
* =====================================================================================
*/
#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
string a, b;
int af[27], bf[27];
while(getline(cin,a))
{
getline(cin,b);
for(int i = 0; i < 27; i++)
{ af[i] = 0; bf[i] = 0; }
int len = a.size();
for(int i = 0; i < len; i++)
af[a[i] - 96]++;
len = b.size();
for(int i = 0; i < len; i++)
bf[b[i] - 96]++;
for(int i = 1; i <= 26; i++)
{
if(af[i] != 0 && bf[i] != 0)
{
if(af[i] < bf[i])
{
for(int j = 0; j < af[i]; j++)
cout << char(i + 96);
}
else
{
for(int j = 0; j < bf[i]; j++)
cout << char(i + 96);
}
}
}
cout << endl;
}
return EXIT_SUCCESS;
}
| [
"[email protected]"
]
| [
[
[
1,
66
]
]
]
|
07fb85afd9e2fb48f6948ec3d6ab44a68289bc23 | 252e638cde99ab2aa84922a2e230511f8f0c84be | /reflib/src/StopSimpleEditForm.cpp | 426729a11764c15101a499c6668990835b5d7f98 | []
| no_license | openlab-vn-ua/tour | abbd8be4f3f2fe4d787e9054385dea2f926f2287 | d467a300bb31a0e82c54004e26e47f7139bd728d | refs/heads/master | 2022-10-02T20:03:43.778821 | 2011-11-10T12:58:15 | 2011-11-10T12:58:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "StopSimpleEditForm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "StopSimpleProcessForm"
#pragma link "VStringStorage"
#pragma link "RxGrdCpt"
#pragma link "VCustomKeyComboBox"
#pragma link "VMemoKeyComboBox"
#pragma resource "*.dfm"
TTourStopSimpleEditForm *TourStopSimpleEditForm;
//---------------------------------------------------------------------------
__fastcall TTourStopSimpleEditForm::TTourStopSimpleEditForm(TComponent* Owner)
: TTourStopSimpleProcessForm(Owner)
{
}
//---------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
21
]
]
]
|
7f0ffd97103723d1a5358f6b37539c5df08129eb | 16d8b25d0d1c0f957c92f8b0d967f71abff1896d | /obse/obse/GameBSExtraData.h | 06aee5f3b0a62105e96686841b8dfba4e599cd06 | []
| no_license | wlasser/oonline | 51973b5ffec0b60407b63b010d0e4e1622cf69b6 | fd37ee6985f1de082cbc9f8625d1d9307e8801a6 | refs/heads/master | 2021-05-28T23:39:16.792763 | 2010-05-12T22:35:20 | 2010-05-12T22:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | h | #pragma once
// Added to remove a cyclic dependency between GameForms.h and GameExtraData.h
// C+?
class BSExtraData
{
public:
BSExtraData();
virtual ~BSExtraData();
virtual void Fn_01(void);
static BSExtraData* Create(UInt8 xType, UInt32 size, UInt32 vtbl);
// void ** _vtbl; // 000
UInt8 type; // 004
UInt8 pad[3]; // 005
BSExtraData * next; // 008
};
// 014+
struct BaseExtraList
{
bool HasType(UInt32 type) const;
BSExtraData * GetByType(UInt32 type) const;
void MarkType(UInt32 type, bool bCleared);
bool Remove(BSExtraData* toRemove);
bool Add(BSExtraData* toAdd);
void ** m_vtbl; // 000
BSExtraData * m_data; // 004
UInt8 m_presenceBitfield[0x0C]; // 008 - if a bit is set, then the extralist should contain that extradata
// bits are numbered starting from the lsb
};
struct ExtraDataList : public BaseExtraList
{
static ExtraDataList * Create();
//
};
| [
"obliviononline@2644d07b-d655-0410-af38-4bee65694944"
]
| [
[
[
1,
42
]
]
]
|
8926c8abd54f1b31a4833ba1e84d58793b5ef09f | 8d466583574663248d9197c83d490f8de6914f01 | /Irina.Burdova/Stack/main.cpp | 89c7b402c3cae85a97cf04850b705ba1d11caeb2 | []
| no_license | andrey-malets/usuoop | 186b421080d7ff1fbaed2b230f2f2c77eb081138 | 5ae5876f3622ab8a4598a67a414d544c4d6a7bcb | refs/heads/master | 2021-01-25T10:15:48.239369 | 2011-06-18T08:03:42 | 2011-06-18T08:03:42 | 32,697,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 821 | cpp | #include <iostream>
#include <cassert>
#include "stack.h"
using std::cout;
using std::cerr;
using std::endl;
using std::string;
void test1(){
try{
double d = 1.23456;
Stack<double> *s = new Stack<double>();
assert(s->capacity() == 10);
assert(s->size() == 0);
s->push(d);
assert(s->capacity() == 10);
assert(s->size() == 1);
double r= s->pop();
assert(s->capacity() == 10);
assert(s->size() == 0);
assert(r == d);
for(int i = 0; i != 15; ++i)
s->push(d);
assert(s->capacity() == 20);
assert(s->size() == 15);
for(int i = 0; i != 5; ++i)
s->pop();
assert(s->capacity() == 20);
assert(s->size() == 10);
}
catch(StackException* e){
cerr << "Exception: " << e->getMessage() << endl;
}
}
int main(){
test1();
return 0;
}
| [
"[email protected]@fe86108a-a7a1-bde3-b2d4-a6a6cc998503"
]
| [
[
[
1,
46
]
]
]
|
2beab95010e29802950acd75ec3b87d8a7b0f776 | 0454def9ffc8db9884871a7bccbd7baa4322343b | /src/report/QUAbstractReportData.h | caec1ca79c2e6e4859abad84a183af7e69c06f87 | []
| no_license | escaped/uman | e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3 | bedc1c6c4fc464be4669f03abc9bac93e7e442b0 | refs/heads/master | 2016-09-05T19:26:36.679240 | 2010-07-26T07:55:31 | 2010-07-26T07:55:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | h | #ifndef QUABSTRACTREPORTDATA_H_
#define QUABSTRACTREPORTDATA_H_
#include <QObject>
#include <QIcon>
#include "QU.h"
#include "QUSongFile.h"
class QUAbstractReportData: public QObject {
Q_OBJECT
public:
QUAbstractReportData(QObject *parent = 0);
virtual QString textData(QUSongFile *song) = 0;
virtual QString iconData(QUSongFile *song) = 0;
virtual QString headerTextData() = 0;
virtual QString headerIconData() = 0;
const QIcon& icon() const { return _icon; }
const QString& description() const { return _description; }
const QString& toolTip() const { return _toolTip; }
virtual void sort(QList<QUSongFile*> &songs) = 0;
QUAbstractReportData* next() const { return _next; }
void setNext(QUAbstractReportData *next) { _next = next; }
private:
QIcon _icon;
QString _description;
QString _toolTip;
QUAbstractReportData *_next;
protected:
void setIcon(const QIcon &icon) { _icon = icon; }
void setDescription(const QString &description) { _description = description; }
void setToolTip(const QString &toolTip) { _toolTip = toolTip; }
};
#endif /*QUABSTRACTREPORTDATA_H_*/
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
42fac3cc236e5bafb8b82b9339a026a89486208c | 3772fc400d7b73de80ab81bb4ccef973c2a83220 | /sourcecode/tutorial2app.cpp | 6ea2a0d65f8966c6f13cf924b09c3b6781a84627 | []
| no_license | tlandn/Lan-Tra-Ex1 | 882ddc59f008686fb5ef2c3e7fc8bdca7e5e2103 | 504c840323884f22cf466b22508c2f73d98dbd06 | refs/heads/master | 2020-12-24T15:58:52.179699 | 2011-08-04T10:45:58 | 2011-08-04T10:45:58 | 2,153,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,282 | cpp | /////////////////////////////////////////////////////////////////
//
// tutorial2app.cpp
// Application class
//
/////////////////////////////////////////////////////////////////
//
// Copyright (C) 2009 Daniel Jeppsson
// All Rights Reserved. These instructions, statements, computer
// programs, and/or related material (collectively, the "Source")
// contain unpublished information propietary to Daniel Jeppsson
// which is protected by US federal copyright law and by
// international treaties. This Source may NOT be disclosed to
// third parties, or be copied or duplicated, in whole or in
// part, without the written consent of Daniel Jeppsson.
//
/////////////////////////////////////////////////////////////////
//
// Author: Daniel Jeppsson
//
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// Engine Includes
#include <djmodulemanager.h>
#include <djostime.h>
#include <dj2d.h>
#include <dj2dutil.h>
#include <djgamesounds.h>
#include <djfont.h>
/////////////////////////////////////////////////////////////////
// Game Includes
#include "tutorial2app.h"
#include "constants.h"
#include "player.h"
#include "djuinode.h"
#include "mainmenu.h"
/////////////////////////////////////////////////////////////////
// Name of the game module
const char *GetGameModuleName()
{
return "Tutorial2";
}
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// Name of the game application
const char *GetGameObjectName()
{
return "Tutorial2Application";
}
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
IMPORT_STATIC_MODULE(Tutorial2)
IMPORT_STATIC_MODULE(OpenGLRender)
#if defined (_AIRPLAY)
IMPORT_STATIC_MODULE(AirSound)
#else
IMPORT_STATIC_MODULE(OpenALSound)
#endif
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
void DJSystem_AddStaticModules()
{
ADD_STATIC_MODULE(OpenGLRender);
#if defined (_AIRPLAY)
ADD_STATIC_MODULE(AirSound);
#else
ADD_STATIC_MODULE(OpenALSound);
#endif
ADD_STATIC_MODULE(Tutorial2);
}
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
BEGIN_ENUMERATE_INTERFACE()
ENUMERATE_INTERFACE(Tutorial2Application)
ENUMERATE_INTERFACE(MainMenuPageUINode)
END_ENUMERATE_INTERFACE()
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
BEGIN_CREATE_INTERFACE()
CREATE_INTERFACE(Tutorial2Application)
CREATE_INTERFACE(MainMenuPageUINode)
END_CREATE_INTERFACE()
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
BEGIN_REGISTER_SYMBOL(Tutorial2)
REGISTER_INTERFACE(Tutorial2Application)
REGISTER_INTERFACE(MainMenuPageUINode)
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
REGISTER_ENUMERATE_INTERFACE()
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
END_REGISTER_SYMBOL()
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
// Linked list of players
DJLinkedList<Player> g_players;
Player* g_PlayerBeingClicked = NULL;
void CreateNewPlayer();
/////////////////////////////////////////////////////////////////
// Application class
DJTutorial2Application::DJTutorial2Application()
{
DJTrace("%s()", __FUNCTION__);
}
///
DJTutorial2Application::~DJTutorial2Application()
{
DJTrace("%s()", __FUNCTION__);
}
///
djresult DJTutorial2Application::OnInit()
{
DJTrace("%s()", __FUNCTION__);
// Set screen orientation depending on device
#if defined(_DJIPHONE)
theSpriteEngine.SetScreenOrientation(1);
#else
theSpriteEngine.SetScreenOrientation(0);
#endif
// Get size of screen and put in global variables
pTheRenderDevice->GetScreenSize(g_nScreenWidth, g_nScreenHeight);
if (g_nScreenWidth < 800)
{
g_UIViewport.SetViewport(0,0,800,(djint32)(400.0f*((float)(g_nScreenHeight)/(float)(g_nScreenWidth))/(480.0f/854.0f)));
g_nHUDWidth = 800;
g_nHUDHeight = 800*g_nScreenHeight/g_nScreenWidth;
}
else
{
g_UIViewport.SetViewport(0,0,854,(djint32)(480.0f*((float)(g_nScreenHeight)/(float)(g_nScreenWidth))/(480.0f/854.0f)));
g_nHUDWidth = g_nScreenWidth;
g_nHUDHeight = g_nScreenHeight;
}
// Create UI system
pTheUI = DJ_NEW(DJUI);
pTheUI->Init();
pTheUI->SetUIWidth(g_UIViewport.GetWidth());
pTheUI->SetUIHeight(g_UIViewport.GetHeight());
pTheUI->RegisterEventListener(this);
// Randomize random seed by using system time
djRandomSetSeed( (djuint32)(djGetSystemTimeFloat() * 65536.0f) );
// Initialize sprite engine with the layers we want
if (!theSpriteEngine.Init(LAYER_COUNT))
{
DJError("Failed to initialize the sprite engine!");
return DJ_FAILURE;
}
// Load font
g_pFont = (DJFont*)theResourceManager.GetResource( "font", DJResource::TYPE_FONT );
if (g_pFont == NULL)
{
DJError("Failed to load the font!");
return DJ_FAILURE;
}
// Create a flare sprite sheet
g_pFlareSheet = new DJ2DGraphicsSheet;
if (!g_pFlareSheet->Init("sprites/flare.tga"))
{
DJError("Failed to load flare sheet!");
return DJ_FAILURE;
}
DJVector2 vHotspot = DJVector2(g_pFlareSheet->GetTexture()->GetWidth()/2, g_pFlareSheet->GetTexture()->GetHeight()/2);
g_pFlareSheet->AutoGenFrames(0, 0, -1, -1, 1, 1, &vHotspot);
theSpriteEngine.AddGraphicsSheet(g_pFlareSheet);
g_pCharacterSheet = (DJ2DFrameGroupList*)theResourceManager.GetResource("sprites/characters.sheet", DJResource::TYPE_FRAMEGROUPLIST);
if (g_pCharacterSheet == NULL)
{
DJError("Failed to load character sheet!");
return DJ_FAILURE;
}
// Create background image sheet
g_pBackgroundSheet = new DJ2DGraphicsSheet;
if (!g_pBackgroundSheet->Init("backgrounds/background.tga"))
{
DJError("Failed to load background sheet!");
return DJ_FAILURE;
}
g_pBackgroundSheet->AutoGenFrames(0, 0, -1, -1, 1, 1, NULL);
theSpriteEngine.AddGraphicsSheet(g_pBackgroundSheet);
// Set the background layer to draw the background image
DJ2DLayer *pLayer = theSpriteEngine.GetLayer(LAYER_BACKGROUND);
DJ2DGraphicsFrame *pFrame = g_pBackgroundSheet->GetFrame(0);
pLayer->SetBackground(pFrame);
pLayer->SetPosition(0,0);
pLayer->SetScale(1,1);
// Load sprite animations (run up, down, left and right)
g_pAnimations[RED][0] = (DJ2DAnimation*)theResourceManager.GetResource("ranger_n", DJResource::TYPE_ANIMATION2D);
g_pAnimations[RED][1] = (DJ2DAnimation*)theResourceManager.GetResource("ranger_s", DJResource::TYPE_ANIMATION2D);
g_pAnimations[RED][2] = (DJ2DAnimation*)theResourceManager.GetResource("ranger_w", DJResource::TYPE_ANIMATION2D);
g_pAnimations[RED][3] = (DJ2DAnimation*)theResourceManager.GetResource("ranger_e", DJResource::TYPE_ANIMATION2D);
g_pAnimations[BLACK][0] = (DJ2DAnimation*)theResourceManager.GetResource("lizardman_n", DJResource::TYPE_ANIMATION2D);
g_pAnimations[BLACK][1] = (DJ2DAnimation*)theResourceManager.GetResource("lizardman_s", DJResource::TYPE_ANIMATION2D);
g_pAnimations[BLACK][2] = (DJ2DAnimation*)theResourceManager.GetResource("lizardman_w", DJResource::TYPE_ANIMATION2D);
g_pAnimations[BLACK][3] = (DJ2DAnimation*)theResourceManager.GetResource("lizardman_e", DJResource::TYPE_ANIMATION2D);
// Set layer to sort sprites
pLayer = theSpriteEngine.GetLayer(LAYER_SPRITES);
//pLayer->AddLayerFlags(DJ2DLayer::flagLayerSorted);
// Create 100 players
for (int q=0; q<2; q++)
{
CreateNewPlayer();
}
// Set position of Cages
cage1.topleft_x = 0;
cage1.topleft_y = (float) g_nScreenHeight *3 / 8;
cage1.width = (float) g_nScreenHeight / 4;
cage1.height = (float) g_nScreenHeight / 4;
cage2.topleft_x = g_nScreenWidth - (float) g_nScreenHeight / 4;
cage2.topleft_y = (float) g_nScreenHeight *3 / 8;
cage2.width = (float) g_nScreenHeight / 4;
cage2.height = (float) g_nScreenHeight / 4;
// Time
m_fTimer = TIME_CREATE_PLAYER;
// Load sound effects using the DJEngine gamesound helper functions (internally uses DJSoundDevice)
if (!djGameSoundsInit(l_szSoundFiles, SOUND_COUNT))
{
DJError("Failed to load sound effects!");
return DJ_FAILURE;
}
// Load menus
m_pMenus[MENU_MAIN] = (DJUINode*)theResourceManager.GetResource("mainmenu", DJResource::TYPE_UINODE);
if (m_pMenus[MENU_MAIN])
{
m_pMenus[MENU_MAIN]->ShowNode(DJFALSE);
pTheUI->GetRootNode()->GetChildList().AddLast(m_pMenus[MENU_MAIN]);
m_pMenus[MENU_MAIN]->AddToParent(pTheUI->GetRootNode());
}
return DJ_SUCCESS;
}
///
void DJTutorial2Application::OnTerm()
{
DJTrace("%s()", __FUNCTION__);
// Delete the players
g_players.Clear(DJTRUE);
g_pFlareSheet = NULL; // No need to delete this since the sprite engine takes care of it (we added it above)
g_pBackgroundSheet = NULL; // No need to delete this since the sprite engine takes care of it (we added it above)
// Terminate sprite engine
theSpriteEngine.Term();
// Terminate DJEngine gamesound helper function
djGameSoundsTerm();
}
///
void DJTutorial2Application::PaintIngame()
{
}
void DJTutorial2Application::UpdateIngame()
{
// Update player
DJLinkedListIter<Player> iter(g_players);
Player * pPlayer;
while ( (pPlayer = iter.GetStep()) ) //Get current position and advance
{
pPlayer->OnUpdate();
}
// Update sprite engine
theSpriteEngine.OnUpdate(GetDeltaAppTime());
//
m_fTimer -= GetDeltaAppTime();
if (m_fTimer < 0) {
m_fTimer = TIME_CREATE_PLAYER;
//Create new player
CreateNewPlayer();
}
// Set the clear color
pTheRenderDevice->SetClearColor(DJColor(1,0,0,0));
// Clear the screen
pTheRenderDevice->Clear(DJRenderDevice::flagClearAll);
// Disable the depth buffer (no need for it in 2D games usually)
pTheRenderDevice->EnableZBuffer(0);
// Set render context
DJ2DRenderContext rc;
//rc.m_dwFlags = 0;
rc.m_cModColor = DJColor(1,1,1,1);
rc.m_cAddColor = DJColor(0,0,0,0);
rc.m_mLayerTransform = DJMatrix2D::Identity();
rc.m_pLayer = NULL;
rc.m_mTransform = DJMatrix2D::Identity();
// Render sprites and all layers
theSpriteEngine.OnPaint(rc);
// Setup screen for rendering text
pTheRenderDevice->SetViewTransform(DJMatrix::Identity());
pTheRenderDevice->SetPerspectiveOrtho(0,0,g_nScreenWidth,g_nScreenHeight,0.0f,100.0f);
char buffer[100];
djStringFormat(buffer, 100, "Scores : %d", g_scores);
g_pFont->DrawString(buffer , DJVector3(10,10,0), DJVector2(16,16), 0xFFFFFFFF);
}
void DJTutorial2Application::OnUpdate()
{
//DJTrace(__FUNCTION__"()");
switch (g_GameState)
{
case GS_MENU:
UpdateMenu();
break;
case GS_INGAME:
UpdateIngame();
break;
}
}
///
void DJTutorial2Application::OnPaint()
{
//DJTrace(__FUNCTION__"()");
switch (g_GameState)
{
case GS_MENU:
PaintMenu();
break;
case GS_INGAME:
PaintIngame();
break;
}
}
void CreateNewPlayer()
{
int random = djRoundToInt(djRandomGetFloat());
Player* pPlayer;
if (random == RED) {
pPlayer = new Player(RED);
} else {
pPlayer = new Player(BLACK);
}
g_players.AddLast(pPlayer);
}
void SetStopAnimation(DJLinkedList<Player> &_g_players, djbool b, float x=-1, float y=-1) {
DJLinkedListIter<Player> iter(_g_players);
Player *player;
while (player = iter.GetStep()) {
if (player->IsClicked(x,y)) {
player->SetStopAnimation(b);
}
}
}
void mark_player_being_clicked( float x, float y )
{
DJLinkedListIter<Player> iter(g_players);
Player *player;
while (player = iter.GetStep()) {
if (player->IsClicked(x,y)) {
g_PlayerBeingClicked = player;
player->SetStopAnimation(DJTRUE);
break;
}
}
}
djint32 DJTutorial2Application::OnTouchBegin(djint32 nID, float x, float y)
{
DJInfo("Touch Begin: %d %.2f %.2f", nID, x, y);
if (DJApplication::OnTouchBegin(nID, x,y))
return 1;
if (nID ==0) {
// Mark player being clicked
mark_player_being_clicked(x,y);
} else {
//Play normally
SetStopAnimation(g_players,DJFALSE);
}
return 0;
}
///
djint32 DJTutorial2Application::OnTouchMove(djint32 nID, float x, float y)
{
DJInfo("Touch Move: %d %.2f %.2f", nID, x, y);
if (DJApplication::OnTouchMove(nID, x,y))
return 1;
if (g_PlayerBeingClicked == NULL)
return 0;
// Move player
g_PlayerBeingClicked->MoveTo(x,y);
return 0;
}
///
djint32 DJTutorial2Application::OnTouchEnd(djint32 nID, float x, float y)
{
DJInfo("Touch End: %d %.2f %.2f", nID, x, y);
if (DJApplication::OnTouchEnd(nID, x,y))
return 1;
if (g_PlayerBeingClicked == NULL)
return 0;
if (nID ==0) {
//Check if player being clicked is in cages
if ((g_PlayerBeingClicked->GetType() == RED && g_PlayerBeingClicked->InCage(cage1)) ||
(g_PlayerBeingClicked->GetType() == BLACK && g_PlayerBeingClicked->InCage(cage2))) {
DJ2DLayer* pLayer = theSpriteEngine.GetLayer(LAYER_SPRITES);
pLayer->RemoveNode(g_PlayerBeingClicked->m_pSprite);
g_scores++;
} else if (g_PlayerBeingClicked->InCage(cage1) || g_PlayerBeingClicked->InCage(cage2)) { // Wrong cage, move player to middle of screen
g_PlayerBeingClicked->m_pSprite->SetPosition((float) g_nScreenWidth/2,(float) g_nScreenHeight/2);
}
g_PlayerBeingClicked = NULL;
} else {
}
return 0;
}
///
djint32 DJTutorial2Application::OnAccelerate(float x, float y, float z)
{
if (DJApplication::OnAccelerate(x,y,z))
return 1;
//DJInfo("%s %.2f %.2f %.2f", __FUNCTION__, x, y, z);
return 0;
}
///
djint32 DJTutorial2Application::OnButtonDown(djint32 nKey)
{
DJInfo("Button Down: %d", nKey);
//nKey 1 2 3 4: Len Phai Xuong Trai
if (DJApplication::OnButtonDown(nKey))
return 1;
return 0;
}
///
djint32 DJTutorial2Application::OnButtonUp(djint32 nKey)
{
DJInfo("Button Up: %d", nKey);
if (DJApplication::OnButtonUp(nKey))
return 1;
return 0;
}
///
void DJTutorial2Application::OnMessage(djuint32 nMessage, djuint32 nParam1, djuint32 nParam2)
{
//DJTrace(__FUNCTION__"()");
}
void DJTutorial2Application::GotoMenu(djuint32 MENU_LEVELSELECT)
{
}
void DJTutorial2Application::UpdateMenu()
{
}
void DJTutorial2Application::PaintMenu()
{
pTheRenderDevice->SetViewTransform(DJMatrix::Translate(DJVector3(0, 0, 0)));
pTheRenderDevice->SetPerspectiveOrtho(0,0,854,480,0.0f,100.0f);
//PaintMenuBackground(DJTRUE);
pTheRenderDevice->SetViewTransform(DJMatrix::Translate(DJVector3(0, 0, 0)));
pTheRenderDevice->SetPerspectiveOrtho(0,0,854,480,0.0f,100.0f);
//pTheRenderDevice->SetViewport(DJViewport(0,0,854,480));
DJ2DRenderContext rc;
rc.m_uFlags = 0;
rc.m_cModColor = DJColor(1,1,1,1);
rc.m_cAddColor = DJColor(0,0,0,0);
rc.m_mLayerTransform = DJMatrix2D::Identity();
rc.m_pLayer = NULL;
rc.m_mTransform = DJMatrix2D::Identity();
// Render UI
pTheRenderDevice->SetViewTransform(DJMatrix::Translate(DJVector3(0, 0, 0)));
pTheRenderDevice->SetPerspectiveOrtho(0,0,(float)g_UIViewport.GetWidth(),(float)g_UIViewport.GetHeight(),0.0f,100.0f);
rc.m_pViewport = &g_UIViewport;
pTheUI->OnPaint(rc);
rc.m_pViewport = NULL;
}
djbool DJTutorial2Application::OnUIEvent( DJUINode *pNode, const DJUIEvent &ev )
{
if (ev.m_uEventID == pTheUI->EVENTID_ON_CLICKED)
{
if (ev.m_uStateID == pTheUI->GetStateID("QUIT"))
{
m_bQuit = DJTRUE;
return DJTRUE;
}
}
return DJFALSE;
}
// Application class
/////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////
DJ_FILE_END();
/////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
593
]
]
]
|
3840544c8fe02bfed8a7622f5bb85c6d9c582eef | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Internet/HtmlParser.cpp | 4c663b1f5d32de605c957039e1ac45121b3dfc7e | []
| 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 | 20,443 | cpp | /*
© Vestris Inc., Geneva Switzerland
http://www.vestris.com, 1998, All Rights Reserved
__________________________________________________
written by Daniel Doubrovkine - [email protected]
Revision history:
29.08.1999: fixed TransateQuotes to read &#[x]DDD; sequences
29.08.1999: added TranslateDecimalToken to convert
&#[x]DDD; sequences
08.05.2000: forward re-parsing of apparent HTML errors
*/
#include <baseclasses.hpp>
#include "HtmlParser.hpp"
#include <File/Progress.hpp>
#include <String/GStrings.hpp>
#define _HTML_QUOT(__HtmlSymbol) ('&' + CString(__HtmlSymbol) + ';')
void CHtmlParser::Quote(CString& String)
{
CString Target(String);
Quote(Target, &String);
}
void CHtmlParser::Quote(const CString& String, CString * pResult) {
typedef struct {
char m_ch;
const char * m_pString;
} CQuoteStruct;
static const CQuoteStruct QuoteStruct[] = {
{ '&', g_strHtml_amp },
{ '>', g_strHtml_gt },
{ '<', g_strHtml_lt },
{ 'à', g_strHtml_agrave },
{ 'á', g_strHtml_aacute },
{ 'â', g_strHtml_acirc },
{ 'ã', g_strHtml_atilde },
{ 'ä', g_strHtml_auml },
{ 'å', g_strHtml_aring },
{ 'æ', g_strHtml_aelig },
{ 'ç', g_strHtml_ccedil },
{ 'è', g_strHtml_egrave },
{ 'é', g_strHtml_eacute },
{ 'ê', g_strHtml_ecirc },
{ 'ë', g_strHtml_euml },
{ 'ì', g_strHtml_igrave },
{ 'í', g_strHtml_iacute },
{ 'î', g_strHtml_icirc },
{ 'ï', g_strHtml_iuml },
{ 'ð', g_strHtml_eth },
{ 'ñ', g_strHtml_ntilde },
{ 'ò', g_strHtml_ograve },
{ 'ó', g_strHtml_oacute },
{ 'ô', g_strHtml_ocirc },
{ 'õ', g_strHtml_otilde },
{ 'ö', g_strHtml_ouml },
{ '÷', g_strHtml_divide },
{ 'ø', g_strHtml_oslash },
{ 'ù', g_strHtml_ugrave },
{ 'ú', g_strHtml_uacute },
{ 'û', g_strHtml_ucirc },
{ 'ü', g_strHtml_uuml },
{ 'ý', g_strHtml_yacute },
{ 'þ', g_strHtml_thorn },
{ 'ÿ', g_strHtml_yuml },
{ 'À', g_strHtml_Agrave },
{ 'Á', g_strHtml_Aacute },
{ 'Â', g_strHtml_Acirc },
{ 'Ã', g_strHtml_Atilde },
{ 'Ä', g_strHtml_Auml },
{ 'Å', g_strHtml_Aring },
{ 'Æ', g_strHtml_AElig },
{ 'Ç', g_strHtml_Ccedil },
{ 'È', g_strHtml_Egrave },
{ 'É', g_strHtml_Eacute },
{ 'Ê', g_strHtml_Ecirc },
{ 'Ë', g_strHtml_Euml },
{ 'Ì', g_strHtml_Igrave },
{ 'Í', g_strHtml_Iacute },
{ 'Î', g_strHtml_Icirc },
{ 'Ï', g_strHtml_Iuml },
{ 'Ð', g_strHtml_ETH },
{ 'Ñ', g_strHtml_Ntilde },
{ 'Ò', g_strHtml_Ograve },
{ 'Ó', g_strHtml_Oacute },
{ 'Ô', g_strHtml_Ocirc },
{ 'Õ', g_strHtml_Otilde },
{ 'Ö', g_strHtml_Ouml },
{ '×', g_strHtml_times },
{ 'Ø', g_strHtml_Oslash },
{ 'Ù', g_strHtml_Ugrave },
{ 'Ú', g_strHtml_Uacute },
{ 'Û', g_strHtml_Ucirc },
{ 'Ü', g_strHtml_Uuml },
{ 'Ý', g_strHtml_Yacute },
{ 'Þ', g_strHtml_THORN },
{ 'ß', g_strHtml_szlig },
{ '¡', g_strHtml_iexcl },
{ '¢', g_strHtml_cent },
{ '£', g_strHtml_pound },
{ '¤', g_strHtml_curren },
{ '¥', g_strHtml_yen },
{ '¦', g_strHtml_brvbar },
{ '§', g_strHtml_sect },
{ '¨', g_strHtml_uml },
{ '©', g_strHtml_copy },
{ 'ª', g_strHtml_ordf },
{ '«', g_strHtml_laquo },
{ '¬', g_strHtml_not },
{ '', g_strHtml_shy },
{ '®', g_strHtml_reg },
{ '¯', g_strHtml_macr },
{ '°', g_strHtml_deg },
{ '±', g_strHtml_plusmn },
{ '²', g_strHtml_sup2 },
{ '³', g_strHtml_sup3 },
{ '´', g_strHtml_acute },
{ 'µ', g_strHtml_micro },
{ '¶', g_strHtml_para },
{ '·', g_strHtml_middot },
{ '¸', g_strHtml_cedil },
{ '¹', g_strHtml_sup1 },
{ 'º', g_strHtml_ordm },
{ '»', g_strHtml_raquo },
{ '¼', g_strHtml_frac14 },
{ '½', g_strHtml_frac12 },
{ '¾', g_strHtml_frac34 },
{ '¿', g_strHtml_iquest },
{ '\"', g_strHtml_quot }
};
pResult->Empty();
pResult->SetSize(String.GetLength());
bool bFound = false;
for (int i=0;i < (int) String.GetLength(); i++) {
bFound = false;
for (int j = 0; j < (int) (sizeof(QuoteStruct) / sizeof(CQuoteStruct)); j++) {
if (String[i] == QuoteStruct[j].m_ch) {
(* pResult) += _HTML_QUOT(QuoteStruct[j].m_pString);
bFound = true;
break;
}
}
if (! bFound) {
(* pResult) += String[i];
}
}
}
int CHtmlParser::ReadText(int& curPos, const CString& iStr, CString * pResult){
int prevPos = curPos;
pResult->Empty();
while ((curPos < (int) iStr.GetLength())&&(iStr[curPos]!='<'))
curPos++;
if (curPos < (int) iStr.GetLength()) m_LastToken = iStr[curPos];
if (prevPos != curPos)
return iStr.Mid(prevPos, curPos-prevPos, pResult);
else return 0;
}
void CHtmlParser::ForwardParse(int curPos, const CString& iStr, int ForwardDepth) {
// try to parse the remaining string once so we catch both cases
if (m_Errors >= 3)
return;
m_Errors++;
if (m_Verbose) {
cout << '#'; cout.flush();
}
int InIllegalSave = m_InIllegal;
int ErrorsSave = m_Errors;
ParseString(curPos, iStr, NULL, ForwardDepth);
m_Errors = ErrorsSave;
m_InIllegal = InIllegalSave;
}
bool CHtmlParser::ReadToken(int& curPos, const CString& iStr, int ForwardDepth, CString& HtmlToken){
if ((curPos + 1) < (int) iStr.GetLength()) {
if (iStr[curPos+1] <= ' ') {
HtmlToken.Empty();
return true;
}
}
int prevPos = curPos + 1;
int InComment = 0;
bool InQuote = false;
while (curPos < (int) iStr.GetLength()) {
if (iStr[curPos] == '<') {
if (! InQuote) {
if (curPos + 3 < (int) iStr.GetLength()) {
if ((iStr[curPos + 1] == '!') &&
(iStr[curPos + 2] == '-') &&
(iStr[curPos + 3] == '-')) {
// nested comment
InComment++;
curPos += 3;
}
}
}
} else if (iStr[curPos] == '>') {
if ((!InQuote) && (!InComment)) {
curPos++;
break;
} else if (
InComment &&
(curPos >= 2) &&
(iStr[curPos-1] == '-') &&
(iStr[curPos-2] == '-')) {
InComment--;
curPos++;
if (InComment == 0)
break;
} else if (InQuote) {
if (ForwardDepth)
return false;
// ForwardParse(curPos+1, iStr, ForwardDepth+1);
}
} else if (iStr[curPos] == '\"') {
InQuote = !InQuote;
// common quote mistake name="value""
while (! InQuote && ((curPos+1) < (int) iStr.GetLength()) && iStr[curPos + 1] == '\"')
curPos++;
} else if (InQuote && iStr[curPos] == '<') {
if (ForwardDepth)
return false;
// ForwardParse(curPos, iStr, ForwardDepth+1);
}
curPos++;
}
if (curPos < (int) iStr.GetLength())
if ((iStr[curPos] == '>')&&(m_LastToken == '<'))
curPos++;
int lLen = curPos - prevPos - 1;
if (InComment)
lLen -= 2;
if (lLen > 0)
iStr.Mid(prevPos, lLen, &HtmlToken);
return true;
}
bool CHtmlParser::TranslateDecimalToken(const CString& Token, CString& Target) {
/*
The syntax "&#D;", where D is a decimal number, refers to the Unicode
decimal character number D.
The syntax "&#xH;" or "&#XH;", where H is an hexadecimal number, refers
to the Unicode hexadecimal character number H. Hexadecimal numbers in
numeric character references are case-insensitive.
*/
if (Token.GetLength()) {
int Value;
if ((Token[0] == 'X')||(Token[0]=='x')) {
CString MidString;
Token.Mid(1, Token.GetLength(), &MidString);
if ((MidString.IsHex(&Value))&&(Value < 255)&&(Value >= 32)) {
Target.Append((unsigned char) Value);
return true;
}
} else {
if ((Token.IsInt(&Value))&&(Value < 255)&&(Value >= 32)) {
Target.Append((unsigned char) Value);
return true;
}
}
}
Target.Append('&' + Token + ';');
return false;
}
void CHtmlParser::TranslateQuote(const CString& Token, CString& Target){
if (Token.GetLength()) {
if (Token[0] == '#') {
CString MidString;
Token.Mid(1, Token.GetLength(), &MidString);
TranslateDecimalToken(MidString, Target);
return;
}
typedef struct {
const char * m_pString;
char m_ch;
} CQuoteStruct;
static const CQuoteStruct QuoteStruct[] = {
{ g_strHtml_amp, '&' },
{ g_strHtml_nbsp, ' ' },
{ g_strHtml_agrave, 'à' },
{ g_strHtml_aacute, 'á' },
{ g_strHtml_acirc, 'â' },
{ g_strHtml_atilde, 'ã' },
{ g_strHtml_auml, 'ä' },
{ g_strHtml_aring, 'å' },
{ g_strHtml_aelig, 'æ' },
{ g_strHtml_ccedil, 'ç' },
{ g_strHtml_egrave, 'è' },
{ g_strHtml_eacute, 'é' },
{ g_strHtml_ecirc, 'ê' },
{ g_strHtml_euml, 'ë' },
{ g_strHtml_igrave, 'ì' },
{ g_strHtml_iacute, 'í' },
{ g_strHtml_icirc, 'î' },
{ g_strHtml_iuml, 'ï' },
{ g_strHtml_eth, 'ð' },
{ g_strHtml_ntilde, 'ñ' },
{ g_strHtml_ograve, 'ò' },
{ g_strHtml_oacute, 'ó' },
{ g_strHtml_ocirc, 'ô' },
{ g_strHtml_otilde, 'õ' },
{ g_strHtml_ouml, 'ö' },
{ g_strHtml_divide, '÷' },
{ g_strHtml_oslash, 'ø' },
{ g_strHtml_ugrave, 'ù' },
{ g_strHtml_uacute, 'ú' },
{ g_strHtml_ucirc, 'û' },
{ g_strHtml_uuml, 'ü' },
{ g_strHtml_yacute, 'ý' },
{ g_strHtml_thorn, 'þ' },
{ g_strHtml_yuml, 'ÿ' },
{ g_strHtml_Agrave, 'À' },
{ g_strHtml_Aacute, 'Á' },
{ g_strHtml_Acirc, 'Â' },
{ g_strHtml_Atilde, 'Ã' },
{ g_strHtml_Auml, 'Ä' },
{ g_strHtml_Aring, 'Å' },
{ g_strHtml_AElig, 'Æ' },
{ g_strHtml_Ccedil, 'Ç' },
{ g_strHtml_Egrave, 'È' },
{ g_strHtml_Eacute, 'É' },
{ g_strHtml_Ecirc, 'Ê' },
{ g_strHtml_Euml, 'Ë' },
{ g_strHtml_Igrave, 'Ì' },
{ g_strHtml_Iacute, 'Í' },
{ g_strHtml_Icirc, 'Î' },
{ g_strHtml_Iuml, 'Ï' },
{ g_strHtml_ETH, 'Ð' },
{ g_strHtml_Ntilde, 'Ñ' },
{ g_strHtml_Ograve, 'Ò' },
{ g_strHtml_Oacute, 'Ó' },
{ g_strHtml_Ocirc, 'Ô' },
{ g_strHtml_Otilde, 'Õ' },
{ g_strHtml_Ouml, 'Ö' },
{ g_strHtml_times, '×' },
{ g_strHtml_Oslash, 'Ø' },
{ g_strHtml_Ugrave, 'Ù' },
{ g_strHtml_Uacute, 'Ú' },
{ g_strHtml_Ucirc, 'Û' },
{ g_strHtml_Uuml, 'Ü' },
{ g_strHtml_Yacute, 'Ý' },
{ g_strHtml_THORN, 'Þ' },
{ g_strHtml_szlig, 'ß' },
{ g_strHtml_iexcl, '¡' },
{ g_strHtml_cent, '¢' },
{ g_strHtml_pound, '£' },
{ g_strHtml_curren, '¤' },
{ g_strHtml_yen, '¥' },
{ g_strHtml_brvbar, '¦' },
{ g_strHtml_sect, '§' },
{ g_strHtml_uml, '¨' },
{ g_strHtml_copy, '©' },
{ g_strHtml_ordf, 'ª' },
{ g_strHtml_laquo, '«' },
{ g_strHtml_not, '¬' },
{ g_strHtml_shy, '' },
{ g_strHtml_reg, '®' },
{ g_strHtml_macr, '¯' },
{ g_strHtml_deg, '°' },
{ g_strHtml_plusmn, '±' },
{ g_strHtml_sup2, '²' },
{ g_strHtml_sup3, '³' },
{ g_strHtml_acute, '´' },
{ g_strHtml_micro, 'µ' },
{ g_strHtml_para, '¶' },
{ g_strHtml_middot, '·' },
{ g_strHtml_cedil, '¸' },
{ g_strHtml_sup1, '¹' },
{ g_strHtml_ordm, 'º' },
{ g_strHtml_raquo, '»' },
{ g_strHtml_frac14, '¼' },
{ g_strHtml_frac12, '½' },
{ g_strHtml_frac34, '¾' },
{ g_strHtml_iquest, '¿' },
{ g_strHtml_quot, '\"' }
// { g_strHtml_gt, '>' }
// { g_strHtml_lt, '<' }
};
for (int j=0; j < (int) (sizeof(QuoteStruct) / sizeof(CQuoteStruct)); j++) {
if (Token.Equal(QuoteStruct[j].m_pString)) {
Target.Append(QuoteStruct[j].m_ch);
return;
}
}
Target.Append('&' + Token + ';');
}
}
void CHtmlParser::TranslateQuotes(CString& iStr){
int curPos = 0;
while (curPos < (int) iStr.GetLength()) {
if (iStr[curPos] == '&'){
int iPos = curPos+1;
while ((iPos < (int) iStr.GetLength())&&(isalnum((unsigned char) iStr[iPos]) || (iStr[iPos] == '#')))
iPos++;
if ((iPos < (int) iStr.GetLength())&&(iStr[iPos] == ';')) {
CString InQuote; iStr.Mid(curPos+1, iPos-curPos-1, &InQuote);
CString PQuote; TranslateQuote(InQuote, PQuote);
iStr.Delete(curPos, iPos-curPos+1);
iStr.Insert(curPos, PQuote);
curPos += PQuote.GetLength();
} else curPos = iPos;
} else curPos++;
}
}
void CHtmlParser::ParseToken(const CString& Token, CHtmlTag& Target) {
int curPos = 0;
int prevPos = 0;
if (Token.GetLength() && (Token[0] == '/')) { curPos++; }
while ((curPos < (int) Token.GetLength())&&(Token[curPos] > ' ')) curPos++;
CString Name; Token.Mid(prevPos, curPos - prevPos, &Name);
Target.SetName(Name);
while (curPos < (int) Token.GetLength()) {
SkipSpaces(curPos, Token);
if (curPos >= (int) Token.GetLength()) break;
CString IName; CString IValue;
ReadNameValue(curPos, Token, IName, IValue);
Target.Set(IName, IValue);
}
}
void CHtmlParser::ParseToken(const CString& Token){
CHtmlTag CurrentTag;
ParseToken(Token, CurrentTag);
m_HtmlList.Add(CurrentTag);
OnNewTag(CurrentTag);
}
int CHtmlParser::ReadString(int& curPos, const CString& Token, bool NameInNameValue, CString * pResult){
SkipSpaces(curPos, Token);
char pToken = 0;
int prevPos = curPos;
int Level = 0;
while (curPos < (int) Token.GetLength()) {
if ((Token[curPos] == '=')&&(!Level)&&(NameInNameValue)) break;
else if ((curPos < (int) Token.GetLength())&&(Token[curPos] <= ' ')&&(!Level)) break;
else if ((Token[curPos] == '\"')||(Token[curPos] == '\'')) {
if (!Level) {
Level++;
pToken = Token[curPos];
} else if (Token[curPos] == pToken) {
Level--;
curPos++;
break;
}
}
curPos++;
}
Token.Mid(prevPos, curPos-prevPos, pResult);
if (curPos < (int) Token.GetLength())
while ((curPos < (int) Token.GetLength())&&(Token[curPos] <= ' '))
curPos++;
pResult->Trim32();
return pResult->GetLength();
}
void CHtmlParser::ReadNameValue(int& curPos, const CString& Token, CString& Name, CString& Value){
Value.Empty();
ReadString(curPos, Token, true, &Name);
Name.Dequote();
if ((curPos < (int) Token.GetLength())&&(Token[curPos] == '=')) {
while ((curPos < (int) Token.GetLength())&&(Token[curPos] == '=')) curPos++;
ReadString(curPos, Token, false, &Value);
Value.Dequote();
}
}
void CHtmlParser::ParseString(int& curPos, const CString& iStr, CProgress * Progress, int ForwardDepth) {
while (curPos < (int) iStr.GetLength()) {
if (Progress)
Progress->Show(curPos, iStr.GetLength(), m_Verbose);
CString FreeText;
ReadText(curPos, iStr, &FreeText);
if (FreeText.GetLength()) {
CHtmlTag Tag;
Tag.SetFree(FreeText);
m_HtmlList.Add(Tag);
OnNewTag(Tag);
}
CString HtmlToken;
if (curPos < (int) iStr.GetLength()) {
if (!ReadToken(curPos, iStr, ForwardDepth, HtmlToken))
break;
if (HtmlToken.GetLength()) {
if (!PrepareToken(HtmlToken, iStr, curPos))
ParseToken(HtmlToken);
} else {
curPos++;
}
} else break;
}
}
void CHtmlParser::Parse(const CString& iStr) {
CProgress Progress(20, m_Verbose);
m_InIllegal = 0;
// m_Errors = 0;
int curPos = 0;
if (m_ParseHtmlContent) {
ParseString(curPos, iStr, &Progress, 0);
} else {
CHtmlTag Tag;
Tag.SetFree(iStr);
m_HtmlList.Add(Tag);
OnNewTag(Tag);
}
Progress.Finish(m_Verbose);
}
bool CHtmlParser::PrepareToken(const CString& HtmlToken, const CString& iStr, int& curPos) {
int tPos = 0;
if (HtmlToken.GetLength() && HtmlToken[0] == '/') tPos++;
while ((tPos < (int) HtmlToken.GetLength())&&(isalnum((unsigned char) HtmlToken[tPos]))) tPos++;
CString TName;
HtmlToken.Mid(0, tPos, &TName);
TName.UpperCase();
if (
(TName.Equal(g_strHtml_SCRIPT))
|| (TName.Equal(g_strHtml_STYLE))
// || (TName.Equal(g_strHtml_OBJECT))
) {
CString TEndName = ("</" + TName + '>');
int ePos = iStr.SamePos(TEndName, curPos);
if (ePos != -1) {
curPos = (ePos + TEndName.GetLength());
return true;
} else m_InIllegal++;
} else if (
(TName.Equal(g_strHtml_CSCRIPT))
|| (TName.Equal(g_strHtml_CSTYLE))
// || (TName.Equal(g_strHtml_COBJECT))
) {
if (m_InIllegal > 0) m_InIllegal--;
}
return false;
}
CHtmlParser::CHtmlParser(void) {
m_Verbose = false;
m_ParseHtmlContent = true;
}
CHtmlParser::~CHtmlParser(void){
}
void CHtmlParser::OnNewTag(const CHtmlTag&) {
}
void CHtmlParser::QuoteQuotes(const CString& String, CString * pResult) {
* pResult = String;
for (register int i=((int)pResult->GetLength())-1;i>=0;i--)
switch((* pResult)[i]) {
case '\"': (* pResult)[i] = ';'; (* pResult).Insert(i, """); break;
case '>': (* pResult)[i] = ';'; (* pResult).Insert(i, ">"); break;
case '<': (* pResult)[i] = ';'; (* pResult).Insert(i, "<"); break;
case '&': (* pResult)[i] = ';'; (* pResult).Insert(i, "&"); break;
}
}
| [
"[email protected]"
]
| [
[
[
1,
616
]
]
]
|
d280483806bacc9c0c6c6deb5a705c4973ef50f0 | 138a353006eb1376668037fcdfbafc05450aa413 | /source/TextRenderer.h | 073306ba46e79a88b974688e5594fab264d5a8cc | []
| no_license | sonicma7/choreopower | 107ed0a5f2eb5fa9e47378702469b77554e44746 | 1480a8f9512531665695b46dcfdde3f689888053 | refs/heads/master | 2020-05-16T20:53:11.590126 | 2009-11-18T03:10:12 | 2009-11-18T03:10:12 | 32,246,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | h | #include <Ogre.h>
#include <OgreSingleton.h>
class TextRenderer : public Ogre::Singleton<TextRenderer>
{
private:
Ogre::OverlayManager* _overlayMgr;
Ogre::Overlay* _overlay;
Ogre::OverlayContainer* _panel;
public:
TextRenderer();
~TextRenderer();
void addTextBox(
const std::string& ID,
const std::string& text,
Ogre::Real x, Ogre::Real y,
Ogre::Real width, Ogre::Real height,
const Ogre::ColourValue& color = Ogre::ColourValue(1.0, 1.0, 1.0, 1.0));
void removeTextBox(const std::string& ID);
void setText(const std::string& ID, const std::string& Text);
}; | [
"Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e"
]
| [
[
[
1,
27
]
]
]
|
3b206279621c0732eb3e7c07e37e611ed4ffd916 | c7fb3080028a93c7d121ce2473dc919c983775e9 | /RStation/TimingData.h | d4d8331cab185d06cd47913c945c3a79bb8f32fd | []
| no_license | taiyal/Rhythm-Station | a52f33cb72574c1cae1afe5d1504f265ceda4109 | b66111048fff4c6eef978b706307843871d01329 | refs/heads/master | 2020-06-26T07:23:39.893040 | 2010-09-14T17:49:28 | 2010-09-14T17:49:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | h | #ifndef _TIMING_DATA_H_
#define _TIMING_DATA_H_
#include "RStation.h"
// please edit this until you think it is sane.
enum NoteType {
NOTE_TAP,
NOTE_HOLD,
NOTE_ROLL,
NOTE_TAIL,
NOTE_MINE
};
enum NoteAttribute {
NOTE_ATTR_FAKE,
NOTE_ATTR_VISIBLE
};
struct Note
{
// Generic stuff.
NoteType type;
std::vector<NoteAttribute> flags;
// For games which use columns (StepMania-esque)
int column;
int width; // cover multiple columns
// For mouse-based games which use coords (osu!-esque)
float scale;
vec3 position;
};
struct NoteRow
{
std::vector<Note> notes; // Notes on this row
int time; // Time in milliseconds.
// This is independent of time - use for stops, delays, warping, whatever.
float scroll_speed;
};
struct NoteRegion
{
int combo_rate; // aka tickcount
float bpm; // For display purposes, not timing.
struct TimeSignature
{
int numerator;
int denominator;
} time_sig;
int time;
};
struct TimingData
{
std::vector<NoteRow> note_rows;
std::vector<NoteRegion> note_regions;
int timing_offset;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
5bd62f3b6be870ebd3ab64bbd8795d759e48d106 | ac559231a41a5833220a1319456073365f13d484 | /src/old/server-jaus/jaus/mobility/list/listmanager.h | fc24fda7947d4b1bfbaa0f99e1443dae6bed8392 | []
| no_license | mtboswell/mtboswell-auvc2 | 6521002ca12f9f7e1ec5df781ed03419129b8f56 | 02bb0dd47936967a7b9fa7d091398812f441c1dc | refs/heads/master | 2020-04-01T23:02:15.282160 | 2011-07-17T16:48:34 | 2011-07-17T16:48:34 | 32,832,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,471 | h | ////////////////////////////////////////////////////////////////////////////////////
///
/// \file listmanager.h
/// \brief This file contains the implementation of the List Manager service.
///
/// <br>Author(s): Daniel Barber
/// <br>Created: 27 February 2010
/// <br>Copyright (c) 2010
/// <br>Applied Cognition and Training in Immersive Virtual Environments
/// <br>(ACTIVE) Laboratory
/// <br>Institute for Simulation and Training (IST)
/// <br>University of Central Florida (UCF)
/// <br>All rights reserved.
/// <br>Email: [email protected]
/// <br>Web: http://active.ist.ucf.edu
///
/// 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 ACTIVE LAB, IST, UCF, nor the
/// names of its contributors may be used to endorse or promote products
/// derived from this software without specific prior written permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE ACTIVE LAB''AS IS'' AND ANY
/// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
/// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
/// DISCLAIMED. IN NO EVENT SHALL UCF BE LIABLE FOR ANY
/// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
/// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
/// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
/// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///
////////////////////////////////////////////////////////////////////////////////////
#ifndef __JAUS_MOBILITY_LIST_MANAGER__H
#define __JAUS_MOBILITY_LIST_MANAGER__H
#include "jaus/core/management/management.h"
#include "jaus/mobility/list/element.h"
#include "jaus/mobility/list/setelement.h"
#include "jaus/mobility/list/confirmelementrequest.h"
#include "jaus/mobility/list/deleteelement.h"
#include "jaus/mobility/list/executelist.h"
#include "jaus/mobility/list/queryactiveelement.h"
#include "jaus/mobility/list/queryelement.h"
#include "jaus/mobility/list/queryelementcount.h"
#include "jaus/mobility/list/queryelementlist.h"
#include "jaus/mobility/list/rejectelementrequest.h"
#include "jaus/mobility/list/reportactiveelement.h"
#include "jaus/mobility/list/reportelement.h"
#include "jaus/mobility/list/reportelementcount.h"
#include "jaus/mobility/list/reportelementlist.h"
namespace JAUS
{
////////////////////////////////////////////////////////////////////////////////////
///
/// \class ListManager
/// \brief The List Manager Service permits operations on a single ordered
/// sequence of connected elements.
///
/// This service supports add, replace, or delete elements from a list, as
/// well as query and report optoins. Lists are stored similarly to a
/// double linked list.
///
/// 1) A list must contain exactly one head element which is defined as having
/// a previous (parent) identifier of zero (0).
/// 2) For non-circular lists, the list must contain exactly one tail element
/// which is defined as having a next (child) identifier of (0).
/// 3) Each element must reference existing (previous) parent and next (child)
/// elements, or zero.
/// 4) Elements cannot be orphaned. An orphan is defined as an element that is
/// not connected in any way to the other elements in the list.
/// 5) The prevous (parent) and next(child) reference for each element cannot
/// point to itself.
///
////////////////////////////////////////////////////////////////////////////////////
class JAUS_MOBILITY_DLL ListManager : public Management::Child
{
public:
////////////////////////////////////////////////////////////////////////////////////
///
/// \class Child
/// \brief This class is used to create services that inherit from the
/// List Manager service.
///
/// This service class maintains the list to be executed, and has methods
/// to advance to the next element and get the current list element so
/// that your service does not need to maintain it itself.
///
////////////////////////////////////////////////////////////////////////////////////
class JAUS_MOBILITY_DLL Child : public Management::Child
{
friend class ListManager;
public:
Child(const ID& serviceIdentifier,
const ID& parentServiceIdentifier);
virtual ~Child();
// Method called when transitioning to a ready state.
virtual bool Resume() = 0;
// Method called to transition due to reset.
virtual bool Reset() = 0;
// Method called when transitioning to a standby state.
virtual bool Standby() = 0;
// Method called to begin/continue execution of a list.
virtual void ExecuteList(const double speedMetersPerSecond) = 0;
// Method called to check if an element type (message payload) is supported.
virtual bool IsElementSupported(const Message* message) const = 0;
// Method to check if list execution is complete (i.e. keep executing list?).
bool IsListExecutionComplete() const;
// Deletes an element from the list.
bool DeleteListElement(const UShort id, Byte& rejectReason);
// Inserts an element into the list.
bool SetElements(const Element::List& elements);
// Get the current active element in the list.
Element GetActiveListElement() const;
// Method to get a specific element.
Element GetElement(const UShort id) const;
// Gets the current active element (0 if not initialized yet or list is complete).
UShort GetActiveListElementID() const { return mActiveElement; }
// Advances the active element in the list (called when active element is completed).
void AdvanceListElement();
// Method to get a copy of the element list.
Element::Map GetElementList() const;
// Gets a copy of the list IDs.
void GetElementList(std::vector<UShort>& list) const;
// Get the size of the element list.
unsigned int GetElementCount() const;
private:
Mutex mListMutex; ///< Mutex for thread protection of list.
Element::Map mElementList; ///< List of elements to execute.
UShort mActiveElement; ///< The active element in the list.
bool mListCompleteFlag; ///< Flag to mark list execution is complete.
};
const static std::string Name; ///< String name of the Service.
ListManager();
~ListManager();
virtual bool Resume() { return true; }
virtual bool Reset();
virtual bool Standby() { return true; }
virtual bool IsDiscoverable() const { return true; }
virtual bool GenerateEvent(const Events::Subscription& info) const;
virtual bool IsEventSupported(const Events::Type type,
const double requestedPeriodicRate,
const Message* queryMessage,
double& confirmedPeriodicRate,
std::string& errorMessage) const;
virtual void Receive(const Message* message);
virtual Message* CreateMessage(const UShort messageCode) const;
};
}
#endif
/* End of File */
| [
"[email protected]"
]
| [
[
[
1,
159
]
]
]
|
59c83d8477cb58717c0d1d40af5f79af232a0afd | 3de9e77565881674bf6b785326e85ab6e702715f | /src/math/Quaternion.hpp | 505c3c6cc347c199a37d10e8d202855e2318d936 | []
| no_license | adbrown85/gloop-old | 1b7f6deccf16eb4326603a7558660d8875b0b745 | 8857b528c97cfc1fd57c02f055b94cbde6781aa1 | refs/heads/master | 2021-01-19T18:07:39.112088 | 2011-02-27T07:17:14 | 2011-02-27T07:17:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 775 | hpp | /*
* Quaternion.hpp
*
* Author
* Andrew Brown <[email protected]>
*/
#ifndef GLOOP_QUATERNION_HPP
#define GLOOP_QUATERNION_HPP
#include "gloop_common.h"
#include <cmath>
#include <iomanip>
#include "Math.hpp"
#include "Matrix.hpp"
#include "Vec4.hpp"
using namespace std;
/** @brief Encapsulation of an axis/angle rotation that avoids gimbal lock.
* @ingroup system
*/
class Quaternion {
public:
Quaternion();
Quaternion(float angle, const Vec4 &axis);
Matrix getMatrix() const;
Quaternion operator*(const Quaternion &B);
void print();
void set(float angle, const Vec4 &axis);
void rotate(float angle, const Vec4 &axis);
string toString() const;
protected:
void normalize();
private:
float s;
Vec4 v;
};
#endif
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
2
],
[
4,
4
],
[
6,
6
],
[
10,
11
],
[
13,
13
],
[
16,
17
],
[
20,
21
],
[
36,
37
],
[
39,
39
]
],
[
[
3,
3
],
[
5,
5
],
[
15,
15
]
],
[
[
7,
9
],
[
12,
12
],
[
14,
14
],
[
18,
19
],
[
22,
35
],
[
38,
38
]
]
]
|
886211f745e923f73a97ae934d2f918e11f05c4d | 5bd189ea897b10ece778fbf9c7a0891bf76ef371 | /BasicEngine/BasicEngine/Graphics/Skeletal/cal3d/mixer.cpp | c3377cc2bee1b6e8f1df6ce2943cb9f960a0e735 | []
| no_license | boriel/masterullgrupo | c323bdf91f5e1e62c4c44a739daaedf095029710 | 81b3d81e831eb4d55ede181f875f57c715aa18e3 | refs/heads/master | 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 23,411 | cpp | //****************************************************************************//
// mixer.cpp //
// Copyright (C) 2001, 2002 Bruno 'Beosil' Heidelberger //
//****************************************************************************//
// 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. //
//****************************************************************************//
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
//****************************************************************************//
// Includes //
//****************************************************************************//
#include "cal3d/error.h"
#include "cal3d/mixer.h"
#include "cal3d/coremodel.h"
#include "cal3d/corebone.h"
#include "cal3d/coreanimation.h"
#include "cal3d/coretrack.h"
#include "cal3d/corekeyframe.h"
#include "cal3d/model.h"
#include "cal3d/skeleton.h"
#include "cal3d/bone.h"
#include "cal3d/animation.h"
#include "cal3d/animation_action.h"
#include "cal3d/animation_cycle.h"
/*****************************************************************************/
/** Constructs the mixer instance.
*
* This function is the default constructor of the mixer instance.
*****************************************************************************/
CalMixer::CalMixer(CalModel* pModel)
{
assert(pModel);
m_pModel = pModel;
// build the animation table
int coreAnimationCount = m_pModel->getCoreModel()->getCoreAnimationCount();
m_vectorAnimation.reserve(coreAnimationCount);
CalAnimation* null = 0;
m_vectorAnimation.insert(m_vectorAnimation.begin(), coreAnimationCount, null);
// set the animation time/duration values to default
m_animationTime = 0.0f;
m_animationDuration = 0.0f;
m_timeFactor = 1.0f;
}
/*****************************************************************************/
/** Destructs the mixer instance.
*
* This function is the destructor of the mixer instance.
*****************************************************************************/
CalMixer::~CalMixer()
{
// destroy all active animation actions
while(!m_listAnimationAction.empty())
{
CalAnimationAction *pAnimationAction = m_listAnimationAction.front();
m_listAnimationAction.pop_front();
delete pAnimationAction;
}
// destroy all active animation cycles
while(!m_listAnimationCycle.empty())
{
CalAnimationCycle *pAnimationCycle;
pAnimationCycle = m_listAnimationCycle.front();
m_listAnimationCycle.pop_front();
delete pAnimationCycle;
}
// clear the animation table
m_vectorAnimation.clear();
m_pModel = 0;
}
///
/// Examines the given animation and if the first and last keyframe of a given track
/// do not match up, the first key frame is duplicated and added to the end of the track
/// to ensure smooth looping.
///
static void addExtraKeyframeForLoopedAnim(CalCoreAnimation* pCoreAnimation)
{
std::list<CalCoreTrack*>& listCoreTrack = pCoreAnimation->getListCoreTrack();
if(listCoreTrack.size() == 0)
return;
CalCoreTrack *coreTrack = listCoreTrack.front();
if(coreTrack == 0)
return;
CalCoreKeyframe *lastKeyframe = coreTrack->getCoreKeyframe(coreTrack->getCoreKeyframeCount()-1);
if(lastKeyframe == 0)
return;
if(lastKeyframe->getTime() < pCoreAnimation->getDuration())
{
std::list<CalCoreTrack *>::iterator itr;
for(itr=listCoreTrack.begin();itr!=listCoreTrack.end();++itr)
{
coreTrack = *itr;
CalCoreKeyframe *firstKeyframe = coreTrack->getCoreKeyframe(0);
CalCoreKeyframe *newKeyframe = new CalCoreKeyframe();
newKeyframe->setTranslation(firstKeyframe->getTranslation());
newKeyframe->setRotation(firstKeyframe->getRotation());
newKeyframe->setTime(pCoreAnimation->getDuration());
coreTrack->addCoreKeyframe(newKeyframe);
}
}
}
/*****************************************************************************/
/** Interpolates the weight of an animation cycle.
*
* This function interpolates the weight of an animation cycle to a new value
* in a given amount of time. If the specified animation cycle is not active
* yet, it is activated.
*
* @param id The ID of the animation cycle that should be blended.
* @param weight The weight to interpolate the animation cycle to.
* @param delay The time in seconds until the new weight should be reached.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMixer::blendCycle(int id, float weight, float delay)
{
if((id < 0) || (id >= (int)m_vectorAnimation.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
// get the animation for the given id
CalAnimation *pAnimation = m_vectorAnimation[id];
// create a new animation instance if it is not active yet
if(pAnimation == 0)
{
// take the fast way out if we are trying to clear an inactive animation
if(weight == 0.0f) return true;
// get the core animation
CalCoreAnimation *pCoreAnimation = m_pModel->getCoreModel()->getCoreAnimation(id);
if(pCoreAnimation == 0) return false;
// Ensure that the animation's first and last key frame match for proper
// looping.
::addExtraKeyframeForLoopedAnim(pCoreAnimation);
// allocate a new animation cycle instance
CalAnimationCycle *pAnimationCycle = new CalAnimationCycle(pCoreAnimation);
if(pAnimationCycle == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return false;
}
// insert new animation into the tables
m_vectorAnimation[id] = pAnimationCycle;
m_listAnimationCycle.push_front(pAnimationCycle);
// blend the animation
return pAnimationCycle->blend(weight, delay);
}
// check if this is really a animation cycle instance
if(pAnimation->getType() != CalAnimation::TYPE_CYCLE)
{
CalError::setLastError(CalError::INVALID_ANIMATION_TYPE, __FILE__, __LINE__);
return false;
}
// clear the animation cycle from the active vector if the target weight is zero
if(weight == 0.0f)
{
m_vectorAnimation[id] = 0;
}
// cast it to an animation cycle
CalAnimationCycle *pAnimationCycle;
pAnimationCycle = (CalAnimationCycle *)pAnimation;
// blend the animation cycle
pAnimationCycle->blend(weight, delay);
pAnimationCycle->checkCallbacks(0,m_pModel);
return true;
}
/*****************************************************************************/
/** Fades an animation cycle out.
*
* This function fades an animation cycle out in a given amount of time.
*
* @param id The ID of the animation cycle that should be faded out.
* @param delay The time in seconds until the the animation cycle is
* completely removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMixer::clearCycle(int id, float delay)
{
// check if the animation id is valid
if((id < 0) || (id >= (int)m_vectorAnimation.size()))
{
CalError::setLastError(CalError::INVALID_HANDLE, __FILE__, __LINE__);
return false;
}
// get the animation for the given id
CalAnimation *pAnimation;
pAnimation = m_vectorAnimation[id];
// we can only clear cycles that are active
if(pAnimation == 0) return true;
// check if this is really a animation cycle instance
if(pAnimation->getType() != CalAnimation::TYPE_CYCLE)
{
CalError::setLastError(CalError::INVALID_ANIMATION_TYPE, __FILE__, __LINE__);
return false;
}
// clear the animation cycle from the active vector
m_vectorAnimation[id] = 0;
// cast it to an animation cycle
CalAnimationCycle *pAnimationCycle;
pAnimationCycle = (CalAnimationCycle *)pAnimation;
// set animation cycle to async state
pAnimationCycle->setAsync(m_animationTime, m_animationDuration);
// blend the animation cycle
pAnimationCycle->blend(0.0f, delay);
pAnimationCycle->checkCallbacks(0, m_pModel);
return true;
}
/*****************************************************************************/
/** Executes an animation action.
*
* This function executes an animation action.
*
* @param id The ID of the animation action that should be blended.
* @param delayIn The time in seconds until the animation action reaches the
* full weight from the beginning of its execution.
* @param delayOut The time in seconds in which the animation action reaches
* zero weight at the end of its execution.
* @param weightTarget The weight to interpolate the animation action to.
* @param autoLock This prevents the Action from being reset and removed
* on the last keyframe if true.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happend
*****************************************************************************/
bool CalMixer::executeAction(int id, float delayIn, float delayOut, float weightTarget, bool autoLock)
{
// get the core animation
CalCoreAnimation *pCoreAnimation;
pCoreAnimation = m_pModel->getCoreModel()->getCoreAnimation(id);
if(pCoreAnimation == 0)
{
return false;
}
// allocate a new animation action instance
CalAnimationAction *pAnimationAction = new CalAnimationAction(pCoreAnimation);
if(pAnimationAction == 0)
{
CalError::setLastError(CalError::MEMORY_ALLOCATION_FAILED, __FILE__, __LINE__);
return false;
}
// insert new animation into the table
m_listAnimationAction.push_front(pAnimationAction);
// execute the animation
pAnimationAction->execute(delayIn, delayOut, weightTarget, autoLock);
pAnimationAction->checkCallbacks(0, m_pModel);
return true;
}
/*****************************************************************************/
/** Clears an active animation action.
*
* This function removes an animation action from the blend list. This is
* particularly useful with auto-locked actions on their last frame.
*
* @param id The ID of the animation action that should be removed.
*
* @return One of the following values:
* \li \b true if successful
* \li \b false if an error happened or action was not found
*****************************************************************************/
bool CalMixer::removeAction(int id)
{
// get the core animation
CalCoreAnimation *pCoreAnimation;
pCoreAnimation = m_pModel->getCoreModel()->getCoreAnimation(id);
if(pCoreAnimation == 0)
{
return false;
}
// update all active animation actions of this model
std::list<CalAnimationAction *>::iterator iteratorAnimationAction;
iteratorAnimationAction = m_listAnimationAction.begin();
while(iteratorAnimationAction != m_listAnimationAction.end())
{
// find the specified action and remove it
if((*iteratorAnimationAction)->getCoreAnimation() == pCoreAnimation )
{
// found, so remove
(*iteratorAnimationAction)->completeCallbacks(m_pModel);
delete (*iteratorAnimationAction);
iteratorAnimationAction = m_listAnimationAction.erase(iteratorAnimationAction);
return true;
}
iteratorAnimationAction++;
}
return false;
}
/*****************************************************************************/
/** Updates all active animations.
*
* This function updates all active animations of the mixer instance for a
* given amount of time.
*
* @param deltaTime The elapsed time in seconds since the last update.
*****************************************************************************/
void CalMixer::updateAnimation(float deltaTime)
{
// update the current animation time
if(m_animationDuration == 0.0f)
{
m_animationTime = 0.0f;
}
else
{
m_animationTime += deltaTime * m_timeFactor;
if(m_animationTime >= m_animationDuration || m_animationTime<0)
{
m_animationTime = (float) fmod(m_animationTime, m_animationDuration);
}
if (m_animationTime < 0)
m_animationTime += m_animationDuration;
}
// update all active animation actions of this model
std::list<CalAnimationAction *>::iterator iteratorAnimationAction;
iteratorAnimationAction = m_listAnimationAction.begin();
while(iteratorAnimationAction != m_listAnimationAction.end())
{
// update and check if animation action is still active
if((*iteratorAnimationAction)->update(deltaTime))
{
(*iteratorAnimationAction)->checkCallbacks((*iteratorAnimationAction)->getTime(),m_pModel);
++iteratorAnimationAction;
}
else
{
// animation action has ended, destroy and remove it from the animation list
(*iteratorAnimationAction)->completeCallbacks(m_pModel);
delete (*iteratorAnimationAction);
iteratorAnimationAction = m_listAnimationAction.erase(iteratorAnimationAction);
}
}
// todo: update all active animation poses of this model
// update the weight of all active animation cycles of this model
std::list<CalAnimationCycle *>::iterator iteratorAnimationCycle;
iteratorAnimationCycle = m_listAnimationCycle.begin();
float accumulatedWeight, accumulatedDuration;
accumulatedWeight = 0.0f;
accumulatedDuration = 0.0f;
while(iteratorAnimationCycle != m_listAnimationCycle.end())
{
// update and check if animation cycle is still active
if((*iteratorAnimationCycle)->update(deltaTime))
{
// check if it is in sync. if yes, update accumulated weight and duration
if((*iteratorAnimationCycle)->getState() == CalAnimation::STATE_SYNC)
{
accumulatedWeight += (*iteratorAnimationCycle)->getWeight();
accumulatedDuration += (*iteratorAnimationCycle)->getWeight() * (*iteratorAnimationCycle)->getCoreAnimation()->getDuration();
}
(*iteratorAnimationCycle)->checkCallbacks(m_animationTime,m_pModel);
++iteratorAnimationCycle;
}
else
{
// animation cycle has ended, destroy and remove it from the animation list
(*iteratorAnimationCycle)->completeCallbacks(m_pModel);
delete (*iteratorAnimationCycle);
iteratorAnimationCycle = m_listAnimationCycle.erase(iteratorAnimationCycle);
}
}
// adjust the global animation cycle duration
if(accumulatedWeight > 0.0f)
{
m_animationDuration = accumulatedDuration / accumulatedWeight;
}
else
{
m_animationDuration = 0.0f;
}
}
void CalMixer::updateSkeleton()
{
// get the skeleton we need to update
CalSkeleton *pSkeleton;
pSkeleton = m_pModel->getSkeleton();
if(pSkeleton == 0) return;
// clear the skeleton state
pSkeleton->clearState();
// get the bone vector of the skeleton
std::vector<CalBone *>& vectorBone = pSkeleton->getVectorBone();
// loop through all animation actions
std::list<CalAnimationAction *>::iterator iteratorAnimationAction;
for(iteratorAnimationAction = m_listAnimationAction.begin(); iteratorAnimationAction != m_listAnimationAction.end(); ++iteratorAnimationAction)
{
// get the core animation instance
CalCoreAnimation *pCoreAnimation;
pCoreAnimation = (*iteratorAnimationAction)->getCoreAnimation();
// get the list of core tracks of above core animation
std::list<CalCoreTrack *>& listCoreTrack = pCoreAnimation->getListCoreTrack();
// loop through all core tracks of the core animation
std::list<CalCoreTrack *>::iterator iteratorCoreTrack;
for(iteratorCoreTrack = listCoreTrack.begin(); iteratorCoreTrack != listCoreTrack.end(); ++iteratorCoreTrack)
{
// get the appropriate bone of the track
CalBone *pBone;
pBone = vectorBone[(*iteratorCoreTrack)->getCoreBoneId()];
// get the current translation and rotation
CalVector translation;
CalQuaternion rotation;
(*iteratorCoreTrack)->getState((*iteratorAnimationAction)->getTime(), translation, rotation);
// blend the bone state with the new state
pBone->blendState((*iteratorAnimationAction)->getWeight(), translation, rotation);
}
}
// lock the skeleton state
pSkeleton->lockState();
// loop through all animation cycles
std::list<CalAnimationCycle *>::iterator iteratorAnimationCycle;
for(iteratorAnimationCycle = m_listAnimationCycle.begin(); iteratorAnimationCycle != m_listAnimationCycle.end(); ++iteratorAnimationCycle)
{
// get the core animation instance
CalCoreAnimation *pCoreAnimation;
pCoreAnimation = (*iteratorAnimationCycle)->getCoreAnimation();
// calculate adjusted time
float animationTime;
if((*iteratorAnimationCycle)->getState() == CalAnimation::STATE_SYNC)
{
if(m_animationDuration == 0.0f)
{
animationTime = 0.0f;
}
else
{
animationTime = m_animationTime * pCoreAnimation->getDuration() / m_animationDuration;
}
}
else
{
animationTime = (*iteratorAnimationCycle)->getTime();
}
// get the list of core tracks of above core animation
std::list<CalCoreTrack *>& listCoreTrack = pCoreAnimation->getListCoreTrack();
// loop through all core tracks of the core animation
std::list<CalCoreTrack *>::iterator iteratorCoreTrack;
for(iteratorCoreTrack = listCoreTrack.begin(); iteratorCoreTrack != listCoreTrack.end(); ++iteratorCoreTrack)
{
// get the appropriate bone of the track
CalBone *pBone;
pBone = vectorBone[(*iteratorCoreTrack)->getCoreBoneId()];
// get the current translation and rotation
CalVector translation;
CalQuaternion rotation;
(*iteratorCoreTrack)->getState(animationTime, translation, rotation);
// blend the bone state with the new state
pBone->blendState((*iteratorAnimationCycle)->getWeight(), translation, rotation);
}
}
// lock the skeleton state
pSkeleton->lockState();
// let the skeleton calculate its final state
pSkeleton->calculateState();
}
/*****************************************************************************/
/** Returns the animation time.
*
* This function returns the animation time of the mixer instance.
*
* @return The animation time in seconds.
*****************************************************************************/
float CalMixer::getAnimationTime()
{
return m_animationTime;
}
/*****************************************************************************/
/** Returns the animation duration.
*
* This function returns the animation duration of the mixer instance.
*
* @return The animation duration in seconds.
*****************************************************************************/
float CalMixer::getAnimationDuration()
{
return m_animationDuration;
}
/*****************************************************************************/
/** Sets the animation time.
*
* This function sets the animation time of the mixer instance.
*
*****************************************************************************/
void CalMixer::setAnimationTime(float animationTime)
{
m_animationTime=animationTime;
}
/*****************************************************************************/
/** Set the time factor.
*
* This function sets the time factor of the mixer instance.
* this time factor affect only sync animation
*
*****************************************************************************/
void CalMixer::setTimeFactor(float timeFactor)
{
m_timeFactor = timeFactor;
}
/*****************************************************************************/
/** Get the time factor.
*
* This function return the time factor of the mixer instance.
*
*****************************************************************************/
float CalMixer::getTimeFactor()
{
return m_timeFactor;
}
/*****************************************************************************/
/** Get the model.
*
* This function return the CalModel of the mixer instance.
*
*****************************************************************************/
CalModel *CalMixer::getCalModel()
{
return m_pModel;
}
/*****************************************************************************/
/** Get the animation vector.
*
* This function return the animation vector of the mixer instance.
*
*****************************************************************************/
std::vector<CalAnimation *> & CalMixer::getAnimationVector()
{
return m_vectorAnimation;
}
/*****************************************************************************/
/** Get the list of the action animation.
*
* This function return the list of the action animation of the mixer instance.
*
*****************************************************************************/
std::list<CalAnimationAction *> & CalMixer::getAnimationActionList()
{
return m_listAnimationAction;
}
/*****************************************************************************/
/** Get the list of the cycle animation.
*
* This function return the list of the cycle animation of the mixer instance.
*
*****************************************************************************/
std::list<CalAnimationCycle *> & CalMixer::getAnimationCycle()
{
return m_listAnimationCycle;
}
//****************************************************************************//
//Nuevo implementacion añadida
//Esta función lo que hace es buscar la animación correspondiente y llamar a la función
//que creamos antes (remove en animation_action)
bool CalMixer::removeAction(int liId, float lfDelayOut)
{
// get the core animation
CalCoreAnimation *lpCoreAnimation;
lpCoreAnimation = m_pModel->getCoreModel()->getCoreAnimation(liId);
if(lpCoreAnimation == 0)
return false;
// update all active animation actions of this model
std::list<CalAnimationAction *>::iterator lpIt;
lpIt = m_listAnimationAction.begin();
while(lpIt != m_listAnimationAction.end())
{
// find the specified action and remove it
if((*lpIt)->getCoreAnimation() == lpCoreAnimation )
{
// found, so remove with delayOut
(*lpIt)->remove(lfDelayOut);
return true;
}
lpIt++;
}
return false;
}
| [
"[email protected]@f2da8aa9-0175-0678-5dcd-d323193514b7"
]
| [
[
[
1,
685
]
]
]
|
352363d3db34481474f27c48e26f2a2476d15c22 | fbd2deaa66c52fc8c38baa90dd8f662aabf1f0dd | /totalFirePower/ta demo/code/Gaf.cpp | 735c52ca0ec36af8e6049cbdac51c5dbd55e63f8 | []
| no_license | arlukin/dev | ea4f62f3a2f95e1bd451fb446409ab33e5c0d6e1 | b71fa9e9d8953e33f25c2ae7e5b3c8e0defd18e0 | refs/heads/master | 2021-01-15T11:29:03.247836 | 2011-02-24T23:27:03 | 2011-02-24T23:27:03 | 1,408,455 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,896 | cpp | #include "Gaf.h"
#include "hash.h"
#include "hpihandler.h"
#include "mygl.h"
#include "infoconsole.h"
//---------------------------------------------------------------------------
using namespace std;
CGaf* gafHandler;
CGaf::CGaf()
{
PrintLoadMsg("Mapping gaf files");
GafTable = hash_new(1, hash_function, hash_compare);
map<string,CHpiHandler::FileData>::iterator fi;
for(fi=hpiHandler->files.begin();fi!=hpiHandler->files.end();++fi){
if(fi->first.find(".gaf")!=string::npos){
PutGafs(fi->first.c_str());
}
}
/*
GafDir=GafDira;
GafTable = hash_new(1, hash_function, hash_compare);
//ffblk ffblk;
std::string SearchDir;
SearchDir=GafDir+"*.gaf";
WIN32_FIND_DATA FindFileData;
HANDLE Find = FindFirstFile(SearchDir.c_str(), &FindFileData);//findfirst(SearchDir, &ffblk, 0);
PutGafs((GafDir+FindFileData.cFileName).c_str());
while(FindNextFile(Find, &FindFileData))
{
PutGafs((GafDir+FindFileData.cFileName).c_str());
}
FindClose(Find);
*/
}
CGaf::~CGaf()
{
hash_for_each(hash_freea_alla, GafTable);
hash_free(GafTable);
}
unsigned char *CGaf::GetGaf(const char *Name, const char *File,int SubFrame)
{
unsigned char *ReturnData;
cGaf TempGaf;
strcpy(TempGaf.GafName, Name);
MakeLower(TempGaf.GafName);
int size=hpiHandler->GetFileSize(File);
unsigned char* fileBuf=new unsigned char[size];
hpiHandler->LoadFile(File,fileBuf);
_GAFHEADER GafHeader;
memcpy(&GafHeader,&fileBuf[0],sizeof(GafHeader));
long *EntryPTR = new long[GafHeader.Entries];
memcpy(EntryPTR,&fileBuf[sizeof(GafHeader)],GafHeader.Entries*sizeof(EntryPTR));
long offset=0;
_GAFENTRY GafEntry;
for(int i=0; i<GafHeader.Entries; i++){
memcpy(&GafEntry,&fileBuf[EntryPTR[i]],sizeof(GafEntry));
char gname[64];
strcpy(gname, GafEntry.Name);
MakeLower(gname);
if(strcmp(gname,TempGaf.GafName)==0){
offset=EntryPTR[i]+sizeof(GafEntry);
break;
}
}
delete[] EntryPTR;
if(offset==0)
return 0;
int curOffset=offset;
_GAFFRAMEENTRY GafFrameEntry;
if(GafEntry.Frames< (2>(SubFrame+1) ? 2:(SubFrame+1))){
SubFrames = false;
} else {
for(int i=0; i<SubFrame; i++){
curOffset+=sizeof(GafFrameEntry);
}
SubFrames = true;
}
memcpy(&GafFrameEntry,&fileBuf[curOffset],sizeof(GafFrameEntry));
_GAFFRAMEDATA GafFrameData;
memcpy(&GafFrameData,&fileBuf[GafFrameEntry.PtrFrameTable],sizeof(GafFrameData));
Height = GafFrameData.Height;
Width = GafFrameData.Width;
xOffset=GafFrameData.XPos;
yOffset=GafFrameData.YPos;
if(GafFrameData.FramePointers!=0){
int pp=*(int*)&fileBuf[GafFrameData.PtrFrameData];
memcpy(&GafFrameData,&fileBuf[pp],sizeof(GafFrameData));
}
if(GafFrameData.Compressed == 0){
//no compression, just copy bytes
ReturnData = new unsigned char[Width * Height];
memcpy(ReturnData,&fileBuf[GafFrameData.PtrFrameData],Width * Height);
} else {
ReturnData=DecodeGaf(fileBuf,&GafFrameData);
}
delete[] fileBuf;
return ReturnData;
}
unsigned char *CGaf::GetGaf(const char *Name, int SubFrame)
{
unsigned char *ReturnData;
if(Name[0]==0)
return 0;
cGaf TempGaf;
strcpy(TempGaf.GafName, Name);
MakeLower(TempGaf.GafName);
cGaf *GafEntry = (cGaf*)hash_search((void*)&TempGaf, GafTable);
if(GafEntry == NULL)
return NULL;
int size=hpiHandler->GetFileSize(GafEntry->FileName);
unsigned char* fileBuf=new unsigned char[size];
hpiHandler->LoadFile(GafEntry->FileName,fileBuf);
// ifstream GAF(GafEntry->FileName, ios::binary);
// GAF.seekg(GafEntry->Offset);
int curOffset=GafEntry->Offset;
_GAFFRAMEENTRY GafFrameEntry;
/*
if(strcmpi(GafEntry->FileName + (strlen(GafEntry->FileName)-9), "logos.gaf")!=0)
SubFrame = 0;
*/
if(GafEntry->GafEntry.Frames< (2>(SubFrame+1) ? 2:(SubFrame+1))){
SubFrames = false;
} else {
for(int i=0; i<SubFrame; i++){
//GAF.read((char*)&GafFrameEntry, sizeof(GafFrameEntry));
curOffset+=sizeof(GafFrameEntry);
}
SubFrames = true;
}
/*
if(strcmpi(GafEntry->FileName + (strlen(GafEntry->FileName)-9), "logos.gaf")!=0)
SubFrames = false;
*/
// GAF.read((char*)&GafFrameEntry, sizeof(GafFrameEntry));
memcpy(&GafFrameEntry,&fileBuf[curOffset],sizeof(GafFrameEntry));
_GAFFRAMEDATA GafFrameData;
// GAF.seekg(GafFrameEntry.PtrFrameTable);
// GAF.read((char*)&GafFrameData, sizeof(GafFrameData));
memcpy(&GafFrameData,&fileBuf[GafFrameEntry.PtrFrameTable],sizeof(GafFrameData));
Height = GafFrameData.Height;
Width = GafFrameData.Width;
xOffset=GafFrameData.XPos;
yOffset=GafFrameData.YPos;
if(GafFrameData.FramePointers!=0){
//put only first subframe
// GAF.seekg(GafFrameData.PtrFrameData);
// GAF.read((char*)&pp, sizeof(pp));
int pp=*(int*)&fileBuf[GafFrameData.PtrFrameData];
// GAF.seekg(pp);
// GAF.read((char*)&GafFrameData, sizeof(GafFrameData));
memcpy(&GafFrameData,&fileBuf[pp],sizeof(GafFrameData));
}
if(GafFrameData.Compressed == 0){
//no compression, just copy bytes
ReturnData = new unsigned char[Width * Height];
// GAF.seekg(GafFrameData.PtrFrameData);
// GAF.read(ReturnData, Width * Height);
// GAF.close();
memcpy(ReturnData,&fileBuf[GafFrameData.PtrFrameData],Width * Height);
if(GafFrameData.Unknown1!=9){
for(int a=0;a<Width*Height;++a){
if(ReturnData[a]==GafFrameData.Unknown1)
ReturnData[a]=9;
}
}
} else {
ReturnData=DecodeGaf(fileBuf,&GafFrameData);
// MessageBox(0,"Compressed gafs not supported","Lazy eha",0);
// return NULL;
}
delete[] fileBuf;
return ReturnData;
}
unsigned char *CGaf::DecodeGaf(unsigned char *fileBuf, _GAFFRAMEDATA *GafFrameData)
{
Height = GafFrameData->Height;
Width = GafFrameData->Width;
// ifstream GAF(FileName, ios::binary);
unsigned char *ReturnData = new unsigned char[Height * Width];
// GAF.seekg(GafFrameData->PtrFrameData);
int fileOffset=GafFrameData->PtrFrameData;
for(int i=0; i<Height; i++){
unsigned short Count=*(unsigned short*)&fileBuf[fileOffset];
fileOffset+=2;
int offset = i*Width;
unsigned char Byte;
unsigned char mask;
while(Count){
mask=fileBuf[fileOffset++];
Count--;
if((mask & 0x01) == 0x01){
for(int k=0; k<(mask >> 1); k++){
ReturnData[offset] = 0x0;
offset++;// += (mask >> 1);
}
} else if((mask & 0x02) == 0x02) {
Byte=fileBuf[fileOffset++];
Count--;
for(int k=0; k<(mask >> 2)+1; k++){
ReturnData[offset] = Byte;
offset++;
}
} else {
for(int k=0; k<(mask >> 2)+1; k++) {
Byte=fileBuf[fileOffset++];
Count--;
ReturnData[offset] = Byte;
offset++;
}
}
}
for(;offset<(i+1)*Width;++offset)
ReturnData[offset]=0;
}
return ReturnData;
}
void CGaf::PutGafs(const char *FileName)
{
// ifstream GAF(FileName, ios::binary);
int size=hpiHandler->GetFileSize(FileName);
unsigned char* fileBuf=new unsigned char[size];
hpiHandler->LoadFile(FileName,fileBuf);
_GAFHEADER GafHeader;
// GAF.read((char*)&GafHeader, sizeof(GafHeader));
memcpy(&GafHeader,&fileBuf[0],sizeof(GafHeader));
long *EntryPTR = new long[GafHeader.Entries];
// GAF.read((char*)EntryPTR, GafHeader.Entries*sizeof(EntryPTR));
memcpy(EntryPTR,&fileBuf[sizeof(GafHeader)],GafHeader.Entries*sizeof(EntryPTR));
for(int i=0; i<GafHeader.Entries; i++)
{
cGaf *GafStruct = new cGaf;
_GAFENTRY GafEntry;
// GAF.seekg(EntryPTR[i]);
// GAF.read((char*)&GafEntry, sizeof(GafEntry));
memcpy(&GafEntry,&fileBuf[EntryPTR[i]],sizeof(GafEntry));
strcpy(GafStruct->FileName, FileName);
strcpy(GafStruct->GafName, GafEntry.Name);
MakeLower(GafStruct->GafName);
// GafStruct->Offset = GAF.tellg();
GafStruct->Offset=EntryPTR[i]+sizeof(GafEntry);
// char FileTMP[MAX_PATH];
// strcpy(FileTMP, GafDir);
// strcpy(FileTMP, FileName);
memcpy(&(GafStruct->GafEntry), &GafEntry, sizeof(_GAFENTRY));
hash_insert((void *)GafStruct, GafTable);
}
// GAF.close();
delete[] fileBuf;
delete[] EntryPTR;
}
void CGaf::MakeLower(char *s)
{
for(int a=0;s[a]!=0;++a)
if(s[a]>='A' && s[a]<='Z')
s[a]+='a'-'A';
}
int hash_function(void *element, int storlek)
{
cGaf *E = (cGaf*)element;
int Value = 0;
for(int i=0; i<(int)strlen((*E).GafName); i++)
Value += (*E).GafName[i];
return Value % storlek;
}
int hash_compare(void *el1, void *el2)
{
cGaf *E1 = (cGaf*)el1;
cGaf *E2 = (cGaf*)el2;
return strcmp((*E1).GafName, (*E2).GafName);
}
void hash_freea_alla (void *elem)
{
delete elem;
}
| [
"[email protected]"
]
| [
[
[
1,
331
]
]
]
|
66e10ea5919cbafe5b783f0a36e0999c404a7615 | 41c264ec05b297caa2a6e05e4476ce0576a8d7a9 | /OpenHoldem/DialogScraperOutput.h | 90aa31c32187c65e254d3f2fea44a875a0220e9b | []
| no_license | seawei/openholdem | cf19a90911903d7f4d07f956756bd7e521609af3 | ba408c835b71dc1a9d674eee32958b69090fb86c | refs/heads/master | 2020-12-25T05:40:09.628277 | 2009-01-25T01:17:10 | 2009-01-25T01:17:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,208 | h | #ifndef INC_DIALOGSCRAPEROUTPUT_H
#define INC_DIALOGSCRAPEROUTPUT_H
#include "WinMgr.h"
#include "SizerBar.h"
#include "Resource.h"
// CDlgScraperOutput dialog
class CDlgScraperOutput : public CDialog
{
public:
CDlgScraperOutput(CWnd* pParent = NULL); // standard constructor
virtual ~CDlgScraperOutput();
virtual void OnCancel();
virtual BOOL OnInitDialog();
virtual BOOL DestroyWindow();
void AddListboxItems(void);
void UpdateDisplay();
enum { IDD = IDD_SCRAPER_OUTPUT };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual void PostNcDestroy();
afx_msg void OnLbnSelchangeRegionlist();
afx_msg void OnCbnSelchangeZoom();
afx_msg void OnPaint();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg LRESULT OnWinMgr(WPARAM wp, LPARAM lp);
void DoBitblt(HBITMAP bitmap, int r$index);
CWinMgr m_winMgr; // window manager
CSizerBar m_winMgrSizerBar; // sizer bar
CListBox m_RegionList;
CStatic m_ScraperBitmap;
CComboBox m_Zoom;
CEdit m_ScraperResult;
bool in_startup;
DECLARE_MESSAGE_MAP()
};
extern CDlgScraperOutput *m_ScraperOutputDlg;
#endif //INC_DIALOGSCRAPEROUTPUT_H | [
"[email protected]"
]
| [
[
[
1,
46
]
]
]
|
744373865d5e5205307da5ad2c22058cbf58b354 | 102d8810abb4d1c8aecb454304ec564030bf2f64 | /TP3/Tanque/Tanque/Tanque/stdafx.cpp | a984270d2dd05b90f85ddd32bfa2f0d7dab46c7d | []
| 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 | 293 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Tanque.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
| [
"juan.facorro@6dff32cf-8f48-0410-9a2e-7b8b34aa6dfb"
]
| [
[
[
1,
8
]
]
]
|
88a420552273d90e4f087435357ad68e73e8e203 | 36d0ddb69764f39c440089ecebd10d7df14f75f3 | /プログラム/Ngllib/include/Ngl/XML/XMLFile.h | 940078cf3e878786666b8db70ba6d40a00a4be2f | []
| no_license | weimingtom/tanuki-mo-issyo | 3f57518b4e59f684db642bf064a30fc5cc4715b3 | ab57362f3228354179927f58b14fa76b3d334472 | refs/heads/master | 2021-01-10T01:36:32.162752 | 2009-04-19T10:37:37 | 2009-04-19T10:37:37 | 48,733,344 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,357 | h | /*******************************************************************************/
/**
* @file XMLFile.h.
*
* @brief XMLファイルクラスヘッダファイル.
*
* @date 2008/11/30.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#ifndef _NGL_XML_XMLFILE_H_
#define _NGL_XML_XMLFILE_H_
#include "Ngl/IXMLFile.h"
#include <vector>
namespace Ngl{
namespace XML{
// XML要素クラス
class XMLElement;
/**
* @class XMLFile.
* @brief XMLファイルクラス.
*/
class XMLFile : public IXMLFile
{
public:
/*=========================================================================*/
/**
* @brief コンストラクタ
*
* @param[in] なし.
*/
XMLFile();
/*=========================================================================*/
/**
* @brief デストラクタ
*
* @param[in] なし.
*/
~XMLFile();
/*=========================================================================*/
/**
* @brief 先頭のエレメントを追加
*
* @param[in] elm 追加するエレメント.
* @return なし.
*/
void addElement( XMLElement* elm );
/*=========================================================================*/
/**
* @brief 名前から要素を取得
*
* @param[in] name 取得する要素名.
* @return 取得した要素.
*/
virtual IXMLElement* getElementByName( const std::string name );
/*=========================================================================*/
/**
* @brief インデックス番号から要素を取得
*
* @param[in] index 取得する要素のインデックス番号.
* @return 取得した要素.
*/
virtual IXMLElement* getElementByIndex( unsigned int index );
/*=========================================================================*/
/**
* @brief 要素数を取得
*
* @param[in] なし.
* @return 取得した要素数.
*/
virtual unsigned int elementCount();
/*=========================================================================*/
/**
* @brief [] 演算子オーバーロード
*
* nameで指定した要素を取得する.
*
* @param[in] name 取得する要素名.
* @return 取得した要素.
*/
virtual IXMLElement* operator [] ( const std::string name );
private:
/*=========================================================================*/
/**
* @brief コピーコンストラクタ ( コピー禁止 )
*
* @param[in] other コピーするオブジェクト.
*/
XMLFile( const XMLFile& other );
/*=========================================================================*/
/**
* @brief = 演算子オーバーロード ( コピー禁止 )
*
* @param[in] other 代入するオブジェクト.
* @return 代入結果のオブジェクト.
*/
XMLFile& operator = ( const XMLFile& other );
private:
/** 要素コンテナ型 */
typedef std::vector< XMLElement* > ElementContainer;
private:
/** エレメントコンテナ */
ElementContainer elementContainer_;
};
} // namespace XML
} // namespace Ngl
#endif
/*===== EOF ==================================================================*/ | [
"rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33"
]
| [
[
[
1,
144
]
]
]
|
45011804f0c8f6b79d9a0ec1859e815e597bd777 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/thread/src/mac/init.cpp | 108ff41eb04e082d1ec276634e543b208eb2a9f2 | [
"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 | 1,035 | cpp | // (C) Copyright Mac Murrett 2001.
// 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 for most recent version.
#include "init.hpp"
#include "remote_call_manager.hpp"
#include <boost/thread/detail/singleton.hpp>
#include <Multiprocessing.h>
namespace boost {
namespace threads {
namespace mac {
namespace detail {
namespace {
// force these to get called by the end of static initialization time.
static bool g_bInitialized = (thread_init() && create_singletons());
}
bool thread_init()
{
static bool bResult = MPLibraryIsLoaded();
return(bResult);
}
bool create_singletons()
{
using ::boost::detail::thread::singleton;
singleton<remote_call_manager>::instance();
return(true);
}
} // namespace detail
} // namespace mac
} // namespace threads
} // namespace boost
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
58
]
]
]
|
b29a09e3664ea4c435ee9bd491a93b3b7fed38a3 | 51ebb9684ac1a4b65a5426e5c9ee79ebf8eb3db8 | /Windows/Tool/src/Helper/Helper/Helper.h | 24c519392f8c50e80ffaf00470ab6e5df31a21c9 | []
| no_license | buf1024/lgcbasic | d4dfe6a6bd19e4e4ac0e5ac2b7a0590e04dd5779 | 11db32c9be46d9ac0740429e09ebf880a7a00299 | refs/heads/master | 2021-01-10T12:55:12.046835 | 2011-09-03T15:45:57 | 2011-09-03T15:45:57 | 49,615,513 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 489 | h |
// Helper.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CHelperApp:
// 有关此类的实现,请参阅 Helper.cpp
//
class CHelperApp : public CWinAppEx
{
public:
CHelperApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
};
extern CHelperApp theApp; | [
"buf1024@10f8a008-2033-b5f4-5ad9-01b5c2a83ee0"
]
| [
[
[
1,
32
]
]
]
|
2a85b4aa024a54bcad61f6faef991e47bb3c10ed | faa30f88bd88c37ad26aeda4571668db572a140d | /Error.h | 9475a9a55d3dc5c7497ce6ca944eb749054b12cd | []
| no_license | simophin/remotevision | 88fa6ea7183c79c239474d330c05b2879836735b | 2f28b9fbb82a5b92a36e0a2b1ead067dbf0e55ab | refs/heads/master | 2016-09-05T18:07:42.069906 | 2011-06-16T08:42:31 | 2011-06-16T08:42:31 | 1,744,350 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,330 | h | /*
* Error.h
*
* Created on: 2011-5-14
* Author: simophin
*/
#ifndef ERROR_H_
#define ERROR_H_
#include "RString.h"
#include "utils/SharedPtr.hpp"
#include <iostream>
typedef int syserrno_t;
class Error {
public:
enum Type {
ERR_SUCCESS,
ERR_UNKNOWN,
ERR_SYS_UNKNOWN,
ERR_STATE,
ERR_TIMEOUT,
ERR_INVALID,
ERR_ADDRINUSE
};
Error (Type t = ERR_SUCCESS);
explicit Error (Type t, const String &str);
explicit Error (syserrno_t sys);
explicit Error (syserrno_t sys, const String &str);
virtual ~Error ();
Type getErrorType() const;
void setErrorType (Type t);
void setErrorType (Type t, const String &str);
String getErrorString() const;
void setErrorString (const String &str);
syserrno_t getSystemError () const;
void setSystemError (syserrno_t);
void setSystemError (syserrno_t, const String &);
bool isSuccess () const;
inline bool isError() const {
return !isSuccess();
}
String toString() const;
static Error fromString(const String &,bool *ok = NULL);
friend std::ostream& operator <<(std::ostream &os,const Error &obj);
class SystemMap {
public:
syserrno_t system;
Type type;
const char * message;
};
private:
class Impl;
Utils::SharedPtr<Impl> d;
};
#endif /* ERROR_H_ */
| [
"[email protected]",
"simophin@localhost",
"Fanchao [email protected]",
"[email protected]"
]
| [
[
[
1,
10
],
[
16,
20
],
[
53,
53
],
[
58,
58
],
[
66,
66
],
[
69,
70
],
[
74,
75
]
],
[
[
11,
11
],
[
13,
15
],
[
22,
22
],
[
26,
28
],
[
31,
34
],
[
36,
41
],
[
43,
47
],
[
49,
52
],
[
59,
65
],
[
67,
68
],
[
71,
73
]
],
[
[
12,
12
],
[
21,
21
],
[
23,
25
],
[
29,
30
],
[
35,
35
],
[
42,
42
],
[
48,
48
],
[
54,
55
]
],
[
[
56,
57
]
]
]
|
866666af68e338122098dd6bb08062cff97bf4bf | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /core_billiard/PixelColor.h | 2461cb7ffd2bb377e8966d59bc47789e8580e2f2 | []
| no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | h | #pragma once
namespace my_render_imp {
class PixelColor {
public:
typedef unsigned char Color256;
public:
NxU32 getARGB();
void setARGB( NxU32 );
Color256 getA();
Color256 getR();
Color256 getG();
Color256 getB();
void setA( Color256 );
void setR( Color256 );
void setG( Color256 );
void setB( Color256 );
public:
PixelColor();
explicit PixelColor( NxU32 argb );
explicit PixelColor( Color256 a, Color256 r, Color256 g, Color256 b );
explicit PixelColor( int a, int r, int g, int b );
explicit PixelColor( unsigned int a, unsigned int r, unsigned int g, unsigned int b );
explicit PixelColor( float a, NxVec3 rgb );
explicit PixelColor( float a, float r, float g, float b );
public:
operator NxU32 ();
private:
NxU32 pixelColor_;
private:
Color256 clamp_from0_to255( int );
Color256 clamp_from0_to255( unsigned int );
};
}
| [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
]
| [
[
[
1,
44
]
]
]
|
b6087825cd3e212989197e5eace809bc714e5fbb | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/WheelAnimal2Model/src/logic/RunLogic.cpp | 68eb4b7d7d67257c9abf4d0d49c997a70e7d4ea4 | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | #include "logic/AllLogic.h"
#include "WheelEvents.h"
using namespace Orz;
RunLogic::RunLogic(my_context ctx):LogicAdv(ctx)
{
ORZ_LOG_NORMAL<<"State In: RunLogic!";
getOwner()->runWinner();
//WheelUI::getSingleton().runZXH(Hardware::getSingleton().getWinType()->getBanker());
_process.reset( new Process( getOwner()->getWorld(), WheelEvents::PROCESS_RUN_ENABLE, WheelEvents::PROCESS_RUN_DISABLE));
}
RunLogic::~RunLogic(void)
{
ORZ_LOG_NORMAL<<"State Out: RunLogic!";
}
sc::result RunLogic::react(const UpdateEvt & evt)
{
if(_process->update(evt.getInterval()))
return forward_event();
//return forward_event();
return transit<WinLogic>();
}
sc::result RunLogic::react(const LogicEvent::AskState & evt)
{
evt.execute(getOwner(), 0x02);
//Hardware::getSingleton().answerState(0x01);
return forward_event();
}
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
8f0703428377814d425ddc7fcc9ffe7669bd9ade | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/Valkyrie/Moteur/Materielle.cpp | 9675ebbc25e2033348bd9c0687758b93f1c596b0 | []
| 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 | 5,099 | cpp | #include "Materielle.h"
float TabMaterielle[][10] =
{
{0.0215f ,0.1745f ,0.0215f ,0.07568f ,0.61424f ,0.07568f ,0.633f ,0.727811f,0.633f ,0.6f},
{0.135f ,0.2225f ,0.1575f ,0.54f ,0.89f ,0.63f ,0.316228f,0.316228f,0.316228f,0.1f},
{0.05375f ,0.05f ,0.06625f ,0.18275f ,0.17f ,0.22525f ,0.332741f,0.328634f,0.346435f,0.3f},
{0.25f ,0.20725f ,0.20725f ,1.0f ,0.829f ,0.829f ,0.296648f,0.296648f,0.296648f,0.088f},
{0.1745f ,0.01175f ,0.01175f ,0.61424f ,0.04136f ,0.04136f ,0.727811f,0.626959f,0.626959f,0.6f},
{0.1f ,0.18725f ,0.1745f ,0.396f ,0.74151f ,0.69102f ,0.297254f,0.30829f ,0.306678f,0.1f},
{0.329412f,0.223529f,0.027451f,0.780392f,0.568627f,0.113725f,0.992157f,0.941176f,0.807843f,0.21794872f},
{0.2125f ,0.1275f ,0.054f ,0.714f ,0.4284f ,0.18144f ,0.393548f,0.271906f,0.166721f,0.2f},
{0.25f ,0.25f ,0.25f ,0.4f ,0.4f ,0.4f ,0.774597f,0.774597f,0.774597f,0.6f},
{0.19125f ,0.0735f ,0.0225f ,0.7038f ,0.27048f ,0.0828f ,0.256777f,0.137622f,0.086014f,0.1f},
{0.24725f ,0.1995f ,0.0745f ,0.75164f ,0.60648f ,0.22648f ,0.628281f,0.555802f,0.366065f,0.4f},
{0.19225f ,0.19225f ,0.19225f ,0.50754f ,0.50754f ,0.50754f ,0.508273f,0.508273f,0.508273f,0.4f},
};
CMaterielle::CMaterielle()
{
ZeroMemory(&m_Materielle, sizeof(D3DMATERIAL9));
m_Materielle.Ambient.r = 0.2f;
m_Materielle.Ambient.g = 0.2f;
m_Materielle.Ambient.b = 0.2f;
m_Materielle.Ambient.a = 1.0f;
m_Materielle.Diffuse.r = 0.8f;
m_Materielle.Diffuse.g = 0.8f;
m_Materielle.Diffuse.b = 0.8f;
m_Materielle.Diffuse.a = 1.0f;
m_Materielle.Specular.r = 1.0f;
m_Materielle.Specular.g = 1.0f;
m_Materielle.Specular.b = 1.0f;
m_Materielle.Specular.a = 1.0f;
m_Materielle.Power = 30.f;
}
CMaterielle::~CMaterielle()
{
}
void CMaterielle::SetAmbiante(D3DCOLOR Couleur)
{
m_Materielle.Ambient.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Materielle.Ambient.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Materielle.Ambient.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Materielle.Ambient.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CMaterielle::SetAmbiante(D3DCOLORVALUE* Couleur)
{
m_Materielle.Ambient = *Couleur;
}
void CMaterielle::SetAmbiante(float r, float g, float b, float a)
{
m_Materielle.Ambient.r = r;
m_Materielle.Ambient.g = g;
m_Materielle.Ambient.b = b;
m_Materielle.Ambient.a = a;
}
void CMaterielle::SetDiffuse(D3DCOLOR Couleur)
{
m_Materielle.Diffuse.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Materielle.Diffuse.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Materielle.Diffuse.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Materielle.Diffuse.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CMaterielle::SetDiffuse(D3DCOLORVALUE* Couleur)
{
m_Materielle.Diffuse = *Couleur;
}
void CMaterielle::SetDiffuse(float r, float g, float b, float a)
{
m_Materielle.Diffuse.r = r;
m_Materielle.Diffuse.g = g;
m_Materielle.Diffuse.b = b;
m_Materielle.Diffuse.a = a;
}
void CMaterielle::SetAmbianteDiffuse(D3DCOLOR Couleur)
{
SetDiffuse(Couleur);
SetAmbiante(Couleur);
}
void CMaterielle::SetAmbianteDiffuse(D3DCOLORVALUE* Couleur)
{
SetDiffuse(Couleur);
SetAmbiante(Couleur);
}
void CMaterielle::SetAmbianteDiffuse(float r, float g, float b, float a)
{
SetDiffuse(r, g, b, a);
SetAmbiante(r, g, b, a);
}
void CMaterielle::SetSpeculaire(D3DCOLOR Couleur)
{
m_Materielle.Specular.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Materielle.Specular.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Materielle.Specular.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Materielle.Specular.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CMaterielle::SetSpeculaire(D3DCOLORVALUE* Couleur)
{
m_Materielle.Specular = *Couleur;
}
void CMaterielle::SetSpeculaire(float r, float g, float b, float a)
{
m_Materielle.Specular.r = r;
m_Materielle.Specular.g = g;
m_Materielle.Specular.b = b;
m_Materielle.Specular.a = a;
}
void CMaterielle::SetPuissance(float Puissance)
{
m_Materielle.Power = Puissance;
}
void CMaterielle::SetEmissive(D3DCOLOR Couleur)
{
m_Materielle.Emissive.r = D3DCOLOR_R(Couleur) / 255.0f;
m_Materielle.Emissive.g = D3DCOLOR_G(Couleur) / 255.0f;
m_Materielle.Emissive.b = D3DCOLOR_B(Couleur) / 255.0f;
m_Materielle.Emissive.a = D3DCOLOR_A(Couleur) / 255.0f;
}
void CMaterielle::SetEmissive(D3DCOLORVALUE* Couleur)
{
m_Materielle.Emissive = *Couleur;
}
void CMaterielle::SetEmissive(float r, float g, float b, float a)
{
m_Materielle.Emissive.r = r;
m_Materielle.Emissive.g = g;
m_Materielle.Emissive.b = b;
m_Materielle.Emissive.a = a;
}
void CMaterielle::SetMaterielle(DWORD Type)
{
if(Type >= sizeof(TabMaterielle)/sizeof(TabMaterielle[0]))
return;
SetAmbiante(TabMaterielle[Type][0], TabMaterielle[Type][1], TabMaterielle[Type][2]);
SetDiffuse(TabMaterielle[Type][3], TabMaterielle[Type][4], TabMaterielle[Type][5]);
SetSpeculaire(TabMaterielle[Type][6], TabMaterielle[Type][7], TabMaterielle[Type][8]);
SetPuissance(TabMaterielle[Type][9]*128.0f);
} | [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
]
| [
[
[
1,
156
]
]
]
|
7fd40db8315f0a3c1ec7b77a5697ea7e86ca1d6d | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Serialize/UnitTest/PatchTest/patchDataObjectTest.cxx | 5f674cbf607cabf49f89eda21674859b0108f666 | []
| 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,597 | cxx | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
// ---------------------
// C(100-102) -> NONE
// ---------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestC", 100) // 0
HK_PATCH_MEMBER_ADDED("number1", TYPE_INT, HK_NULL, 0)
HK_PATCH_MEMBER_ADDED("number2", TYPE_INT, HK_NULL, 0)
HK_PATCH_MEMBER_ADDED("number3", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 100, "hkTestC", 101) // 1
HK_PATCH_MEMBER_REMOVED("number1", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 101, "hkTestC", 102) // 2
HK_PATCH_MEMBER_REMOVED("number2", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 102, HK_NULL, HK_CLASS_REMOVED) // 3
HK_PATCH_MEMBER_REMOVED("number3", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
// ---------------------
// A(0-2...) -> C(0-1)
// ---------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestA", 0) // 4
HK_PATCH_MEMBER_ADDED("object", TYPE_OBJECT, "hkTestC", 0)
HK_PATCH_MEMBER_ADDED("float", TYPE_REAL, HK_NULL, 0)
HK_PATCH_DEPENDS("hkTestC", 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestA", 0, "hkTestA", 1) // 5
HK_PATCH_DEPENDS("hkTestC", 1)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestA", 1, "hkTestA", 2) // 6
HK_PATCH_MEMBER_REMOVED("object", TYPE_OBJECT, "hkTestC", 0)
HK_PATCH_DEPENDS("hkTestC", 1)
HK_PATCH_END()
// ---------------------------
// D(0-2) -> C(101-102), A(0-1)
// ---------------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestD", 0) // 7
HK_PATCH_MEMBER_ADDED("object", TYPE_OBJECT, "hkTestC", 0)
HK_PATCH_DEPENDS("hkTestC", 101)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestD", 0, "hkTestD", 1) // 8
HK_PATCH_MEMBER_REMOVED("object", TYPE_OBJECT, "hkTestC", 0)
HK_PATCH_MEMBER_ADDED("number", TYPE_INT, HK_NULL, 0)
HK_PATCH_DEPENDS("hkTestC", 102)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestD", 1, "hkTestD", 2) // 9
HK_PATCH_MEMBER_ADDED("object", TYPE_OBJECT, "hkTestA", 0)
HK_PATCH_DEPENDS("hkTestA", 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestD", 2, HK_NULL, HK_CLASS_REMOVED) // 10
HK_PATCH_MEMBER_REMOVED("object", TYPE_OBJECT, "hkTestA", 0)
HK_PATCH_MEMBER_REMOVED("number", TYPE_INT, HK_NULL, 0)
HK_PATCH_DEPENDS("hkTestA", 1)
HK_PATCH_END()
// ---------------------
// B(0-1...) -> C(2)
// ---------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestB", 0) // 11
HK_PATCH_MEMBER_ADDED("string", TYPE_CSTRING, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestB", 0, "hkTestB", 1) // 12
HK_PATCH_MEMBER_ADDED("object", TYPE_OBJECT, "hkTestC", 0)
HK_PATCH_DEPENDS("hkTestC", 2)
HK_PATCH_END()
// ---------------------
// C(0-1) -> NONE
// ---------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestC", 0) // 13
HK_PATCH_MEMBER_ADDED("string", TYPE_CSTRING, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 0, "hkTestC", 1) // 14
HK_PATCH_MEMBER_ADDED("number", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 1, HK_NULL, HK_CLASS_REMOVED) // 15
HK_PATCH_MEMBER_REMOVED("string", TYPE_CSTRING, HK_NULL, 0)
HK_PATCH_MEMBER_REMOVED("number", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
// ---------------------
// C(2-...) -> NONE
// ---------------------
HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkTestC", 2) // 16
HK_PATCH_MEMBER_ADDED("userData", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
HK_PATCH_BEGIN("hkTestC", 2, "hkTestC", 3) // 17
HK_PATCH_MEMBER_ADDED("userData2", TYPE_INT, HK_NULL, 0)
HK_PATCH_END()
/*
* 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,
125
]
]
]
|
346b18c7f32c80b9297056854f031eefec9a9c17 | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Graphic/Renderer/D3D10CubeTexture.h | efb4bf426d68c11f0b75041183f1790c5b677011 | []
| no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,195 | h | #ifndef _D3D10CUBETEXTURE_H_
#define _D3D10CUBETEXTURE_H_
#include "D3D10Prerequisites.h"
#include "../Main/Texture.h"
namespace Flagship
{
class _DLL_Export D3D10CubeTexture : public Texture
{
public:
D3D10CubeTexture();
virtual ~D3D10CubeTexture();
// 获取实例对象指针
ID3D10Texture2D * GetImpliment();
// 获取资源对象
ID3D10ShaderResourceView * GetShaderResourceView();
public:
// 从资源创建效果
virtual bool CreateFromMemory();
// 创建贴图
virtual bool CreateRenderTarget( UINT uiWidth, UINT uiHeight, DWORD dwFormat );
// 创建贴图
virtual bool CreateDepthStencil( UINT uiWidth, UINT uiHeight, DWORD dwFormat );
// 清空贴图
virtual bool ClearTexture();
protected:
// 释放缓存
virtual void UnCache();
protected:
// D3D10贴图对象
ID3D10Texture2D * m_pD3D10CubeTexture;
// Shader资源对象
ID3D10ShaderResourceView * m_pD3D10ShaderResource;
private:
};
typedef ResHandle<D3D10CubeTexture> D3D10CubeTextureHandle;
}
#endif | [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
]
| [
[
[
1,
52
]
]
]
|
0f58010f315a8c4e0fad561cf537ed7dea39138c | fac8de123987842827a68da1b580f1361926ab67 | /inc/physics/Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldViewerBase.h | 48cd80608009acb493d96a20216773da30edc84f | []
| no_license | blockspacer/transporter-game | 23496e1651b3c19f6727712a5652f8e49c45c076 | 083ae2ee48fcab2c7d8a68670a71be4d09954428 | refs/heads/master | 2021-05-31T04:06:07.101459 | 2009-02-19T20:59:59 | 2009-02-19T20:59:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,607 | 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-2008 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_UTILITIES2_WORLDVIEWER_BASE_H
#define HK_UTILITIES2_WORLDVIEWER_BASE_H
#include <Physics/Dynamics/World/Listener/hkpWorldDeletionListener.h>
#include <Physics/Utilities/VisualDebugger/hkpPhysicsContext.h>
#include <Common/Visualize/hkProcess.h>
class hkpWorldViewerBase : public hkReferencedObject,
public hkProcess,
protected hkpPhysicsContextWorldListener
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_VDB);
// Ctor will register as all the listeners
hkpWorldViewerBase( const hkArray<hkProcessContext*>& contexts );
// Dtor will unregister as all the listeners, from the context if any
virtual ~hkpWorldViewerBase();
// Sub classes should impliment what they require rom the following:
//Process:
virtual void getConsumableCommands( hkUint8*& commands, int& numCommands ) { commands = HK_NULL; numCommands = 0; }
virtual void consumeCommand( hkUint8 command ) { }
virtual void step( hkReal frameTimeInMs ) { /* nothing to do, driven by the simulation callbacks usually */ }
//World deletion listener:
virtual void worldRemovedCallback( hkpWorld* world ) { }
//World added listener. Should impl this in sub class, but call up to this one to get the listener reg'd.
virtual void worldAddedCallback( hkpWorld* world ) { }
protected:
hkpPhysicsContext* m_context;
};
#endif // HK_UTILITIES2_WORLDVIEWER_BASE_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529)
*
* Confidential Information of Havok. (C) Copyright 1999-2008
* 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
*
*/
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
65
]
]
]
|
e7dce96515a9590d1acbaccbf00ee544cc5bc5d7 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/dom/impl/DOMParentNode.cpp | 186fe638096d65b5cd3f5aeae65f755c096d7f7a | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,595 | cpp | /*
* Copyright 2001-2002,2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: DOMParentNode.cpp 176377 2005-04-07 15:08:57Z amassari $
*/
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMNode.hpp>
#include "DOMDocumentImpl.hpp"
#include "DOMNodeListImpl.hpp"
#include "DOMRangeImpl.hpp"
#include "DOMNodeIteratorImpl.hpp"
#include "DOMParentNode.hpp"
#include "DOMCasts.hpp"
XERCES_CPP_NAMESPACE_BEGIN
DOMParentNode::DOMParentNode(DOMDocument *ownerDoc)
: fOwnerDocument(ownerDoc), fFirstChild(0), fChildNodeList(castToNode(this))
{
}
// This only makes a shallow copy, cloneChildren must also be called for a
// deep clone
DOMParentNode::DOMParentNode(const DOMParentNode &other) :
fChildNodeList(castToNode(this))
{
this->fOwnerDocument = other.fOwnerDocument;
// Need to break the association w/ original kids
this->fFirstChild = 0;
}
void DOMParentNode::changed()
{
DOMDocumentImpl *doc = (DOMDocumentImpl *)this->getOwnerDocument();
doc->changed();
}
int DOMParentNode::changes() const
{
DOMDocumentImpl *doc = (DOMDocumentImpl *)this->getOwnerDocument();
return doc->changes();
}
DOMNode * DOMParentNode::appendChild(DOMNode *newChild)
{
return insertBefore(newChild, 0);
}
void DOMParentNode::cloneChildren(const DOMNode *other) {
// for (DOMNode *mykid = other.getFirstChild();
for (DOMNode *mykid = other->getFirstChild();
mykid != 0;
mykid = mykid->getNextSibling())
{
appendChild(mykid->cloneNode(true));
}
}
DOMDocument * DOMParentNode::getOwnerDocument() const {
return fOwnerDocument;
}
// unlike getOwnerDocument this is not overriden by DocumentImpl to return 0
DOMDocument * DOMParentNode::getDocument() const {
return fOwnerDocument;
}
void DOMParentNode::setOwnerDocument(DOMDocument* doc) {
fOwnerDocument = doc;
}
DOMNodeList *DOMParentNode::getChildNodes() const {
const DOMNodeList *ret = &fChildNodeList;
return (DOMNodeList *)ret; // cast off const.
}
DOMNode * DOMParentNode::getFirstChild() const {
return fFirstChild;
}
DOMNode * DOMParentNode::getLastChild() const
{
return lastChild();
}
DOMNode * DOMParentNode::lastChild() const
{
// last child is stored as the previous sibling of first child
if (fFirstChild == 0) {
return 0;
}
DOMChildNode *firstChild = castToChildImpl(fFirstChild);
DOMNode *ret = firstChild->previousSibling;
return ret;
}
//
// revisit. Is this function used anywhere? I don't see it.
//
void DOMParentNode::lastChild(DOMNode *node) {
// store lastChild as previous sibling of first child
if (fFirstChild != 0) {
DOMChildNode *firstChild = castToChildImpl(fFirstChild);
firstChild->previousSibling = node;
}
}
bool DOMParentNode::hasChildNodes() const
{
return fFirstChild!=0;
}
DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) {
//not really in the specs, but better than nothing
if(newChild==NULL)
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
DOMNodeImpl *thisNodeImpl = castToNodeImpl(this);
if (thisNodeImpl->isReadOnly())
throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMParentNodeMemoryManager);
if (newChild->getOwnerDocument() != fOwnerDocument)
throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0, GetDOMParentNodeMemoryManager);
// Prevent cycles in the tree
//only need to do this if the node has children
if(newChild->hasChildNodes()) {
bool treeSafe=true;
for(DOMNode *a=castToNode(this)->getParentNode();
treeSafe && a!=0;
a=a->getParentNode())
treeSafe=(newChild!=a);
if(!treeSafe)
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
}
// refChild must in fact be a child of this node (or 0)
if (refChild!=0 && refChild->getParentNode() != castToNode(this))
throw DOMException(DOMException::NOT_FOUND_ERR,0, GetDOMParentNodeMemoryManager);
// if the new node has to be placed before itself, we don't have to do anything
// (even worse, we would crash if we continue, as we assume they are two distinct nodes)
if (refChild!=0 && newChild->isSameNode(refChild))
return newChild;
if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE)
{
// SLOW BUT SAFE: We could insert the whole subtree without
// juggling so many next/previous pointers. (Wipe out the
// parent's child-list, patch the parent pointers, set the
// ends of the list.) But we know some subclasses have special-
// case behavior they add to insertBefore(), so we don't risk it.
// This approch also takes fewer bytecodes.
// NOTE: If one of the children is not a legal child of this
// node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
// have been transferred. (Alternative behaviors would be to
// reparent up to the first failure point or reparent all those
// which are acceptable to the target node, neither of which is
// as robust. PR-DOM-0818 isn't entirely clear on which it
// recommends?????
// No need to check kids for right-document; if they weren't,
// they wouldn't be kids of that DocFrag.
for(DOMNode *kid=newChild->getFirstChild(); // Prescan
kid!=0;
kid=kid->getNextSibling())
{
if (!DOMDocumentImpl::isKidOK(castToNode(this), kid))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
}
while(newChild->hasChildNodes()) // Move
insertBefore(newChild->getFirstChild(),refChild);
}
else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild))
throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0, GetDOMParentNodeMemoryManager);
else
{
DOMNode *oldparent=newChild->getParentNode();
if(oldparent!=0)
oldparent->removeChild(newChild);
// Attach up
castToNodeImpl(newChild)->fOwnerNode = castToNode(this);
castToNodeImpl(newChild)->isOwned(true);
// Attach before and after
// Note: fFirstChild.previousSibling == lastChild!!
if (fFirstChild == 0) {
// this our first and only child
fFirstChild = newChild;
castToNodeImpl(newChild)->isFirstChild(true);
// castToChildImpl(newChild)->previousSibling = newChild;
DOMChildNode *newChild_ci = castToChildImpl(newChild);
newChild_ci->previousSibling = newChild;
} else {
if (refChild == 0) {
// this is an append
DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling;
castToChildImpl(lastChild)->nextSibling = newChild;
castToChildImpl(newChild)->previousSibling = lastChild;
castToChildImpl(fFirstChild)->previousSibling = newChild;
} else {
// this is an insert
if (refChild == fFirstChild) {
// at the head of the list
castToNodeImpl(fFirstChild)->isFirstChild(false);
castToChildImpl(newChild)->nextSibling = fFirstChild;
castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling;
castToChildImpl(fFirstChild)->previousSibling = newChild;
fFirstChild = newChild;
castToNodeImpl(newChild)->isFirstChild(true);
} else {
// somewhere in the middle
DOMNode *prev = castToChildImpl(refChild)->previousSibling;
castToChildImpl(newChild)->nextSibling = refChild;
castToChildImpl(prev)->nextSibling = newChild;
castToChildImpl(refChild)->previousSibling = newChild;
castToChildImpl(newChild)->previousSibling = prev;
}
}
}
}
changed();
if (this->getOwnerDocument() != 0) {
Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
if ( ranges != 0) {
XMLSize_t sz = ranges->size();
if (sz != 0) {
for (XMLSize_t i =0; i<sz; i++) {
ranges->elementAt(i)->updateRangeForInsertedNode(newChild);
}
}
}
}
return newChild;
}
DOMNode *DOMParentNode::removeChild(DOMNode *oldChild)
{
if (castToNodeImpl(this)->isReadOnly())
throw DOMException(
DOMException::NO_MODIFICATION_ALLOWED_ERR, 0, GetDOMParentNodeMemoryManager);
if (oldChild == 0 || oldChild->getParentNode() != castToNode(this))
throw DOMException(DOMException::NOT_FOUND_ERR, 0, GetDOMParentNodeMemoryManager);
if (this->getOwnerDocument() != 0 ) {
//notify iterators
NodeIterators* nodeIterators = ((DOMDocumentImpl *)this->getOwnerDocument())->getNodeIterators();
if (nodeIterators != 0) {
XMLSize_t sz = nodeIterators->size();
if (sz != 0) {
for (XMLSize_t i =0; i<sz; i++) {
if (nodeIterators->elementAt(i) != 0)
nodeIterators->elementAt(i)->removeNode(oldChild);
}
}
}
//fix other ranges for change before deleting the node
Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
if (ranges != 0) {
XMLSize_t sz = ranges->size();
if (sz != 0) {
for (XMLSize_t i =0; i<sz; i++) {
if (ranges->elementAt(i) != 0)
ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);
}
}
}
}
// Patch linked list around oldChild
// Note: lastChild == fFirstChild->previousSibling
if (oldChild == fFirstChild) {
// removing first child
castToNodeImpl(oldChild)->isFirstChild(false);
fFirstChild = castToChildImpl(oldChild)->nextSibling;
if (fFirstChild != 0) {
castToNodeImpl(fFirstChild)->isFirstChild(true);
castToChildImpl(fFirstChild)->previousSibling = castToChildImpl(oldChild)->previousSibling;
}
} else {
DOMNode *prev = castToChildImpl(oldChild)->previousSibling;
DOMNode *next = castToChildImpl(oldChild)->nextSibling;
castToChildImpl(prev)->nextSibling = next;
if (next == 0) {
// removing last child
castToChildImpl(fFirstChild)->previousSibling = prev;
} else {
// removing some other child in the middle
castToChildImpl(next)->previousSibling = prev;
}
}
// Remove oldChild's references to tree
castToNodeImpl(oldChild)->fOwnerNode = fOwnerDocument;
castToNodeImpl(oldChild)->isOwned(false);
castToChildImpl(oldChild)->nextSibling = 0;
castToChildImpl(oldChild)->previousSibling = 0;
changed();
return oldChild;
}
DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild)
{
insertBefore(newChild, oldChild);
// changed() already done.
return removeChild(oldChild);
}
//Introduced in DOM Level 2
void DOMParentNode::normalize()
{
DOMNode *kid, *next;
for (kid = fFirstChild; kid != 0; kid = next)
{
next = castToChildImpl(kid)->nextSibling;
// If kid and next are both Text nodes (but _not_ CDATASection,
// which is a subclass of Text), they can be merged.
if (next != 0 &&
kid->getNodeType() == DOMNode::TEXT_NODE &&
next->getNodeType() == DOMNode::TEXT_NODE )
{
((DOMTextImpl *) kid)->appendData(((DOMTextImpl *) next)->getData());
// revisit:
// should I release the removed node?
// not released in case user still referencing it externally
removeChild(next);
next = kid; // Don't advance; there might be another.
}
// Otherwise it might be an Element, which is handled recursively
else
if (kid->getNodeType() == DOMNode::ELEMENT_NODE)
kid->normalize();
}
// changed() will have occurred when the removeChild() was done,
// so does not have to be reissued.
}
//Introduced in DOM Level 3
bool DOMParentNode::isEqualNode(const DOMNode* arg) const
{
if (arg && castToNodeImpl(this)->isSameNode(arg))
return true;
if (arg && castToNodeImpl(this)->isEqualNode(arg))
{
DOMNode *kid, *argKid;
for (kid = fFirstChild, argKid = arg->getFirstChild();
kid != 0 && argKid != 0;
kid = kid->getNextSibling(), argKid = argKid->getNextSibling())
{
if (!kid->isEqualNode(argKid))
return false;
}
return (kid || argKid) ? false : true;
}
return false;
}
//Non-standard extension
void DOMParentNode::release()
{
DOMNode *kid, *next;
for (kid = fFirstChild; kid != 0; kid = next)
{
next = castToChildImpl(kid)->nextSibling;
// set is Owned false before releasing its child
castToNodeImpl(kid)->isToBeReleased(true);
kid->release();
}
}
XERCES_CPP_NAMESPACE_END
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
426
]
]
]
|
2afaa9bc77f9472b1423e41c50fed376278cf2b3 | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvimage/openexr/src/HalfTest/testArithmetic.cpp | 13d9443669099aef01b75f320e8020be0071443a | []
| 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 | 946 | cpp | #include <testArithmetic.h>
#include "half.h"
#include <iostream>
#include <assert.h>
using namespace std;
void
testArithmetic ()
{
cout << "basic arithmetic operations:\n";
float f1 (1);
float f2 (2);
half h1 (3);
half h2 (4);
cout << "f1 = " << f1 << ", "
"f2 = " << f2 << ", "
"h1 = " << h1 << ", "
"h2 = " << h2 << endl;
h1 = f1 + f2;
assert (h1 == 3);
cout << "h1 = f1 + f2: " << h1 << endl;
h2 += f1;
assert (h2 == 5);
cout << "h2 += f1: " << h2 << endl;
h2 = h1 + h2;
assert (h2 == 8);
cout << "h2 = h1 + h2: " << h2 << endl;
h2 += h1;
assert (h2 == 11);
cout << "h2 += h1: " << h2 << endl;
h1 = h2;
assert (h1 == 11);
cout << "h1 = h2: " << h1 << endl;
h2 = -h1;
assert (h2 == -11);
cout << "h2 = -h1: " << h2 << endl;
cout << "ok\n\n" << flush;
}
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
55
]
]
]
|
d5c9b8185d8ad2257efedda9e31924c5575462d4 | 2ec6a4926883ef3e970297aaeebba2134491b984 | /clclass.cpp | 2a62f1a6eb0dd05d7cd57ceccf891ac2615aa2f4 | []
| no_license | ambling/rtGPU | 272dc65b0a19e0b913306b21ddccc6bfe7f3f215 | 155612dc82aeec4ef4a5a58230261d914deac2e5 | refs/heads/master | 2020-12-25T18:23:24.880039 | 2011-05-23T11:05:43 | 2011-05-23T11:05:43 | 1,717,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,498 | cpp | #include <iostream>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <string.h>
#include "clclass.h"
//#include "global.c"
#include "util.h"
#include <math.h>
CL* rtGPU;
CL::CL()
{
//this function is defined in util.cpp
//it comes from the NVIDIA SDK example code
err = oclGetPlatformID(&platform);
if(err != CL_SUCCESS)
{
printf("oclGetPlatformID: %s\n", oclErrorString(err));
exit(-1);
}
cl_uint numDevices;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
if(err != CL_SUCCESS)
{
printf("clGetDeviceIDs (get number of devices): %s\n", oclErrorString(err));
exit(-1);
}
devices = new cl_device_id[numDevices];
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, devices, NULL);
if(err != CL_SUCCESS)
{
printf("clGetDeviceIDs (create device list): %s\n", oclErrorString(err));
exit(-1);
}
context = clCreateContext(0, 1, devices, NULL, NULL, &err);
if(err != CL_SUCCESS)
{
printf("clCreateContext : %s\n", oclErrorString(err));
exit(-1);
}
device_used = 0;
command_queue = clCreateCommandQueue(context, devices[device_used], 0, &err);
if(err != CL_SUCCESS)
{
printf("clCreateCommandQueue : %s\n", oclErrorString(err));
exit(-1);
}
rtGPU = this;
printf("OpenCL initialized successful.\n");
}
CL::~CL()
{
if(kernel) clReleaseKernel(kernel);
if(program) clReleaseProgram(program);
if(command_queue) clReleaseCommandQueue(command_queue);
//need to release any other OpenCL memory objects here
if(context) clReleaseContext(context);
if(devices) delete devices;
if(spheres) delete spheres;
if(vertices) delete vertices;
if(meshes) delete meshes;
if(materials) delete materials;
if(output) delete output;
if(pixels) delete pixels;
}
void CL::loadProgram()
{
sources = readKernelSources();
//printf("kernel: \n%s", sources);
//std::cout<<sources; //print the kernel source for debugging
program = clCreateProgramWithSource(context, 1, &sources, 0, &err);
if(err != CL_SUCCESS)
{
printf("clCreateProgramWithSource : %s\n", oclErrorString(err));
exit(-1);
}
err = clBuildProgram(program, 1, devices, "-I. ", NULL, NULL);
/* for debug
size_t len;
char *buffer;
clGetProgramBuildInfo(program, devices[device_used], CL_PROGRAM_BUILD_LOG, 0, NULL, &len);
buffer = (char *)malloc(len);
clGetProgramBuildInfo(program, devices[device_used], CL_PROGRAM_BUILD_LOG, len, buffer, NULL);
printf("%s\n", buffer);
//*/
if(err != CL_SUCCESS)
{
printf("clBuildProgram : %s\n", oclErrorString(err));
exit(-1);
}
kernel = clCreateKernel(program, "test", &err);
if(err != CL_SUCCESS)
{
printf("clCreateKernel : %s\n", oclErrorString(err));
exit(-1);
}
printf("OpenCL program loading successful.\n");
}
char* CL::readKernelSources()
{
FILE *file = fopen("kernel.cl", "r");
fseek(file, 0, SEEK_END);
long long int size = ftell(file);
rewind(file);
char *source = (char *) malloc(sizeof(char) * size + 1);
fread(source, 1, sizeof(char) * size, file);
source[size] = '\0';
//printf ("%s", source);
fclose(file);
return source;
/*
std::ifstream file;
std::string tmp, source;
file.open("kernel.cl");
while(! file.eof())
{
std::getline(file, tmp);
tmp += '\n';
source.append(tmp);
}
//std::cout<<"kernel source:"<<std::endl;
//std::cout<<source; //print the kernel source for debugging
return source.c_str();
*/
}
void CL::dataPrepare(int w, int h, std::string sceneFile)
{
imWidth = w;
imHeight = h;
cameraBuf = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(Camera), &camera, NULL); //created ahead for update
readScene(sceneFile); //default as simple.scn
printf("OpenCL scene reading successful.\n");
output = new Color[w*h];
for(int i = 0; i < w*h; i++)
{
output[i].x = 0;
output[i].y = 0;
output[i].z = 0;
}
pixels = new unsigned int[w * h];
//create buffer for kernel
outputBuf = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(Color) * imWidth * imHeight, NULL, NULL);
sphereBuf = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(Sphere) * sphereNum, spheres, NULL);
vertexBuf = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(Vertex) * vertexNum, vertices, NULL);
meshBuf = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(Mesh) * meshNum, meshes, NULL);
materialBuf = clCreateBuffer(context, CL_MEM_READ_ONLY, sizeof(Material) * materialNum, materials, NULL);
clEnqueueWriteBuffer(command_queue, outputBuf, CL_TRUE, 0, sizeof(Color)*w*h, (void*)output, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
if(sphereNum != 0)
{
clEnqueueWriteBuffer(command_queue, sphereBuf, CL_TRUE, 0, sizeof(Sphere) * sphereNum,
(void*)spheres, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
}
if(vertexNum != 0)
{
clEnqueueWriteBuffer(command_queue, vertexBuf, CL_TRUE, 0, sizeof(Vertex) * vertexNum,
(void*)vertices, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
}
if(meshNum != 0)
{
clEnqueueWriteBuffer(command_queue, meshBuf, CL_TRUE, 0, sizeof(Mesh) * meshNum,
(void*)meshes, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
}
if(materialNum != 0)
{
clEnqueueWriteBuffer(command_queue, materialBuf, CL_TRUE, 0, sizeof(Material) * materialNum,
(void*)materials, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
}
/*
__kernel void test(const int width, const int sphereNum, const int vertexNum,
const int materialNum, const int meshNum,
__constant Camera* camera,
__global Sphere* spheres,
__global Vertex* vertices,
__global Material* materials,
__global Mesh* meshes,
__global Color* output)
*/
clSetKernelArg(kernel, 0, sizeof(int), (void* )&imWidth);
clSetKernelArg(kernel, 1, sizeof(int), (void* )&sphereNum);
clSetKernelArg(kernel, 2, sizeof(int), (void* )&vertexNum);
clSetKernelArg(kernel, 3, sizeof(int), (void* )&materialNum);
clSetKernelArg(kernel, 4, sizeof(int), (void* )&meshNum);
clSetKernelArg(kernel, 5, sizeof(cl_mem), (void* )&cameraBuf);
clSetKernelArg(kernel, 6, sizeof(cl_mem), (void* )&sphereBuf);
clSetKernelArg(kernel, 7, sizeof(cl_mem), (void* )&vertexBuf);
clSetKernelArg(kernel, 8, sizeof(cl_mem), (void* )&materialBuf);
clSetKernelArg(kernel, 9, sizeof(cl_mem), (void* )&meshBuf);
clSetKernelArg(kernel, 10, sizeof(cl_mem), (void* )&outputBuf);
clFinish(command_queue);
printf("OpenCL data preparation successful.\n");
}
void CL::readScene(std::string sceneFile)
{//get information from scene file
//sceneFile = "simple.scn";
//sceneFile = "simplest.scn";
std::ifstream in;
in.open(sceneFile.c_str());
std::string tmp;
int sphereCnt = 0;
int vertexCnt = 0;
int meshCnt = 0;
int materialCnt = 0;
while(in>>tmp)
{
if(tmp == "camera")
{
in>>camera.orig.x>>camera.orig.y>>camera.orig.z
>>camera.targ.x>>camera.targ.y>>camera.targ.z;
updateCamera();
}
else if(tmp == "size")
{
in>>vertexNum>>meshNum>>sphereNum>>materialNum;
vertices = new Vertex[vertexNum];
meshes = new Mesh[meshNum];
spheres = new Sphere[sphereNum];
materials = new Material[materialNum];
}
else if(tmp == "sphere")
{
Sphere *p = &spheres[sphereCnt];
in>>(p->rad);
in>>(p->pos.x)>>(p->pos.y)>>(p->pos.z)
>>(p->emi.x)>>(p->emi.y)>>(p->emi.z)
>>(p->color.x)>>(p->color.y)>>(p->color.z);
in>>p->ref;
in>>p->outrfr>>p->inrfr;
if(p->emi.x != 0 || p->emi.y != 0 || p->emi.z != 0)
{
//vNorm(p->emi);
float max = p->emi.x;
if(p->emi.y > max) max = p->emi.y;
if(p->emi.z > max) max = p->emi.z;
vMul(p->emi, p->emi, 1.0/max);
}
//vPrint(p->emi);
sphereCnt ++;
}
else if(tmp == "vertex")
{
Vertex *v = &vertices[vertexCnt];
in>>v->x>>v->y>>v->z;
vertexCnt ++;
}
else if(tmp == "mesh")
{
Mesh *m = &meshes[meshCnt];
in>>m->a>>m->b>>m->c>>m->ma;
meshCnt ++;
}
else if(tmp == "material")
{
Material *p = &materials[materialCnt];
in>>(p->emi.x)>>(p->emi.y)>>(p->emi.z)
>>(p->color.x)>>(p->color.y)>>(p->color.z);
in>>p->ref;
in>>p->outrfr>>p->inrfr;
if(p->emi.x != 0 || p->emi.y != 0 || p->emi.z != 0)
{
//vNorm(p->emi);
float max = p->emi.x;
if(p->emi.y > max) max = p->emi.y;
if(p->emi.z > max) max = p->emi.z;
vMul(p->emi, p->emi, 1.0/max);
}
materialCnt ++;
}
}
}
void CL::updateCamera()
{
vSub(camera.dirc, camera.targ, camera.orig); //global function, camera direction
vNorm(camera.dirc);
vec3f up, distance;
float angle = 45;
vSub(distance, camera.targ, camera.orig);
float dis = sqrt(vDot(distance, distance));
float scale = tan(angle / 2.0) * dis * 2.0 / imWidth;
//printf("distance is %f, scale is %f", dis, scale);
up.x = 0.0; up.y = 1.0; up.z = 0.0;
//vInit(up, 7.16376, -6.19517, 6.23901);
vCross(camera.x, camera.dirc, up); //global function, x base direction
vNorm(camera.x);
vMul(camera.x, camera.x, scale);
vCross(camera.y, camera.x, camera.dirc); //global function, y base direction
vNorm(camera.y);
vMul(camera.y, camera.y, scale);
vec3f displace_x, displace_y; //displacement from the target to base
vMul(displace_x, camera.x, 1.0 * imWidth / 2);
vMul(displace_y, camera.y, 1.0 * imHeight / 2);
vSub(camera.base, camera.targ, displace_x);
vSub(camera.base, camera.base, displace_y); //base of the coordinate
/*for debug
vPrint(camera.orig);
vPrint(camera.targ);
vPrint(camera.dirc);
vPrint(camera.x);
vPrint(camera.y);
vPrint(camera.base);
vPrint(displace);
*/
//printf("OpenCL camera update successful.\n");
clEnqueueWriteBuffer(command_queue, cameraBuf, CL_TRUE, 0, sizeof(Camera), (void*)&camera, 0, NULL, &event);
clReleaseEvent(event);
clFinish(command_queue);
//printf("OpenCL camera buffer update successful.\n");
}
void CL::runKernel()
{
size_t size = imWidth * imHeight;
err = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &size, NULL, 0, NULL, &event);
if(err != CL_SUCCESS)
{
printf("clEnqueueNDRangeKernel : %s\n", oclErrorString(err));
clReleaseEvent(event);
exit(-1);
}
clReleaseEvent(event);
err = clFinish(command_queue);
if(err != CL_SUCCESS)
{
printf("clFinish : %s\n", oclErrorString(err));
exit(-1);
}
///*
err = clEnqueueReadBuffer(command_queue, outputBuf, CL_TRUE, 0, sizeof(Color) * size, output, 0, NULL, &event);
if(err != CL_SUCCESS)
{
printf("clEnqueueReadBuffer : %s\n", oclErrorString(err));
clReleaseEvent(event);
exit(-1);
}
clReleaseEvent(event);
clFinish(command_queue);
//printf("OpenCL kernel task is completed successful.\n");
///*
for(int index = 0; index < size; index ++)
{
pixels[index] = (int)(255*output[index].x) |
((int)(255*output[index].y) << 8) |
((int)(255*output[index].z) << 16);
}
//printf("OpenCL pixels buffer update successful.\n");
//*/
//*/
/*
for(int i = 0; i < size; i++)
{
std::cout<<"No.: "<<i<<std::endl;
std::cout<<output[i].x<<std::endl;
std::cout<<output[i].y<<std::endl;
std::cout<<output[i].z<<std::endl;
}
*/
/*for test
Camera c;
clEnqueueReadBuffer(command_queue, cameraBuf, CL_TRUE, 0, sizeof(Camera), &c, 0, NULL, &event);
clReleaseEvent(event);
printf("camera %f %f %f %f %f %f %f %f %f\n",
c.orig.x, c.orig.y, c.orig.z,
c.targ.x, c.targ.y, c.targ.z,
c.dirc.x, c.dirc.y, c.dirc.z);
//*/
}
void CL::putout()
{
FILE *file = fopen("output", "w");
fprintf(file, "%d %d\n", imWidth, imHeight);
for(int i = 0; i < imWidth * imHeight; i++)
{
fprintf(file, "%.2f %.2f %.2f\n", output[i].x, output[i].y, output[i].z);
}
fclose(file);
}
double elapseTimeGPU;
void ReInitGPU(const int reallocBuffers) {
/* no support of resize
// Check if I have to reallocate buffers
if (reallocBuffers) {
freeBuffer();
const int pixelCount = imWidth * imHeight ;
pixels = (unsigned int*)malloc(sizeof(unsigned int[pixelCount]));
output = new Color[size];
readScene();
}
*/
double startTime = WallClockTime();
rtGPU->updateCamera();
rtGPU->runKernel();
elapseTimeGPU = WallClockTime() - startTime;
}
void idleFuncGPU(void) {
//rtGPU->runKernel();
glutPostRedisplay();
}
void displayFuncGPU(void) {
glClear(GL_COLOR_BUFFER_BIT);
glRasterPos2i(0, 0);
glDrawPixels(rtGPU->imWidth, rtGPU->imHeight, GL_RGBA, GL_UNSIGNED_BYTE, rtGPU->pixels);
//show the fps
double fps = 1.0 / elapseTimeGPU;
char *fpsStr = new char[15];
sprintf(fpsStr, "fps: %.4f", fps);
glColor3f(1.f, 1.f, 1.f);
glRasterPos2i(4, 10);
for (int i = 0; i < (int)strlen(fpsStr); i++)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, fpsStr[i]);
glutSwapBuffers();
}
void reshapeFuncGPU(int newWidth, int newHeight) {
rtGPU->imWidth = newWidth;
rtGPU->imHeight = newHeight;
glViewport(0, 0, newWidth, newHeight);
glLoadIdentity();
glOrtho(0.f, newWidth - 1.f, 0.f, newHeight - 1.f, -1.f, 1.f);
ReInitGPU(1);
glutPostRedisplay();
}
#define MOVE_STEP 10.0
#define ROTATE_STEP (10.0 * 3.1415926 / 180.0)
void keyFuncGPU(unsigned char key, int x, int y) {
switch (key) {
case 27: /* Escape key */
exit(0);
break;
case 'q': /* quit */
exit(0);
break;
case 'w': /* closer */
{
vec3f t = rtGPU->camera.dirc;
vMul(t, t, MOVE_STEP);
vAdd(rtGPU->camera.orig, rtGPU->camera.orig, t);
ReInitGPU(0);
break;
}
case 's': /* farther */
{
vec3f t = rtGPU->camera.dirc;
vMul(t, t, MOVE_STEP);
vSub(rtGPU->camera.orig, rtGPU->camera.orig, t);
ReInitGPU(0);
break;
}
case 'a': /* move left */
{
vec3f t = rtGPU->camera.x;
vMul(t, t, MOVE_STEP);
vAdd(rtGPU->camera.orig, rtGPU->camera.orig, t);
ReInitGPU(0);
break;
}
case 'd': /* move right */
{
vec3f t = rtGPU->camera.x;
vMul(t, t, MOVE_STEP);
vSub(rtGPU->camera.orig, rtGPU->camera.orig, t);
ReInitGPU(0);
break;
}
default:
break;
}
}
void specialFuncGPU(int key, int x, int y) {
switch (key) {
case GLUT_KEY_DOWN: {
vec3f t = rtGPU->camera.targ;
vSub(t, t, rtGPU->camera.orig);
t.y = t.y * cos(-ROTATE_STEP) + t.z * sin(-ROTATE_STEP);
t.z = -t.y * sin(-ROTATE_STEP) + t.z * cos(-ROTATE_STEP);
vSub(t, rtGPU->camera.targ, t);
rtGPU->camera.orig = t;
ReInitGPU(0);
break;
}
case GLUT_KEY_UP: {
vec3f t = rtGPU->camera.targ;
vSub(t, t, rtGPU->camera.orig);
t.y = t.y * cos(ROTATE_STEP) + t.z * sin(ROTATE_STEP);
t.z = -t.y * sin(ROTATE_STEP) + t.z * cos(ROTATE_STEP);
vSub(t, rtGPU->camera.targ, t);
rtGPU->camera.orig = t;
ReInitGPU(0);
break;
}
case GLUT_KEY_RIGHT: {
vec3f t = rtGPU->camera.targ;
vSub(t, t, rtGPU->camera.orig);
t.x = t.x * cos(-ROTATE_STEP) - t.z * sin(-ROTATE_STEP);
t.z = t.x * sin(-ROTATE_STEP) + t.z * cos(-ROTATE_STEP);
vSub(t, rtGPU->camera.targ, t);
rtGPU->camera.orig = t;
ReInitGPU(0);
break;
}
case GLUT_KEY_LEFT: {
vec3f t = rtGPU->camera.targ;
vSub(t, t, rtGPU->camera.orig);
t.x = t.x * cos(ROTATE_STEP) - t.z * sin(ROTATE_STEP);
t.z = t.x * sin(ROTATE_STEP) + t.z * cos(ROTATE_STEP);
vSub(t, rtGPU->camera.targ, t);
rtGPU->camera.orig = t;
ReInitGPU(0);
break;
}
case GLUT_KEY_PAGE_UP:
rtGPU->camera.targ.y += MOVE_STEP;
ReInitGPU(0);
break;
case GLUT_KEY_PAGE_DOWN:
rtGPU->camera.targ.y -= MOVE_STEP;
ReInitGPU(0);
break;
default:
break;
}
}
void CL::initGlut(int argc, char **argv, std::string windowTittle)
{
glutInitWindowSize(imWidth, imHeight);
glutInitWindowPosition(0,0);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInit(&argc, argv);
glutCreateWindow(windowTittle.c_str());
glutReshapeFunc(reshapeFuncGPU);
glutKeyboardFunc(keyFuncGPU);
glutSpecialFunc(specialFuncGPU);
glutDisplayFunc(displayFuncGPU);
glutIdleFunc(idleFuncGPU);
glViewport(0, 0, imWidth, imHeight);
glLoadIdentity();
glOrtho(0.f, imWidth - 1.f, 0.f, imHeight - 1.f, -1.f, 1.f);
}
| [
"[email protected]"
]
| [
[
[
1,
613
]
]
]
|
858927bf4610b2e501f4e12ed12c5a4e76d4abd8 | d425cf21f2066a0cce2d6e804bf3efbf6dd00c00 | /TileEngine/Explosion Control.cpp | b78fe6226b3ca6d93e0f41cc136515af4d534110 | []
| no_license | infernuslord/ja2 | d5ac783931044e9b9311fc61629eb671f376d064 | 91f88d470e48e60ebfdb584c23cc9814f620ccee | refs/heads/master | 2021-01-02T23:07:58.941216 | 2011-10-18T09:22:53 | 2011-10-18T09:22:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 139,805 | cpp | #include "builddefines.h"
#ifdef PRECOMPILEDHEADERS
#include "TileEngine All.h"
#include "end game.h"
#include "Morale.h"
#else
#include <stdio.h>
#include <string.h>
#include "wcheck.h"
#include "stdlib.h"
#include "debug.h"
//#include "soldier control.h"
#include "weapons.h"
#include "handle items.h"
#include "worlddef.h"
#include "worldman.h"
#include "rotting corpses.h"
#include "tile cache.h"
#include "isometric utils.h"
#include "animation control.h"
#include "utilities.h"
#include "game clock.h"
#include "soldier create.h"
#include "renderworld.h"
#include "soldier add.h"
#include "explosion control.h"
#include "tile animation.h"
#include "sound control.h"
#include "weapons.h"
#include "handle items.h"
#include "world items.h"
#include "structure wrap.h"
#include "tiledef.h"
#include "tiledat.h"
#include "interactive tiles.h"
#include "SaveLoadMap.h"
#include "Handle Doors.h"
#include "Message.h"
#include "Random.h"
#include "smokeeffects.h"
#include "handle ui.h"
#include "pathai.h"
#include "pits.h"
#include "campaign Types.h"
#include "strategicmap.h"
#include "strategic.h"
#include "Action Items.h"
#include "Soldier Profile.h"
#include "Quests.h"
#include "Interface Dialogue.h"
#include "LightEffects.h"
#include "AI.h"
#include "Soldier tile.h"
#include "lighting.h"
#include "Render Fun.h"
#include "Opplist.h"
#include "smell.h"
#include "GameSettings.h"
#include "Interface.h"
#include "end game.h"
#include "WorldDat.h"
#include "environment.h"
#include "Buildings.h"
#include "Keys.h"
#include "Morale.h"
#include "fov.h"
#include "Map Information.h"
#include "Soldier Functions.h"//dnl ch40 200909
#include "Text.h" // added by SANDRO
#include "campaign.h" // yet another one added
#endif
#include "Soldier Macros.h"
#include "connect.h"
#include "debug control.h"
#include "LuaInitNPCs.h"
#ifdef JA2UB
#include "interface Dialogue.h"
#include "Ja25_Tactical.h"
#include "Ja25 Strategic Ai.h"
#include "Dialogue Control.h"
#include "legion cfg.h"
#endif
//forward declarations of common classes to eliminate includes
class OBJECTTYPE;
class SOLDIERTYPE;
BOOLEAN HookerInRoom( UINT8 ubRoom );
// MODULE FOR EXPLOSIONS
// Spreads the effects of explosions...
BOOLEAN ExpAffect( INT32 sBombGridNo, INT32 sGridNo, UINT32 uiDist, UINT16 usItem, UINT8 ubOwner, INT16 sSubsequent, BOOLEAN *pfMercHit, INT8 bLevel, INT32 iSmokeEffectID );
// Flashbang effect on soldier
UINT8 DetermineFlashbangEffect( SOLDIERTYPE *pSoldier, INT8 ubExplosionDir, BOOLEAN fInBuilding);
extern INT8 gbSAMGraphicList[ MAX_NUMBER_OF_SAMS ];
extern void AddToShouldBecomeHostileOrSayQuoteList( UINT8 ubID );
extern void RecompileLocalMovementCostsForWall( INT32 sGridNo, UINT8 ubOrientation );
void FatigueCharacter( SOLDIERTYPE *pSoldier );
#ifdef JA2UB
void HandleSeeingFortifiedDoor( UINT32 sGridNo );//Ja25 UB
#endif
#define NO_ALT_SOUND -1
EXPLOSION_DATA gExpAniData[ NUM_EXP_TYPES ] =
{
// Trans Damage Explosion Alternative Explosion Animation
// Key Key Sound Explosion Animation Speed
// Frame Frame ID SoundID Filename
{0, 0, EXPLOSION_1, EXPLOSION_ALT_BLAST_1, "", 0},
{17, 3, EXPLOSION_1, EXPLOSION_ALT_BLAST_1, "TILECACHE\\ZGRAV_D.STI", 80},
{28, 5, EXPLOSION_BLAST_2, NO_ALT_SOUND, "TILECACHE\\ZGRAV_C.STI", 80},
{24, 5, EXPLOSION_BLAST_2, NO_ALT_SOUND, "TILECACHE\\ZGRAV_B.STI", 80},
{1, 5, EXPLOSION_1, EXPLOSION_ALT_BLAST_1, "TILECACHE\\shckwave.STI", 20},
{1, 18, AIR_ESCAPING_1, NO_ALT_SOUND, "TILECACHE\\WAT_EXP.STI", 80},
{1, 18, AIR_ESCAPING_1, NO_ALT_SOUND, "TILECACHE\\TEAR_EXP.STI", 80},
{1, 18, AIR_ESCAPING_1, NO_ALT_SOUND, "TILECACHE\\TEAR_EXP.STI", 80},
{1, 18, AIR_ESCAPING_1, NO_ALT_SOUND, "TILECACHE\\MUST_EXP.STI", 80}
};
//UINT8 ubTransKeyFrame[ NUM_EXP_TYPES ] =
//{
// 0,
// 17,
// 28,
// 24,
// 1,
// 1,
// 1,
// 1,
// 1,
//};
//
//UINT8 ubDamageKeyFrame[ NUM_EXP_TYPES ] =
//{
// 0,
// 3,
// 5,
// 5,
// 5,
// 18,
// 18,
// 18,
// 18,
//};
//
//
//UINT32 uiExplosionSoundID[ NUM_EXP_TYPES ] =
//{
// EXPLOSION_1,
// EXPLOSION_1,
// EXPLOSION_BLAST_2, //LARGE
// EXPLOSION_BLAST_2,
// EXPLOSION_1,
// AIR_ESCAPING_1,
// AIR_ESCAPING_1,
// AIR_ESCAPING_1,
// AIR_ESCAPING_1,
//};
//
//
//CHAR8 zBlastFilenames[][70] =
//{
// "",
// "TILECACHE\\ZGRAV_D.STI",
// "TILECACHE\\ZGRAV_C.STI",
// "TILECACHE\\ZGRAV_B.STI",
// "TILECACHE\\shckwave.STI",
// "TILECACHE\\WAT_EXP.STI",
// "TILECACHE\\TEAR_EXP.STI",
// "TILECACHE\\TEAR_EXP.STI",
// "TILECACHE\\MUST_EXP.STI",
//};
//
//CHAR8 sBlastSpeeds[] =
//{
// 0,
// 80,
// 80,
// 80,
// 20,
// 80,
// 80,
// 80,
// 80,
//};
#define BOMB_QUEUE_DELAY (1000 + Random( 500 ) )
#define MAX_BOMB_QUEUE 40
ExplosionQueueElement gExplosionQueue[MAX_BOMB_QUEUE];
UINT8 gubElementsOnExplosionQueue = 0;
BOOLEAN gfExplosionQueueActive = FALSE;
BOOLEAN gfExplosionQueueMayHaveChangedSight = FALSE;
UINT8 gubPersonToSetOffExplosions = NOBODY;
INT32 gsTempActionGridNo = NOWHERE;
extern UINT8 gubInterruptProvoker;
#define NUM_EXPLOSION_SLOTS 100
// GLOBAL FOR SMOKE LISTING
EXPLOSIONTYPE gExplosionData[ NUM_EXPLOSION_SLOTS ];
UINT32 guiNumExplosions = 0;
INT32 GetFreeExplosion( void );
void RecountExplosions( void );
void GenerateExplosionFromExplosionPointer( EXPLOSIONTYPE *pExplosion );
void HandleBuldingDestruction( INT32 sGridNo, UINT8 ubOwner );
#ifdef JA2UB
//JA25 UB
void HavePersonAtGridnoStop( UINT32 sGridNo );
BOOLEAN ShouldThePlayerStopWhenWalkingOnBiggensActionItem( UINT8 ubRecordNum );
void HandleDestructionOfPowerGenFan();
BOOLEAN IsFanGraphicInSectorAtThisGridNo( UINT32 sGridNo );
void HandleExplosionsInTunnelSector( UINT32 sGridNo );
void HandleSwitchToOpenFortifiedDoor( UINT32 sGridNo );
void HandleSeeingPowerGenFan( UINT32 sGridNo );
#endif
INT32 GetFreeExplosion( void )
{
UINT32 uiCount;
for(uiCount=0; uiCount < guiNumExplosions; uiCount++)
{
if(( gExplosionData[uiCount].fAllocated==FALSE ) )
return( (INT32)uiCount );
}
if( guiNumExplosions < NUM_EXPLOSION_SLOTS )
return( (INT32) guiNumExplosions++ );
return( -1 );
}
void RecountExplosions( void )
{
INT32 uiCount;
for(uiCount=guiNumExplosions-1; (uiCount >=0) ; uiCount--)
{
if( ( gExplosionData[uiCount].fAllocated ) )
{
guiNumExplosions=(UINT32)(uiCount+1);
break;
}
}
}
// GENERATE EXPLOSION
void InternalIgniteExplosion( UINT8 ubOwner, INT16 sX, INT16 sY, INT16 sZ, INT32 sGridNo, UINT16 usItem, BOOLEAN fLocate, INT8 bLevel )
{
#ifdef JA2BETAVERSION
if (is_networked) {
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"InternalIgniteExplosion ( ubOwner : %i , sX : %i , sY : %i , sZ : %i , sGridNo : %i , usItem : %i , fLocate : %i , bLevel : %i )\n",ubOwner, sX , sY , sZ , sGridNo , usItem , (int)fLocate , bLevel );
MPDebugMsg(tmpMPDbgString);
}
#endif
EXPLOSION_PARAMS ExpParams ;
// Callahan start
// Double check that we are using an explosive!
// Check if there is an explosive or an attacker
if ( !( Item[ usItem ].usItemClass & IC_EXPLOSV ) && ubOwner == NOBODY )
{
return; // no explosive / no attacker
}
// Okay, we either got an explosive or a real attacker to check for.
// Let's check for the attacker first.
if ( ubOwner != NOBODY )
{
if ( !( Item[ usItem ].usItemClass & IC_EXPLOSV ) && AmmoTypes[MercPtrs[ubOwner]->inv[MercPtrs[ubOwner]->ubAttackingHand ][0]->data.gun.ubGunAmmoType].explosionSize < 2 )
{
return; // no explosive and attackers gun is not fireing HE
}
}
// Increment attack counter...
if (gubElementsOnExplosionQueue == 0)
{
// single explosion, disable sight until the end, and set flag
// to check sight at end of attack
gTacticalStatus.uiFlags |= (DISALLOW_SIGHT | CHECK_SIGHT_AT_END_OF_ATTACK);
}
// gTacticalStatus.ubAttackBusyCount++;
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Incrementing Attack: Explosion gone off, COunt now %d", gTacticalStatus.ubAttackBusyCount ) );
// OK, go on!
ExpParams.uiFlags = EXPLOSION_FLAG_USEABSPOS;
ExpParams.ubOwner = ubOwner;
// No explosive but an attacker with HE ammo.
if ( !( Item[ usItem ].usItemClass & IC_EXPLOSV ) && ubOwner != NOBODY)
{
ExpParams.ubTypeID = (INT8)Explosive[AmmoTypes[MercPtrs[ubOwner]->inv[MercPtrs[ubOwner]->ubAttackingHand ][0]->data.gun.ubGunAmmoType].highExplosive].ubAnimationID;
// return;
}
else // just normal explosives should get here
{
ExpParams.ubTypeID = (INT8)Explosive[ Item[ usItem ].ubClassIndex ].ubAnimationID;
}
// Callahan end
ExpParams.sX = sX;
ExpParams.sY = sY;
ExpParams.sZ = sZ;
ExpParams.sGridNo = sGridNo;
ExpParams.usItem = usItem;
ExpParams.fLocate = fLocate;
ExpParams.bLevel = bLevel;
GenerateExplosion( &ExpParams );
}
void IgniteExplosion( UINT8 ubOwner, INT16 sX, INT16 sY, INT16 sZ, INT32 sGridNo, UINT16 usItem, INT8 bLevel )
{
InternalIgniteExplosion( ubOwner, sX, sY, sZ, sGridNo, usItem, TRUE, bLevel );
}
void GenerateExplosion( EXPLOSION_PARAMS *pExpParams )
{
EXPLOSIONTYPE *pExplosion;
UINT32 uiFlags;
UINT8 ubOwner;
UINT8 ubTypeID;
INT16 sX;
INT16 sY;
INT16 sZ;
INT32 sGridNo;
UINT16 usItem;
INT32 iIndex;
INT8 bLevel;
// Assign param values
uiFlags = pExpParams->uiFlags;
ubOwner = pExpParams->ubOwner;
ubTypeID = pExpParams->ubTypeID;
sX = pExpParams->sX;
sY = pExpParams->sY;
sZ = pExpParams->sZ;
sGridNo = pExpParams->sGridNo;
usItem = pExpParams->usItem;
bLevel = pExpParams->bLevel;
{
// GET AND SETUP EXPLOSION INFO IN TABLE....
iIndex = GetFreeExplosion( );
if ( iIndex == -1 )
{
return;
}
// OK, get pointer...
pExplosion = &( gExplosionData[ iIndex ] );
memset( pExplosion, 0, sizeof( EXPLOSIONTYPE ) );
// Setup some data...
memcpy( &(pExplosion->Params), pExpParams, sizeof( EXPLOSION_PARAMS ) );
pExplosion->fAllocated = TRUE;
pExplosion->iID = iIndex;
GenerateExplosionFromExplosionPointer( pExplosion );
}
// ATE: Locate to explosion....
if ( pExpParams->fLocate )
{
LocateGridNo( sGridNo );
}
}
void GenerateExplosionFromExplosionPointer( EXPLOSIONTYPE *pExplosion )
{
UINT32 uiFlags;
UINT8 ubOwner;
UINT8 ubTypeID;
INT16 sX;
INT16 sY;
INT16 sZ;
INT32 sGridNo;
UINT16 usItem;
UINT8 ubTerrainType;
INT8 bLevel;
UINT32 uiSoundID;
ANITILE_PARAMS AniParams;
// Assign param values
uiFlags = pExplosion->Params.uiFlags;
ubOwner = pExplosion->Params.ubOwner;
ubTypeID = pExplosion->Params.ubTypeID;
sX = pExplosion->Params.sX;
sY = pExplosion->Params.sY;
sZ = pExplosion->Params.sZ;
sGridNo = pExplosion->Params.sGridNo;
usItem = pExplosion->Params.usItem;
bLevel = pExplosion->Params.bLevel;
// If Z value given is 0 and bLevel > 0, make z heigher
if ( sZ == 0 && bLevel > 0 )
{
sZ = ROOF_LEVEL_HEIGHT;
}
pExplosion->iLightID = -1;
// OK, if we are over water.... use water explosion...
ubTerrainType = GetTerrainType( sGridNo );
// Setup explosion!
memset( &AniParams, 0, sizeof( ANITILE_PARAMS ) );
AniParams.sGridNo = sGridNo;
AniParams.ubLevelID = ANI_TOPMOST_LEVEL;
AniParams.sDelay = gExpAniData[ ubTypeID ].sBlastSpeed; // Lesh: edit this line
AniParams.sStartFrame = pExplosion->sCurrentFrame;
AniParams.uiFlags = ANITILE_CACHEDTILE | ANITILE_FORWARD | ANITILE_EXPLOSION;
if ( TERRAIN_IS_WATER(ubTerrainType) )
{
// Change type to water explosion...
ubTypeID = WATER_BLAST;
AniParams.uiFlags |= ANITILE_ALWAYS_TRANSLUCENT;
}
if ( sZ < WALL_HEIGHT )
{
AniParams.uiFlags |= ANITILE_NOZBLITTER;
}
if ( uiFlags & EXPLOSION_FLAG_USEABSPOS )
{
AniParams.sX = sX;
AniParams.sY = sY;
AniParams.sZ = sZ;
//AniParams.uiFlags |= ANITILE_USEABSOLUTEPOS;
}
AniParams.ubKeyFrame1 = gExpAniData[ ubTypeID ].ubTransKeyFrame; // Lesh: edit this line
AniParams.uiKeyFrame1Code = ANI_KEYFRAME_BEGIN_TRANSLUCENCY;
if ( !( uiFlags & EXPLOSION_FLAG_DISPLAYONLY ) )
{
AniParams.ubKeyFrame2 = gExpAniData[ ubTypeID ].ubDamageKeyFrame; // Lesh: edit this line
AniParams.uiKeyFrame2Code = ANI_KEYFRAME_BEGIN_DAMAGE;
}
AniParams.uiUserData = usItem;
AniParams.ubUserData2 = ubOwner;
AniParams.uiUserData3 = pExplosion->iID;
strcpy( AniParams.zCachedFile, gExpAniData[ ubTypeID ].zBlastFilename ); // Lesh: edit this line
// A little safety here, for just in case. If it fails to create an explosion tile, don't increase the attack busy count.
// But if it succeeds, do it here. Don't futz with the count in other locations when it can be centralized!
if (CreateAnimationTile( &AniParams ) )
{
gTacticalStatus.ubAttackBusyCount++;
DebugAttackBusy( String( "Explosion started. Incrementing attack busy, now %d\n", gTacticalStatus.ubAttackBusyCount ) );
}
// set light source for flashbangs.... or...
if ( pExplosion->Params.ubTypeID == FLASHBANG_EXP )
{
pExplosion->iLightID = LightSpriteCreate("FLSHBANG.LHT", 0 );
}
else
// generic light
// DO ONLY IF WE'RE AT A GOOD LEVEL
if ( ubAmbientLightLevel >= MIN_AMB_LEVEL_FOR_MERC_LIGHTS )
{
pExplosion->iLightID = LightSpriteCreate("L-R04.LHT", 0 );
}
if( pExplosion->iLightID != -1 )
{
LightSpritePower ( pExplosion->iLightID, TRUE );
LightSpriteRoofStatus( pExplosion->iLightID, pExplosion->Params.bLevel );
LightSpritePosition ( pExplosion->iLightID, (INT16)(sX/CELL_X_SIZE), (INT16)(sY/CELL_Y_SIZE) );
}
// Lesh: sound randomization
uiSoundID = gExpAniData[ ubTypeID ].uiExplosionSoundID;
if ( gExpAniData[ ubTypeID ].uiAltExplosionSoundID != NO_ALT_SOUND )
{
// Randomize
if ( Random( 2 ) == 0 )
{
uiSoundID = gExpAniData[ ubTypeID ].uiAltExplosionSoundID;
}
}
// Lesh: sound randomization ends
PlayJA2Sample( uiSoundID, RATE_11025, SoundVolume( HIGHVOLUME, sGridNo ), 1, SoundDir( sGridNo ) );
}
void UpdateExplosionFrame( INT32 iIndex, INT16 sCurrentFrame )
{
gExplosionData[ iIndex ].sCurrentFrame = sCurrentFrame;
// Lesh: make sparkling effect
if ( gExplosionData[iIndex].Params.ubTypeID == FLASHBANG_EXP )
{
if ( gExplosionData[iIndex].iLightID != -1 )
{
INT16 iX, iY;
iX = (INT16) (gExplosionData[iIndex].Params.sX/CELL_X_SIZE + Random(3) - 1);
iY = (INT16) (gExplosionData[iIndex].Params.sY/CELL_Y_SIZE + Random(3) - 1);
LightSpritePosition( gExplosionData[iIndex].iLightID, iX, iY);
}
}
}
void RemoveExplosionData( INT32 iIndex )
{
gExplosionData[ iIndex ].fAllocated = FALSE;
if ( gExplosionData[ iIndex ].iLightID != -1 )
{
LightSpriteDestroy( gExplosionData[ iIndex ].iLightID );
}
}
void HandleFencePartnerCheck( INT32 sStructGridNo )
{
STRUCTURE *pFenceStructure, *pFenceBaseStructure;
LEVELNODE *pFenceNode;
INT8 bFenceDestructionPartner = -1;
UINT32 uiFenceType;
UINT16 usTileIndex;
pFenceStructure = FindStructure( sStructGridNo, STRUCTURE_FENCE );
if ( pFenceStructure )
{
// How does our explosion partner look?
if ( pFenceStructure->pDBStructureRef->pDBStructure->bDestructionPartner < 0 )
{
// Find level node.....
pFenceBaseStructure = FindBaseStructure( pFenceStructure );
// Get LEVELNODE for struct and remove!
pFenceNode = FindLevelNodeBasedOnStructure( pFenceBaseStructure->sGridNo, pFenceBaseStructure );
// Get type from index...
GetTileType( pFenceNode->usIndex, &uiFenceType );
bFenceDestructionPartner = -1 * ( pFenceBaseStructure->pDBStructureRef->pDBStructure->bDestructionPartner );
// Get new index
GetTileIndexFromTypeSubIndex( uiFenceType, (INT8)( bFenceDestructionPartner ), &usTileIndex );
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
// Remove it!
RemoveStructFromLevelNode( pFenceBaseStructure->sGridNo, pFenceNode );
// Add it!
AddStructToHead( pFenceBaseStructure->sGridNo, (UINT16)( usTileIndex ) );
ApplyMapChangesToMapTempFile( FALSE );
}
}
}
BOOLEAN ExplosiveDamageStructureAtGridNo( STRUCTURE * pCurrent, STRUCTURE **ppNextCurrent, INT32 sGridNo, INT16 sWoundAmt, UINT32 uiDist, BOOLEAN *pfRecompileMovementCosts, BOOLEAN fOnlyWalls, BOOLEAN fSubSequentMultiTilesTransitionDamage, UINT8 ubOwner, INT8 bLevel )
{
#ifdef JA2BETAVERSION
if (is_networked) {
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"ExplosiveDamageStructureAtGridNo ( sGridNo : %i , sWoundAmt : %i , uiDist : %i , fRecompMoveCosts : %i , fOnlyWalls : %i , SubsMulTilTransDmg : %i , ubOwner : %i , bLevel : %i )\n",sGridNo, sWoundAmt , (int)*pfRecompileMovementCosts , (int)fOnlyWalls , (int)fSubSequentMultiTilesTransitionDamage , ubOwner , bLevel );
MPDebugMsg(tmpMPDbgString);
}
#endif
INT16 sX, sY;
STRUCTURE *pBase, *pWallStruct, *pAttached, *pAttachedBase;
LEVELNODE *pNode = NULL, *pNewNode = NULL, *pAttachedNode;
INT32 sNewGridNo, sStructGridNo;
INT16 sNewIndex, sSubIndex;
UINT16 usObjectIndex, usTileIndex;
UINT8 ubNumberOfTiles, ubLoop;
DB_STRUCTURE_TILE ** ppTile;
INT8 bDestructionPartner=-1;
INT8 bDamageReturnVal;
BOOLEAN fContinue;
UINT32 uiTileType;
INT32 sBaseGridNo;
BOOLEAN fExplosive;
// ATE: Check for O3 statue for special damage..
// note we do this check every time explosion goes off in game, but it's
// an effiecnent check...
if ( DoesO3SectorStatueExistHere( sGridNo ) && uiDist <= 1 )
{
ChangeO3SectorStatue( TRUE );
return( TRUE );
}
#ifdef JA2UB
//JA25 UB
//should we replace the mine entrance graphic
if( IsMineEntranceInSectorI13AtThisGridNo( sGridNo ) && ubOwner == NOBODY )
{
//Yup, replace it
ReplaceMineEntranceGraphicWithCollapsedEntrance();
}
//ja25 ub
//Handle Explosions in the tunnel sectors
HandleExplosionsInTunnelSector( sGridNo );
#endif
// Get xy
sX = CenterX( sGridNo );
sY = CenterY( sGridNo );
// ATE: Continue if we are only looking for walls
if ( fOnlyWalls && !( pCurrent->fFlags & STRUCTURE_WALLSTUFF ) )
{
return( TRUE );
}
if ( bLevel > 0 )
{
return( TRUE );
}
// Is this a corpse?
if ( ( pCurrent->fFlags & STRUCTURE_CORPSE ) && gGameSettings.fOptions[ TOPTION_BLOOD_N_GORE ] && sWoundAmt > 10 )
{
// Spray corpse in a fine mist....
if ( uiDist <= 1 )
{
// Remove corpse...
VaporizeCorpse( sGridNo, pCurrent->usStructureID );
}
}
else if ( !( pCurrent->fFlags & STRUCTURE_PERSON ) )
{
// Damage structure!
if ( ( bDamageReturnVal = DamageStructure( pCurrent, (UINT8)sWoundAmt, STRUCTURE_DAMAGE_EXPLOSION, sGridNo, sX, sY, NOBODY ) ) != 0 )
{
fContinue = FALSE;
#ifdef JA2UB
//Ja25 ub
//are we exploding the Fan in the power gen facility
if( IsFanGraphicInSectorAtThisGridNo( sGridNo ) )
{
HandleDestructionOfPowerGenFan();
}
#endif
pBase = FindBaseStructure( pCurrent );
sBaseGridNo = pBase->sGridNo;
// if the structure is openable, destroy all items there
if ( pBase->fFlags & STRUCTURE_OPENABLE && !(pBase->fFlags & STRUCTURE_DOOR ) )
{
RemoveAllUnburiedItems( pBase->sGridNo, bLevel );
}
fExplosive = ( ( pCurrent->fFlags & STRUCTURE_EXPLOSIVE ) != 0 );
// Get LEVELNODE for struct and remove!
pNode = FindLevelNodeBasedOnStructure( pBase->sGridNo, pBase );
// ATE: if we have completely destroyed a structure,
// and this structure should have a in-between explosion partner,
// make damage code 2 - which means only damaged - the normal explosion
// spreading will cause it do use the proper peices..
if ( bDamageReturnVal == 1 && pBase->pDBStructureRef->pDBStructure->bDestructionPartner < 0 )
{
bDamageReturnVal = 2;
}
if ( bDamageReturnVal == 1 )
{
fContinue = TRUE;
}
// Check for a damaged looking graphic...
else if ( bDamageReturnVal == 2 )
{
if ( pBase->pDBStructureRef->pDBStructure->bDestructionPartner < 0 )
{
// We swap to another graphic!
// It's -ve and 1-based, change to +ve, 1 based
bDestructionPartner = ( -1 * pBase->pDBStructureRef->pDBStructure->bDestructionPartner );
GetTileType( pNode->usIndex, &uiTileType );
fContinue = 2;
}
}
if ( fContinue )
{
// Remove the beast!
while ( (*ppNextCurrent) != NULL && (*ppNextCurrent)->usStructureID == pCurrent->usStructureID )
{
// the next structure will also be deleted so we had better
// skip past it!
(*ppNextCurrent) = (*ppNextCurrent)->pNext;
}
// Replace with explosion debris if there are any....
// ( and there already sin;t explosion debris there.... )
if ( pBase->pDBStructureRef->pDBStructure->bDestructionPartner > 0 )
{
// Alrighty add!
// Add to every gridno structure is in
ubNumberOfTiles = pBase->pDBStructureRef->pDBStructure->ubNumberOfTiles;
ppTile = pBase->pDBStructureRef->ppTile;
bDestructionPartner = pBase->pDBStructureRef->pDBStructure->bDestructionPartner;
// OK, destrcution index is , as default, the partner, until we go over the first set of explsion
// debris...
if ( bDestructionPartner > 39 )
{
GetTileIndexFromTypeSubIndex( SECONDEXPLDEBRIS, (INT8)( bDestructionPartner - 40 ), &usTileIndex );
}
else
{
GetTileIndexFromTypeSubIndex( FIRSTEXPLDEBRIS, bDestructionPartner, &usTileIndex );
}
// Free all the non-base tiles; the base tile is at pointer 0
for (ubLoop = BASE_TILE; ubLoop < ubNumberOfTiles; ubLoop++)
{
if ( !(ppTile[ ubLoop ]->fFlags & TILE_ON_ROOF ) )
{
sStructGridNo = pBase->sGridNo + ppTile[ubLoop]->sPosRelToBase;
// there might be two structures in this tile, one on each level, but we just want to
// delete one on each pass
if ( !TypeRangeExistsInObjectLayer( sStructGridNo, FIRSTEXPLDEBRIS, SECONDEXPLDEBRIS, &usObjectIndex ) )
{
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
AddObjectToHead( sStructGridNo, (UINT16)(usTileIndex + Random( 3 ) ) );
ApplyMapChangesToMapTempFile( FALSE );
}
}
}
// IF we are a wall, add debris for the other side
if ( pCurrent->fFlags & STRUCTURE_WALLSTUFF )
{
switch( pCurrent->ubWallOrientation )
{
case OUTSIDE_TOP_LEFT:
case INSIDE_TOP_LEFT:
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( SOUTH ) );
if ( !TypeRangeExistsInObjectLayer( sStructGridNo, FIRSTEXPLDEBRIS, SECONDEXPLDEBRIS, &usObjectIndex ) )
{
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
AddObjectToHead( sStructGridNo, (UINT16)(usTileIndex + Random( 3 ) ) );
ApplyMapChangesToMapTempFile( FALSE );
}
break;
case OUTSIDE_TOP_RIGHT:
case INSIDE_TOP_RIGHT:
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( EAST ) );
if ( !TypeRangeExistsInObjectLayer( sStructGridNo, FIRSTEXPLDEBRIS, SECONDEXPLDEBRIS, &usObjectIndex ) )
{
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
AddObjectToHead( sStructGridNo, (UINT16)(usTileIndex + Random( 3 ) ) );
ApplyMapChangesToMapTempFile( FALSE );
}
break;
}
}
}
// Else look for fences, walk along them to change to destroyed peices...
else if ( pCurrent->fFlags & STRUCTURE_FENCE )
{
// walk along based on orientation
switch( pCurrent->ubWallOrientation )
{
case OUTSIDE_TOP_RIGHT:
case INSIDE_TOP_RIGHT:
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( SOUTH ) );
HandleFencePartnerCheck( sStructGridNo );
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( NORTH ) );
HandleFencePartnerCheck( sStructGridNo );
break;
case OUTSIDE_TOP_LEFT:
case INSIDE_TOP_LEFT:
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( EAST ) );
HandleFencePartnerCheck( sStructGridNo );
sStructGridNo = NewGridNo( pBase->sGridNo, DirectionInc( WEST ) );
HandleFencePartnerCheck( sStructGridNo );
break;
}
}
// OK, Check if this is a wall, then search and change other walls based on this
if ( pCurrent->fFlags & STRUCTURE_WALLSTUFF )
{
// ATE
// Remove any decals in tile....
// Use tile database for this as apposed to stuct data
RemoveAllStructsOfTypeRange( pBase->sGridNo, FIRSTWALLDECAL, FOURTHWALLDECAL );
RemoveAllStructsOfTypeRange( pBase->sGridNo, FIFTHWALLDECAL, EIGTHWALLDECAL );
// Alrighty, now do this
// Get orientation
// based on orientation, go either x or y dir
// check for wall in both _ve and -ve directions
// if found, replace!
switch( pCurrent->ubWallOrientation )
{
case OUTSIDE_TOP_LEFT:
case INSIDE_TOP_LEFT:
// Move WEST
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( WEST ) );
pNewNode = GetWallLevelNodeAndStructOfSameOrientationAtGridNo( sNewGridNo, pCurrent->ubWallOrientation, &pWallStruct );
if ( pNewNode != NULL )
{
if ( pWallStruct->fFlags & STRUCTURE_WALL )
{
if ( pCurrent->ubWallOrientation == OUTSIDE_TOP_LEFT )
{
sSubIndex = 48;
}
else
{
sSubIndex = 52;
}
// Replace!
GetTileIndexFromTypeSubIndex( gTileDatabase[ pNewNode->usIndex ].fType, sSubIndex, (UINT16 *)&sNewIndex );
//Set a flag indicating that the following changes are to go the the maps temp file
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( sNewGridNo, pNewNode );
AddWallToStructLayer( sNewGridNo, sNewIndex, TRUE );
ApplyMapChangesToMapTempFile( FALSE );
}
}
// Move in EAST
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( EAST ) );
pNewNode = GetWallLevelNodeAndStructOfSameOrientationAtGridNo( sNewGridNo, pCurrent->ubWallOrientation, &pWallStruct );
if ( pNewNode != NULL )
{
if ( pWallStruct->fFlags & STRUCTURE_WALL )
{
if ( pCurrent->ubWallOrientation == OUTSIDE_TOP_LEFT )
{
sSubIndex = 49;
}
else
{
sSubIndex = 53;
}
// Replace!
GetTileIndexFromTypeSubIndex( gTileDatabase[ pNewNode->usIndex ].fType, sSubIndex, (UINT16 *)&sNewIndex );
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( sNewGridNo, pNewNode );
AddWallToStructLayer( sNewGridNo, sNewIndex, TRUE );
ApplyMapChangesToMapTempFile( FALSE );
}
}
// look for attached structures in same tile
sNewGridNo = pBase->sGridNo;
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_LEFT_WALL );
while (pAttached)
{
pAttachedBase = FindBaseStructure( pAttached );
if (pAttachedBase)
{
// Remove the beast!
while ( (*ppNextCurrent) != NULL && (*ppNextCurrent)->usStructureID == pAttachedBase->usStructureID )
{
// the next structure will also be deleted so we had better
// skip past it!
(*ppNextCurrent) = (*ppNextCurrent)->pNext;
}
pAttachedNode = FindLevelNodeBasedOnStructure( pAttachedBase->sGridNo, pAttachedBase );
if (pAttachedNode)
{
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( pAttachedBase->sGridNo, pAttachedNode );
ApplyMapChangesToMapTempFile( FALSE );
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
// search for another, from the start of the list
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_LEFT_WALL );
}
// Move in SOUTH, looking for attached structures to remove
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( SOUTH ) );
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_LEFT_WALL );
while (pAttached)
{
pAttachedBase = FindBaseStructure( pAttached );
if (pAttachedBase)
{
pAttachedNode = FindLevelNodeBasedOnStructure( pAttachedBase->sGridNo, pAttachedBase );
if (pAttachedNode)
{
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( pAttachedBase->sGridNo, pAttachedNode );
ApplyMapChangesToMapTempFile( FALSE );
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
// search for another, from the start of the list
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_LEFT_WALL );
}
break;
case OUTSIDE_TOP_RIGHT:
case INSIDE_TOP_RIGHT:
// Move in NORTH
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( NORTH ) );
pNewNode = GetWallLevelNodeAndStructOfSameOrientationAtGridNo( sNewGridNo, pCurrent->ubWallOrientation, &pWallStruct );
if ( pNewNode != NULL )
{
if ( pWallStruct->fFlags & STRUCTURE_WALL )
{
if ( pCurrent->ubWallOrientation == OUTSIDE_TOP_RIGHT )
{
sSubIndex = 51;
}
else
{
sSubIndex = 55;
}
// Replace!
GetTileIndexFromTypeSubIndex( gTileDatabase[ pNewNode->usIndex ].fType, sSubIndex, (UINT16 *)&sNewIndex );
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( sNewGridNo, pNewNode );
AddWallToStructLayer( sNewGridNo, sNewIndex, TRUE );
ApplyMapChangesToMapTempFile( FALSE );
}
}
// Move in SOUTH
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( SOUTH ) );
pNewNode = GetWallLevelNodeAndStructOfSameOrientationAtGridNo( sNewGridNo, pCurrent->ubWallOrientation, &pWallStruct );
if ( pNewNode != NULL )
{
if ( pWallStruct->fFlags & STRUCTURE_WALL )
{
if ( pCurrent->ubWallOrientation == OUTSIDE_TOP_RIGHT )
{
sSubIndex = 50;
}
else
{
sSubIndex = 54;
}
// Replace!
GetTileIndexFromTypeSubIndex( gTileDatabase[ pNewNode->usIndex ].fType, sSubIndex, (UINT16 *)&sNewIndex );
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( sNewGridNo, pNewNode );
AddWallToStructLayer( sNewGridNo, sNewIndex, TRUE );
ApplyMapChangesToMapTempFile( FALSE );
}
}
// looking for attached structures to remove in base tile
sNewGridNo = pBase->sGridNo;
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_RIGHT_WALL );
while (pAttached)
{
pAttachedBase = FindBaseStructure( pAttached );
if (pAttachedBase)
{
pAttachedNode = FindLevelNodeBasedOnStructure( pAttachedBase->sGridNo, pAttachedBase );
if (pAttachedNode)
{
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( pAttachedBase->sGridNo, pAttachedNode );
ApplyMapChangesToMapTempFile( FALSE );
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
// search for another, from the start of the list
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_RIGHT_WALL );
}
// Move in EAST, looking for attached structures to remove
sNewGridNo = NewGridNo( pBase->sGridNo, DirectionInc( EAST ) );
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_RIGHT_WALL );
while (pAttached)
{
pAttachedBase = FindBaseStructure( pAttached );
if (pAttachedBase)
{
pAttachedNode = FindLevelNodeBasedOnStructure( pAttachedBase->sGridNo, pAttachedBase );
if (pAttachedNode)
{
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( pAttachedBase->sGridNo, pAttachedNode );
ApplyMapChangesToMapTempFile( FALSE );
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
}
else
{
// error!
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Problems removing structure attached to wall at %d", sNewGridNo );
#endif
break;
}
// search for another, from the start of the list
pAttached = FindStructure( sNewGridNo, STRUCTURE_ON_RIGHT_WALL );
}
break;
}
// CJC, Sept 16: if we destroy any wall of the brothel, make Kingpin's men hostile!
if ( gWorldSectorX == 5 && gWorldSectorY == MAP_ROW_C && gbWorldSectorZ == 0 )
{
UINT8 ubRoom;
BOOLEAN fInRoom;
fInRoom = InARoom( sGridNo, &ubRoom );
if ( !fInRoom )
{
// try to south
fInRoom = InARoom( sGridNo + DirectionInc( SOUTH ) , &ubRoom );
if ( !fInRoom )
{
// try to east
fInRoom = InARoom( sGridNo + DirectionInc( EAST ) , &ubRoom );
}
}
if ( fInRoom && IN_BROTHEL( ubRoom ) )
{
CivilianGroupChangesSides( KINGPIN_CIV_GROUP );
}
}
}
// OK, we need to remove the water from the fountain
// Lots of HARD CODING HERE :(
// Get tile type
GetTileType( pNode->usIndex, &uiTileType );
// Check if we are a fountain!
if ( _stricmp( gTilesets[ giCurrentTilesetID ].TileSurfaceFilenames[ uiTileType ], "fount1.sti" ) == 0 )
{
// Yes we are!
// Remove water....
ApplyMapChangesToMapTempFile( TRUE );
GetTileIndexFromTypeSubIndex( uiTileType, 1, (UINT16 *)&sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
GetTileIndexFromTypeSubIndex( uiTileType, 2, (UINT16 *)&sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
GetTileIndexFromTypeSubIndex( uiTileType, 3, (UINT16 *)&sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
RemoveStruct( sBaseGridNo, sNewIndex );
ApplyMapChangesToMapTempFile( FALSE );
}
// Remove any interactive tiles we could be over!
BeginCurInteractiveTileCheck( INTILE_CHECK_SELECTIVE );
if ( pCurrent->fFlags & STRUCTURE_WALLSTUFF )
{
RecompileLocalMovementCostsForWall( pBase->sGridNo, pBase->ubWallOrientation );
}
// Remove!
//Set a flag indicating that the following changes are to go the the maps, temp file
ApplyMapChangesToMapTempFile( TRUE );
RemoveStructFromLevelNode( pBase->sGridNo, pNode );
ApplyMapChangesToMapTempFile( FALSE );
// OK, if we are to swap structures, do it now...
if ( fContinue == 2 )
{
// We have a levelnode...
// Get new index for new grpahic....
GetTileIndexFromTypeSubIndex( uiTileType, bDestructionPartner, &usTileIndex );
ApplyMapChangesToMapTempFile( TRUE );
AddStructToHead( sBaseGridNo, usTileIndex );
ApplyMapChangesToMapTempFile( FALSE );
}
// Rerender world!
// Reevaluate world movement costs, reduncency!
gTacticalStatus.uiFlags |= NOHIDE_REDUNDENCY;
// FOR THE NEXT RENDER LOOP, RE-EVALUATE REDUNDENT TILES
InvalidateWorldRedundency( );
SetRenderFlags(RENDER_FLAG_FULL);
// Handle properly lighting the structure that was modified
if( gbWorldSectorZ == 0 )
{
// ATE: make sure the lighting on the graphic gets updateds
LightSetBaseLevel( GetTimeOfDayAmbientLightLevel() );
}
else
{
LightSetBaseLevel( LightGetAmbient() );
}
// Movement costs!
( *pfRecompileMovementCosts ) = TRUE;
{
// Make secondary explosion if eplosive....
if ( fExplosive )
{
InternalIgniteExplosion( ubOwner, CenterX( sBaseGridNo ), CenterY( sBaseGridNo ), 0, sBaseGridNo, STRUCTURE_EXPLOSION, FALSE, bLevel );
}
}
if ( fContinue == 2 )
{
return( FALSE );
}
}
// 2 is NO DAMAGE
return( 2 );
}
}
return( 1 );
}
STRUCTURE *gStruct;
void ExplosiveDamageGridNo( INT32 sGridNo, INT16 sWoundAmt, UINT32 uiDist, BOOLEAN *pfRecompileMovementCosts, BOOLEAN fOnlyWalls, INT8 bMultiStructSpecialFlag, BOOLEAN fSubSequentMultiTilesTransitionDamage, UINT8 ubOwner, INT8 bLevel )
{
#ifdef JA2BETAVERSION
if (is_networked) {
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"ExplosiveDamageGridNo ( sGridNo : %i , sWoundAmt : %i , uiDist : %i , fRecompileMoveCosts : %i , fOnlyWalls : %i , MultiStructSpecialFlag : %i ,fSubsequentMultiTilesTransDmg : %i , ubOwner : %i , bLevel : %i )\n",sGridNo, sWoundAmt , (int)*pfRecompileMovementCosts , (int)fOnlyWalls , bMultiStructSpecialFlag , (int)fSubSequentMultiTilesTransitionDamage , ubOwner , bLevel );
MPDebugMsg(tmpMPDbgString);
}
#endif
STRUCTURE *pCurrent, *pNextCurrent, *pStructure;
STRUCTURE *pBaseStructure;
INT16 sDesiredLevel;
DB_STRUCTURE_TILE **ppTile = NULL;
UINT8 ubLoop, ubLoop2;
INT32 sNewGridNo, sNewGridNo2, sBaseGridNo = NOWHERE;
BOOLEAN fToBreak = FALSE;
BOOLEAN fMultiStructure = FALSE;
UINT8 ubNumberOfTiles = 0xff;
BOOLEAN fMultiStructSpecialFlag = FALSE;
BOOLEAN fExplodeDamageReturn = FALSE;
// Based on distance away, damage any struct at this gridno
// OK, loop through structures and damage!
pCurrent = gpWorldLevelData[ sGridNo ].pStructureHead;
sDesiredLevel = STRUCTURE_ON_GROUND;
// This code gets a little hairy because
// (1) we might need to destroy the currently-examined structure
while (pCurrent != NULL)
{
// ATE: These are for the checks below for multi-structs....
pBaseStructure = FindBaseStructure( pCurrent );
if ( pBaseStructure )
{
sBaseGridNo = pBaseStructure->sGridNo;
ubNumberOfTiles = pBaseStructure->pDBStructureRef->pDBStructure->ubNumberOfTiles;
fMultiStructure = ( ( pBaseStructure->fFlags & STRUCTURE_MULTI ) != 0 );
ppTile = (DB_STRUCTURE_TILE **) MemAlloc( sizeof( DB_STRUCTURE_TILE* ) * ubNumberOfTiles );
memcpy( ppTile, pBaseStructure->pDBStructureRef->ppTile, sizeof( DB_STRUCTURE_TILE* ) * ubNumberOfTiles );
if ( bMultiStructSpecialFlag == -1 )
{
// Set it!
bMultiStructSpecialFlag = ( ( pBaseStructure->fFlags & STRUCTURE_SPECIAL ) != 0 );
}
if ( pBaseStructure->fFlags & STRUCTURE_EXPLOSIVE )
{
// ATE: Set hit points to zero....
pBaseStructure->ubHitPoints = 0;
}
}
else
{
fMultiStructure = FALSE;
sBaseGridNo = 0;
ubNumberOfTiles = 0;
ppTile = 0;
}
pNextCurrent = pCurrent->pNext;
gStruct = pNextCurrent;
// Check level!
if (pCurrent->sCubeOffset == sDesiredLevel )
{
fExplodeDamageReturn = ExplosiveDamageStructureAtGridNo( pCurrent, &pNextCurrent, sGridNo, sWoundAmt, uiDist, pfRecompileMovementCosts, fOnlyWalls, 0, ubOwner, bLevel );
// Are we overwriting damage due to multi-tile...?
if ( fExplodeDamageReturn )
{
if ( fSubSequentMultiTilesTransitionDamage == 2)
{
fExplodeDamageReturn = 2;
}
else
{
fExplodeDamageReturn = 1;
}
}
if ( !fExplodeDamageReturn )
{
fToBreak = TRUE;
}
//}
// 0verhaul: The following was combined with the previous code block. I don't think they intended to execute this
// part unless fExplodeDamageReturn was actually set. When it was being executed, tossing a grenade just behind the
// plane in Drassen, for instance, would cause an infinite recursion in this code. The reason is that the plane's
// armor is (amazingly enough) stronger than a grenade blast can even damage. This code here seems to rely on the
// structure in question being destroyed by the blast since it indiscriminently recurses on neighbors, creating a
// ping pong on two adjacent parts of the plane. Probably the reason this was not found before is that fExplodeDamageReturn
// was uninitialized before and usually was non-zero. Now it is initialized to false.
// OK, for multi-structs...
// AND we took damage...
if ( fMultiStructure && !fOnlyWalls && fExplodeDamageReturn == 0 )
{
// ATE: Don't after first attack...
if ( uiDist > 1 )
{
if ( pBaseStructure )
{
MemFree( ppTile );
}
return;
}
{
for ( ubLoop = BASE_TILE; ubLoop < ubNumberOfTiles; ubLoop++)
{
sNewGridNo = sBaseGridNo + ppTile[ubLoop]->sPosRelToBase;
// look in adjacent tiles
for ( ubLoop2 = 0; ubLoop2 < NUM_WORLD_DIRECTIONS; ubLoop2++ )
{
sNewGridNo2 = NewGridNo( sNewGridNo, DirectionInc( ubLoop2 ) );
if ( sNewGridNo2 != sNewGridNo && sNewGridNo2 != sGridNo )
{
pStructure = FindStructure( sNewGridNo2, STRUCTURE_MULTI );
if ( pStructure )
{
fMultiStructSpecialFlag = ( ( pStructure->fFlags & STRUCTURE_SPECIAL ) != 0 );
if ( ( bMultiStructSpecialFlag == fMultiStructSpecialFlag ) )
{
// If we just damaged it, use same damage value....
if ( fMultiStructSpecialFlag )
{
ExplosiveDamageGridNo( sNewGridNo2, sWoundAmt, uiDist, pfRecompileMovementCosts, fOnlyWalls, bMultiStructSpecialFlag, 1, ubOwner, bLevel );
}
else
{
ExplosiveDamageGridNo( sNewGridNo2, sWoundAmt, uiDist, pfRecompileMovementCosts, fOnlyWalls, bMultiStructSpecialFlag, 2, ubOwner, bLevel );
}
{
InternalIgniteExplosion( ubOwner, CenterX( sNewGridNo2 ), CenterY( sNewGridNo2 ), 0, sNewGridNo2, RDX, FALSE, bLevel );
}
fToBreak = TRUE;
}
}
}
}
}
}
if ( fToBreak )
{
break;
}
}
}
if ( pBaseStructure )
{
MemFree( ppTile );
}
pCurrent = pNextCurrent;
}
}
BOOLEAN DamageSoldierFromBlast( UINT8 ubPerson, UINT8 ubOwner, INT32 sBombGridNo, INT16 sWoundAmt, INT16 sBreathAmt, UINT32 uiDist, UINT16 usItem, INT16 sSubsequent , BOOL fFromRemoteClient )
{
// OJW - 20091028
if (is_networked && is_client)
{
SOLDIERTYPE* pSoldier = MercPtrs[ubPerson];
if (pSoldier != NULL)
{
// only the owner of a merc may send damage (as this takes into account equipped armor)
if (IsOurSoldier(pSoldier) || (pSoldier->bTeam == 1 && is_server) && !fFromRemoteClient)
{
// let this function proceed, we will send damage towards the end
}
else if (!fFromRemoteClient)
{
// skip executing locally because we want the random number generator to be aligned
// with the client that spawns set off the explosion/grenade/whatever
return FALSE;
}
}
#ifdef JA2BETAVERSION
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"DamageSoldierFromBlast ( ubPerson : %i , ubOwner : %i , sBombGridNo : %i , sWoundAmt : %i , sBreathAmt : %i , uiDist : %i , usItem : %i , sSubs : %i , fFromRemoteClient : %i )\n",ubPerson, ubOwner , sBombGridNo , sWoundAmt , sBreathAmt , uiDist , usItem , sSubsequent , fFromRemoteClient );
MPDebugMsg(tmpMPDbgString);
#endif
}
SOLDIERTYPE *pSoldier;
INT16 sNewWoundAmt = 0;
UINT8 ubDirection;
UINT8 ubSpecial = 0;
BOOLEAN fInBuilding = InBuilding(sBombGridNo);
BOOLEAN fFlashbang = Explosive[Item[usItem].ubClassIndex].ubType == EXPLOSV_FLASHBANG;
UINT16 usHalfExplosionRadius;
pSoldier = MercPtrs[ ubPerson ]; // someone is here, and they're gonna get hurt
if (!pSoldier->bActive || !pSoldier->bInSector || !pSoldier->stats.bLife )
return( FALSE );
if ( pSoldier->ubMiscSoldierFlags & SOLDIER_MISC_HURT_BY_EXPLOSION )
{
// don't want to damage the guy twice
return( FALSE );
}
// Lesh: if flashbang
// check if soldier is outdoor and situated farther that half explosion radius and not underground
usHalfExplosionRadius = Explosive[Item[usItem].ubClassIndex].ubRadius / 2;
if ( fFlashbang && !gbWorldSectorZ && !fInBuilding && uiDist > usHalfExplosionRadius )
{
// HEADROCK HAM 3.3: Flashbang at half distance causes up to 6 suppression points. Roughly equivalent of being
// "lightly" shot at.
if (gGameExternalOptions.usExplosionSuppressionEffect > 0)
{
pSoldier->ubSuppressionPoints += (PreRandom(6) * gGameExternalOptions.usExplosionSuppressionEffect) / 100;
}
// then no effect
return( FALSE );
}
// Direction to center of explosion
ubDirection = (UINT8)GetDirectionFromGridNo( sBombGridNo, pSoldier );
// Increment attack counter...
// gTacticalStatus.ubAttackBusyCount++;
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Incrementing Attack: Explosion dishing out damage, Count now %d", gTacticalStatus.ubAttackBusyCount ) );
DebugAttackBusy( String("Explosion dishing out damage to %d\n", pSoldier->ubID) );
sNewWoundAmt = sWoundAmt - __min( sWoundAmt, 35 ) * ArmourVersusExplosivesPercent( pSoldier ) / 100;
if ( sNewWoundAmt < 0 )
{
sNewWoundAmt = 0;
}
////////////////////////////////////////////////////////////////////////////////////
// SANDRO - STOMP traits
else
{
if ( (MercPtrs[ ubOwner ] != NULL) && gGameOptions.fNewTraitSystem)
{
// Demolitions damage bonus with bombs and mines
if ( HAS_SKILL_TRAIT( MercPtrs[ ubOwner ], DEMOLITIONS_NT ) &&
Explosive[Item[usItem].ubClassIndex].ubType == EXPLOSV_NORMAL && Item[usItem].usItemClass == IC_BOMB &&
(!Item[usItem].attachment || Item[usItem].mine ))
{
sNewWoundAmt = (INT16)(((sNewWoundAmt * (100 + gSkillTraitValues.ubDEDamageOfBombsAndMines)) / 100) + 0.5);
}
// Heavy Weapons trait bonus damage to tanks
if ( HAS_SKILL_TRAIT( MercPtrs[ ubOwner ], HEAVY_WEAPONS_NT ) && TANK( pSoldier ) &&
Explosive[Item[usItem].ubClassIndex].ubType == EXPLOSV_NORMAL )
{
sNewWoundAmt = (INT16)(((sNewWoundAmt * (100 + gSkillTraitValues.ubHWDamageTanksBonusPercent * NUM_SKILL_TRAITS( MercPtrs[ ubOwner ], HEAVY_WEAPONS_NT ))) / 100) + 0.5); // +30%
}
// Heavy Weapons trait bonus damage with rocket, grenade launchers and mortar
else if ( HAS_SKILL_TRAIT( MercPtrs[ ubOwner ], HEAVY_WEAPONS_NT ) &&
Explosive[Item[usItem].ubClassIndex].ubType == EXPLOSV_NORMAL &&
((Item[usItem].usItemClass == IC_BOMB && Item[usItem].attachment && !Item[usItem].mine ) || // mortar shells
(Item[usItem].usItemClass == IC_GRENADE && (Item[usItem].glgrenade || Item[usItem].electronic) ) || // rockets for rocketlaunchers (I haven't found any other way)
(Item[usItem].usItemClass == IC_LAUNCHER ) || Item[usItem].rocketlauncher || Item[usItem].singleshotrocketlauncher ) )
{
sNewWoundAmt = (INT16)(((sNewWoundAmt * (100 + gSkillTraitValues.ubHWDamageBonusPercentForHW * NUM_SKILL_TRAITS( MercPtrs[ ubOwner ], HEAVY_WEAPONS_NT ))) / 100) + 0.5); // +15%
}
}
// adjust damage resistance of TANKS
if ( TANK( pSoldier ) && gGameOptions.fNewTraitSystem )
{
sNewWoundAmt = (INT16)(sNewWoundAmt * (100 - gSkillTraitValues.bTanksDamageResistanceModifier) / 100);
// another half of this for ordinary grenades
if ( (( Item[usItem].usItemClass == IC_GRENADE ) || Item[usItem].glgrenade ) && !Item[usItem].electronic )
sNewWoundAmt = (INT16)(sNewWoundAmt * (100 - (gSkillTraitValues.bTanksDamageResistanceModifier / 2)) / 100);
}
// Bodybuilding damage resistance
if ( gGameOptions.fNewTraitSystem && HAS_SKILL_TRAIT( pSoldier, BODYBUILDING_NT ) )
sNewWoundAmt = max( 1, (INT16)(sNewWoundAmt * (100 - gSkillTraitValues.ubBBDamageResistance) / 100));
// Damage resistance for Militia
if (pSoldier->ubSoldierClass == SOLDIER_CLASS_GREEN_MILITIA && gGameExternalOptions.bGreenMilitiaDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.bGreenMilitiaDamageResistance) /100);
else if (pSoldier->ubSoldierClass == SOLDIER_CLASS_REG_MILITIA && gGameExternalOptions.bRegularMilitiaDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.bRegularMilitiaDamageResistance) /100);
else if (pSoldier->ubSoldierClass == SOLDIER_CLASS_ELITE_MILITIA && gGameExternalOptions.bVeteranMilitiaDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.bVeteranMilitiaDamageResistance) /100);
// bonus for enemy too
else if (pSoldier->ubSoldierClass == SOLDIER_CLASS_ADMINISTRATOR && gGameExternalOptions.sEnemyAdminDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.sEnemyAdminDamageResistance) /100);
else if (pSoldier->ubSoldierClass == SOLDIER_CLASS_ARMY && gGameExternalOptions.sEnemyRegularDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.sEnemyRegularDamageResistance) /100);
else if (pSoldier->ubSoldierClass == SOLDIER_CLASS_ELITE && gGameExternalOptions.sEnemyEliteDamageResistance != 0)
sNewWoundAmt -= ((sNewWoundAmt * gGameExternalOptions.sEnemyEliteDamageResistance) /100);
// we can loose stats due to being hit by the blast
else if ( gGameOptions.fNewTraitSystem && Explosive[Item[usItem].ubClassIndex].ubType == EXPLOSV_NORMAL &&
!AM_A_ROBOT( pSoldier ) && !(pSoldier->flags.uiStatusFlags & SOLDIER_MONSTER) &&
sNewWoundAmt > 2 && sNewWoundAmt < pSoldier->stats.bLife )
{
if ( PreRandom( sNewWoundAmt ) > gSkillTraitValues.ubDamageNeededToLoseStats )
{
UINT8 ubStatLoss = PreRandom( sNewWoundAmt ) + 1;
UINT8 ubPickStat = PreRandom( 20 );
if (ubPickStat < 3 ) // 15% chance to lose Wisdom
{
if (ubStatLoss >= pSoldier->stats.bWisdom)
{
ubStatLoss = pSoldier->stats.bWisdom - 1;
}
if ( ubStatLoss > 0 )
{
pSoldier->stats.bWisdom -= ubStatLoss;
pSoldier->ubCriticalStatDamage[DAMAGED_STAT_WISDOM] += ubStatLoss;
if (pSoldier->ubProfile != NO_PROFILE)
{
gMercProfiles[ pSoldier->ubProfile ].bWisdom = pSoldier->stats.bWisdom;
}
if (pSoldier->name[0] && pSoldier->bVisible == TRUE)
{
// make stat RED for a while...
pSoldier->timeChanges.uiChangeWisdomTime = GetJA2Clock();
pSoldier->usValueGoneUp &= ~( WIS_INCREASE );
if (ubStatLoss == 1)
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_1_WISDOM], pSoldier->name );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_WISDOM], pSoldier->name, ubStatLoss );
}
}
}
}
else if (ubPickStat < 7 ) // 20% chance to lose Dexterity
{
if (ubStatLoss >= pSoldier->stats.bDexterity)
{
ubStatLoss = pSoldier->stats.bDexterity - 1;
}
if ( ubStatLoss > 0 )
{
pSoldier->stats.bDexterity -= ubStatLoss;
pSoldier->ubCriticalStatDamage[DAMAGED_STAT_DEXTERITY] += ubStatLoss;
if (pSoldier->ubProfile != NO_PROFILE)
{
gMercProfiles[ pSoldier->ubProfile ].bDexterity = pSoldier->stats.bDexterity;
}
if (pSoldier->name[0] && pSoldier->bVisible == TRUE)
{
// make stat RED for a while...
pSoldier->timeChanges.uiChangeDexterityTime = GetJA2Clock();
pSoldier->usValueGoneUp &= ~( DEX_INCREASE );
if (ubStatLoss == 1)
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_1_DEX], pSoldier->name );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_DEX], pSoldier->name, ubStatLoss );
}
}
}
}
else if (ubPickStat < 11 ) // 20% chance to lose Strength
{
if (ubStatLoss >= pSoldier->stats.bStrength)
{
ubStatLoss = pSoldier->stats.bStrength - 1;
}
if ( ubStatLoss > 0 )
{
pSoldier->stats.bStrength -= ubStatLoss;
// added this for healing lost stats feature
pSoldier->ubCriticalStatDamage[DAMAGED_STAT_STRENGTH] += ubStatLoss;
if (pSoldier->ubProfile != NO_PROFILE)
{
gMercProfiles[ pSoldier->ubProfile ].bStrength = pSoldier->stats.bStrength;
}
if (pSoldier->name[0] && pSoldier->bVisible == TRUE)
{
// make stat RED for a while...
pSoldier->timeChanges.uiChangeStrengthTime = GetJA2Clock();
pSoldier->usValueGoneUp &= ~( STRENGTH_INCREASE );
if (ubStatLoss == 1)
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_1_STRENGTH], pSoldier->name );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_STRENGTH], pSoldier->name, ubStatLoss );
}
}
}
}
else if (ubPickStat < 15 ) // 20% chance to lose Agility
{
if (ubStatLoss >= pSoldier->stats.bAgility)
{
ubStatLoss = pSoldier->stats.bAgility - 1;
}
if ( ubStatLoss > 0 )
{
pSoldier->stats.bAgility -= ubStatLoss;
// added this for healing lost stats feature
pSoldier->ubCriticalStatDamage[DAMAGED_STAT_AGILITY] += ubStatLoss;
if (pSoldier->ubProfile != NO_PROFILE)
{
gMercProfiles[ pSoldier->ubProfile ].bAgility = pSoldier->stats.bAgility;
}
if (pSoldier->name[0] && pSoldier->bVisible == TRUE)
{
// make stat RED for a while...
pSoldier->timeChanges.uiChangeAgilityTime = GetJA2Clock();
pSoldier->usValueGoneUp &= ~( AGIL_INCREASE );
if (ubStatLoss == 1)
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_1_AGIL], pSoldier->name );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, Message[STR_LOSES_AGIL], pSoldier->name, ubStatLoss );
}
}
}
}
else if (ubPickStat < 18 ) // 15% chance to lose Health
{
if (ubStatLoss >= (pSoldier->stats.bLifeMax - OKLIFE))
{
ubStatLoss = pSoldier->stats.bLifeMax - OKLIFE - 1;
}
if ( ubStatLoss > sNewWoundAmt)
{
ubStatLoss = (UINT8)sNewWoundAmt;
}
if ( ubStatLoss > 0 )
{
pSoldier->stats.bLifeMax -= ubStatLoss;
pSoldier->ubCriticalStatDamage[DAMAGED_STAT_HEALTH] += ubStatLoss;
if (pSoldier->ubProfile != NO_PROFILE)
{
gMercProfiles[ pSoldier->ubProfile ].bLifeMax = pSoldier->stats.bLifeMax;
}
if (pSoldier->name[0] && pSoldier->bVisible == TRUE)
{
// make stat RED for a while...
pSoldier->timeChanges.uiChangeDexterityTime = GetJA2Clock();
pSoldier->usValueGoneUp &= ~( HEALTH_INCREASE );
if (ubStatLoss == 1)
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, New113Message[MSG113_LOSES_ONE_POINT_MAX_HEALTH], pSoldier->name );
}
else
{
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, New113Message[MSG113_LOSES_X_POINTS_MAX_HEALTH], pSoldier->name, ubStatLoss );
}
}
}
}
else // 10% chance to be blinded
{
if (pSoldier->bBlindedCounter < ubStatLoss )
{
pSoldier->bBlindedCounter = ubStatLoss ;
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, L"%s was blinded by the blast!", pSoldier->name );
}
}
// SANDRO - new merc records - times stat damaged
if ( ubStatLoss > 0 && pSoldier->ubProfile != NO_PROFILE )
gMercProfiles[ pSoldier->ubProfile ].records.usTimesStatDamaged++;
}
}
sNewWoundAmt = max(1, sNewWoundAmt);
}
//////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// SANDRO - option to make special NPCs stronger - damage resistance
if (gGameExternalOptions.usSpecialNPCStronger > 0)
{
switch( pSoldier->ubProfile )
{
case CARMEN:
case QUEEN:
case JOE:
case ANNIE:
case CHRIS:
case KINGPIN:
case TIFFANY:
case T_REX:
case DRUGGIST:
case GENERAL:
case JACK:
case OLAF:
case RAY:
case OLGA:
case TYRONE:
case MIKE:
sNewWoundAmt -= (sNewWoundAmt * gGameExternalOptions.usSpecialNPCStronger / 200);
sNewWoundAmt = max( 1, sNewWoundAmt);
break;
}
}
// SANDRO - new merc records - times wounded (blasted by explosion)
if ( ( sNewWoundAmt > 1 || sBreathAmt > 1000 ) && pSoldier->ubProfile != NO_PROFILE )
gMercProfiles[ pSoldier->ubProfile ].records.usTimesWoundedBlasted++;
////////////////////////////////////////////////////////////////////////////////////
// Lesh: flashbang does affect on soldier or not - check it
if ( (Item[usItem].usItemClass & IC_EXPLOSV) && fFlashbang )
{
ubSpecial = DetermineFlashbangEffect( pSoldier, ubDirection, fInBuilding);
}
// HEADROCK HAM 3.3: Explosions cause suppression based on distance.
if (gGameExternalOptions.usExplosionSuppressionEffect > 0)
{
pSoldier->ubSuppressionPoints += ((__max(0,((Explosive[Item[usItem].ubClassIndex].ubRadius * 3) - uiDist)))* gGameExternalOptions.usExplosionSuppressionEffect) / 100;
if (fFlashbang && (gbWorldSectorZ || fInBuilding) && (UINT16)uiDist <= usHalfExplosionRadius)
{
pSoldier->ubSuppressionPoints += (15 * gGameExternalOptions.usExplosionSuppressionEffect) / 100;
}
}
if (is_networked && is_client)
{
if (IsOurSoldier(pSoldier) || (pSoldier->bTeam == 1 && is_server) && !fFromRemoteClient)
{
// if it gets here then we can let the other clients know our merc took damage
send_explosivedamage( ubPerson , ubOwner , sBombGridNo , sNewWoundAmt , sBreathAmt , uiDist , usItem , sSubsequent );
}
}
// OJW - 20091028 - If from a remote client, use unadjusted damage amount
pSoldier->EVENT_SoldierGotHit( usItem, (fFromRemoteClient ? sWoundAmt : sNewWoundAmt) , sBreathAmt, ubDirection, (INT16)uiDist, ubOwner, ubSpecial, ANIM_CROUCH, sSubsequent, sBombGridNo );
pSoldier->ubMiscSoldierFlags |= SOLDIER_MISC_HURT_BY_EXPLOSION;
if ( ubOwner != NOBODY && MercPtrs[ ubOwner ]->bTeam == gbPlayerNum && pSoldier->bTeam != gbPlayerNum )
{
ProcessImplicationsOfPCAttack( MercPtrs[ ubOwner ], &pSoldier, REASON_EXPLOSION );
}
return( TRUE );
}
BOOLEAN DishOutGasDamage( SOLDIERTYPE * pSoldier, EXPLOSIVETYPE * pExplosive, INT16 sSubsequent, BOOLEAN fRecompileMovementCosts, INT16 sWoundAmt, INT16 sBreathAmt, UINT8 ubOwner , BOOL fFromRemoteClient )
{
// OJW - 20091028
if (is_networked && is_client)
{
// only the owner of a merc may send damage (as this takes into account equipped gas mask)
if (IsOurSoldier(pSoldier) || (pSoldier->bTeam == 1 && is_server) && !fFromRemoteClient)
{
// allow this function to proceed, we will send it later, when we are sure we take damage this turn and from this function call
}
else if (!fFromRemoteClient)
{
// skip executing locally because we want the random number generator to be aligned
// with the client that spawns set off the explosion/grenade/whatever
return FALSE;
}
#ifdef JA2BETAVERSION
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"DishOutGasDamage ( ubSoldierID : %i , ubExplosiveType : %i , sSubsequent : %i , recompileMoveCosts : %i , sWoundAmt : %i , sBreathAmt : %i , ubOwner : %i , fRemote : %i)\n", pSoldier->ubID , pExplosive->ubType , sSubsequent , fRecompileMovementCosts , sWoundAmt , sBreathAmt , ubOwner , fFromRemoteClient );
MPDebugMsg(tmpMPDbgString);
#endif
}
INT8 bPosOfMask = NO_SLOT;
if (!pSoldier->bActive || !pSoldier->bInSector || !pSoldier->stats.bLife || AM_A_ROBOT( pSoldier ) )
{
return( fRecompileMovementCosts );
}
if ( pExplosive->ubType == EXPLOSV_CREATUREGAS || pExplosive->ubType == EXPLOSV_BURNABLEGAS)
{
if ( pSoldier->flags.uiStatusFlags & SOLDIER_MONSTER )
{
// unaffected by own gas effects
return( fRecompileMovementCosts );
}
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_CREATUREGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_BURNABLEGAS )
{
// already affected by BURNABLEGAS this turn
return( fRecompileMovementCosts );
}
}
else // no gas mask help from creature attacks
// ATE/CJC: gas stuff
{
if ( pExplosive->ubType == EXPLOSV_TEARGAS )
{
if ( AM_A_ROBOT( pSoldier ) )
{
return( fRecompileMovementCosts );
}
// ignore whether subsequent or not if hit this turn
if ( pSoldier->flags.fHitByGasFlags & HIT_BY_TEARGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
}
else if ( pExplosive->ubType == EXPLOSV_MUSTGAS )
{
if ( AM_A_ROBOT( pSoldier ) )
{
return( fRecompileMovementCosts );
}
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_MUSTARDGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
}
else if(pExplosive->ubType == EXPLOSV_SMOKE)//dnl ch40 200909
{
// ignore whether subsequent or not if hit this turn
if(AM_A_ROBOT(pSoldier) || (pSoldier->flags.fHitByGasFlags & HIT_BY_SMOKEGAS))
return(fRecompileMovementCosts);
}
bPosOfMask = FindGasMask(pSoldier);
if(!DoesSoldierWearGasMask(pSoldier))//dnl ch40 200909
bPosOfMask = NO_SLOT;
if ( bPosOfMask == NO_SLOT || pSoldier->inv[ bPosOfMask ][0]->data.objectStatus < USABLE )
{
bPosOfMask = NO_SLOT;
}
//if ( pSoldier->inv[ HEAD1POS ].usItem == GASMASK && pSoldier->inv[ HEAD1POS ][0]->data.objectStatus >= USABLE )
//{
// bPosOfMask = HEAD1POS;
//}
//else if ( pSoldier->inv[ HEAD2POS ].usItem == GASMASK && pSoldier->inv[ HEAD2POS ][0]->data.objectStatus >= USABLE )
//{
// bPosOfMask = HEAD2POS;
//}
if ( bPosOfMask != NO_SLOT )
{
if ( pSoldier->inv[ bPosOfMask ][0]->data.objectStatus < GASMASK_MIN_STATUS )
{
// GAS MASK reduces breath loss by its work% (it leaks if not at least 70%)
sBreathAmt = ( sBreathAmt * ( 100 - pSoldier->inv[ bPosOfMask ][0]->data.objectStatus ) ) / 100;
if ( sBreathAmt > 500 )
{
// if at least 500 of breath damage got through
// the soldier within the blast radius is gassed for at least one
// turn, possibly more if it's tear gas (which hangs around a while)
pSoldier->flags.uiStatusFlags |= SOLDIER_GASSED;
}
if ( pSoldier->flags.uiStatusFlags & SOLDIER_PC )
{
if ( sWoundAmt > 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus =
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus - (INT8) Random( 4 );
sWoundAmt = ( sWoundAmt * ( 100 - pSoldier->inv[ bPosOfMask ][0]->data.objectStatus ) ) / 100;
}
else if ( sWoundAmt == 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus =
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus - (INT8) Random( 2 );
}
}
}
else
{
sBreathAmt = 0;
if ( sWoundAmt > 0 )
{
if ( sWoundAmt == 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus =
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus - (INT8) Random( 2 );
}
else
{
// use up gas mask
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus =
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus - (INT8) Random( 4 );
}
}
sWoundAmt = 0;
}
}
}
if ( sWoundAmt != 0 || sBreathAmt != 0 )
{
switch( pExplosive->ubType )
{
case EXPLOSV_CREATUREGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_CREATUREGAS;
break;
case EXPLOSV_TEARGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_TEARGAS;
break;
case EXPLOSV_MUSTGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_MUSTARDGAS;
break;
case EXPLOSV_BURNABLEGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_BURNABLEGAS;
break;
case EXPLOSV_SMOKE://dnl ch40 200909
pSoldier->flags.fHitByGasFlags |= HIT_BY_SMOKEGAS;
break;
default:
break;
}
//ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_INTERFACE, L"ExpControl pSoldier->flags.fHitByGasFlags: %d", pSoldier->flags.fHitByGasFlags );
// a gas effect, take damage directly...
pSoldier->SoldierTakeDamage( ANIM_STAND, sWoundAmt, sBreathAmt, TAKE_DAMAGE_GAS, NOBODY, NOWHERE, 0, TRUE );
if (is_networked && is_client)
{
// if it gets here we are supposed to send it.
// let all the other clients know that our merc got gassed
// and align them with our random number generator
if (IsOurSoldier(pSoldier) || (pSoldier->bTeam == 1 && is_server) && !fFromRemoteClient)
{
send_gasdamage( pSoldier , pExplosive->uiIndex , sSubsequent , fRecompileMovementCosts , sWoundAmt , sBreathAmt , ubOwner );
}
}
if ( pSoldier->stats.bLife >= CONSCIOUSNESS )
{
pSoldier->DoMercBattleSound( (INT8)( BATTLE_SOUND_HIT1 + Random( 2 ) ) );
}
if ( ubOwner != NOBODY && MercPtrs[ ubOwner ]->bTeam == gbPlayerNum && pSoldier->bTeam != gbPlayerNum )
{
ProcessImplicationsOfPCAttack( MercPtrs[ ubOwner ], &pSoldier, REASON_EXPLOSION );
}
}
return( fRecompileMovementCosts );
}
BOOLEAN ExpAffect( INT32 sBombGridNo, INT32 sGridNo, UINT32 uiDist, UINT16 usItem, UINT8 ubOwner, INT16 sSubsequent, BOOLEAN *pfMercHit, INT8 bLevel, INT32 iSmokeEffectID )
{
#ifdef JA2BETAVERSION
if (is_networked) {
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"ExpAffect ( sBombGridNo : %i , sGridNo : %i , uiDist : %i , usItem : %i , ubOwner : %i , sSubsequent : %i , fMercHit : %i , bLevel : %i , iSmokeEffectID : %i )\n",sBombGridNo, sGridNo , uiDist , usItem , ubOwner , sSubsequent , (int)*pfMercHit , bLevel , iSmokeEffectID );
MPDebugMsg(tmpMPDbgString);
}
#endif
INT16 sWoundAmt = 0,sBreathAmt = 0, /* sNewWoundAmt = 0, sNewBreathAmt = 0, */ sStructDmgAmt;
UINT8 ubPerson;
SOLDIERTYPE *pSoldier;
EXPLOSIVETYPE *pExplosive;
INT16 sX, sY;
BOOLEAN fRecompileMovementCosts = FALSE;
BOOLEAN fSmokeEffect = FALSE;
BOOLEAN fStunEffect = FALSE;
BOOLEAN fBlastEffect = TRUE;
BOOLEAN fBloodEffect = FALSE;
INT8 bSmokeEffectType = 0;
INT32 sNewGridNo;
ITEM_POOL * pItemPool, * pItemPoolNext;
UINT32 uiRoll;
//Init the variables
sX = sY = -1;
if ( sSubsequent == BLOOD_SPREAD_EFFECT )
{
fSmokeEffect = FALSE;
fBlastEffect = FALSE;
fBloodEffect = TRUE;
}
else
{
// Turn off blast effect if some types of items...
switch( Explosive[Item[usItem].ubClassIndex].ubType )
{
case EXPLOSV_MUSTGAS:
fSmokeEffect = TRUE;
bSmokeEffectType = MUSTARDGAS_SMOKE_EFFECT;
fBlastEffect = FALSE;
break;
case EXPLOSV_BURNABLEGAS:
fSmokeEffect = TRUE;
bSmokeEffectType = BURNABLEGAS_SMOKE_EFFECT;
fBlastEffect = FALSE;
break;
case EXPLOSV_TEARGAS:
fSmokeEffect = TRUE;
bSmokeEffectType = TEARGAS_SMOKE_EFFECT;
fBlastEffect = FALSE;
break;
case EXPLOSV_SMOKE:
fSmokeEffect = TRUE;
bSmokeEffectType = NORMAL_SMOKE_EFFECT;
fBlastEffect = FALSE;
break;
case EXPLOSV_STUN:
fStunEffect = TRUE;
break;
case EXPLOSV_CREATUREGAS:
fSmokeEffect = TRUE;
bSmokeEffectType = CREATURE_SMOKE_EFFECT;
fBlastEffect = FALSE;
break;
}
}
// OK, here we:
// Get explosive data from table
pExplosive = &(Explosive[ Item[ usItem ].ubClassIndex ] );
uiRoll = PreRandom( 100 );
// Calculate wound amount
// HEADROCK HAM 3.6: Can now use negative modifier.
INT16 newDamage = (INT16)GetModifiedExplosiveDamage( pExplosive->ubDamage );
//INT16 newDamage = pExplosive->ubDamage + (INT16)(( pExplosive->ubDamage * gGameExternalOptions.ubExplosivesDamageMultiplier) / 100); //lal
sWoundAmt = newDamage + (INT16) ( (newDamage * uiRoll) / 100 );
// Calculate breath amount ( if stun damage applicable )
INT16 newBreath = (INT16)GetModifiedExplosiveDamage( pExplosive->ubStunDamage );
//INT16 newBreath = pExplosive->ubStunDamage + (INT16)(( pExplosive->ubStunDamage * gGameExternalOptions.ubExplosivesDamageMultiplier) / 100); //lal
sBreathAmt = ( newBreath * 100 ) + (INT16) ( ( ( newBreath / 2 ) * 100 * uiRoll ) / 100 ) ;
// ATE: Make sure guys get pissed at us!
HandleBuldingDestruction( sGridNo ,ubOwner );
if ( fBlastEffect )
{
// lower effects for distance away from center of explosion
// If radius is 3, damage % is (100)/66/33/17
// If radius is 5, damage % is (100)/80/60/40/20/10
// If radius is 8, damage % is (100)/88/75/63/50/37/25/13/6
if ( pExplosive->ubRadius == 0 )
{
// leave as is, has to be at range 0 here
}
else if (uiDist < pExplosive->ubRadius)
{
// if radius is 5, go down by 5ths ~ 20%
sWoundAmt = sWoundAmt - (INT16) (sWoundAmt * uiDist / pExplosive->ubRadius );
sBreathAmt = sBreathAmt - (INT16) (sBreathAmt * uiDist / pExplosive->ubRadius );
}
else
{
// at the edge of the explosion, do half the previous damage
sWoundAmt = (INT16) ( (sWoundAmt / pExplosive->ubRadius) / 2);
sBreathAmt = (INT16) ( (sBreathAmt / pExplosive->ubRadius) / 2);
}
if (sWoundAmt < 0)
sWoundAmt = 0;
if (sBreathAmt < 0)
sBreathAmt = 0;
// damage structures
if ( uiDist <= __max( 1, (UINT32) (newDamage / 30) ) )
{
if ( Item[ usItem ].usItemClass & IC_GRENADE )
{
sStructDmgAmt = sWoundAmt / 3;
}
else // most explosives
{
sStructDmgAmt = sWoundAmt;
}
ExplosiveDamageGridNo( sGridNo, sStructDmgAmt, uiDist, &fRecompileMovementCosts, FALSE, -1, 0 , ubOwner, bLevel );
// ATE: Look for damage to walls ONLY for next two gridnos
sNewGridNo = NewGridNo( sGridNo, DirectionInc( NORTH ) );
if ( GridNoOnVisibleWorldTile( sNewGridNo ) )
{
ExplosiveDamageGridNo( sNewGridNo, sStructDmgAmt, uiDist, &fRecompileMovementCosts, TRUE, -1, 0, ubOwner, bLevel );
}
// ATE: Look for damage to walls ONLY for next two gridnos
sNewGridNo = NewGridNo( sGridNo, DirectionInc( WEST ) );
if ( GridNoOnVisibleWorldTile( sNewGridNo ) )
{
ExplosiveDamageGridNo( sNewGridNo, sStructDmgAmt, uiDist, &fRecompileMovementCosts, TRUE, -1, 0, ubOwner, bLevel );
}
}
// Add burn marks to ground randomly....
if ( Random( 50 ) < 15 && uiDist == 1 )
{
//if ( !TypeRangeExistsInObjectLayer( sGridNo, FIRSTEXPLDEBRIS, SECONDEXPLDEBRIS, &usObjectIndex ) )
//{
// GetTileIndexFromTypeSubIndex( SECONDEXPLDEBRIS, (UINT16)( Random( 10 ) + 1 ), &usTileIndex );
// AddObjectToHead( sGridNo, usTileIndex );
// SetRenderFlags(RENDER_FLAG_FULL);
//}
}
// NB radius can be 0 so cannot divide it by 2 here
if (!fStunEffect && (uiDist * 2 <= pExplosive->ubRadius) )
{
GetItemPool( sGridNo, &pItemPool, bLevel );
while( pItemPool )
{
pItemPoolNext = pItemPool->pNext;
if ( DamageItemOnGround( &(gWorldItems[ pItemPool->iItemIndex ].object), sGridNo, bLevel, (INT32) (sWoundAmt * 2), ubOwner ) )
{
// item was destroyed
RemoveItemFromPool( sGridNo, pItemPool->iItemIndex, bLevel );
}
pItemPool = pItemPoolNext;
}
/*
// Search for an explosive item in item pool
while ( ( iWorldItem = GetItemOfClassTypeInPool( sGridNo, IC_EXPLOSV, bLevel ) ) != -1 )
{
// Get usItem
usItem = gWorldItems[ iWorldItem ].object.usItem;
DamageItem
if ( CheckForChainReaction( usItem, gWorldItems[ iWorldItem ].object[0]->data.objectStatus, sWoundAmt, TRUE ) )
{
RemoveItemFromPool( sGridNo, iWorldItem, bLevel );
// OK, Ignite this explosion!
IgniteExplosion( NOBODY, sX, sY, 0, sGridNo, usItem, bLevel );
}
else
{
RemoveItemFromPool( sGridNo, iWorldItem, bLevel );
}
}
// Remove any unburied items here!
RemoveAllUnburiedItems( sGridNo, bLevel );
*/
}
}
else if ( fSmokeEffect )
{
// If tear gar, determine turns to spread.....
if ( sSubsequent == ERASE_SPREAD_EFFECT )
{
RemoveSmokeEffectFromTile( sGridNo, bLevel );
}
else if ( sSubsequent != REDO_SPREAD_EFFECT )
{
AddSmokeEffectToTile( iSmokeEffectID, bSmokeEffectType, sGridNo, bLevel );
}
}
else
{
// Drop blood ....
// Get blood quantity....
InternalDropBlood( sGridNo, 0, 0, (UINT8)(__max( ( MAXBLOODQUANTITY - ( uiDist * 2 ) ), 0 ) ), 1 );
}
if ( sSubsequent != ERASE_SPREAD_EFFECT && sSubsequent != BLOOD_SPREAD_EFFECT )
{
// if an explosion effect....
if ( fBlastEffect )
{
// don't hurt anyone who is already dead & waiting to be removed
if ( ( ubPerson = WhoIsThere2( sGridNo, bLevel ) ) != NOBODY )
{
DamageSoldierFromBlast( ubPerson, ubOwner, sBombGridNo, sWoundAmt, sBreathAmt, uiDist, usItem, sSubsequent );
}
if ( bLevel == 1 )
{
if ( ( ubPerson = WhoIsThere2(sGridNo, 0 ) ) != NOBODY )
{
if ( (sWoundAmt / 2) > 20 )
{
// debris damage!
if ( (sBreathAmt / 2) > 20 )
{
DamageSoldierFromBlast( ubPerson, ubOwner, sBombGridNo, (INT16) Random( (sWoundAmt / 2) - 20 ), (INT16) Random( (sBreathAmt / 2) - 20 ), uiDist, usItem, sSubsequent );
}
else
{
DamageSoldierFromBlast( ubPerson, ubOwner, sBombGridNo, (INT16) Random( (sWoundAmt / 2) - 20 ), 1, uiDist, usItem, sSubsequent );
}
}
}
}
}
else
{
if ( ( ubPerson = WhoIsThere2(sGridNo, bLevel ) ) >= TOTAL_SOLDIERS )
{
return( fRecompileMovementCosts );
}
pSoldier = MercPtrs[ ubPerson ]; // someone is here, and they're gonna get hurt
fRecompileMovementCosts = DishOutGasDamage( pSoldier, pExplosive, sSubsequent, fRecompileMovementCosts, sWoundAmt, sBreathAmt, ubOwner );
/*
if (!pSoldier->bActive || !pSoldier->bInSector || !pSoldier->stats.bLife || AM_A_ROBOT( pSoldier ) )
{
return( fRecompileMovementCosts );
}
if ( pExplosive->ubType == EXPLOSV_CREATUREGAS )
{
if ( pSoldier->flags.uiStatusFlags & SOLDIER_MONSTER )
{
// unaffected by own gas effects
return( fRecompileMovementCosts );
}
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_CREATUREGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
}
else // no gas mask help from creature attacks
// ATE/CJC: gas stuff
{
INT8 bPosOfMask = NO_SLOT;
if ( pExplosive->ubType == EXPLOSV_TEARGAS )
{
// ignore whether subsequent or not if hit this turn
if ( pSoldier->flags.fHitByGasFlags & HIT_BY_TEARGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
}
else if ( pExplosive->ubType == EXPLOSV_MUSTGAS )
{
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_MUSTARDGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
}
if ( sSubsequent && pSoldier->flags.fHitByGasFlags & HIT_BY_CREATUREGAS )
{
// already affected by creature gas this turn
return( fRecompileMovementCosts );
}
if ( pSoldier->inv[ HEAD1POS ].usItem == GASMASK && pSoldier->inv[ HEAD1POS ][0]->data.objectStatus >= USABLE )
{
bPosOfMask = HEAD1POS;
}
else if ( pSoldier->inv[ HEAD2POS ].usItem == GASMASK && pSoldier->inv[ HEAD2POS ][0]->data.objectStatus >= USABLE )
{
bPosOfMask = HEAD2POS;
}
if ( bPosOfMask != NO_SLOT )
{
if ( pSoldier->inv[ bPosOfMask ][0]->data.objectStatus < GASMASK_MIN_STATUS )
{
// GAS MASK reduces breath loss by its work% (it leaks if not at least 70%)
sBreathAmt = ( sBreathAmt * ( 100 - pSoldier->inv[ bPosOfMask ][0]->data.objectStatus ) ) / 100;
if ( sBreathAmt > 500 )
{
// if at least 500 of breath damage got through
// the soldier within the blast radius is gassed for at least one
// turn, possibly more if it's tear gas (which hangs around a while)
pSoldier->flags.uiStatusFlags |= SOLDIER_GASSED;
}
if ( sWoundAmt > 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus -= (INT8) Random( 4 );
sWoundAmt = ( sWoundAmt * ( 100 - pSoldier->inv[ bPosOfMask ][0]->data.objectStatus ) ) / 100;
}
else if ( sWoundAmt == 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus -= (INT8) Random( 2 );
}
}
else
{
sBreathAmt = 0;
if ( sWoundAmt > 0 )
{
if ( sWoundAmt == 1 )
{
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus -= (INT8) Random( 2 );
}
else
{
// use up gas mask
pSoldier->inv[ bPosOfMask ][0]->data.objectStatus -= (INT8) Random( 4 );
}
}
sWoundAmt = 0;
}
}
}
if ( sWoundAmt != 0 || sBreathAmt != 0 )
{
switch( pExplosive->ubType )
{
case EXPLOSV_CREATUREGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_CREATUREGAS;
break;
case EXPLOSV_TEARGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_TEARGAS;
break;
case EXPLOSV_MUSTGAS:
pSoldier->flags.fHitByGasFlags |= HIT_BY_MUSTARDGAS;
break;
default:
break;
}
// a gas effect, take damage directly...
pSoldier->SoldierTakeDamage( ANIM_STAND, sWoundAmt, sBreathAmt, TAKE_DAMAGE_GAS, NOBODY, NOWHERE, 0, TRUE );
if ( pSoldier->stats.bLife >= CONSCIOUSNESS )
{
pSoldier->DoMercBattleSound( (INT8)( BATTLE_SOUND_HIT1 + Random( 2 ) ) );
}
}
*/
}
(*pfMercHit) = TRUE;
}
return( fRecompileMovementCosts );
}
void GetRayStopInfo( UINT32 uiNewSpot, UINT8 ubDir, INT8 bLevel, BOOLEAN fSmokeEffect, INT32 uiCurRange, INT32 *piMaxRange, UINT8 *pubKeepGoing )
{
INT8 bStructHeight;
UINT8 ubMovementCost;
INT8 Blocking, BlockingTemp;
BOOLEAN fTravelCostObs = FALSE;
UINT32 uiRangeReduce;
INT32 sNewGridNo;
STRUCTURE * pBlockingStructure;
BOOLEAN fBlowWindowSouth = FALSE;
BOOLEAN fReduceRay = TRUE;
ubMovementCost = gubWorldMovementCosts[ uiNewSpot ][ ubDir ][ bLevel ];
if ( IS_TRAVELCOST_DOOR( ubMovementCost ) )
{
ubMovementCost = DoorTravelCost( NULL, uiNewSpot, ubMovementCost, FALSE, NULL );
// If we have hit a wall, STOP HERE
if (ubMovementCost >= TRAVELCOST_BLOCKED)
{
fTravelCostObs = TRUE;
}
}
else
{
// If we have hit a wall, STOP HERE
if ( ubMovementCost == TRAVELCOST_WALL )
{
// We have an obstacle here..
fTravelCostObs = TRUE;
}
}
Blocking = GetBlockingStructureInfo( uiNewSpot, ubDir, 0, bLevel, &bStructHeight, &pBlockingStructure, TRUE );//dnl ch53 111009
if ( pBlockingStructure )
{
if ( pBlockingStructure->fFlags & STRUCTURE_CAVEWALL )
{
// block completely!
fTravelCostObs = TRUE;
}
else if ( pBlockingStructure->pDBStructureRef->pDBStructure->ubDensity <= 15 )
{
// not stopped
fTravelCostObs = FALSE;
fReduceRay = FALSE;
}
}
// ATE: For smoke, don't let it go over roof....
// 0verhaul: Why not?
if ( fSmokeEffect )
{
if ( bLevel )
{
STRUCTURE * pStructure;
// Check for roof here....
pStructure = FindStructure( uiNewSpot, STRUCTURE_ROOF );
if ( pStructure == NULL )
{
// block completely!
fTravelCostObs = TRUE;
}
}
}
if ( fTravelCostObs )
{
if ( fSmokeEffect )
{
if ( Blocking == BLOCKING_TOPRIGHT_OPEN_WINDOW || Blocking == BLOCKING_TOPLEFT_OPEN_WINDOW )
{
// If open, fTravelCostObs set to false and reduce range....
fTravelCostObs = FALSE;
// Range will be reduced below...
}
if ( fTravelCostObs )
{
// ATE: For windows, check to the west and north for a broken window, as movement costs
// will override there...
sNewGridNo = NewGridNo( uiNewSpot, DirectionInc( WEST ) );
BlockingTemp = GetBlockingStructureInfo( sNewGridNo, ubDir, 0, bLevel, &bStructHeight, &pBlockingStructure, TRUE );
if ( BlockingTemp == BLOCKING_TOPRIGHT_OPEN_WINDOW || BlockingTemp == BLOCKING_TOPLEFT_OPEN_WINDOW )
{
// If open, fTravelCostObs set to false and reduce range....
fTravelCostObs = FALSE;
// Range will be reduced below...
}
if ( pBlockingStructure && pBlockingStructure->pDBStructureRef->pDBStructure->ubDensity <= 15 )
{
fTravelCostObs = FALSE;
fReduceRay = FALSE;
}
}
if ( fTravelCostObs )
{
sNewGridNo = NewGridNo( uiNewSpot, DirectionInc( NORTH ) );
BlockingTemp = GetBlockingStructureInfo( sNewGridNo, ubDir, 0, bLevel, &bStructHeight, &pBlockingStructure, TRUE );
if ( BlockingTemp == BLOCKING_TOPRIGHT_OPEN_WINDOW || BlockingTemp == BLOCKING_TOPLEFT_OPEN_WINDOW )
{
// If open, fTravelCostObs set to false and reduce range....
fTravelCostObs = FALSE;
// Range will be reduced below...
}
if ( pBlockingStructure && pBlockingStructure->pDBStructureRef->pDBStructure->ubDensity <= 15 )
{
fTravelCostObs = FALSE;
fReduceRay = FALSE;
}
}
}
else
{
// We are a blast effect....
// ATE: explode windows!!!!
if ( Blocking == BLOCKING_TOPLEFT_WINDOW || Blocking == BLOCKING_TOPRIGHT_WINDOW )
{
// Explode!
if ( ubDir == SOUTH || ubDir == SOUTHEAST || ubDir == SOUTHWEST )
{
fBlowWindowSouth = TRUE;
}
if ( pBlockingStructure != NULL )
{
WindowHit( uiNewSpot, pBlockingStructure->usStructureID, fBlowWindowSouth, TRUE );
}
}
// ATE: For windows, check to the west and north for a broken window, as movement costs
// will override there...
sNewGridNo = NewGridNo( uiNewSpot, DirectionInc( WEST ) );
BlockingTemp = GetBlockingStructureInfo( sNewGridNo, ubDir, 0, bLevel, &bStructHeight, &pBlockingStructure , TRUE );
if ( pBlockingStructure && pBlockingStructure->pDBStructureRef->pDBStructure->ubDensity <= 15 )
{
fTravelCostObs = FALSE;
fReduceRay = FALSE;
}
if ( BlockingTemp == BLOCKING_TOPRIGHT_WINDOW || BlockingTemp == BLOCKING_TOPLEFT_WINDOW )
{
if ( pBlockingStructure != NULL )
{
WindowHit( sNewGridNo, pBlockingStructure->usStructureID, FALSE, TRUE );
}
}
sNewGridNo = NewGridNo( uiNewSpot, DirectionInc( NORTH ) );
BlockingTemp = GetBlockingStructureInfo( sNewGridNo, ubDir, 0, bLevel, &bStructHeight, &pBlockingStructure, TRUE );
if ( pBlockingStructure && pBlockingStructure->pDBStructureRef->pDBStructure->ubDensity <= 15 )
{
fTravelCostObs = FALSE;
fReduceRay = FALSE;
}
if ( BlockingTemp == BLOCKING_TOPRIGHT_WINDOW || BlockingTemp == BLOCKING_TOPLEFT_WINDOW )
{
if ( pBlockingStructure != NULL )
{
WindowHit( sNewGridNo, pBlockingStructure->usStructureID, FALSE, TRUE );
}
}
}
}
// Have we hit things like furniture, etc?
if ( Blocking != NOTHING_BLOCKING && !fTravelCostObs )
{
// ATE: Tall things should blaock all
if ( bStructHeight == 4 )
{
(*pubKeepGoing) = FALSE;
}
else
{
// If we are smoke, reduce range variably....
if ( fReduceRay )
{
if ( fSmokeEffect )
{
switch( bStructHeight )
{
case 3:
uiRangeReduce = 2;
break;
case 2:
uiRangeReduce = 1;
break;
default:
uiRangeReduce = 0;
break;
}
}
else
{
uiRangeReduce = 2;
}
( *piMaxRange ) -= uiRangeReduce;
}
if ( uiCurRange <= (*piMaxRange) )
{
(*pubKeepGoing) = TRUE;
}
else
{
(*pubKeepGoing) = FALSE;
}
}
}
else
{
if ( fTravelCostObs )
{
( *pubKeepGoing ) = FALSE;
}
else
{
( *pubKeepGoing ) = TRUE;
}
}
}
void SpreadEffect( INT32 sGridNo, UINT8 ubRadius, UINT16 usItem, UINT8 ubOwner, BOOLEAN fSubsequent, INT8 bLevel, INT32 iSmokeEffectID , BOOL fFromRemoteClient , BOOL fNewSmokeEffect )
{
if (is_networked && is_client)
{
SOLDIERTYPE* pAttacker = MercPtrs[ubOwner];
if (pAttacker != NULL)
{
if (IsOurSoldier(pAttacker) || (pAttacker->bTeam == 1 && is_server))
{
// dont send SpreadEffect if it was just called from NewSmokeEffect - as now we sync that seperately
if (!fNewSmokeEffect)
{
// let all the other clients know we are spawning this effect
// and align them with our random number generator
send_spreadeffect(sGridNo,ubRadius,usItem,ubOwner,fSubsequent,bLevel,iSmokeEffectID);
}
}
else if (!fFromRemoteClient)
{
// skip executing locally because we want the random number generator to be aligned
// with the client that spawns set off the explosion/grenade/whatever
return;
}
}
#ifdef JA2BETAVERSION
CHAR tmpMPDbgString[512];
sprintf(tmpMPDbgString,"SpreadEffect ( sGridNo : %i , ubRadius : %i , usItem : %i , ubOwner : %i , fSubsequent : %i , bLevel : %i , iSmokeEffectID : %i , fFromRemote : %i , fNewSmoke : %i )\n",sGridNo, ubRadius , usItem , ubOwner , (int)fSubsequent , bLevel , iSmokeEffectID , fFromRemoteClient , fNewSmokeEffect );
MPDebugMsg(tmpMPDbgString);
gfMPDebugOutputRandoms = true;
#endif
}
INT32 uiNewSpot, uiTempSpot, uiBranchSpot, cnt, branchCnt;
INT32 uiTempRange, ubBranchRange;
UINT8 ubDir,ubBranchDir, ubKeepGoing;
INT16 sRange;
BOOLEAN fRecompileMovement = FALSE;
BOOLEAN fAnyMercHit = FALSE;
BOOLEAN fSmokeEffect = FALSE;
switch( Explosive[Item[usItem].ubClassIndex].ubType )
{
case EXPLOSV_MUSTGAS:
case EXPLOSV_BURNABLEGAS:
case EXPLOSV_TEARGAS:
case EXPLOSV_SMOKE:
case EXPLOSV_CREATUREGAS:
fSmokeEffect = TRUE;
break;
}
/*if(is_networked)
{
ScreenMsg( FONT_LTBLUE, MSG_MPSYSTEM, L"explosives not coded in MP");
return;
}*/
// Set values for recompile region to optimize area we need to recompile for MPs
gsRecompileAreaTop = sGridNo / WORLD_COLS;
gsRecompileAreaLeft = sGridNo % WORLD_COLS;
gsRecompileAreaRight = gsRecompileAreaLeft;
gsRecompileAreaBottom = gsRecompileAreaTop;
// multiply range by 2 so we can correctly calculate approximately round explosion regions
sRange = ubRadius * 2;
// first, affect main spot
if ( ExpAffect( sGridNo, sGridNo, 0, usItem, ubOwner, fSubsequent, &fAnyMercHit, bLevel, iSmokeEffectID ) )
{
fRecompileMovement = TRUE;
}
for (ubDir = NORTH; ubDir <= NORTHWEST; ubDir++ )
{
uiTempSpot = sGridNo;
uiTempRange = sRange;
if (ubDir & 1)
{
cnt = 3;
}
else
{
cnt = 2;
}
while( cnt <= uiTempRange) // end of range loop
{
// move one tile in direction
uiNewSpot = NewGridNo( uiTempSpot, DirectionInc( ubDir ) );
// see if this was a different spot & if we should be able to reach
// this spot
if (uiNewSpot == uiTempSpot)
{
ubKeepGoing = FALSE;
}
else
{
// Check if struct is a tree, etc and reduce range...
GetRayStopInfo( uiNewSpot, ubDir, bLevel, fSmokeEffect, cnt, &uiTempRange, &ubKeepGoing );
}
if (ubKeepGoing)
{
uiTempSpot = uiNewSpot;
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Explosion affects %d", uiNewSpot) );
// ok, do what we do here...
if ( ExpAffect( sGridNo, uiNewSpot, cnt / 2, usItem, ubOwner, fSubsequent, &fAnyMercHit, bLevel, iSmokeEffectID ) )
{
fRecompileMovement = TRUE;
}
// how far should we branch out here?
ubBranchRange = (UINT8)( sRange - cnt );
if ( ubBranchRange )
{
// ok, there's a branch here. Mark where we start this branch.
uiBranchSpot = uiNewSpot;
// figure the branch direction - which is one dir clockwise
ubBranchDir = (ubDir + 1) % 8;
if (ubBranchDir & 1)
{
branchCnt = 3;
}
else
{
branchCnt = 2;
}
while( branchCnt <= ubBranchRange) // end of range loop
{
ubKeepGoing = TRUE;
uiNewSpot = NewGridNo( uiBranchSpot, DirectionInc(ubBranchDir));
if (uiNewSpot != uiBranchSpot)
{
// Check if struct is a tree, etc and reduce range...
GetRayStopInfo( uiNewSpot, ubBranchDir, bLevel, fSmokeEffect, branchCnt, &ubBranchRange, &ubKeepGoing );
if ( ubKeepGoing )
{
// ok, do what we do here
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Explosion affects %d", uiNewSpot) );
if ( ExpAffect( sGridNo, uiNewSpot, (INT16)((cnt + branchCnt) / 2), usItem, ubOwner, fSubsequent, &fAnyMercHit, bLevel, iSmokeEffectID ) )
{
fRecompileMovement = TRUE;
}
uiBranchSpot = uiNewSpot;
}
//else
{
// check if it's ANY door, and if so, affect that spot so it's damaged
// if (RealDoorAt(uiNewSpot))
// {
// ExpAffect(sGridNo,uiNewSpot,cnt,ubReason,fSubsequent);
// }
// blocked, break out of the the sub-branch loop
// break;
}
}
if (ubBranchDir & 1)
{
branchCnt += 3;
}
else
{
branchCnt += 2;
}
}
} // end of if a branch to do
}
else // at edge, or tile blocks further spread in that direction
{
break;
}
if (ubDir & 1)
{
cnt += 3;
}
else
{
cnt += 2;
}
}
} // end of dir loop
// Recompile movement costs...
if ( fRecompileMovement )
{
INT16 sX, sY;
// DO wireframes as well
ConvertGridNoToXY( sGridNo, &sX, &sY );
SetRecalculateWireFrameFlagRadius( sX, sY, ubRadius );
CalculateWorldWireFrameTiles( FALSE );
RecompileLocalMovementCostsInAreaWithFlags();
RecompileLocalMovementCostsFromRadius( sGridNo, MAX_DISTANCE_EXPLOSIVE_CAN_DESTROY_STRUCTURES );
// if anything has been done to change movement costs and this is a potential POW situation, check
// paths for POWs
if ( gWorldSectorX == 13 && gWorldSectorY == MAP_ROW_I )
{
DoPOWPathChecks();
}
}
// do sight checks if something damaged or smoke stuff involved
if ( fRecompileMovement || fSmokeEffect )
{
if ( gubElementsOnExplosionQueue )
{
gfExplosionQueueMayHaveChangedSight = TRUE;
}
}
gsRecompileAreaTop = 0;
gsRecompileAreaLeft = 0;
gsRecompileAreaRight = 0;
gsRecompileAreaBottom = 0;
if (fAnyMercHit)
{
// reset explosion hit flag so we can damage mercs again
for ( cnt = 0; cnt < (INT32)guiNumMercSlots; cnt++ )
{
if ( MercSlots[ cnt ] )
{
MercSlots[ cnt ]->ubMiscSoldierFlags &= ~SOLDIER_MISC_HURT_BY_EXPLOSION;
}
}
}
if ( fSubsequent != BLOOD_SPREAD_EFFECT )
{
MakeNoise( NOBODY, sGridNo, bLevel, gpWorldLevelData[sGridNo].ubTerrainID, (UINT8)Explosive[ Item [ usItem ].ubClassIndex ].ubVolume, NOISE_EXPLOSION );
}
gfMPDebugOutputRandoms = false;
}
void ToggleActionItemsByFrequency( INT8 bFrequency )
{
UINT32 uiWorldBombIndex;
OBJECTTYPE * pObj;
// Go through all the bombs in the world, and look for remote ones
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists)
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( (*pObj)[0]->data.misc.bDetonatorType == BOMB_REMOTE )
{
// Found a remote bomb, so check to see if it has the same frequency
if ((*pObj)[0]->data.misc.bFrequency == bFrequency)
{
// toggle its active flag
if ((*pObj).fFlags & OBJECT_DISABLED_BOMB)
{
(*pObj).fFlags &= (~OBJECT_DISABLED_BOMB);
}
else
{
(*pObj).fFlags |= OBJECT_DISABLED_BOMB;
}
}
}
}
}
}
void TogglePressureActionItemsInGridNo( INT32 sGridNo )
{
UINT32 uiWorldBombIndex;
OBJECTTYPE * pObj;
// Go through all the bombs in the world, and look for remote ones
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if ( gWorldBombs[uiWorldBombIndex].fExists && gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].sGridNo == sGridNo )
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( (*pObj)[0]->data.misc.bDetonatorType == BOMB_PRESSURE )
{
// Found a pressure item
// toggle its active flag
if ((*pObj).fFlags & OBJECT_DISABLED_BOMB)
{
(*pObj).fFlags &= (~OBJECT_DISABLED_BOMB);
}
else
{
(*pObj).fFlags |= OBJECT_DISABLED_BOMB;
}
}
}
}
}
void DelayedBillyTriggerToBlockOnExit( void )
{
if ( WhoIsThere2( gsTempActionGridNo, 0 ) == NOBODY )
{
TriggerNPCRecord( BILLY, 6 );
}
else
{
// delay further!
SetCustomizableTimerCallbackAndDelay( 1000, DelayedBillyTriggerToBlockOnExit, TRUE );
}
}
void BillyBlocksDoorCallback( void )
{
TriggerNPCRecord( BILLY, 6 );
}
BOOLEAN HookerInRoom( UINT8 ubRoom )
{
UINT8 ubLoop, ubTempRoom;
SOLDIERTYPE * pSoldier;
for ( ubLoop = gTacticalStatus.Team[ CIV_TEAM ].bFirstID; ubLoop <= gTacticalStatus.Team[ CIV_TEAM ].bLastID; ubLoop++ )
{
pSoldier = MercPtrs[ ubLoop ];
if ( pSoldier->bActive && pSoldier->bInSector && pSoldier->stats.bLife >= OKLIFE && pSoldier->aiData.bNeutral && pSoldier->ubBodyType == MINICIV )
{
if ( InARoom( pSoldier->sGridNo, &ubTempRoom ) && ubTempRoom == ubRoom )
{
return( TRUE );
}
}
}
return( FALSE );
}
void PerformItemAction( INT32 sGridNo, OBJECTTYPE * pObj )
{
#if 0
STRUCTURE * pStructure;
#endif
UINT32 i;
for (i = ACTION_ITEM_OPEN_DOOR; i <= ACTION_ITEM_NEW; i++ )
{
if ( (*pObj)[0]->data.misc.bActionValue == i )
LetLuaPerformItemAction( i, sGridNo, 0 );
}
#if 0
switch( (*pObj)[0]->data.misc.bActionValue )
{
case ACTION_ITEM_OPEN_DOOR:
pStructure = FindStructure( sGridNo, STRUCTURE_ANYDOOR );
if (pStructure)
{
if (pStructure->fFlags & STRUCTURE_OPEN)
{
// it's already open - this MIGHT be an error but probably not
// because we are basically just ensuring that the door is open
}
else
{
if (pStructure->fFlags & STRUCTURE_BASE_TILE)
{
HandleDoorChangeFromGridNo( NULL, sGridNo, FALSE );
}
else
{
HandleDoorChangeFromGridNo( NULL, pStructure->sBaseGridNo, FALSE );
}
gfExplosionQueueMayHaveChangedSight = TRUE;
}
}
else
{
// error message here
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Action item to open door in gridno %d but there is none!", sGridNo );
#endif
}
break;
case ACTION_ITEM_CLOSE_DOOR:
pStructure = FindStructure( sGridNo, STRUCTURE_ANYDOOR );
if (pStructure)
{
if (pStructure->fFlags & STRUCTURE_OPEN)
{
if (pStructure->fFlags & STRUCTURE_BASE_TILE)
{
HandleDoorChangeFromGridNo( NULL, sGridNo , FALSE );
}
else
{
HandleDoorChangeFromGridNo( NULL, pStructure->sBaseGridNo, FALSE );
}
gfExplosionQueueMayHaveChangedSight = TRUE;
}
else
{
// it's already closed - this MIGHT be an error but probably not
// because we are basically just ensuring that the door is closed
}
}
else
{
// error message here
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Action item to close door in gridno %d but there is none!", sGridNo );
#endif
}
break;
case ACTION_ITEM_TOGGLE_DOOR:
pStructure = FindStructure( sGridNo, STRUCTURE_ANYDOOR );
if (pStructure)
{
if (pStructure->fFlags & STRUCTURE_BASE_TILE)
{
HandleDoorChangeFromGridNo( NULL, sGridNo, FALSE );
}
else
{
HandleDoorChangeFromGridNo( NULL, pStructure->sBaseGridNo , FALSE );
}
gfExplosionQueueMayHaveChangedSight = TRUE;
}
else
{
// error message here
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_TESTVERSION, L"Action item to toggle door in gridno %d but there is none!", sGridNo );
#endif
}
break;
case ACTION_ITEM_UNLOCK_DOOR:
{
DOOR * pDoor;
pDoor = FindDoorInfoAtGridNo( sGridNo );
if ( pDoor )
{
pDoor->fLocked = FALSE;
}
}
break;
case ACTION_ITEM_TOGGLE_LOCK:
{
DOOR * pDoor;
pDoor = FindDoorInfoAtGridNo( sGridNo );
if ( pDoor )
{
if ( pDoor->fLocked )
{
pDoor->fLocked = FALSE;
}
else
{
pDoor->fLocked = TRUE;
}
}
}
break;
case ACTION_ITEM_UNTRAP_DOOR:
{
DOOR * pDoor;
pDoor = FindDoorInfoAtGridNo( sGridNo );
if ( pDoor )
{
pDoor->ubTrapLevel = 0;
pDoor->ubTrapID = NO_TRAP;
}
}
break;
case ACTION_ITEM_SMALL_PIT:
Add3X3Pit( sGridNo );
SearchForOtherMembersWithinPitRadiusAndMakeThemFall( sGridNo, 1 );
break;
case ACTION_ITEM_LARGE_PIT:
Add5X5Pit( sGridNo );
SearchForOtherMembersWithinPitRadiusAndMakeThemFall( sGridNo, 2 );
break;
case ACTION_ITEM_TOGGLE_ACTION1:
ToggleActionItemsByFrequency( FIRST_MAP_PLACED_FREQUENCY + 1 );
break;
case ACTION_ITEM_TOGGLE_ACTION2:
ToggleActionItemsByFrequency( FIRST_MAP_PLACED_FREQUENCY + 2 );
break;
case ACTION_ITEM_TOGGLE_ACTION3:
ToggleActionItemsByFrequency( FIRST_MAP_PLACED_FREQUENCY + 3 );
break;
case ACTION_ITEM_TOGGLE_ACTION4:
ToggleActionItemsByFrequency( FIRST_MAP_PLACED_FREQUENCY + 4 );
break;
case ACTION_ITEM_TOGGLE_PRESSURE_ITEMS:
TogglePressureActionItemsInGridNo( sGridNo );
break;
case ACTION_ITEM_ENTER_BROTHEL:
// JA2Gold: Disable brothel tracking
/*
if ( ! (gTacticalStatus.uiFlags & INCOMBAT) )
{
UINT8 ubID;
ubID = WhoIsThere2( sGridNo, 0 );
if ( (ubID != NOBODY) && (MercPtrs[ ubID ]->bTeam == gbPlayerNum) )
{
if ( MercPtrs[ ubID ]->sOldGridNo == sGridNo + DirectionInc( SOUTH ) )
{
gMercProfiles[ MADAME ].bNPCData2++;
SetFactTrue( FACT_PLAYER_USED_BROTHEL );
SetFactTrue( FACT_PLAYER_PASSED_GOON );
// If we for any reason trigger Madame's record 34 then we don't bother to do
// anything else
// Billy always moves back on a timer so that the player has a chance to sneak
// someone else through
// Madame's quote about female mercs should therefore not be made on a timer
if ( gMercProfiles[ MADAME ].bNPCData2 > 2 )
{
// more than 2 entering brothel
TriggerNPCRecord( MADAME, 35 );
return;
}
if ( gMercProfiles[ MADAME ].bNPCData2 == gMercProfiles[ MADAME ].bNPCData )
{
// full # of mercs who paid have entered brothel
// have Billy block the way again
SetCustomizableTimerCallbackAndDelay( 2000, BillyBlocksDoorCallback, FALSE );
//TriggerNPCRecord( BILLY, 6 );
}
else if ( gMercProfiles[ MADAME ].bNPCData2 > gMercProfiles[ MADAME ].bNPCData )
{
// more than full # of mercs who paid have entered brothel
// have Billy block the way again?
if ( CheckFact( FACT_PLAYER_FORCED_WAY_INTO_BROTHEL, 0 ) )
{
// player already did this once!
TriggerNPCRecord( MADAME, 35 );
return;
}
else
{
SetCustomizableTimerCallbackAndDelay( 2000, BillyBlocksDoorCallback, FALSE );
SetFactTrue( FACT_PLAYER_FORCED_WAY_INTO_BROTHEL );
TriggerNPCRecord( MADAME, 34 );
}
}
if ( gMercProfiles[ MercPtrs[ ubID ]->ubProfile ].bSex == FEMALE )
{
// woman walking into brothel
TriggerNPCRecordImmediately( MADAME, 33 );
}
}
else
{
// someone wants to leave the brothel
TriggerNPCRecord( BILLY, 5 );
}
}
}
*/
break;
case ACTION_ITEM_EXIT_BROTHEL:
// JA2Gold: Disable brothel tracking
/*
if ( ! (gTacticalStatus.uiFlags & INCOMBAT) )
{
UINT8 ubID;
ubID = WhoIsThere2( sGridNo, 0 );
if ( (ubID != NOBODY) && (MercPtrs[ ubID ]->bTeam == gbPlayerNum) && MercPtrs[ ubID ]->sOldGridNo == sGridNo + DirectionInc( NORTH ) )
{
gMercProfiles[ MADAME ].bNPCData2--;
if ( gMercProfiles[ MADAME ].bNPCData2 == 0 )
{
// reset paid #
gMercProfiles[ MADAME ].bNPCData = 0;
}
// Billy should move back to block the door again
gsTempActionGridNo = sGridNo;
SetCustomizableTimerCallbackAndDelay( 1000, DelayedBillyTriggerToBlockOnExit, TRUE );
}
}
*/
break;
case ACTION_ITEM_KINGPIN_ALARM:
PlayJA2Sample( KLAXON_ALARM, RATE_11025, SoundVolume( MIDVOLUME, sGridNo ), 5, SoundDir( sGridNo ) );
CallAvailableKingpinMenTo( sGridNo );
gTacticalStatus.fCivGroupHostile[ KINGPIN_CIV_GROUP ] = CIV_GROUP_HOSTILE;
{
UINT8 ubID, ubID2;
BOOLEAN fEnterCombat = FALSE;
for ( ubID = gTacticalStatus.Team[ CIV_TEAM ].bFirstID; ubID <= gTacticalStatus.Team[ CIV_TEAM ].bLastID; ubID++ )
{
if ( MercPtrs[ ubID ]->bActive && MercPtrs[ ubID ]->bInSector && MercPtrs[ ubID ]->ubCivilianGroup == KINGPIN_CIV_GROUP )
{
for ( ubID2 = gTacticalStatus.Team[ gbPlayerNum ].bFirstID; ubID2 <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubID2++ )
{
if ( MercPtrs[ ubID ]->aiData.bOppList[ ubID2 ] == SEEN_CURRENTLY )
{
MakeCivHostile( MercPtrs[ ubID ], 2 );
fEnterCombat = TRUE;
}
}
}
}
if ( ! (gTacticalStatus.uiFlags & INCOMBAT) )
{
EnterCombatMode( CIV_TEAM );
}
}
// now zap this object so it won't activate again
(*pObj).fFlags &= (~OBJECT_DISABLED_BOMB);
break;
case ACTION_ITEM_SEX:
// JA2Gold: Disable brothel sex Madd: Re-enabled
if ( ! (gTacticalStatus.uiFlags & INCOMBAT) )
{
UINT8 ubID;
OBJECTTYPE DoorCloser;
INT16 sTeleportSpot;
INT16 sDoorSpot;
UINT8 ubDirection;
UINT8 ubRoom, ubOldRoom;
ubID = WhoIsThere2( sGridNo, 0 );
if ( (ubID != NOBODY) && (MercPtrs[ ubID ]->bTeam == gbPlayerNum) )
{
if ( InARoom( sGridNo, &ubRoom ) && InARoom( MercPtrs[ ubID ]->sOldGridNo, &ubOldRoom ) && ubOldRoom != ubRoom )
{
// also require there to be a miniskirt civ in the room
if ( HookerInRoom( ubRoom ) )
{
// stop the merc...
MercPtrs[ ubID ]->EVENT_StopMerc( MercPtrs[ ubID ]->sGridNo, MercPtrs[ ubID ]->ubDirection );
switch( sGridNo )
{
case 13414:
sDoorSpot = 13413;
sTeleportSpot = 13413;
break;
case 11174:
sDoorSpot = 11173;
sTeleportSpot = 11173;
break;
case 12290:
sDoorSpot = 12290;
sTeleportSpot = 12291;
break;
default:
sDoorSpot = NOWHERE;
sTeleportSpot = NOWHERE;
}
if (!TileIsOutOfBounds(sDoorSpot) && !TileIsOutOfBounds(sTeleportSpot) )
{
// close the door...
DoorCloser[0]->data.misc.bActionValue = ACTION_ITEM_CLOSE_DOOR;
PerformItemAction( sDoorSpot, &DoorCloser );
// have sex
HandleNPCDoAction( 0, NPC_ACTION_SEX, 0 );
// move the merc outside of the room again
sTeleportSpot = FindGridNoFromSweetSpotWithStructData( MercPtrs[ ubID ], STANDING, sTeleportSpot, 2, &ubDirection, FALSE );
MercPtrs[ ubID ]->ChangeSoldierState( STANDING, 0, TRUE );
TeleportSoldier( MercPtrs[ ubID ], sTeleportSpot, FALSE );
HandleMoraleEvent( MercPtrs[ ubID ], MORALE_SEX, gWorldSectorX, gWorldSectorY, gbWorldSectorZ );
FatigueCharacter( MercPtrs[ ubID ] );
FatigueCharacter( MercPtrs[ ubID ] );
FatigueCharacter( MercPtrs[ ubID ] );
FatigueCharacter( MercPtrs[ ubID ] );
DirtyMercPanelInterface( MercPtrs[ ubID ], DIRTYLEVEL1 );
}
}
}
break;
}
}
break;
case ACTION_ITEM_REVEAL_ROOM:
{
UINT8 ubRoom;
if ( InAHiddenRoom( sGridNo, &ubRoom ) )
{
RemoveRoomRoof( sGridNo, ubRoom, NULL );
}
}
break;
case ACTION_ITEM_LOCAL_ALARM:
MakeNoise( NOBODY, sGridNo, 0, gpWorldLevelData[sGridNo].ubTerrainID, 30, NOISE_SILENT_ALARM );
break;
case ACTION_ITEM_GLOBAL_ALARM:
CallAvailableEnemiesTo( sGridNo );
break;
case ACTION_ITEM_BLOODCAT_ALARM:
CallAvailableTeamEnemiesTo( sGridNo, CREATURE_TEAM );
break;
case ACTION_ITEM_KLAXON:
PlayJA2Sample( KLAXON_ALARM, RATE_11025, SoundVolume( MIDVOLUME, sGridNo ), 5, SoundDir( sGridNo ) );
break;
case ACTION_ITEM_MUSEUM_ALARM:
PlayJA2Sample( KLAXON_ALARM, RATE_11025, SoundVolume( MIDVOLUME, sGridNo ), 5, SoundDir( sGridNo ) );
CallEldinTo( sGridNo );
break;
#ifdef JA2UB
case ACTION_ITEM_BIGGENS_BOMBS:
if( ShouldThePlayerStopWhenWalkingOnBiggensActionItem( 17 ) )
{
HavePersonAtGridnoStop( sGridNo );
//Make Biggens run for cover and then detonate the explosives
TriggerNPCRecord( 61 , 17 ); //BIGGENS
}
break;
case ACTION_ITEM_BIGGENS_WARNING:
if( ShouldThePlayerStopWhenWalkingOnBiggensActionItem( 16 ) )
{
HavePersonAtGridnoStop( sGridNo );
//Have Biggens spit out a warning about the bombs
TriggerNPCRecord( 61, 16 ); //BIGGENS
}
break;
case ACTION_ITEM_SEE_FORTIFIED_DOOR:
HandleSeeingFortifiedDoor( sGridNo );
break;
case ACTION_ITEM_OPEN_FORTIFED_DOOR:
HandleSwitchToOpenFortifiedDoor( sGridNo );
break;
case ACTION_ITEM_SEE_POWER_GEN_FAN:
//if the player is in the power plant
if( gWorldSectorX == 13 && gWorldSectorY == 10 && gbWorldSectorZ == 0 )
{
HandleSeeingPowerGenFan( sGridNo );
}
else if( gWorldSectorX == 15 && gWorldSectorY == 12 && gbWorldSectorZ == 3 )
{
//The player is hitting the switch to launch the missles
HandlePlayerHittingSwitchToLaunchMissles();
}
break;
#endif
default:
// error message here
#ifdef JA2BETAVERSION
ScreenMsg( FONT_MCOLOR_LTYELLOW, MSG_BETAVERSION, L"Action item with invalid action in gridno %d!", sGridNo );
#endif
break;
}
#endif
}
void AddBombToQueue( UINT32 uiWorldBombIndex, UINT32 uiTimeStamp, BOOL fFromRemoteClient )
{
if (gubElementsOnExplosionQueue == MAX_BOMB_QUEUE)
{
return;
}
// 20091002 - OJW - MP Explosives
if (is_networked && is_client)
{
/*if (gWorldBombs[uiWorldBombIndex].bIsFromRemotePlayer && !fFromRemoteClient)
{
return;
}
else
{
// this is the world item index
UINT32 iWorldIndex = gWorldBombs[uiWorldBombIndex].iItemIndex;
WORLDITEM wi = gWorldItems[iWorldIndex];
if (wi.fExists)
{
INT8 soldierID = wi.soldierID;
if (soldierID == -1)
soldierID = wi.object[0]->data.misc.ubBombOwner - 2; // undo the hack
send_detonate_explosive(iWorldIndex,soldierID);
}
}*/
UINT32 iWorldIndex = gWorldBombs[uiWorldBombIndex].iItemIndex;
WORLDITEM wi = gWorldItems[iWorldIndex];
if (wi.fExists)
{
INT8 soldierID = wi.soldierID; // bomb's owner
if (soldierID == -1)
soldierID = wi.object[0]->data.misc.ubBombOwner - 2; // undo the hack
if (IsOurSoldier(gubPersonToSetOffExplosions) || IsOurSoldier(soldierID))
{
// we set off the bomb (could be failed disarm) or we own it, tell the other clients we are setting it off
send_detonate_explosive(iWorldIndex,gubPersonToSetOffExplosions);
}
else if (gWorldBombs[uiWorldBombIndex].bIsFromRemotePlayer && !fFromRemoteClient)
{
return; // dont explode bombs which arent originating from our client unless we were told to
}
}
}
gExplosionQueue[gubElementsOnExplosionQueue].uiWorldBombIndex = uiWorldBombIndex;
gExplosionQueue[gubElementsOnExplosionQueue].uiTimeStamp = uiTimeStamp;
gExplosionQueue[gubElementsOnExplosionQueue].fExists = TRUE;
if (!gfExplosionQueueActive)
{
// lock UI
guiPendingOverrideEvent = LU_BEGINUILOCK;
// disable sight
gTacticalStatus.uiFlags |= DISALLOW_SIGHT;
}
gubElementsOnExplosionQueue++;
gfExplosionQueueActive = TRUE;
}
void HandleExplosionQueue( void )
{
UINT32 uiIndex;
UINT32 uiWorldBombIndex;
UINT32 uiCurrentTime;
INT32 sGridNo;
OBJECTTYPE * pObj;
UINT8 ubLevel;
if ( !gfExplosionQueueActive )
{
return;
}
uiCurrentTime = GetJA2Clock();
// WDS 07/25/2008 - Avoid error where gWorldItems and/or gWorldBombs is nil
if (gWorldBombs && gWorldItems) {
for ( uiIndex = 0; uiIndex < gubElementsOnExplosionQueue; uiIndex++ )
{
if ( gExplosionQueue[ uiIndex ].fExists && uiCurrentTime >= gExplosionQueue[ uiIndex ].uiTimeStamp )
{
// Set off this bomb now!
// Preliminary assignments:
uiWorldBombIndex = gExplosionQueue[ uiIndex ].uiWorldBombIndex;
pObj = &( gWorldItems[ gWorldBombs[ uiWorldBombIndex ].iItemIndex ].object );
sGridNo = gWorldItems[ gWorldBombs[ uiWorldBombIndex ].iItemIndex ].sGridNo;
ubLevel = gWorldItems[ gWorldBombs[ uiWorldBombIndex ].iItemIndex ].ubLevel;
if (pObj->usItem == ACTION_ITEM && (*pObj)[0]->data.misc.bActionValue != ACTION_ITEM_BLOW_UP)
{
PerformItemAction( sGridNo, pObj );
}
else if ( (*pObj)[0]->data.misc.usBombItem == TRIP_KLAXON )
{
PlayJA2Sample( KLAXON_ALARM, RATE_11025, SoundVolume( MIDVOLUME, sGridNo ), 5, SoundDir( sGridNo ) );
CallAvailableEnemiesTo( sGridNo );
//RemoveItemFromPool( sGridNo, gWorldBombs[ uiWorldBombIndex ].iItemIndex, 0 );
}
else if ( (*pObj)[0]->data.misc.usBombItem == TRIP_FLARE )
{
NewLightEffect( sGridNo, (UINT8)Explosive[pObj->usItem].ubDuration, (UINT8)Explosive[pObj->usItem].ubStartRadius );
RemoveItemFromPool( sGridNo, gWorldBombs[ uiWorldBombIndex ].iItemIndex, ubLevel );
}
else
{
gfExplosionQueueMayHaveChangedSight = TRUE;
// We have to remove the item first to prevent the explosion from detonating it
// a second time :-)
RemoveItemFromPool( sGridNo, gWorldBombs[ uiWorldBombIndex ].iItemIndex, ubLevel );
// make sure no one thinks there is a bomb here any more!
if ( gpWorldLevelData[sGridNo].uiFlags & MAPELEMENT_PLAYER_MINE_PRESENT )
{
RemoveBlueFlag( sGridNo, ubLevel );
}
gpWorldLevelData[sGridNo].uiFlags &= ~(MAPELEMENT_ENEMY_MINE_PRESENT);
// BOOM!
// bomb objects only store the SIDE who placed the bomb! :-(
if ( (*pObj)[0]->data.misc.ubBombOwner > 1 )
{
IgniteExplosion( (UINT8) ((*pObj)[0]->data.misc.ubBombOwner - 2), CenterX( sGridNo ), CenterY( sGridNo ), 0, sGridNo, (*pObj)[0]->data.misc.usBombItem, ubLevel );
}
else
{
// pre-placed
IgniteExplosion( NOBODY, CenterX( sGridNo ), CenterY( sGridNo ), 0, sGridNo, (*pObj)[0]->data.misc.usBombItem, ubLevel );
}
}
// Bye bye bomb
gExplosionQueue[ uiIndex ].fExists = FALSE;
}
}
}
// See if we can reduce the # of elements on the queue that we have recorded
// Easier to do it at this time rather than in the loop above
while ( gubElementsOnExplosionQueue > 0 && gExplosionQueue[ gubElementsOnExplosionQueue - 1 ].fExists == FALSE )
{
gubElementsOnExplosionQueue--;
}
if ( gubElementsOnExplosionQueue == 0 && (gubPersonToSetOffExplosions == NOBODY || gTacticalStatus.ubAttackBusyCount == 0) )
{
// turn off explosion queue
// re-enable sight
gTacticalStatus.uiFlags &= (~DISALLOW_SIGHT);
if ( gubPersonToSetOffExplosions != NOBODY && !(MercPtrs[ gubPersonToSetOffExplosions ]->flags.uiStatusFlags & SOLDIER_PC) )
{
FreeUpNPCFromPendingAction( MercPtrs[ gubPersonToSetOffExplosions ] );
}
if (gfExplosionQueueMayHaveChangedSight)
{
UINT8 ubLoop;
SOLDIERTYPE * pTeamSoldier;
// set variable so we may at least have someone to resolve interrupts vs
gubInterruptProvoker = gubPersonToSetOffExplosions;
AllTeamsLookForAll( TRUE );
// call fov code
ubLoop = gTacticalStatus.Team[ gbPlayerNum ].bFirstID;
for ( pTeamSoldier = MercPtrs[ ubLoop ]; ubLoop <= gTacticalStatus.Team[ gbPlayerNum ].bLastID; ubLoop++, pTeamSoldier++ )
{
if ( pTeamSoldier->bActive && pTeamSoldier->bInSector )
{
RevealRoofsAndItems( pTeamSoldier, TRUE, FALSE, pTeamSoldier->pathing.bLevel, FALSE );
}
}
gfExplosionQueueMayHaveChangedSight = FALSE;
gubPersonToSetOffExplosions = NOBODY;
}
// unlock UI
//UnSetUIBusy( (UINT8)gusSelectedSoldier );
// OJW - 20091028 - fix explosion UI lock bug on unoriginating clients
if ( !(gTacticalStatus.uiFlags & INCOMBAT) || gTacticalStatus.ubCurrentTeam == gbPlayerNum || (is_networked && gTacticalStatus.ubCurrentTeam != 1) )
{
// don't end UI lock when it's a computer turn
guiPendingOverrideEvent = LU_ENDUILOCK;
}
gfExplosionQueueActive = FALSE;
}
}
void DecayBombTimers( void )
{
UINT32 uiWorldBombIndex;
UINT32 uiTimeStamp;
OBJECTTYPE * pObj;
uiTimeStamp = GetJA2Clock();
// Go through all the bombs in the world, and look for timed ones
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists)
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( (*pObj)[0]->data.misc.bDetonatorType == BOMB_TIMED && !((*pObj).fFlags & OBJECT_DISABLED_BOMB) )
{
// Found a timed bomb, so decay its delay value and see if it goes off
(*pObj)[0]->data.misc.bDelay--;
if ((*pObj)[0]->data.misc.bDelay == 0)
{
// ATE: CC black magic....
if ( (*pObj)[0]->data.misc.ubBombOwner > 1 )
{
gubPersonToSetOffExplosions = (UINT8) ((*pObj)[0]->data.misc.ubBombOwner - 2);
// SANDRO - merc records - detonating explosives
if ( MercPtrs[ gubPersonToSetOffExplosions ]->ubProfile != NO_PROFILE && MercPtrs[ gubPersonToSetOffExplosions ]->bTeam == gbPlayerNum )
{
gMercProfiles[ MercPtrs[ gubPersonToSetOffExplosions ]->ubProfile ].records.usExpDetonated++;
}
}
else
{
gubPersonToSetOffExplosions = NOBODY;
}
// put this bomb on the queue
AddBombToQueue( uiWorldBombIndex, uiTimeStamp );
if (pObj->usItem != ACTION_ITEM || (*pObj)[0]->data.misc.bActionValue == ACTION_ITEM_BLOW_UP)
{
uiTimeStamp += BOMB_QUEUE_DELAY;
}
}
}
}
}
}
void SetOffBombsByFrequency( UINT8 ubID, INT8 bFrequency )
{
UINT32 uiWorldBombIndex;
UINT32 uiTimeStamp;
OBJECTTYPE * pObj;
uiTimeStamp = GetJA2Clock();
// Go through all the bombs in the world, and look for remote ones
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists)
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( (*pObj)[0]->data.misc.bDetonatorType == BOMB_REMOTE && !((*pObj).fFlags & OBJECT_DISABLED_BOMB) )
{
// Found a remote bomb, so check to see if it has the same frequency
if ((*pObj)[0]->data.misc.bFrequency == bFrequency)
{
// SANDRO - added merc records and some exp
if ( ((*pObj)[0]->data.misc.ubBombOwner) > 1 )
{
if ( MercPtrs[((*pObj)[0]->data.misc.ubBombOwner - 2)]->ubProfile != NO_PROFILE &&
MercPtrs[((*pObj)[0]->data.misc.ubBombOwner - 2)]->bTeam == gbPlayerNum )
{
gMercProfiles[MercPtrs[((*pObj)[0]->data.misc.ubBombOwner - 2)]->ubProfile].records.usExpDetonated++;
StatChange( MercPtrs[((*pObj)[0]->data.misc.ubBombOwner - 2)], EXPLODEAMT, ( 5 ), FALSE );
}
}
gubPersonToSetOffExplosions = ubID;
// put this bomb on the queue
AddBombToQueue( uiWorldBombIndex, uiTimeStamp );
if (pObj->usItem != ACTION_ITEM || (*pObj)[0]->data.misc.bActionValue == ACTION_ITEM_BLOW_UP)
{
uiTimeStamp += BOMB_QUEUE_DELAY;
}
}
}
}
}
}
void SetOffPanicBombs( UINT8 ubID, INT8 bPanicTrigger )
{
// need to turn off gridnos & flags in gTacticalStatus
gTacticalStatus.sPanicTriggerGridNo[ bPanicTrigger ] = NOWHERE;
if ( ( TileIsOutOfBounds(gTacticalStatus.sPanicTriggerGridNo[0])) &&
( TileIsOutOfBounds(gTacticalStatus.sPanicTriggerGridNo[1])) &&
( TileIsOutOfBounds(gTacticalStatus.sPanicTriggerGridNo[2])) )
{
gTacticalStatus.fPanicFlags &= ~(PANIC_TRIGGERS_HERE);
}
switch( bPanicTrigger )
{
case 0:
SetOffBombsByFrequency( ubID, PANIC_FREQUENCY );
gTacticalStatus.fPanicFlags &= ~(PANIC_BOMBS_HERE);
break;
case 1:
SetOffBombsByFrequency( ubID, PANIC_FREQUENCY_2 );
break;
case 2:
SetOffBombsByFrequency( ubID, PANIC_FREQUENCY_3 );
break;
default:
break;
}
if ( gTacticalStatus.fPanicFlags )
{
// find a new "closest one"
MakeClosestEnemyChosenOne();
}
}
BOOLEAN SetOffBombsInGridNo( UINT8 ubID, INT32 sGridNo, BOOLEAN fAllBombs, INT8 bLevel )
{
UINT32 uiWorldBombIndex;
UINT32 uiTimeStamp;
OBJECTTYPE * pObj;
BOOLEAN fFoundMine = FALSE;
uiTimeStamp = GetJA2Clock();
// Go through all the bombs in the world, and look for mines at this location
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists && gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].sGridNo == sGridNo && gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].ubLevel == bLevel )
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if (!((*pObj).fFlags & OBJECT_DISABLED_BOMB))
{
if (fAllBombs || (*pObj)[0]->data.misc.bDetonatorType == BOMB_PRESSURE)
{
// Snap: if we do set off our own trap (e.g. by trying to disarm it), we pay!
/*if (!fAllBombs && MercPtrs[ ubID ]->bTeam != gbPlayerNum )
{
// ignore this unless it is a mine, etc which would have to have been placed by the
// player, seeing as how the others are all marked as known to the AI.
if ( !(Item[pObj->usItem].mine || pObj->usItem == TRIP_FLARE || pObj->usItem == TRIP_KLAXON ) )
{
continue;
}
}
// player and militia ignore bombs set by player
if ( (*pObj)[0]->data.misc.ubBombOwner > 1 && (MercPtrs[ ubID ]->bTeam == gbPlayerNum || MercPtrs[ ubID ]->bTeam == MILITIA_TEAM) )
{
continue;
}*/
if (pObj->usItem == SWITCH)
{
// send out a signal to detonate other bombs, rather than this which
// isn't a bomb but a trigger
SetOffBombsByFrequency( ubID, (*pObj)[0]->data.misc.bFrequency );
}
else
{
gubPersonToSetOffExplosions = ubID;
// SANDRO - merc records
// only if we blew up somebody not in our team(no achievement for blowing our guys :)), only if owner exists and have profile
if ( (MercPtrs[ubID]->bTeam != gbPlayerNum) && ((*pObj)[0]->data.misc.ubBombOwner > 1) )
{
if ( MercPtrs[ ((*pObj)[0]->data.misc.ubBombOwner - 2) ]->ubProfile != NO_PROFILE && MercPtrs[ ((*pObj)[0]->data.misc.ubBombOwner - 2) ]->bTeam == gbPlayerNum )
gMercProfiles[ MercPtrs[ ((*pObj)[0]->data.misc.ubBombOwner - 2) ]->ubProfile ].records.usExpDetonated++;
}
// put this bomb on the queue
AddBombToQueue( uiWorldBombIndex, uiTimeStamp );
if (pObj->usItem != ACTION_ITEM || (*pObj)[0]->data.misc.bActionValue == ACTION_ITEM_BLOW_UP)
{
uiTimeStamp += BOMB_QUEUE_DELAY;
}
if ( (*pObj)[0]->data.misc.usBombItem != NOTHING && Item[ (*pObj)[0]->data.misc.usBombItem ].usItemClass & IC_EXPLOSV )
{
fFoundMine = TRUE;
}
}
}
}
}
}
return( fFoundMine );
}
void ActivateSwitchInGridNo( UINT8 ubID, INT32 sGridNo )
{
UINT32 uiWorldBombIndex;
OBJECTTYPE * pObj;
// Go through all the bombs in the world, and look for mines at this location
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists && gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].sGridNo == sGridNo)
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( pObj->usItem == SWITCH && ( !((*pObj).fFlags & OBJECT_DISABLED_BOMB) ) && (*pObj)[0]->data.misc.bDetonatorType == BOMB_SWITCH)
{
// send out a signal to detonate other bombs, rather than this which
// isn't a bomb but a trigger
// first set attack busy count to 0 in case of a lingering a.b.c. problem...
// No, not a good idea.
// gTacticalStatus.ubAttackBusyCount = 0;
SetOffBombsByFrequency( ubID, (*pObj)[0]->data.misc.bFrequency );
}
}
}
}
BOOLEAN SaveExplosionTableToSaveGameFile( HWFILE hFile )
{
UINT32 uiNumBytesWritten;
UINT32 uiExplosionCount=0;
UINT32 uiCnt;
//
// Explosion queue Info
//
//Write the number of explosion queues
FileWrite( hFile, &gubElementsOnExplosionQueue, sizeof( UINT32 ), &uiNumBytesWritten );
if( uiNumBytesWritten != sizeof( UINT32 ) )
{
FileClose( hFile );
return( FALSE );
}
//loop through and add all the explosions
for( uiCnt=0; uiCnt< MAX_BOMB_QUEUE; uiCnt++)
{
FileWrite( hFile, &gExplosionQueue[ uiCnt ], sizeof( ExplosionQueueElement ), &uiNumBytesWritten );
if( uiNumBytesWritten != sizeof( ExplosionQueueElement ) )
{
FileClose( hFile );
return( FALSE );
}
}
//
// Explosion Data
//
//loop through and count all the active explosions
uiExplosionCount = 0;
for( uiCnt=0; uiCnt< NUM_EXPLOSION_SLOTS; uiCnt++)
{
if( gExplosionData[ uiCnt ].fAllocated )
{
uiExplosionCount++;
}
}
//Save the number of explosions
FileWrite( hFile, &uiExplosionCount, sizeof( UINT32 ), &uiNumBytesWritten );
if( uiNumBytesWritten != sizeof( UINT32 ) )
{
FileClose( hFile );
return( FALSE );
}
//loop through and count all the active explosions
for( uiCnt=0; uiCnt< NUM_EXPLOSION_SLOTS; uiCnt++)
{
if( gExplosionData[ uiCnt ].fAllocated )
{
FileWrite( hFile, &gExplosionData[ uiCnt ], sizeof( EXPLOSIONTYPE ), &uiNumBytesWritten );
if( uiNumBytesWritten != sizeof( EXPLOSIONTYPE ) )
{
FileClose( hFile );
return( FALSE );
}
}
}
return( TRUE );
}
BOOLEAN LoadExplosionTableFromSavedGameFile( HWFILE hFile )
{
UINT32 uiNumBytesRead;
UINT32 uiCnt;
//
// Explosion Queue
//
//Clear the Explosion queue
memset( gExplosionQueue, 0, sizeof( ExplosionQueueElement ) * MAX_BOMB_QUEUE );
//Read the number of explosions queue's
FileRead( hFile, &gubElementsOnExplosionQueue, sizeof( UINT32 ), &uiNumBytesRead );
if( uiNumBytesRead != sizeof( UINT32 ) )
{
return( FALSE );
}
//loop through read all the active explosions fro the file
for( uiCnt=0; uiCnt<MAX_BOMB_QUEUE; uiCnt++)
{
FileRead( hFile, &gExplosionQueue[ uiCnt ], sizeof( ExplosionQueueElement ), &uiNumBytesRead );
if( uiNumBytesRead != sizeof( ExplosionQueueElement ) )
{
return( FALSE );
}
}
//
// Explosion Data
//
//Load the number of explosions
FileRead( hFile, &guiNumExplosions, sizeof( UINT32 ), &uiNumBytesRead );
if( uiNumBytesRead != sizeof( UINT32 ) )
{
return( FALSE );
}
//loop through and load all the active explosions
for( uiCnt=0; uiCnt< guiNumExplosions; uiCnt++)
{
FileRead( hFile, &gExplosionData[ uiCnt ], sizeof( EXPLOSIONTYPE ), &uiNumBytesRead );
if( uiNumBytesRead != sizeof( EXPLOSIONTYPE ) )
{
return( FALSE );
}
gExplosionData[ uiCnt ].iID = uiCnt;
gExplosionData[ uiCnt ].iLightID = -1;
GenerateExplosionFromExplosionPointer( &gExplosionData[ uiCnt ] );
}
return( TRUE );
}
BOOLEAN DoesSAMExistHere( INT16 sSectorX, INT16 sSectorY, INT16 sSectorZ, INT32 sGridNo )
{
INT32 cnt;
INT16 sSectorNo;
// ATE: If we are belwo, return right away...
if ( sSectorZ != 0 )
{
return( FALSE );
}
sSectorNo = SECTOR( sSectorX, sSectorY );
for ( cnt = 0; cnt < NUMBER_OF_SAMS; cnt++ )
{
// Are we i nthe same sector...
if ( pSamList[ cnt ] == sSectorNo )
{
// Are we in the same gridno?
if ( pSamGridNoAList[ cnt ] == sGridNo || pSamGridNoBList[ cnt ] == sGridNo )
{
return( TRUE );
}
}
}
return( FALSE );
}
void UpdateAndDamageSAMIfFound( INT16 sSectorX, INT16 sSectorY, INT16 sSectorZ, INT32 sGridNo, UINT8 ubDamage )
{
INT16 sSectorNo;
// OK, First check if SAM exists, and if not, return
if ( !DoesSAMExistHere( sSectorX, sSectorY, sSectorZ, sGridNo ) )
{
return;
}
// Damage.....
sSectorNo = CALCULATE_STRATEGIC_INDEX( sSectorX, sSectorY );
if ( StrategicMap[ sSectorNo ].bSAMCondition >= ubDamage )
{
StrategicMap[ sSectorNo ].bSAMCondition =
StrategicMap[ sSectorNo ].bSAMCondition - ubDamage;
}
else
{
StrategicMap[ sSectorNo ].bSAMCondition = 0;
}
// SAM site may have been put out of commission...
UpdateAirspaceControl( );
// ATE: GRAPHICS UPDATE WILL GET DONE VIA NORMAL EXPLOSION CODE.....
}
void UpdateSAMDoneRepair( INT16 sSectorX, INT16 sSectorY, INT16 sSectorZ )
{
INT32 cnt;
INT16 sSectorNo;
BOOLEAN fInSector = FALSE;
UINT16 usGoodGraphic, usDamagedGraphic;
// ATE: If we are below, return right away...
if ( sSectorZ != 0 )
{
return;
}
if ( sSectorX == gWorldSectorX && sSectorY == gWorldSectorY && sSectorZ == gbWorldSectorZ )
{
fInSector = TRUE;
}
sSectorNo = SECTOR( sSectorX, sSectorY );
for ( cnt = 0; cnt < NUMBER_OF_SAMS; cnt++ )
{
// Are we i nthe same sector...
if ( pSamList[ cnt ] == sSectorNo )
{
// get graphic.......
GetTileIndexFromTypeSubIndex( EIGHTISTRUCT, (UINT16)( gbSAMGraphicList[ cnt ] ), &usGoodGraphic );
// Damaged one ( current ) is 2 less...
usDamagedGraphic = usGoodGraphic - 2;
// First gridno listed is base gridno....
// if this is loaded....
if ( fInSector )
{
// Update graphic.....
// Remove old!
ApplyMapChangesToMapTempFile( TRUE );
RemoveStruct( pSamGridNoAList[ cnt ], usDamagedGraphic );
AddStructToHead( pSamGridNoAList[ cnt ], usGoodGraphic );
ApplyMapChangesToMapTempFile( FALSE );
}
else
{
// We add temp changes to map not loaded....
// Remove old
RemoveStructFromUnLoadedMapTempFile( pSamGridNoAList[ cnt ], usDamagedGraphic, sSectorX, sSectorY, (UINT8)sSectorZ );
// Add new
AddStructToUnLoadedMapTempFile( pSamGridNoAList[ cnt ], usGoodGraphic, sSectorX, sSectorY, (UINT8)sSectorZ );
}
}
}
// SAM site may have been put back into working order...
UpdateAirspaceControl( );
}
// loop through civ team and find
// anybody who is an NPC and
// see if they get angry
void HandleBuldingDestruction( INT32 sGridNo, UINT8 ubOwner )
{
SOLDIERTYPE * pSoldier;
UINT8 cnt;
if ( ubOwner == NOBODY )
{
return;
}
if ( MercPtrs[ ubOwner ]->bTeam != gbPlayerNum )
{
return;
}
cnt = gTacticalStatus.Team[ CIV_TEAM ].bFirstID;
for ( pSoldier = MercPtrs[ cnt ]; cnt <= gTacticalStatus.Team[ CIV_TEAM ].bLastID; cnt++ ,pSoldier++ )
{
if ( pSoldier->bActive && pSoldier->bInSector && pSoldier->stats.bLife && pSoldier->aiData.bNeutral )
{
if ( pSoldier->ubProfile != NO_PROFILE )
{
// ignore if the player is fighting the enemy here and this is a good guy
if ( gTacticalStatus.Team[ ENEMY_TEAM ].bMenInSector > 0 && (gMercProfiles[ pSoldier->ubProfile ].ubMiscFlags3 & PROFILE_MISC_FLAG3_GOODGUY) )
{
continue;
}
if ( DoesNPCOwnBuilding( pSoldier, sGridNo ) )
{
MakeNPCGrumpyForMinorOffense( pSoldier, MercPtrs[ ubOwner ] );
}
}
}
}
}
INT32 FindActiveTimedBomb( void )
{
UINT32 uiWorldBombIndex;
UINT32 uiTimeStamp;
OBJECTTYPE * pObj;
uiTimeStamp = GetJA2Clock();
// Go through all the bombs in the world, and look for timed ones
for (uiWorldBombIndex = 0; uiWorldBombIndex < guiNumWorldBombs; uiWorldBombIndex++)
{
if (gWorldBombs[uiWorldBombIndex].fExists)
{
pObj = &( gWorldItems[ gWorldBombs[uiWorldBombIndex].iItemIndex ].object );
if ( (*pObj)[0]->data.misc.bDetonatorType == BOMB_TIMED && !((*pObj).fFlags & OBJECT_DISABLED_BOMB) )
{
return( gWorldBombs[uiWorldBombIndex].iItemIndex );
}
}
}
return( -1 );
}
BOOLEAN ActiveTimedBombExists( void )
{
if ( gfWorldLoaded )
{
return( FindActiveTimedBomb() != -1 );
}
else
{
return( FALSE );
}
}
void RemoveAllActiveTimedBombs( void )
{
INT32 iItemIndex;
do
{
iItemIndex = FindActiveTimedBomb();
if (iItemIndex != -1 )
{
RemoveItemFromWorld( iItemIndex );
}
} while( iItemIndex != -1 );
}
UINT8 DetermineFlashbangEffect( SOLDIERTYPE *pSoldier, INT8 ubExplosionDir, BOOLEAN fInBuilding)
{
INT8 bNumTurns;
UINT16 usHeadItem1, usHeadItem2;
bNumTurns = FindNumTurnsBetweenDirs(pSoldier->ubDirection, ubExplosionDir);
usHeadItem1 = pSoldier->inv[ HEAD1POS ].usItem;
usHeadItem2 = pSoldier->inv[ HEAD2POS ].usItem;
// if soldier got in explosion area check if he is affected by flash
// if soldier wears sun goggles OR grenade behind him OR
// (he is not underground AND it is day AND he is outdoor)
if ( (usHeadItem1 == SUNGOGGLES || usHeadItem2 == SUNGOGGLES) || (bNumTurns > 1) ||
(!gbWorldSectorZ && !NightTime() && !fInBuilding) )
{
// soldier didn't see flash or wears protective sungogles or outdoor at day, so he is only deafened
return ( FIRE_WEAPON_DEAFENED );
}
return ( FIRE_WEAPON_BLINDED_AND_DEAFENED );
}
#ifdef JA2UB
//-- UB
void HavePersonAtGridnoStop( UINT32 sGridNo )
{
UINT8 ubID;
//Sewe if there is a person at the gridno
ubID = WhoIsThere2( sGridNo, 0 );
//is it a valid person
if ( (ubID != NOBODY) && (MercPtrs[ ubID ]->bTeam == gbPlayerNum) )
{
SOLDIERTYPE *pSoldier = MercPtrs[ ubID ];
//Stop the merc
pSoldier->EVENT_StopMerc( pSoldier->sGridNo, pSoldier->ubDirection );
}
}
//JA25 UB
BOOLEAN ShouldThePlayerStopWhenWalkingOnBiggensActionItem( UINT8 ubRecordNum )
{
SOLDIERTYPE *pSoldier=NULL;
pSoldier = FindSoldierByProfileID( 61, TRUE ); //BIGGENS
//if biggens hasnt said the quote before, or is on the players team
if( HasNpcSaidQuoteBefore( 61, ubRecordNum ) || ( pSoldier != NULL || gMercProfiles[ 61 ].bLife <= 0 ) ) //BIGGENS
{
return( FALSE );
}
else
{
return( TRUE );
}
}
// This function checks if we should replace the fan graphic
BOOLEAN IsFanGraphicInSectorAtThisGridNo( UINT32 sGridNo )
{
// First check current sector......
if( gWorldSectorX == 13 && gWorldSectorY == MAP_ROW_J && gbWorldSectorZ == 0 )
{
//if this is the right gridno
/*if( sGridNo == 10978 ||
sGridNo == 10979 ||
sGridNo == 10980 ||
sGridNo == 10818 ||
sGridNo == 10819 ||
sGridNo == 10820 ||
sGridNo == 10658 ||
sGridNo == 10659 ||
sGridNo == 10660 )
*/
if( sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[0] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[1] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[2] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[3] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[4] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[5] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[6] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[7] ||
sGridNo == gGameLegionOptions.IsFanGraphicInSectorAtThisGridNoA[8] )
{
return( TRUE );
}
}
return( FALSE );
}
void HandleDestructionOfPowerGenFan()
{
UINT8 ubShadeLevel=0;
INT8 bID;
//if we have already destroyed the fan
if( gJa25SaveStruct.ubHowPlayerGotThroughFan == PG__PLAYER_BLEW_UP_FAN_TO_GET_THROUGH )
{
//leave
return;
}
//if we have already been in here
if( gJa25SaveStruct.ubStateOfFanInPowerGenSector == PGF__BLOWN_UP )
{
return;
}
//Remeber that the player blew up the fan
gJa25SaveStruct.ubStateOfFanInPowerGenSector = PGF__BLOWN_UP;
//Remeber how the player got through
HandleHowPlayerGotThroughFan();
//Since the player is making LOTS of noise, add more enemies to the tunnel sector
// AddEnemiesToJa25TunnelMaps();
if ( gGameLegionOptions.HandleAddingEnemiesToTunnelMaps_UB == TRUE )
{
HandleAddingEnemiesToTunnelMaps();
}
//Make sure to apply these changes to the map
ApplyMapChangesToMapTempFile( TRUE );
//Add an exit grid to the map
AddExitGridForFanToPowerGenSector();
//done with the changes
ApplyMapChangesToMapTempFile( FALSE );
//Stop the fan sound
HandleRemovingPowerGenFanSound();
//
// Have a qualified merc say a quote
//
//Get a random qualified merc to say the quote
bID = RandomSoldierIdFromNewMercsOnPlayerTeam();
if( bID != -1 )
{
DelayedMercQuote( Menptr[ bID ].ubProfile, QUOTE_ACCEPT_CONTRACT_RENEWAL, GetWorldTotalSeconds() + 2 );
}
}
void HandleExplosionsInTunnelSector( UINT32 sGridNo )
{
//if this isnt the tunnel sectors
if( !( gWorldSectorX == 14 && ( gWorldSectorY == MAP_ROW_J || gWorldSectorY == MAP_ROW_K ) && gbWorldSectorZ == 1 ) )
{
//get the fuck out...
return;
}
//Since the enemy will hear explosions in the tunnel, remember the player made a noise
gJa25SaveStruct.uiJa25GeneralFlags |= JA_GF__DID_PLAYER_MAKE_SOUND_GOING_THROUGH_TUNNEL_GATE;
}
void HandleSeeingFortifiedDoor( UINT32 sGridNo )
{
INT32 sID=0;
//if this isnt the First level of the complex
if( !( gWorldSectorX == 15 && gWorldSectorY == MAP_ROW_K && gbWorldSectorZ == 1 ) )
{
//get the fuck out...
return;
}
//if the player has already seen it
if( gJa25SaveStruct.uiJa25GeneralFlags & JA_GF__PLAYER_HAS_SEEN_FORTIFIED_DOOR )
{
//get out
return;
}
//Remeber that we have said the quote
gJa25SaveStruct.uiJa25GeneralFlags |= JA_GF__PLAYER_HAS_SEEN_FORTIFIED_DOOR;
//find out whos is the one walking across the trap
sID = WhoIsThere2( sGridNo, 0 );
if( sID != NOBODY && IsSoldierQualifiedMerc( &Menptr[ sID ] ) )
{
}
else
{
//Get a random merc to say quote
sID = RandomSoldierIdFromNewMercsOnPlayerTeam();
}
if( sID != -1 )
{
//say the quote
TacticalCharacterDialogue( &Menptr[ sID ], QUOTE_LENGTH_OF_CONTRACT );
}
}
void HandleSwitchToOpenFortifiedDoor( UINT32 sGridNo )
{
INT8 bID;
//if the door is already opened
if( gJa25SaveStruct.ubStatusOfFortifiedDoor == FD__OPEN )
{
return;
}
//remeber that the switch to open the forified door on level 1, has been pulled
gJa25SaveStruct.ubStatusOfFortifiedDoor = FD__OPEN;
bID = RandomSoldierIdFromNewMercsOnPlayerTeam();
if( bID != -1 )
{
TacticalCharacterDialogue( &Menptr[ bID ], QUOTE_COMMENT_BEFORE_HANG_UP );
}
}
void HandleSeeingPowerGenFan( UINT32 sGridNo )
{
// INT8 bID;
UINT8 ubPerson;
BOOLEAN fFanIsStopped;
BOOLEAN fFanHasBeenStopped;
SOLDIERTYPE *pSoldier;
SOLDIERTYPE *pOtherSoldier;
INT32 cnt;
BOOLEAN fSaidQuote=FALSE;
//if the fan has already been seen
if( IsJa25GeneralFlagSet( JA_GF__PLAYER_SEEN_FAN_BEFORE ) )
{
//get out
return;
}
fFanIsStopped = ( gJa25SaveStruct.ubStateOfFanInPowerGenSector == PGF__STOPPED );
fFanHasBeenStopped = IsJa25GeneralFlagSet( JA_GF__POWER_GEN_FAN_HAS_BEEN_STOPPED );
//Get the person who is at the gridno
ubPerson = WhoIsThere2( sGridNo, 0 );
if( ubPerson != NOBODY )
{
pSoldier = &Menptr[ ubPerson ];
//if the fan is stopped And is this merc is a qualified merc but Not a power gen fan qualified merc?
if( IsSoldierQualifiedMerc( pSoldier ) && fFanIsStopped )
{
//Have the merc say the quote
TacticalCharacterDialogue( pSoldier, QUOTE_HATE_MERC_2_ON_TEAM_WONT_RENEW );
fSaidQuote = TRUE;
}
else if( IsSoldierQualifiedMercForSeeingPowerGenFan( pSoldier ) )
{
//Have the merc say the quote
TacticalCharacterDialogue( pSoldier, QUOTE_HATE_MERC_2_ON_TEAM_WONT_RENEW );
fSaidQuote = TRUE;
}
else
{
//see if there is another merc that is close by to say the quote
cnt = gTacticalStatus.Team[ OUR_TEAM ].bFirstID;
for ( pOtherSoldier = MercPtrs[ cnt ]; cnt <= gTacticalStatus.Team[ OUR_TEAM ].bLastID; cnt++,pOtherSoldier++)
{
//if the soldier is in the sector
if( pOtherSoldier->bActive && pOtherSoldier->bInSector && ( pOtherSoldier->stats.bLife >= CONSCIOUSNESS ) )
{
INT16 sDistanceAway;
// if the soldier isnt that far away AND he is qualified merc
sDistanceAway = PythSpacesAway( pSoldier->sGridNo, pOtherSoldier->sGridNo );
if( sDistanceAway <= 5 && ( !InARoom( pOtherSoldier->sGridNo, NULL ) || pOtherSoldier->pathing.bLevel ) &&
( ( IsSoldierQualifiedMerc( pOtherSoldier ) && fFanIsStopped ) ||
( IsSoldierQualifiedMercForSeeingPowerGenFan( pOtherSoldier ) ) ) )
{
//Have the merc say the quote
TacticalCharacterDialogue( pOtherSoldier, QUOTE_HATE_MERC_2_ON_TEAM_WONT_RENEW );
fSaidQuote = TRUE;
break;
}
}
}
}
}
//if the quote was said, dont say it again
if( fSaidQuote )
{
//remeber that the fan has been seen
SetJa25GeneralFlag( JA_GF__PLAYER_SEEN_FAN_BEFORE );
}
}
#endif | [
"jazz_ja@b41f55df-6250-4c49-8e33-4aa727ad62a1"
]
| [
[
[
1,
4630
]
]
]
|
41a5af632f3d6dd083e8059874510cc4b57ce9db | 58ef4939342d5253f6fcb372c56513055d589eb8 | /ScheduleKiller/source/Views/inc/SettingScreenContainer.h | 6b4c89238a0d4209010f7fd8a29dfce13b98e685 | []
| no_license | flaithbheartaigh/lemonplayer | 2d77869e4cf787acb0aef51341dc784b3cf626ba | ea22bc8679d4431460f714cd3476a32927c7080e | refs/heads/master | 2021-01-10T11:29:49.953139 | 2011-04-25T03:15:18 | 2011-04-25T03:15:18 | 50,263,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | h | /*
============================================================================
Name : SettingScreenContainer.h
Author : zengcity
Copyright : Your copyright notice
Description : Declares container control for application.
============================================================================
*/
#ifndef SETTINGSCREENCONTAINER_H
#define SETTINGSCREENCONTAINER_H
// INCLUDES
#include <coecntrl.h>
#include <aknsettingitemlist.h>
// FORWARD DECLARATIONS
// CLASS DECLARATION
/**
* CSettingScreenContainer container control class.
*
*/
class CSettingScreenContainer : public CAknSettingItemList
{
public:
// Constructors and destructor
~CSettingScreenContainer();
static CSettingScreenContainer* NewL(const TRect& aRect);
static CSettingScreenContainer* NewLC(const TRect& aRect);
//private:
// New functions
void ConstructL(const TRect& aRect);
CSettingScreenContainer();
public:
// Functions from base classes
CAknSettingItem* CreateSettingItemL(TInt aSettingId);
void EditItemL(TBool aCalledFromMenu);
void EditItemL(TInt aIndex, TBool aCalledFromMenu);
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType);
//new fuction
TBool Save();
void InitDataFromMain();
void InitDataFromApp();
private:
void ModifyItemL(TInt aIndex);
void JumpToAppView();
private:
TBuf<0x100> iText;
TFileName iRule;
TInt iNumber;
TTime iDate;
TBool iBinary;
};
#endif
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
64
]
]
]
|
1a26385f0bcd775f5e8e40820490b1628a49bd70 | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /zju.finished/1361.cpp | 90a187d3ffe3b15f5a05252c5321bb08bb7d192a | []
| no_license | usherfu/zoj | 4af6de9798bcb0ffa9dbb7f773b903f630e06617 | 8bb41d209b54292d6f596c5be55babd781610a52 | refs/heads/master | 2021-05-28T11:21:55.965737 | 2009-12-15T07:58:33 | 2009-12-15T07:58:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,745 | cpp | #include<iostream>
#include<queue>
#include<ext/hash_set>
using namespace std;
using namespace __gnu_cxx;
enum {
SX = 24,
SY = 16,
SM = 0x1f,
SL = 0x03fff,
};
hash_set<int> tab;
struct Node {
unsigned dis;
unsigned mask;
};
int move[4][2] = {
{-1, 0}, {0, 1}, {1, 0}, {0, -1}
};
int N, M, L;
int lake[8][2];
char lair[24][24];
Node one,nex;
inline int getX(int v){
return (v>>SX)&SM;
}
inline int getY(int v){
return (v>>SY)&SM;
}
void unpack(int m){
lake[0][0] = getX(m);
lake[0][1] = getY(m);
int d, i;
for(i=1; i<L; i++){
d = (m>>((i-1)<<1))&0x3;
lake[i][0] = lake[i-1][0] + move[d][0];
lake[i][1] = lake[i-1][1] + move[d][1];
}
}
int pack(){
int m = 0, d;
for(int i=1; i<L; i++){
for(d=0; d<4; d++){
if(lake[i-1][0] + move[d][0]==lake[i][0]
&& lake[i-1][1] + move[d][1] == lake[i][1]){
break;
}
}
m |= d<<((i-1)<<1);
}
m |= (lake[0][0]<<SX);
m |= (lake[0][1]<<SY);
return m;
}
int fun(){
int d, nx, ny, x, y, nd;
queue<Node> q;
tab.clear();
one.dis = 0;
one.mask = pack();
tab.insert(one.mask);
q.push(one);
while(!q.empty()){
one = q.front(); q.pop();
x = getX(one.mask);
y = getY(one.mask);
if(x==1 && y==1){
return one.dis;
}
unpack(one.mask);
nex.dis = one.dis+1;
for(d=0; d<L; d++){
lair[lake[d][0]][lake[d][1]] = 1;
}
for(d=0; d<4; d++){
nx = x + move[d][0];
ny = y + move[d][1];
if(nx==0||nx>N||ny==0||ny>M||lair[nx][ny]==1){
continue;
}
if(d<2) nd = d+2;
else nd = d-2;
nex.mask = ((one.mask&SL)<<2)+nd;
nex.mask |= (nx<<SX);
nex.mask |= (ny<<SY);
if(tab.find(nex.mask)!=tab.end()){
continue;
}
tab.insert(nex.mask);
q.push(nex);
}
for(d=0; d<L; d++){
lair[lake[d][0]][lake[d][1]] = 0;
}
}
return -1;
}
int readIn(){
scanf("%d%d%d", &N, &M, &L);
if(N + M + L ==0) return 0;
memset(lair, 0, sizeof(lair));
int k, x, y;
for(k=0; k<L; k++){
scanf("%d%d", &lake[k][0], &lake[k][1]);
}
scanf("%d", &k);
while(k--){
scanf("%d%d",&x,&y);
lair[x][y] = 1;
}
return (N+M+L);
}
int main(){
int tst=0;
while(readIn() > 0){
printf("Case %d: %d\n", ++tst, fun());
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
122
]
]
]
|
97514fdd88e73f18c9e46f6cbaeda90dfa598137 | c1c3866586c56ec921cd8c9a690e88ac471adfc8 | /Practise_2005/Xvid.class/XvidEnc.cpp | eb1e3da71a4bea812bda0ea4b1809bbf860c5b91 | []
| no_license | rtmpnewbie/lai3d | 0802dbb5ebe67be2b28d9e8a4d1cc83b4f36b14f | b44c9edfb81fde2b40e180a651793fec7d0e617d | refs/heads/master | 2021-01-10T04:29:07.463289 | 2011-03-22T17:51:24 | 2011-03-22T17:51:24 | 36,842,700 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,221 | cpp | #include "StdAfx.h"
#include ".\xvidenc.h"
#include "xvid.h"
static const int motion_presets[] =
{
/* quality 0 */
0,
/* quality 1 */
XVID_ME_ADVANCEDDIAMOND16,
/* quality 2 */
XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16,
/* quality 3 */
XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8,
/* quality 4 */
XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 |
XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
/* quality 5 */
XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 |
XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 |
XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
/* quality 6 */
XVID_ME_ADVANCEDDIAMOND16 | XVID_ME_HALFPELREFINE16 | XVID_ME_EXTSEARCH16 |
XVID_ME_ADVANCEDDIAMOND8 | XVID_ME_HALFPELREFINE8 | XVID_ME_EXTSEARCH8 |
XVID_ME_CHROMA_PVOP | XVID_ME_CHROMA_BVOP,
};
#define ME_ELEMENTS (sizeof(motion_presets)/sizeof(motion_presets[0]))
static const int vop_presets[] = {
/* quality 0 */
0,
/* quality 1 */
0,
/* quality 2 */
XVID_VOP_HALFPEL,
/* quality 3 */
XVID_VOP_HALFPEL | XVID_VOP_INTER4V,
/* quality 4 */
XVID_VOP_HALFPEL | XVID_VOP_INTER4V,
/* quality 5 */
XVID_VOP_HALFPEL | XVID_VOP_INTER4V |
XVID_VOP_TRELLISQUANT,
/* quality 6 */
XVID_VOP_HALFPEL | XVID_VOP_INTER4V |
XVID_VOP_TRELLISQUANT | XVID_VOP_HQACPRED,
};
#define VOP_ELEMENTS (sizeof(vop_presets)/sizeof(vop_presets[0]))
//////////////////////////////////////////////////////////////////////////
#define MAX_ZONES 64
/* Maximum number of frames to encode */
#define ABS_MAXFRAMENR 9999
static int ARG_STATS = 0;
static int ARG_DUMP = 0;
static int ARG_LUMIMASKING = 0;
static int ARG_BITRATE = 0;
static int ARG_SINGLE = 0;
static char *ARG_PASS1 = 0;
static char *ARG_PASS2 = 0;
static int ARG_QUALITY = ME_ELEMENTS - 1;
static float ARG_FRAMERATE = 25.00f;
static int ARG_MAXFRAMENR = ABS_MAXFRAMENR;
static int ARG_MAXKEYINTERVAL = 0;
static char *ARG_INPUTFILE = NULL;
static int ARG_INPUTTYPE = 0;
static int ARG_SAVEMPEGSTREAM = 0;
static int ARG_SAVEINDIVIDUAL = 0;
static char *ARG_OUTPUTFILE = NULL;
static int ARG_BQRATIO = 150;
static int ARG_BQOFFSET = 100;
static int ARG_MAXBFRAMES = 0;
static int ARG_PACKED = 0;
static int ARG_VOPDEBUG = 0;
static int ARG_GMC = 0;
static int ARG_INTERLACING = 0;
static int ARG_QPEL = 0;
static int ARG_CLOSED_GOP = 0;
#ifndef READ_PNM
#define IMAGE_SIZE(x,y) ((x)*(y)*3/2)
#else
#define IMAGE_SIZE(x,y) ((x)*(y)*3)
#endif
#define MAX(A,B) ( ((A)>(B)) ? (A) : (B) )
#define SMALL_EPS (1e-10)
#define SWAP(a) ( (((a)&0x000000ff)<<24) | (((a)&0x0000ff00)<<8) | (((a)&0x00ff0000)>>8) | (((a)&0xff000000)>>24) )
//////////////////////////////////////////////////////////////////////////
CXvidEnc::CXvidEnc()
{
m_closed = true ;
m_enc_caller = NULL ;
m_enc_handle = NULL ;
m_key = 0 ;
m_width = 0 ;
m_height = 0 ;
m_bitstream = NULL ;
}
CXvidEnc::~CXvidEnc() {
if(m_bitstream) free(m_bitstream) ;
m_bitstream = NULL ;
}
bool CXvidEnc::Close() {
int xerr = 0 ;
m_closed = true;
/* Destroy the encoder instance */
xerr = xvid_encore(m_enc_handle, XVID_ENC_DESTROY, NULL, NULL);
return (xerr) ? false : true ;
}
void CXvidEnc::AttachCaller(int width, int height, CXvidEncHandler * enc_caller)
{
m_width = width ;
m_height = height ;
m_enc_caller = enc_caller ;
if(m_width > 0 && m_height > 0) {
// max size
int max = (m_width > m_height) ? m_width : m_height ;
int xvid_len = (int)(max * max) ;
m_bitstream = (unsigned char *)malloc(xvid_len) ;
memset(m_bitstream, 0, xvid_len) ;
CXvidEnc::XVID_GLOBAL_INIT() ;
}
}
void CXvidEnc::XVID_GLOBAL_INIT(){
/*------------------------------------------------------------------------
* XviD core initialization
*----------------------------------------------------------------------*/
xvid_gbl_init_t xvid_gbl_init;
memset(&xvid_gbl_init, 0, sizeof(xvid_gbl_init));
xvid_gbl_init.version = XVID_VERSION;
xvid_gbl_init.cpu_flags = XVID_CPU_FORCE | XVID_CPU_ASM ; // here we use asm optimized code
/* Initialize XviD core -- Should be done once per __process__ */
xvid_global(NULL, XVID_GBL_INIT, &xvid_gbl_init, NULL);
}
bool CXvidEnc::Open() {
if(!m_enc_caller) return false ;
static xvid_enc_create_t xvid_enc_create;
int xerr = 0;
m_closed = false;
/*------------------------------------------------------------------------
* XviD encoder initialization
*----------------------------------------------------------------------*/
memset(&xvid_enc_create, 0, sizeof(xvid_enc_create));
xvid_enc_create.version = XVID_VERSION;
/* Width and Height of input frames */
xvid_enc_create.width = m_width ;
xvid_enc_create.height = m_height ;
xvid_enc_create.profile = XVID_PROFILE_AS_L4;
/* init plugins */
/*
xvid_enc_create.zones = ZONES;
xvid_enc_create.num_zones = NUM_ZONES;
xvid_enc_create.plugins = plugins;
xvid_enc_create.num_plugins = 0;
*/
/* No fancy thread tests */
xvid_enc_create.num_threads = 0;
/* Frame rate - Do some quick float fps = fincr/fbase hack */
xvid_enc_create.fincr = 1;
xvid_enc_create.fbase = (int)10;
/* Maximum key frame interval */
xvid_enc_create.max_key_interval = (int)-1; //--default 10s
/* Bframes settings */
xvid_enc_create.max_bframes = ARG_MAXBFRAMES;
xvid_enc_create.bquant_ratio = ARG_BQRATIO;
xvid_enc_create.bquant_offset = ARG_BQOFFSET;
/* Dropping ratio frame -- we don't need that */
xvid_enc_create.frame_drop_ratio = 0;
/* Global encoder options */
xvid_enc_create.global = 0;
if (ARG_PACKED)
xvid_enc_create.global |= XVID_GLOBAL_PACKED;
if (ARG_CLOSED_GOP)
xvid_enc_create.global |= XVID_GLOBAL_CLOSED_GOP;
if (ARG_STATS)
xvid_enc_create.global |= XVID_GLOBAL_EXTRASTATS_ENABLE;
/* I use a small value here, since will not encode whole movies, but short clips */
xerr = xvid_encore(NULL, XVID_ENC_CREATE, &xvid_enc_create, NULL);
m_enc_handle = xvid_enc_create.handle;
return true;
}
void CXvidEnc::Encode(unsigned char * image) {
int ret = 0 ;
if(m_closed) return;
ret = enc_core(image, m_bitstream, &m_key) ;
// really encode some images into xvid data
if (ret > 0)
m_enc_caller->PostEncHandler(m_bitstream, m_key, ret) ;
}
/*
raw CXvidEnc procedure
*/
int CXvidEnc::enc_core(unsigned char *image,unsigned char *bitstream, int * key)
{
int ret;
xvid_enc_frame_t xvid_enc_frame;
xvid_enc_stats_t xvid_enc_stats;
/* Version for the frame and the stats */
memset(&xvid_enc_frame, 0, sizeof(xvid_enc_frame));
xvid_enc_frame.version = XVID_VERSION;
memset(&xvid_enc_stats, 0, sizeof(xvid_enc_stats));
xvid_enc_stats.version = XVID_VERSION;
/* Bind output buffer */
xvid_enc_frame.bitstream = bitstream;
xvid_enc_frame.length = -1;
/* Initialize input image fields */
xvid_enc_frame.input.plane[0] = image;
xvid_enc_frame.input.csp = XVID_CSP_BGR; // suppose we get data from usb web cam
xvid_enc_frame.input.stride[0] = m_width*3;
/* Set up core's general features */
xvid_enc_frame.vol_flags = 0;
/* Set up core's general features */
xvid_enc_frame.vop_flags = vop_presets[ARG_QUALITY-2];
/* Frame type -- let core decide for us */
xvid_enc_frame.type = XVID_TYPE_AUTO;
/* Force the right quantizer -- It is internally managed by RC plugins */
xvid_enc_frame.quant = 0;
/* Set up motion estimation flags */
xvid_enc_frame.motion = motion_presets[ARG_QUALITY-2];
/* We don't use special matrices */
xvid_enc_frame.quant_intra_matrix = NULL;
xvid_enc_frame.quant_inter_matrix = NULL;
/* Encode the frame */
ret = xvid_encore(m_enc_handle, XVID_ENC_ENCODE, &xvid_enc_frame,NULL);
// &xvid_enc_stats);
//--ÅбðÊÇ·ñÊǹؼüÖ¡
*key = (xvid_enc_frame.out_flags & XVID_KEYFRAME);
//*stats_type = xvid_enc_stats.type;
//*stats_quant = xvid_enc_stats.quant;
//*stats_length = xvid_enc_stats.length;
//sse[0] = xvid_enc_stats.sse_y;
//sse[1] = xvid_enc_stats.sse_u;
//sse[2] = xvid_enc_stats.sse_v;
return (ret);
}
| [
"laiyanlin@27d9c402-1b7e-11de-9433-ad2e3fad96c5"
]
| [
[
[
1,
245
]
]
]
|
89059bc34941afd2a900bd1dfc4d1ae3882514cf | fd792229322e4042f6e88a01144665cebdb1c339 | /src/user.h | 7447ba33a6679708163e3418bb30a3e3d1940e59 | []
| no_license | weimingtom/mmomm | 228d70d9d68834fa2470d2cd0719b9cd60f8dbcd | cab04fcad551f7f68f99fa0b6bb14cec3b962023 | refs/heads/master | 2021-01-10T02:14:31.896834 | 2010-03-15T16:15:43 | 2010-03-15T16:15:43 | 44,764,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,548 | h | #ifndef USER_H_
#define USER_H_
#include <string>
#include <RakNet/RakNetTypes.h>
#include <boost/unordered_set.hpp>
#include <boost/unordered_map.hpp>
#include "collision.h"
#include "vector2D.h"
class Actor;
class User {
public:
User(const std::string& username, const SystemAddress& address)
: _username(username), _address(address) { }
// Constant data
std::string username() const { return _username; }
SystemAddress address() const { return _address; }
// Send actor updates centered on the given position
// Network-intensive; do not call every frame.
void sendNetworkUpdate(const Actor *userActor);
// Send world updates centered on the given position
// Not-so-network-intensive; can call every frame.
void sendWorldMapUpdate(const Actor *userActor);
private:
// Data we last told the user about
struct ActorData {
ActorID id;
Vector2D position;
Vector2D velocity;
double time;
};
// What actors does this user know about; what'd we tell the player?
typedef boost::unordered_map< Actor *, ActorData > PacketMap;
PacketMap _packetMap;
typedef User::PacketMap::value_type PacketValue;
// Get a score on the specified data
struct ActorScore;
struct ActorScoreComparator;
static double score(const PacketValue& value, const Vector2D& reference);
// What cells this actor has been told about, and when
typedef boost::unordered_map< IVector2D, double > CellMap;
CellMap _cell;
std::string _username;
SystemAddress _address;
};
#endif
| [
"[email protected]",
"grandfunkdynasty@191a6260-07ae-11df-8636-19de83dc8dca"
]
| [
[
[
1,
3
],
[
6,
12
],
[
14,
58
]
],
[
[
4,
5
],
[
13,
13
]
]
]
|
d5df10643c0d8ccdd8121882cdba9b0ffb3a5b2e | 6060f9c92def1805578fe21068c193421e058278 | /src/MilVars.cpp | 0ef548e8ba9956965e89aeefac0fbc5a41bb25a5 | []
| no_license | MatthewNg3416/jaicam_test | 134150cba552a17f9fa94d678ff8a66923a0b82a | 8079fa66acde4b77023678b436891bcfe19ba8ca | refs/heads/master | 2021-05-27T00:19:23.665817 | 2011-05-12T15:53:41 | 2011-05-12T15:53:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,350 | cpp | /*
* $Id: MilVars.cpp,v 1.1.1.1 2009/01/06 19:15:52 scott Exp $
*
*/
#include <windows.h>
#include "MilVars.h"
// global scope, exported in MilVars.h
MilVars gMilVars;
MilVars::MilVars()
{
_MilApplication = 0;
_MilLiveSystem = -1;
}
MilVars::~MilVars()
{
releaseSystemID();
if (_MilApplication) {
MappFree(_MilApplication);
_MilApplication = 0;
}
}
MIL_ID MilVars::getApplicationID()
{
if (!_MilApplication) {
_MilApplication = MappAlloc(M_DEFAULT, M_NULL);
}
return _MilApplication;
}
MIL_ID MilVars::getStaticSystemID()
{
releaseSystemID();
if (!getApplicationID()) {
return -1;
}
return M_DEFAULT_HOST;
}
MIL_ID MilVars::getLiveSystemID()
{
if (_MilLiveSystem >= 0) {
return _MilLiveSystem;
}
if (!getApplicationID()) {
return -1;
}
#if !defined (_DEBUG)
MappControl(M_ERROR, M_PRINT_DISABLE);
#endif
_MilLiveSystem = MsysAlloc(M_SYSTEM_METEOR_II_1394, M_DEFAULT, M_COMPLETE, M_NULL);
if ((_MilLiveSystem == M_NULL) || (M_NULL_ERROR != MappGetError(M_CURRENT, M_NULL))) {
_MilLiveSystem = -1;
}
#if !defined (_DEBUG)
MappControl(M_ERROR, M_PRINT_ENABLE);
#endif
return _MilLiveSystem;
}
void MilVars::releaseSystemID()
{
if (_MilLiveSystem >= 0) {
MsysFree(_MilLiveSystem);
_MilLiveSystem = -1;
}
} | [
"[email protected]"
]
| [
[
[
1,
82
]
]
]
|
8ce49938c1e6779032ae5244a0337c8dd31d41f0 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/Fwd/hkcmalloc.h | 0e6ac36f189ea8229363b48aae84a512f05d816c | []
| 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,423 | 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.
*
*/
#if defined( HK_PLATFORM_PS3_PPU ) || defined( HK_PLATFORM_GC ) || defined( HK_PLATFORM_RVL ) || defined( HK_PLATFORM_MAC386 ) || defined( HK_PLATFORM_MACPPC )
#include <stdlib.h>
#else
#include <malloc.h>
namespace std {}
#endif
/*
* 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,
28
]
]
]
|
8ed0503e5187b6273e8edf8d540ba05883284be0 | 4b09766f45d506e8d451bae1bfe4d40fc25be4db | /cmgvc.h | d21069a4538ba6760bb5742b9b6a107622966268 | []
| no_license | caomw/ct2-inpainting | b8941a92018c6254d8694cec95bd83881db3e5a2 | 1bc707edc0b603146d581a9d3bc587958bf96d54 | refs/heads/master | 2021-01-19T11:53:11.739556 | 2011-05-10T21:22:04 | 2011-05-10T21:22:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | h | #ifndef CMGVC_H
#define CMGVC_H
#include "cimage.h"
/*#include "cmatrimage.h"*/
#include "cimagedouble.h"
#include "cvector2f.h"
#include "QDebug"
#include <QProgressBar>
#include <iostream>
class CMgvc
{
public:
CMgvc();
void appliquer(CImage *init, CImage *masque, CImage *out, float param1, float param2);
void set_progressbar(QProgressBar *);
private:
double TransformInterval (double x, double min1, double max1, double min2, double max2);
void ExpansionDynamique (CImageDouble * im, CImage * masque);
void Laplacien(CImageDouble *in, CImageDouble *out);
void Gradient(CImageDouble *in, CImageDouble * Rx, CImageDouble * Ry,CImageDouble *out);
QProgressBar * progressbar;
};
#endif // CMGVC_H
| [
"inoueediv@5e727123-e3d5-56dc-acd8-72af5541568b",
"[email protected]"
]
| [
[
[
1,
4
],
[
8,
9
],
[
11,
19
],
[
24,
27
]
],
[
[
5,
7
],
[
10,
10
],
[
20,
23
]
]
]
|
02c6c95a8b7723de8dbba95e93321e1cb1630da3 | 6c8c4728e608a4badd88de181910a294be56953a | /InventoryModule/J2kEncoder.cpp | 23c85f46b5ce8a2257ff7281182f614e18f3a624 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,124 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
/// @file J2kEncoder.cpp
/// @brief J2k encoding functionality required by image uploads.
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "J2kEncoder.h"
#include "InventoryModule.h"
#include <OgreColourValue.h>
#include "openjpeg.h"
#include "MemoryLeakCheck.h"
namespace J2k
{
using namespace Inventory;
void J2kErrorCallback(const char *msg, void *)
{
InventoryModule::LogError("J2kErrorCallback: " + std::string(msg));
}
void J2kWarningCallback(const char *msg, void *)
{
InventoryModule::LogWarning("J2kWarningCallback: " + std::string(msg));
}
void J2kInfoCallback(const char *msg, void *)
{
InventoryModule::LogInfo("J2kInfoCallback: " + std::string(msg));
}
bool IsPowerOfTwo(int value)
{
int bitcount = 0;
for (int i = 0; i < 32; ++i)
{
if (value & 1)
bitcount++;
if (bitcount > 1)
return false;
value >>= 1;
}
return true;
}
int GetClosestPowerOfTwo(int value)
{
int closest = 1;
// Use 2048 as max. size
for (int i = 11; i >= 0; --i)
{
int ptwo = 1 << i;
if (abs(ptwo-value) < abs(closest-value))
closest = ptwo;
}
return closest;
}
// Code adapted from LibOpenJpeg (http://www.openjpeg.org/index.php?menu=download), file image_to_j2k.c.
bool J2kEncode(Ogre::Image &src_image, std::vector<u8> &outbuf, bool reversible)
{
bool success;
opj_cparameters_t parameters; // compression parameters
opj_event_mgr_t event_mgr; // event manager
const int cMaxComponents = 5;
// Check for zero size
int width = src_image.getWidth();
int height = src_image.getHeight();
if (!width || !height)
{
InventoryModule::LogError("Zero image dimensions, cannot encode.");
return false;
}
// Scale the image to next power-of-two size, if necessary
// Otherwise old viewer will crash when trying to view the image
if (!IsPowerOfTwo(width) || !IsPowerOfTwo(height))
{
int new_w = GetClosestPowerOfTwo(width);
int new_h = GetClosestPowerOfTwo(height);
InventoryModule::LogInfo("Scaling image from " + ToString<int>(width) + "x" + ToString<int>(height) + " to " +
ToString<int>(new_w) + "x" + ToString<int>(new_h));
// Uses bilinear filter
src_image.resize(new_w, new_h);
width = src_image.getWidth();
height = src_image.getHeight();
}
int num_comps = 3;
if (src_image.getHasAlpha())
++num_comps;
// Configure the event callbacks (optional).
memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
// event_mgr.error_handler = J2kErrorCallback;
// event_mgr.warning_handler = J2kWarningCallback;
// event_mgr.info_handler = J2kInfoCallback;
// Set encoding parameters to default values.
opj_set_default_encoder_parameters(¶meters);
parameters.cod_format = 0; // 0 == J2K_CFMT
parameters.cp_disto_alloc = 1;
if (reversible)
{
parameters.tcp_numlayers = 1;
parameters.tcp_rates[0] = 0.0f;
}
else
{
parameters.tcp_numlayers = 5;
parameters.tcp_rates[0] = 1920.0f;
parameters.tcp_rates[1] = 480.0f;
parameters.tcp_rates[2] = 120.0f;
parameters.tcp_rates[3] = 30.0f;
parameters.tcp_rates[4] = 10.0f;
}
// Create comment for codestream.
///\todo Custom comments / no comments at all?
if(parameters.cp_comment == 0)
{
const char comment[] = "Created by OpenJPEG version ";
const size_t clen = strlen(comment);
const char *version = opj_version();
parameters.cp_comment = (char*)malloc(clen + strlen(version)+1);
sprintf(parameters.cp_comment,"%s%s", comment, version);
}
// Fill in the source image from our raw image
// Code adapted from convert.c.
OPJ_COLOR_SPACE color_space = CLRSPC_SRGB;
opj_image_cmptparm_t cmptparm[cMaxComponents];
opj_image_t *image = 0;
memset(&cmptparm[0], 0, cMaxComponents * sizeof(opj_image_cmptparm_t));
for(int c = 0; c < num_comps; c++)
{
cmptparm[c].prec = 8;
cmptparm[c].bpp = 8;
cmptparm[c].sgnd = 0;
cmptparm[c].dx = parameters.subsampling_dx;
cmptparm[c].dy = parameters.subsampling_dy;
cmptparm[c].w = width;
cmptparm[c].h = height;
}
// Decode the source image.
image = opj_image_create(num_comps, &cmptparm[0], color_space);
// Decide if MCT should be used.
parameters.tcp_mct = image->numcomps >= 3 ? 1 : 0;
image->x1 = width;
image->y1 = height;
int i = 0;
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
Ogre::ColourValue pixel = src_image.getColourAt(x,y,0);
for (int c = 0; c < num_comps; ++c)
{
switch (c)
{
case 0:
image->comps[c].data[i] = pixel.r * 255.0;
break;
case 1:
image->comps[c].data[i] = pixel.g * 255.0;
break;
case 2:
image->comps[c].data[i] = pixel.b * 255.0;
break;
case 3:
image->comps[c].data[i] = pixel.a * 255.0;
break;
}
}
++i;
}
}
// Encode the destination image.
opj_cio_t *cio = 0;
// Get a J2K compressor handle.
opj_cinfo_t* cinfo = opj_create_compress(CODEC_J2K);
// Catch events using our callbacks and give a local context.
opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);
// Setup the encoder parameters using the current image and user parameters.
opj_setup_encoder(cinfo, ¶meters, image);
// Open a byte stream for writing. Allocate memory for all tiles.
cio = opj_cio_open((opj_common_ptr)cinfo, 0, 0);
// Encode the image.
success = opj_encode(cinfo, cio, image, 0);
if (!success)
{
opj_cio_close(cio);
opj_image_destroy(image);
InventoryModule::LogInfo("Failed to encode image.");
return false;
}
// Write encoded data to output buffer.
outbuf.resize(cio_tell(cio));
// InventoryModule::LogDebug("J2k datastream size: " + outbuf.size());
memcpy(&outbuf[0], cio->buffer, outbuf.size());
// Close and free the byte stream.
opj_cio_close(cio);
// Free remaining compression structures.
opj_destroy_compress(cinfo);
// Free image data.
opj_image_destroy(image);
// Free user parameters structure.
if (parameters.cp_comment)
free(parameters.cp_comment);
if (parameters.cp_matrice)
free(parameters.cp_matrice);
return true;
}
}
| [
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jaakkoallander@5b2332b8-efa3-11de-8684-7d64432d61a3",
"jujjyl@5b2332b8-efa3-11de-8684-7d64432d61a3",
"cadaver@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
5
],
[
7,
7
],
[
13,
13
]
],
[
[
6,
6
],
[
8,
9
],
[
11,
12
],
[
14,
62
],
[
64,
84
],
[
87,
240
]
],
[
[
10,
10
]
],
[
[
63,
63
],
[
85,
86
]
]
]
|
5a8c3bd8706c898f630478bb8920f26f867bee0d | 38664d844d9fad34e88160f6ebf86c043db9f1c5 | /branches/initialize/infostudio/InfoStudio/ado/AdoRecordSet.h | d2937a65409c9296a6069bb23ad29427dded539c | []
| no_license | cnsuhao/jezzitest | 84074b938b3e06ae820842dac62dae116d5fdaba | 9b5f6cf40750511350e5456349ead8346cabb56e | refs/heads/master | 2021-05-28T23:08:59.663581 | 2010-11-25T13:44:57 | 2010-11-25T13:44:57 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 9,611 | h | /*########################################################################
【文件名】: ado.h
【名 称】: ADO 封装类.
【版 本】: 0.20
【作 者】: 成真
【E-mail】: [email protected]
########################################################################*/
#if !defined(_ANYOU_COOL_ADORECORDSET_H)
#define _ANYOU_COOL_ADORECORDSET_H
#include "Ado.h"
/*########################################################################
------------------------------------------------
CAdoRecordSet class
------------------------------------------------
########################################################################*/
class CAdoRecordSet
{
// 构建/折构 --------------------------------------------
public:
CAdoRecordSet();
CAdoRecordSet(CAdoConnection *pConnection);
virtual ~CAdoRecordSet();
protected:
void Release();
// 属性 ------------------------------------------------
public:
// 当前编辑状态 ----------------------------
EditModeEnum GetEditMode();
// 当前状态 --------------------------------
BOOL IsEOF();
BOOL IsBOF();
BOOL IsOpen();
long GetState();
long GetStatus();
// 充许返回的最大记录数 --------------------
long GetMaxRecordCount();
BOOL SetMaxRecordCount(long count);
// 光标位置 --------------------------------
CursorLocationEnum GetCursorLocation();
BOOL SetCursorLocation(CursorLocationEnum CursorLocation = adUseClient);
// 光标类型 --------------------------------
CursorTypeEnum GetCursorType();
BOOL SetCursorType(CursorTypeEnum CursorType = adOpenStatic);
// 书签 --------------------------------
_variant_t GetBookmark();
BOOL SetBookmark(_variant_t varBookMark = _variant_t((long)adBookmarkFirst));
// 当前记录位置 ------------------------
long GetAbsolutePosition();
BOOL SetAbsolutePosition(int nPosition);
long GetAbsolutePage();
BOOL SetAbsolutePage(int nPage);
// 每页的记录数 ------------------------
long GetPageSize();
BOOL SetCacheSize(const long& lCacheSize);
// 页数 --------------------------------
long GetPageCount();
// 记录数及字段数 ----------------------
long GetRecordCount();
long GetFieldsCount();
// 查询字符串 --------------------------
CString GetSQLText() {return m_strSQL;}
void SetSQLText(LPCTSTR strSQL) {m_strSQL = strSQL;}
// 连接对象 ----------------------------
CAdoConnection* GetConnection() {return m_pConnection;}
void SetAdoConnection(CAdoConnection *pConnection);
// 记录集对象 --------------------------
_RecordsetPtr& GetRecordset();
CString GetLastError();
// 字段属性 ----------------------------------------------
public:
// 字段集 -------------------------------
FieldsPtr GetFields();
// 字段对象 -----------------------------
FieldPtr GetField(long lIndex);
FieldPtr GetField(LPCTSTR lpszFieldName);
// 字段名 -------------------------------
CString GetFieldName(long lIndex);
// 字段数据类型 -------------------------
DataTypeEnum GetFieldType(long lIndex);
DataTypeEnum GetFieldType(LPCTSTR lpszFieldName);
// 字段属性 -----------------------------
long GetFieldAttributes(long lIndex);
long GetFieldAttributes(LPCTSTR lpszFieldName);
// 字段定义长度 -------------------------
long GetFieldDefineSize(long lIndex);
long GetFieldDefineSize(LPCTSTR lpszFieldName);
// 字段实际长度 -------------------------
long GetFieldActualSize(long lIndex);
long GetFieldActualSize(LPCTSTR lpszFieldName);
// 字段是否为NULL -----------------------
BOOL IsFieldNull(long index);
BOOL IsFieldNull(LPCTSTR lpFieldName);
// 记录更改 --------------------------------------------
public:
BOOL AddNew();
BOOL Update();
BOOL UpdateBatch(AffectEnum AffectRecords = adAffectAll);
BOOL CancelUpdate();
BOOL CancelBatch(AffectEnum AffectRecords = adAffectAll);
BOOL Delete(AffectEnum AffectRecords = adAffectCurrent);
// 刷新记录集中的数据 ------------------
BOOL Requery(long Options = adConnectUnspecified);
BOOL Resync(AffectEnum AffectRecords = adAffectAll, ResyncEnum ResyncValues = adResyncAllValues);
BOOL RecordBinding(CADORecordBinding &pAdoRecordBinding);
BOOL AddNew(CADORecordBinding &pAdoRecordBinding);
// 记录集导航操作 --------------------------------------
public:
BOOL MoveFirst();
BOOL MovePrevious();
BOOL MoveNext();
BOOL MoveLast();
BOOL Move(long lRecords, _variant_t Start = _variant_t((long)adBookmarkFirst));
// 查找指定的记录 ----------------------
BOOL Find(LPCTSTR lpszFind, SearchDirectionEnum SearchDirection = adSearchForward);
BOOL FindNext();
// 查询 ------------------------------------------------
public:
BOOL Open(LPCTSTR strSQL, long lOption = adCmdText, CursorTypeEnum CursorType = adOpenStatic, LockTypeEnum LockType = adLockOptimistic);
BOOL Cancel();
void Close();
// 保存/载入持久性文件 -----------------
BOOL Save(LPCTSTR strFileName = _T(""), PersistFormatEnum PersistFormat = adPersistXML);
BOOL Load(LPCTSTR strFileName);
// 字段存取 --------------------------------------------
public:
BOOL PutCollectV(long index, const _variant_t &value);
BOOL PutCollect(long index, const CString &value);
BOOL PutCollect(long index, const double &value);
BOOL PutCollect(long index, const float &value);
BOOL PutCollect(long index, const long &value);
BOOL PutCollect(long index, const DWORD &value);
BOOL PutCollect(long index, const int &value);
BOOL PutCollect(long index, const short &value);
BOOL PutCollect(long index, const BYTE &value);
BOOL PutCollect(long index, const bool &value);
BOOL PutCollect(long index, const SYSTEMTIME &value);
//BOOL PutCollect(long index, const COleCurrency &value);
BOOL PutCollectV(LPCTSTR strFieldName, const _variant_t &value);
BOOL PutCollect(LPCTSTR strFieldName, const CString &value);
BOOL PutCollect(LPCTSTR strFieldName, const double &value);
BOOL PutCollect(LPCTSTR strFieldName, const float &value);
BOOL PutCollect(LPCTSTR strFieldName, const long &value);
BOOL PutCollect(LPCTSTR strFieldName, const DWORD &value);
BOOL PutCollect(LPCTSTR strFieldName, const int &value);
BOOL PutCollect(LPCTSTR strFieldName, const short &value);
BOOL PutCollect(LPCTSTR strFieldName, const BYTE &value);
BOOL PutCollect(LPCTSTR strFieldName, const bool &value);
BOOL PutCollect(LPCTSTR strFieldName, const SYSTEMTIME &value);
//BOOL PutCollect(LPCTSTR strFieldName, const COleCurrency &value);
// ---------------------------------------------------------
BOOL GetCollect(long index, CString &value);
BOOL GetCollect(long index, double &value);
BOOL GetCollect(long index, float &value);
BOOL GetCollect(long index, long &value);
BOOL GetCollect(long index, DWORD &value);
BOOL GetCollect(long index, int &value);
BOOL GetCollect(long index, short &value);
BOOL GetCollect(long index, BYTE &value);
BOOL GetCollect(long index, bool &value);
BOOL GetCollect(long index, SYSTEMTIME &value);
//BOOL GetCollect(long index, COleCurrency &value);
BOOL GetCollect(LPCTSTR strFieldName, CString &strValue);
BOOL GetCollect(LPCTSTR strFieldName, double &value);
BOOL GetCollect(LPCTSTR strFieldName, float &value);
BOOL GetCollect(LPCTSTR strFieldName, long &value);
BOOL GetCollect(LPCTSTR strFieldName, DWORD &value);
BOOL GetCollect(LPCTSTR strFieldName, int &value);
BOOL GetCollect(LPCTSTR strFieldName, short &value);
BOOL GetCollect(LPCTSTR strFieldName, BYTE &value);
BOOL GetCollect(LPCTSTR strFieldName, bool &value);
BOOL GetCollect(LPCTSTR strFieldName, SYSTEMTIME &value);
//BOOL GetCollect(LPCTSTR strFieldName, COleCurrency &value);
// BLOB 数据存取 ------------------------------------------
BOOL AppendChunk(FieldPtr pField, LPVOID lpData, UINT nBytes);
BOOL AppendChunk(long index, LPVOID lpData, UINT nBytes);
BOOL AppendChunk(LPCTSTR strFieldName, LPVOID lpData, UINT nBytes);
BOOL AppendChunk(long index, LPCTSTR lpszFileName);
BOOL AppendChunk(LPCTSTR strFieldName, LPCTSTR lpszFileName);
BOOL GetChunk(FieldPtr pField, LPVOID lpData);
BOOL GetChunk(long index, LPVOID lpData);
BOOL GetChunk(LPCTSTR strFieldName, LPVOID lpData);
BOOL GetChunk(long index, CBitmap &bitmap);
BOOL GetChunk(LPCTSTR strFieldName, CBitmap &bitmap);
// 其他方法 --------------------------------------------
public:
// 过滤记录 ---------------------------------
BOOL SetFilter(LPCTSTR lpszFilter);
// 排序 -------------------------------------
BOOL SetSort(LPCTSTR lpszCriteria);
// 测试是否支持某方法 -----------------------
BOOL Supports(CursorOptionEnum CursorOptions = adAddNew);
// 克隆 -------------------------------------
BOOL Clone(CAdoRecordSet &pRecordSet);
_RecordsetPtr operator = (_RecordsetPtr &pRecordSet);
// 格式化 _variant_t 类型值 -----------------
//成员变量 --------------------------------------------
protected:
CAdoConnection *m_pConnection;
_RecordsetPtr m_pRecordset;
CString m_strSQL;
CString m_strFind;
CString m_strFileName;
IADORecordBinding *m_pAdoRecordBinding;
SearchDirectionEnum m_SearchDirection;
public:
_variant_t m_varBookmark;
};
//________________________________________________________________________
#endif //_ANYOU_COOL_ADORECORDSET_H | [
"ken.shao@ba8f1dc9-3c1c-0410-9eed-0f8a660c14bd"
]
| [
[
[
1,
256
]
]
]
|
21270964b3ee795675111d1a5005048d910daeac | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/gfx/nshaderprogram.cc | 39db3a941d669dcdf738f5cfebf0eaee6bdd9f8c | []
| 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 | 1,822 | cc | #define N_IMPLEMENTS nShaderProgram
//------------------------------------------------------------------------------
// nshaderprogram.cc
// (C) 2006 Insightec Ltd, -- I.Kliot
//------------------------------------------------------------------------------
#include "gfx/nshaderprogram.h"
#include "gfx/ngfxserver.h"
#include "kernel/nfileserver2.h"
nNebulaClass(nShaderProgram, "nroot");
nShaderProgram::nShaderProgram() :
initialized(false),
activeProgram(false),
refGfx(kernelServer, this),
pairRef(this)
{
this->refGfx = "/sys/servers/gfx";
}
nShaderProgram::~nShaderProgram() {
// invalidate current font
release_ref(this->pairRef);
}
/// load shaders from files
bool nShaderProgram::LoadShaders(const char* vertex, const char* fragment)
{
release_ref(this->pairRef);
nFileServer2* fs = this->kernelServer->GetFileServer2();
stl_string path_vsh("no_vertex");
if (vertex)
{
fs->MakeAbsoluteMangled(vertex, path_vsh);
}
stl_string id(path_vsh);
stl_string path_fsh("no_fragment");
const char* fsh_fname = path_fsh.c_str();
if (fragment)
{
fs->MakeAbsoluteMangled(fragment, path_fsh);
fsh_fname = strrchr(path_fsh.c_str(), '/') + 1;
}
id += '_';
id += fsh_fname;
// see if texture already exists and can be shared
nShaderPair* pair = this->refGfx->FindShaderPair(id.c_str());
if (!pair)
{
pair = this->refGfx->NewShaderPair(id.c_str());
n_assert(pair);
if (!(vertex && fragment))
n_printf("Loading program %s without %s shader\n", id.c_str(), vertex ? "fragment" : "vertex");
this->initialized = pair->Load(vertex, fragment);
}
else
this->initialized = pair->Linked();
if (pair && this->initialized)
this->pairRef = pair;
return this->initialized;
} | [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
74
]
]
]
|
15c78a288aeca1248862baf7ea3ffd80e8482466 | cac9d7127b80c67223135204095e80f7869c1502 | /src/ServerSocket.cpp | e392535dfb1a4f18609146f153d32cbda6f3b770 | []
| no_license | perepechaev/xmud | d26bef482ebd7df23487b4479de236d483609af7 | 9841842b44d7237b4a4c17e40437dc700cad08bc | refs/heads/master | 2020-05-18T02:49:15.102595 | 2011-03-21T09:39:40 | 2011-03-21T09:39:40 | 1,505,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,448 | cpp | // Implementation of the ServerSocket class
#include "ServerSocket.h"
#include "SocketException.h"
ServerSocket::ServerSocket ( int port )
{
if ( ! Socket::create() )
{
throw SocketException ( "Could not create server socket." );
}
if ( ! Socket::bind ( port ) )
{
throw SocketException ( "Could not bind to port." );
}
if ( ! Socket::listen() )
{
throw SocketException ( "Could not listen to socket." );
}
}
ServerSocket::~ServerSocket()
{
}
const ServerSocket& ServerSocket::operator << ( const std::string& s ) const
{
if ( ! Socket::send ( s ) )
{
throw SocketException ( "Could not write to socket." );
}
return *this;
}
const ServerSocket& ServerSocket::operator >> ( std::string& s ) const
{
if ( ! Socket::recv ( s ) )
{
throw SocketException ( "Could not read from socket." );
}
return *this;
}
const ServerSocket& ServerSocket::operator >> ( char*& s ) const
{
std::string *buf = new std::string(s);
printf("Hello: \n");
return *this;
if ( ! Socket::recv ( *buf ) )
{
throw SocketException ( "Could not read from socket." );
}
s = (char *) buf->c_str();
return *this;
}
void ServerSocket::accept ( ServerSocket& sock )
{
if ( ! Socket::accept ( sock ) )
{
throw SocketException ( "Could not accept socket." );
}
}
| [
"[email protected]"
]
| [
[
[
1,
73
]
]
]
|
7542fad51c5f1afc20da764c0dd24169ba31ff2e | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /XMonitor/debug/moc_ReportThread.cpp | 4a376aa0a57a46ea9b9b00ab4fed632802c9c7c2 | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,158 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'ReportThread.h'
**
** Created: Fri Apr 1 12:37:33 2011
** by: The Qt Meta Object Compiler version 62 (Qt 4.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/ReportThread.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ReportThread.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 62
#error "This file was generated using the moc from 4.7.0. 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_ReportThread[] = {
// content:
5, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
static const char qt_meta_stringdata_ReportThread[] = {
"ReportThread\0"
};
const QMetaObject ReportThread::staticMetaObject = {
{ &XThread::staticMetaObject, qt_meta_stringdata_ReportThread,
qt_meta_data_ReportThread, 0 }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &ReportThread::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *ReportThread::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *ReportThread::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_ReportThread))
return static_cast<void*>(const_cast< ReportThread*>(this));
return XThread::qt_metacast(_clname);
}
int ReportThread::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = XThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
69
]
]
]
|
61bd82025e40276ab6b9f0ecf704265b773a8d0a | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Engine/sdk/inc/physics/collision_object.h | e4bc97430a56d81fdb0aa32a6e5f20545a132807 | []
| 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 | 23,450 | h | #ifndef __COLLISION_OBJECT_H__
#define __COLLISION_OBJECT_H__
#ifndef __LTBASETYPES_H__
#include "ltbasetypes.h"
#endif
#ifndef __COLLISION_DATA_H__
#include "collision_data.h"
#endif
//---------------------------------------------------------------------------//
/*!
The LTContactInfo data type contains information about a collision
between two collision objects.
\see ILTCollisionObject, ILTCollisionMgr.
Used for: Physics
*/
struct LTContactInfo
{
/*!
The LTContactInfo::Filter function object interface allows collision
routines to ignore certain contacts based on application-defined
conditions. If the Condition() function returns \b false, the object
is ignored.
\see ILTCollisionMgr::Collide().
Used for: Physics
*/
struct Filter
{
/*!
\param ii An LTContactInfo structure
\return \b false if the contact should be ignored,
\b true otherwise
Override this function with application-specific filter conditions.
\see ILTCollisionMgr::Collide(), ILTCollisionObject::Hit().
Used for: Physics
*/
virtual bool Condition( const LTContactInfo& ci ) const = 0;
};
/*!
This function object always returns true (no filtering).
\see ILTCollisionObject::Filter.
Used for: Physics
*/
struct EmptyFilter : public Filter
{
bool Condition( const LTContactInfo& ci ) const
{
return true;
}
};
/*!handle of contacted object, NULL if static geometry*/
HOBJECT m_hObj;
/*!normalized time of contact [0,1]*/
float m_U;
/*!contact normal and contact point in world space*/
LTVector3f m_N, m_P;
/*!contact surface properties of A and B, respectively*/
LTPhysSurf m_Sa, m_Sb;
LTContactInfo()
: m_U(2), m_hObj(NULL), m_N(0,0,0), m_P(0,0,0)
{}
/*!
\param h object handle
\param u normalized time of contact, \f$ u \in [0,1] \f$.
\param n contact normal
\param p contact point
\param n contact normal
\param sa object A's surface properties at p
\param sb object B's surface properties at p
Construct the LTContactInfo.
\see ILTCollisionMgr::Collide()
Used For: Physics.
*/
LTContactInfo
(
HOBJECT h,
float u,
const LTVector3f& n,
const LTVector3f& p,
const LTPhysSurf& sa,
const LTPhysSurf& sb
)
: m_hObj(h), m_U(u), m_N(n), m_P(p), m_Sa(sa), m_Sb(sb)
{}
};
//---------------------------------------------------------------------------//
/*!
The LTIntersectInfo data type contains information about an intersection
between two collision objects.
\note Only for intersections with line segments will m_P be exact.
Intersections between all other primitives will have approximate m_P
values.
\see ILTCollisionObject, ILTCollisionMgr.
Used for: Physics
*/
struct LTIntersectInfo
{
/*!
The LTIntersectInfo::Filter function object interface allows intersection
routines to ignore certain intersections based on application-defined
conditions. If the Condition() function returns \b false, the object
is ignored.
\see ILTCollisionMgr::Intersect().
Used for: Physics
*/
struct Filter
{
/*!
\param ii An LTIntersectInfo structure
\return \b false if the intersection should be ignored,
\b true otherwise
Override this function with application-specific filter conditions.
\see ILTCollisionMgr::Intersect(), ILTCollisionObject::Intersect().
Used for: Physics
*/
virtual bool Condition( const LTIntersectInfo& ii ) const = 0;
};
/*!
This function object always returns true (no filtering).
\see ILTCollisionObject::Filter.
Used for: Physics
*/
struct EmptyFilter : public Filter
{
bool Condition( const LTIntersectInfo& ii ) const
{
return true;
}
};
/*!
The handle of the LTObject that was intersected, NULL if static geometry.
*/
HOBJECT m_hObj;
/*!
The (approximate) position of intersection.
*/
LTVector3f m_P;
/*!
The vector to translate \b one of the objects so that they are disjoint.
*/
LTVector3f m_T;
LTIntersectInfo()
: m_hObj(NULL), m_P(0,0,0), m_T(0,0,0)
{}
/*!
\param h object handle
\param d depth of penetration
\param n contact normal
Construct the LTIntersectInfo.
\see ILTCollisionMgr::Intersect()
Used For: Physics.
*/
LTIntersectInfo( const HOBJECT h, const LTVector3f& t )
: m_hObj(h), m_T(t)
{}
};
#ifndef DOXYGEN_SHOULD_SKIP_THIS
//pre-declarations
class LTCollisionSphere;
class LTCollisionBox;
class LTCollisionCylinder;
class LTCollisionMesh;
#endif//doxygen
/*!
Types of collision primitives.
\see ILTCollisionObject.
Used for: Physics.
*/
enum COLLISION_OBJECT_TYPE
{
COT_SPHERE,
COT_BOX,
COT_CYLINDER,
COT_MESH,
COT_COUNT //number of types
};
//---------------------------------------------------------------------------//
/*!
The ILTCollisionObject interface represents a geometric shape to the
ILTCollisionMgr.
\see ILTCollisionMgr.
Used for: Physics
*/
class ILTCollisionObject
{
public:
/*!
The ILTCollisionObject::Filter function object interface allows collision
and intersection routines to ignore ILTCollisionObject's based on
application-defined conditions. If the Condition() function returns
\b false, the object is ignored.
\see ILTCollisionMgr::Collide(), ILTCollisionMgr::Intersect().
Used for: Physics
*/
struct Filter
{
/*!
\param o An ILTCollisionObject
\return \b false if the object should be ignored,
\b true otherwise
Override this function with application-specific filter conditions.
\see ILTCollisionMgr::Collide(), ILTCollisionMgr::Intersect().
Used for: Physics
*/
virtual bool Condition( const ILTCollisionObject& o ) const = 0;
};
/*!
This function object always returns true (no filtering).
\see ILTCollisionObject::Filter.
Used for: Physics
*/
struct EmptyFilter : public Filter
{
bool Condition( const ILTCollisionObject& obj ) const
{
return true;
}
};
/*!Type field.*/
COLLISION_OBJECT_TYPE m_Type;
/*! Object handle, NULL if static world geometry */
HOBJECT m_hObj;
/*! Position at time \f$ t_0 \f$ */
LTVector3f m_P0;
/*! Position at time \f$ t_0 + \Delta t \f$ */
LTVector3f m_P1;
/*! Orientation at time \f$ t_0 \f$ */
LTOrientation m_R0;
/*! Orientation at time \f$ t_0 + \Delta t \f$ */
LTOrientation m_R1;
public:
/*!
\param t Type
\param h Object handle
\param p0 Position at time \f$ t_0 \f$
\param p1 Position at time \f$ t_0 + \Delta t \f$
\param R0 Orientation at time \f$ t_0 \f$
\param R1 Orientation at time \f$ t_0 + \Delta t \f$
Construct the object.
\see ILTCollisionMgr
Used For: Physics.
*/
ILTCollisionObject
(
COLLISION_OBJECT_TYPE t,
HOBJECT hobj,
const LTVector3f& p0,
const LTVector3f& p1,
const LTOrientation& R0,
const LTOrientation& R1
)
: m_Type(t), m_hObj(hobj),
m_P0(p0), m_P1(p1),
m_R0(R0), m_R1(R1)
{}
virtual ~ILTCollisionObject()
{}
/*!
\param i [Return parameter] Collision information.
\param o Another ILTCollisionObject
\return \b true if this object hit \b o,
\b false otherwise
Check if this collision object came into contact with \b o
during its linear trajectory.
\note This function assumes both collision objects are
in the same parent coordinate frame.
\see LTContactInfo, ILTCollisionMgr::Collide()
Used For: Physics.
*/
virtual bool Hit
(
LTContactInfo& ci, const ILTCollisionObject& o,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Hit().
Used For: Physics.
*/
virtual bool HitSphere
(
LTContactInfo& ci, const LTCollisionSphere& s,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Hit().
Used For: Physics.
*/
virtual bool HitBox
(
LTContactInfo& ci, const LTCollisionBox& b,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Hit().
Used For: Physics.
*/
virtual bool HitCylinder
(
LTContactInfo& ci, const LTCollisionCylinder& c,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Hit().
Used For: Physics.
*/
virtual bool HitMesh
(
LTContactInfo& ci, const LTCollisionMesh& m,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const = 0;
/*!
\param i [Return parameter] Intersection information.
\param o Another ILTCollisionObject
\return \b true if this object intersects \b o,
\b false otherwise
Check if this collision object intersects \b o at their positions
\f$ {\bf p}_1 \f$.
\see LTIntersectInfo, ILTCollisionMgr::Intersect().
Used For: Physics.
*/
virtual bool Intersect
(
LTIntersectInfo& ii, const ILTCollisionObject& o,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Intersect().
Used For: Physics.
*/
virtual bool IntersectSphere
(
LTIntersectInfo& ii, const LTCollisionSphere& s,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Intersect().
Used For: Physics.
*/
virtual bool IntersectBox
(
LTIntersectInfo& ii, const LTCollisionBox& b,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Intersect().
Used For: Physics.
*/
virtual bool IntersectCylinder
(
LTIntersectInfo& ii, const LTCollisionCylinder& c,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const = 0;
/*!
\see ILTCollisionObject::Intersect().
Used For: Physics.
*/
virtual bool IntersectMesh
(
LTIntersectInfo& ii, const LTCollisionMesh& m,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const = 0;
/*!
\param ii [Return parameter] An array of LTIntersectInfo structures.
\param n [Return parameter] The number of intersections.
\param sz The number of elements in \b ii.
\param p0 The beginning point of the line segment.
\param p1 The ending point of the line segment.
\param of Object filter (empty by default).
\param iif Intersection info filter (empty by default).
\return \b true if the line segment intersects anything,
\b false otherwise.
Check if this collision object intersects the line segment
\f$ \bar{ {\bf p}_0 {\bf p}_1 } \f$.
Ignore objects and intersections based on conditions imposed by the filters..
\see LTIntersectInfo, ILTCollisionMgr::IntersectSegment().
Used For: Physics.
*/
virtual bool IntersectSegment
(
LTIntersectInfo ii[],
int32& n,
const int32 sz,
const LTVector3f& p0,
const LTVector3f& p1,
const LTIntersectInfo::Filter& iif
) const = 0;
};
//---------------------------------------------------------------------------//
/*!
The LTCollisionSphere represents a sphere to the ILTCollisionMgr.
\see ILTCollisionMgr, ILTCollisionObject.
Used for: Physics
*/
class LTCollisionSphere : public ILTCollisionObject
{
public:
/*!sphere radius*/
float m_Radius;
/*!physical surface properties*/
LTPhysSurf m_Surf;
public:
/*!
\param r Sphere radius
\param p0 Position at time \f$ t_0 \f$
\param p1 Position at time \f$ t_0 + \Delta t \f$
\param s Physical surface properties, 0's by default
\param h Object handle, NULL by default
Construct the object.
\see ILTCollisionObject, ILTCollisionMgr
Used For: Physics.
*/
LTCollisionSphere
(
float r,
const LTVector3f& p0,
const LTVector3f& p1,
const LTPhysSurf s = LTPhysSurf(),//dummy
HOBJECT hobj = NULL
)
: ILTCollisionObject(COT_SPHERE,hobj,p0,p1,LTOrientation(),LTOrientation()),
m_Radius(r), m_Surf(s)
{}
//Hit
virtual bool Hit
(
LTContactInfo& ci, const ILTCollisionObject& o,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitSphere
(
LTContactInfo& ci, const LTCollisionSphere& s,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitBox
(
LTContactInfo& ci, const LTCollisionBox& b,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitCylinder
(
LTContactInfo& ci, const LTCollisionCylinder& c,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitMesh
(
LTContactInfo& ci, const LTCollisionMesh& m,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
//Intersect
virtual bool Intersect
(
LTIntersectInfo& ii, const ILTCollisionObject& o,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSphere
(
LTIntersectInfo& ii, const LTCollisionSphere& s,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectBox
(
LTIntersectInfo& ii, const LTCollisionBox& b,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectCylinder
(
LTIntersectInfo& ii, const LTCollisionCylinder& c,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectMesh
(
LTIntersectInfo& ii, const LTCollisionMesh& m,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSegment
(
LTIntersectInfo ii[],
int32& n,
const int32 sz,
const LTVector3f& p0,
const LTVector3f& p1,
const LTIntersectInfo::Filter& iif
) const;
};
//---------------------------------------------------------------------------//
/*!
The LTCollisionBox represents a box to the ILTCollisionMgr.
\see ILTCollisionMgr, ILTCollisionObject.
Used for: Physics
*/
class LTCollisionBox : public ILTCollisionObject
{
public:
/*!half-dimensions*/
LTVector3f m_Dim;
/*!physical surface properties*/
LTPhysSurf m_Surf;
public:
/*!
\param d Half-dimensions of box
\param p0 Position at time \f$ t_0 \f$
\param p1 Position at time \f$ t_0 + \Delta t \f$
\param R0 Orientation at time \f$ t_0 \f$
\param R1 Orientation at time \f$ t_0 + \Delta t \f$
\param s Physical surface properties
\param h Object handle (NULL by default)
Construct the object.
\see ILTCollisionObject, ILTCollisionMgr
Used For: Physics.
*/
LTCollisionBox
(
//half-dimensions
const LTVector3f& d,
//coordinate frame at u=0
const LTVector3f& p0, const LTVector3f& p1,
//coordinate frame at u=1
const LTOrientation& R0, const LTOrientation& R1,
//physical surface properties
const LTPhysSurf s = LTPhysSurf(),
//handle to LTObject
HOBJECT hobj = NULL
)
: ILTCollisionObject(COT_BOX,hobj,p0,p1,R0,R1),
m_Dim(d), m_Surf(s)
{}
//Hit
virtual bool Hit
(
LTContactInfo& ci, const ILTCollisionObject& o,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitSphere
(
LTContactInfo& ci, const LTCollisionSphere& s,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitBox
(
LTContactInfo& ci, const LTCollisionBox& b,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitCylinder
(
LTContactInfo& ci, const LTCollisionCylinder& c,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitMesh
(
LTContactInfo& ci, const LTCollisionMesh& m,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
//Intersect
virtual bool Intersect
(
LTIntersectInfo& ii, const ILTCollisionObject& o,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSphere
(
LTIntersectInfo& ii, const LTCollisionSphere& s,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectBox
(
LTIntersectInfo& ii, const LTCollisionBox& b,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectCylinder
(
LTIntersectInfo& ii, const LTCollisionCylinder& c,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectMesh
(
LTIntersectInfo& ii, const LTCollisionMesh& m,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSegment
(
LTIntersectInfo ii[],
int32& n,
const int32 sz,
const LTVector3f& p0,
const LTVector3f& p1,
const LTIntersectInfo::Filter& iif
) const;
};
//---------------------------------------------------------------------------//
/*!
The LTCollisionCylinder represents a cylinder to the ILTCollisionMgr.
\see ILTCollisionMgr, ILTCollisionObject.
Used for: Physics
*/
class LTCollisionCylinder : public ILTCollisionObject
{
public:
/*! The cylinder's radius */
float m_Radius;
/*! The cylinder's half-height along its local y-axis */
float m_HHeight;//H/2
/*! The cylinder's physical surface properties */
LTPhysSurf m_Surf;
public:
/*!
\param r Radius
\param hh Half-height
\param p0 Position at time \f$ t_0 \f$
\param p1 Position at time \f$ t_0 + \Delta t \f$
\param R0 Orientation at time \f$ t_0 \f$
\param R1 Orientation at time \f$ t_0 + \Delta t \f$
\param s Physical surface properties
\param h Object handle (NULL by default)
Construct the object.
\see ILTCollisionObject, ILTCollisionMgr
Used For: Physics.
*/
LTCollisionCylinder
(
//radius
const float r,
//half-height
const float hh,
//coordinate frame at u=0
const LTVector3f& p0, const LTVector3f& p1,
//coordinate frame at u=1
const LTOrientation& R0, const LTOrientation& R1,
//physical surface properties
const LTPhysSurf s = LTPhysSurf(),
//handle to LTObject
HOBJECT hobj = NULL
)
: ILTCollisionObject(COT_CYLINDER,hobj,p0,p1,R0,R1),
m_Radius( r ), m_HHeight( hh ), m_Surf(s)
{}
//Hit
virtual bool Hit
(
LTContactInfo& ci, const ILTCollisionObject& o,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitSphere
(
LTContactInfo& ci, const LTCollisionSphere& s,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitBox
(
LTContactInfo& ci, const LTCollisionBox& b,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitCylinder
(
LTContactInfo& ci, const LTCollisionCylinder& c,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitMesh
(
LTContactInfo& ci, const LTCollisionMesh& m,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
//Intersect
virtual bool Intersect
(
LTIntersectInfo& ii, const ILTCollisionObject& o,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSphere
(
LTIntersectInfo& ii, const LTCollisionSphere& s,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectBox
(
LTIntersectInfo& ii, const LTCollisionBox& b,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectCylinder
(
LTIntersectInfo& ii, const LTCollisionCylinder& c,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectMesh
(
LTIntersectInfo& ii, const LTCollisionMesh& m,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSegment
(
LTIntersectInfo ii[],
int32& n,
const int32 sz,
const LTVector3f& p0,
const LTVector3f& p1,
const LTIntersectInfo::Filter& iif
) const;
};
//---------------------------------------------------------------------------//
/*!
The LTCollisionMesh represents a polygonal mesh to the ILTCollisionMgr.
\see ILTCollisionMgr, ILTCollisionObject.
Used for: Physics
*/
class LTCollisionMesh : public ILTCollisionObject
{
public:
/*!Polygonal collision data*/
LTCollisionData* m_pData;
/*!\b true if collision data should be deleted, \b false otherwise.*/
bool m_Delete;
public:
/*!
\param d A pointer to a collision data buffer
\param p0 Position at time \f$ t_0 \f$
\param p1 Position at time \f$ t_0 + \Delta t \f$
\param R0 Orientation at time \f$ t_0 \f$
\param R1 Orientation at time \f$ t_0 + \Delta t \f$
\param del \b true if collision data should be deleted (default),
\b false otherwise.
\param h Object handle (NULL by default)
Construct the object.
\see ILTCollisionObject, ILTCollisionMgr
Used For: Physics.
*/
LTCollisionMesh
(
LTCollisionData* d,
const LTVector3f& p0, const LTVector3f& p1,
const LTOrientation& R0, const LTOrientation& R1,
const bool del = true,
HOBJECT h = NULL
)
: ILTCollisionObject(COT_MESH,h,p0,p1,R0,R1),
m_pData(d),
m_Delete(del)
{}
~LTCollisionMesh();
//Hit
virtual bool Hit
(
LTContactInfo& ci, const ILTCollisionObject& o,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitSphere
(
LTContactInfo& ci, const LTCollisionSphere& s,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitBox
(
LTContactInfo& ci, const LTCollisionBox& b,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitCylinder
(
LTContactInfo& ci, const LTCollisionCylinder& c,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const;
virtual bool HitMesh
(
LTContactInfo& ci, const LTCollisionMesh& m,
const LTContactInfo::Filter& cf = LTContactInfo::EmptyFilter()
) const
{
return false;//not yet implemented
}
//Intersect
virtual bool Intersect
(
LTIntersectInfo& ii, const ILTCollisionObject& o,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectSphere
(
LTIntersectInfo& ii, const LTCollisionSphere& s,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectBox
(
LTIntersectInfo& ii, const LTCollisionBox& b,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectCylinder
(
LTIntersectInfo& ii, const LTCollisionCylinder& c,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const;
virtual bool IntersectMesh
(
LTIntersectInfo& ii, const LTCollisionMesh& m,
const LTIntersectInfo::Filter& cf = LTIntersectInfo::EmptyFilter()
) const
{
return false;//not yet implemented
}
virtual bool IntersectSegment
(
LTIntersectInfo ii[],
int32& n,
const int32 sz,
const LTVector3f& p0,
const LTVector3f& p1,
const LTIntersectInfo::Filter& iif
) const;
};
#endif
//EOF
| [
"[email protected]"
]
| [
[
[
1,
955
]
]
]
|
91d3e3c8fb88132ec02db6da8b2163deda0d1168 | 3aafc3c40c1464fc2a32d1b6bba23818903a4ec9 | /Library/frmMain.h | 69f47ba359a3fbc46f50098310db3ff96ace55e6 | []
| no_license | robintw/rlibrary | 13930416649ec38196bfd38e0980616e9f5454c8 | 3e55d49acba665940828e26c8bff60863a86246f | refs/heads/master | 2020-09-22T10:31:55.561804 | 2009-01-24T19:05:19 | 2009-01-24T19:05:19 | 34,583,564 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,154 | h | #pragma once
#include "GlobalConnection.h"
#include "frmAddBook.h"
#include "frmSimpleSearch.h"
#include "frmAdvSearch.h"
#include "frmFvsNFGraph.h"
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
namespace Library {
/// <summary>
/// Summary for frmMain
///
/// WARNING: If you change the name of this class, you will need to change the
/// 'Resource File Name' property for the managed resource compiler tool
/// associated with all .resx files this class depends on. Otherwise,
/// the designers will not be able to interact properly with localized
/// resources associated with this form.
/// </summary>
public ref class frmMain : public System::Windows::Forms::Form
{
public:
frmMain(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~frmMain()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ btnAdd;
private: System::Windows::Forms::Button^ btnSimpleSearch;
private: System::Windows::Forms::Button^ btnAdvSearch;
private: System::Windows::Forms::PictureBox^ pictureBox1;
private: System::Windows::Forms::Button^ button1;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(frmMain::typeid));
this->btnAdd = (gcnew System::Windows::Forms::Button());
this->btnSimpleSearch = (gcnew System::Windows::Forms::Button());
this->btnAdvSearch = (gcnew System::Windows::Forms::Button());
this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox());
this->button1 = (gcnew System::Windows::Forms::Button());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->BeginInit();
this->SuspendLayout();
//
// btnAdd
//
this->btnAdd->Location = System::Drawing::Point(109, 317);
this->btnAdd->Name = L"btnAdd";
this->btnAdd->Size = System::Drawing::Size(118, 54);
this->btnAdd->TabIndex = 0;
this->btnAdd->Text = L"Add Book";
this->btnAdd->UseVisualStyleBackColor = true;
this->btnAdd->Click += gcnew System::EventHandler(this, &frmMain::btnAdd_Click);
//
// btnSimpleSearch
//
this->btnSimpleSearch->Location = System::Drawing::Point(233, 317);
this->btnSimpleSearch->Name = L"btnSimpleSearch";
this->btnSimpleSearch->Size = System::Drawing::Size(118, 54);
this->btnSimpleSearch->TabIndex = 1;
this->btnSimpleSearch->Text = L"Simple Search";
this->btnSimpleSearch->UseVisualStyleBackColor = true;
this->btnSimpleSearch->Click += gcnew System::EventHandler(this, &frmMain::btnSimpleSearch_Click);
//
// btnAdvSearch
//
this->btnAdvSearch->Location = System::Drawing::Point(357, 317);
this->btnAdvSearch->Name = L"btnAdvSearch";
this->btnAdvSearch->Size = System::Drawing::Size(118, 54);
this->btnAdvSearch->TabIndex = 1;
this->btnAdvSearch->Text = L"Advanced Search";
this->btnAdvSearch->UseVisualStyleBackColor = true;
this->btnAdvSearch->Click += gcnew System::EventHandler(this, &frmMain::btnAdvSearch_Click);
//
// pictureBox1
//
this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"pictureBox1.Image")));
this->pictureBox1->Location = System::Drawing::Point(77, 12);
this->pictureBox1->Name = L"pictureBox1";
this->pictureBox1->Size = System::Drawing::Size(431, 264);
this->pictureBox1->TabIndex = 2;
this->pictureBox1->TabStop = false;
//
// button1
//
this->button1->Location = System::Drawing::Point(489, 282);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 3;
this->button1->Text = L"button1";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &frmMain::button1_Click);
//
// frmMain
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(585, 417);
this->Controls->Add(this->button1);
this->Controls->Add(this->pictureBox1);
this->Controls->Add(this->btnAdvSearch);
this->Controls->Add(this->btnSimpleSearch);
this->Controls->Add(this->btnAdd);
this->Name = L"frmMain";
this->Text = L"Library";
this->Load += gcnew System::EventHandler(this, &frmMain::frmMain_Load);
(cli::safe_cast<System::ComponentModel::ISupportInitialize^ >(this->pictureBox1))->EndInit();
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void btnAdd_Click(System::Object^ sender, System::EventArgs^ e) {
frmAddBook^ frm = gcnew frmAddBook();
frm->Show();
}
private: System::Void frmMain_Load(System::Object^ sender, System::EventArgs^ e) {
GlobalConnection::OpenConnection();
}
private: System::Void btnSimpleSearch_Click(System::Object^ sender, System::EventArgs^ e) {
frmSimpleSearch^ frm = gcnew frmSimpleSearch();
frm->Show();
}
private: System::Void btnAdvSearch_Click(System::Object^ sender, System::EventArgs^ e) {
frmAdvSearch^ frm = gcnew frmAdvSearch();
frm->Show();
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
frmFvsNFGraph^ frm = gcnew frmFvsNFGraph();
frm->Show();
}
};
}
| [
"robin@02cab514-f24f-0410-a9ea-a7698ff47c65",
"[email protected]@02cab514-f24f-0410-a9ea-a7698ff47c65"
]
| [
[
[
1,
5
],
[
8,
51
],
[
55,
70
],
[
72,
73
],
[
78,
81
],
[
83,
91
],
[
93,
99
],
[
129,
132
],
[
137,
141
],
[
143,
157
],
[
167,
167
]
],
[
[
6,
7
],
[
52,
54
],
[
71,
71
],
[
74,
77
],
[
82,
82
],
[
92,
92
],
[
100,
128
],
[
133,
136
],
[
142,
142
],
[
158,
166
]
]
]
|
ea8d0387bdad8ca5c9135b2e7213c1c36f09241b | 50f94444677eb6363f2965bc2a29c09f8da7e20d | /Src/EmptyProject/WorldManager.h | 2d4e5d5234e32eb943d3279185ed26fb2927f23b | []
| no_license | gasbank/poolg | efd426db847150536eaa176d17dcddcf35e74e5d | e73221494c4a9fd29c3d75fb823c6fb1983d30e5 | refs/heads/master | 2020-04-10T11:56:52.033568 | 2010-11-04T19:31:00 | 2010-11-04T19:31:00 | 1,051,621 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,446 | h | #pragma once
class World;
class Dialog;
typedef std::list<Dialog*> DialogList;
/**
@brief 모든 게임내 World를 관리하는 클래스
게임 초기화시에 스크립트에 정의된 모든 World를 초기화 및 로드합니다.
또한 실행 중에는 다음으로 바꿀 World를 설정하고, 종료시에는 로드된 World를
해제합니다.
*/
class WorldManager : public Singleton<WorldManager>
{
public:
WorldManager(void);
~WorldManager(void);
void addWorld( World* ws );
void release();
World* getWorld( const char* worldName ) { return m_worlds[worldName]; }
World* getCurWorld() const { return m_curWorld; }
void setNextWorld( World* nextWorld );
void setNextWorld( const char* nextWorldName );
void changeToNextWorldIfExist();
UINT getWorldCount() const { return m_worlds.size(); }
HRESULT onCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
HRESULT onResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext );
void onLostDevice();
private:
void detachAllWorlds();
std::map<std::string, World*> m_worlds; // WorldState pool
World* m_curWorld;
World* m_nextWorld;
DialogList m_globalDialogs;
};
inline WorldManager& GetWorldManager() { return WorldManager::getSingleton(); }
SCRIPT_FACTORY( WorldManager ) | [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
c081797e5775fa66c71165dc6ce87028e15ad2f9 | b407e323eb85b469258b0c30892dc70b160ecdbc | /whoisalive/window.h | d7a1d76d93aee7da4da8300efe725d12611db577 | []
| no_license | vi-k/whoisalive.fromsvn | 7f8acf1cc8f5573008327fb61b419ed0f1676f42 | c77b9619d470291389c8938e7cab87674a09f654 | refs/heads/master | 2021-01-10T02:13:41.786614 | 2010-05-30T23:18:47 | 2010-05-30T23:18:47 | 44,526,121 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,077 | h | #ifndef WHO_WINDOW_H
#define WHO_WINDOW_H
#include "ipgui.h"
#include "ipaddr.h"
#include "widget.h"
#include "scheme.h"
#include "../common/my_thread.h"
#include "../common/my_http.h"
#include "../common/my_inet.h"
#include <memory>
#include <boost/function.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#define MY_WM_CHECK_STATE WM_USER
#define MY_WM_UPDATE WM_USER+1
namespace who {
namespace mousemode
{ enum t { none, capture, move, select, edit }; }
namespace selectmode
{ enum t { normal, add, remove }; }
namespace mousekeys
{ enum : int { ctrl = 1, shift = 2, lbutton = 4, rbutton = 8, mbutton = 16 }; }
class window
{
private:
bool terminate_;
server &server_;
boost::thread anim_thread_;
condition_variable anim_cond_;
HWND hwnd_;
bool focused_;
int w_;
int h_;
std::auto_ptr<Gdiplus::Bitmap> bitmap_;
std::auto_ptr<Gdiplus::Graphics> canvas_;
Gdiplus::Color bg_color_;
scheme *active_scheme_;
boost::ptr_list<scheme> schemes_;
mousemode::t mouse_mode_;
int mouse_start_x_;
int mouse_start_y_;
int mouse_end_x_;
int mouse_end_y_;
widget *select_parent_;
Gdiplus::RectF select_rect_;
mutex canvas_mutex_;
void paint_(void);
static LRESULT CALLBACK static_wndproc_(HWND hwnd, UINT uMsg,
WPARAM wParam, LPARAM lParam);
inline LRESULT wndproc_(HWND hwnd, UINT uMsg,
WPARAM wParam, LPARAM lParam);
void set_active_scheme_(who::scheme *scheme);
inline void on_mouse_event_(
const boost::function<void (window*, int keys, int x, int y)> &f,
WPARAM wparam, LPARAM lparam);
static int window::wparam_to_keys_(WPARAM wparam);
void anim_thread_proc(void);
public:
/* События */
boost::function<void (window*, int delta, int keys, int x, int y)> on_mouse_wheel;
boost::function<void (window*, int keys, int x, int y)> on_mouse_move;
boost::function<void (window*, int keys, int x, int y)> on_lbutton_down;
boost::function<void (window*, int keys, int x, int y)> on_rbutton_down;
boost::function<void (window*, int keys, int x, int y)> on_mbutton_down;
boost::function<void (window*, int keys, int x, int y)> on_lbutton_up;
boost::function<void (window*, int keys, int x, int y)> on_rbutton_up;
boost::function<void (window*, int keys, int x, int y)> on_mbutton_up;
boost::function<void (window*, int keys, int x, int y)> on_lbutton_dblclk;
boost::function<void (window*, int keys, int x, int y)> on_rbutton_dblclk;
boost::function<void (window*, int keys, int x, int y)> on_mbutton_dblclk;
boost::function<void (window*, int key)> on_keydown;
boost::function<void (window*, int key)> on_keyup;
window(server &server, HWND parent);
~window();
inline HWND hwnd(void)
{ return hwnd_; }
inline widget* select_parent(void)
{ return select_parent_; }
inline Gdiplus::RectF select_rect(void)
{ return select_rect_; }
inline int w(void)
{ return w_; }
inline int h(void)
{ return h_; }
void animate(void);
void add_schemes(xml::wptree &config);
void set_link(HWND parent);
void delete_link(void);
void on_destroy(void);
void set_active_scheme(int index);
inline scheme* active_scheme(void)
{ return active_scheme_; }
scheme* get_scheme(int index);
inline int get_schemes_count(void)
{ return schemes_.size(); }
void set_size(int w, int h);
void mouse_start(mousemode::t mm, int x, int y,
selectmode::t sm = selectmode::normal);
void mouse_move_to(int x, int y);
void mouse_end(int x, int y);
void mouse_cancel(void);
virtual void do_check_state(void);
void zoom(float ds);
void set_scale(float scale)
{
if (active_scheme_)
active_scheme_->set_scale(scale);
}
void set_pos(float x, float y)
{
if (active_scheme_)
active_scheme_->set_pos(x, y);
}
inline mousemode::t mouse_mode(void)
{ return mouse_mode_; }
void align(void)
{
if (active_scheme_)
active_scheme_->align( (float)w_, (float)h_ );
}
widget* hittest(int x, int y);
void clear(void);
};
}
#endif
| [
"victor.dunaev@localhost"
]
| [
[
[
1,
159
]
]
]
|
a6ae4f14752c681edb25078489e8e792172f9ca5 | 559770fbf0654bc0aecc0f8eb33843cbfb5834d9 | /haina/codes/beluga/client/moblie/BelugaDb/src/BelugaDbDllMain.cpp | b74391c2d16d170d024f1e4348c5d73a51eca5ec | []
| no_license | 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 | 2,385 | cpp | /*
============================================================================
Name : BelugaDbDll.cpp
Author : shaochuan.yang
Copyright : haina
Description : BelugaDbDll.cpp - main DLL source
============================================================================
*/
// Include Files
#include <glib.h>
#include <time.h>
#include "Beluga.h"
static void free_gstring (gpointer data, gpointer user_data)
{
g_string_free((GString*)data, TRUE);
}
static void free_address_struct(gpointer data, gpointer user_data)
{
g_free(data);
}
static void free_recent_contact_struct(gpointer data, gpointer user_data)
{
g_free(data);
}
// Exported Functions
EXPORT_C void freeGStringArray(GPtrArray * pArray)
{
if (pArray)
{
g_ptr_array_foreach(pArray, free_gstring, NULL);
g_ptr_array_free(pArray, TRUE);
}
}
EXPORT_C void freeAddressArray(GPtrArray * pArray)
{
if (pArray)
{
g_ptr_array_foreach(pArray, free_address_struct, NULL);
g_ptr_array_free(pArray, TRUE);
}
}
EXPORT_C void freeRecentContactArray(GPtrArray * pArray)
{
if (pArray)
{
g_ptr_array_foreach(pArray, free_recent_contact_struct, NULL);
g_ptr_array_free(pArray, TRUE);
}
}
#ifdef _WIN32_WCE
#include <winbase.h>
EXPORT_C void GetLocalTime(tm* time)
{
SYSTEMTIME systime;
GetLocalTime(&systime);
time->tm_year = systime.wYear;
time->tm_mon = systime.wMonth;
time->tm_mday = systime.wDay;
time->tm_hour = systime.wHour;
time->tm_min = systime.wMinute;
time->tm_sec = systime.wSecond;
}
static WCHAR *utf8ToUnicode(const char *zFilename)
{
int nChar;
WCHAR *zWideFilename;
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
zWideFilename = (WCHAR*)malloc(nChar * sizeof(zWideFilename[0]));
if ( zWideFilename == 0 )
{
return 0;
}
nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
if( nChar==0 )
{
free(zWideFilename);
zWideFilename = 0;
}
return zWideFilename;
}
EXPORT_C void deleteFile(gchar * file)
{
WCHAR *zWide = utf8ToUnicode(file);
if( zWide )
{
DeleteFileW(zWide);
}
}
#else
EXPORT_C void GetLocalTime(tm* tim)
{
time_t t;
time(&t);
tim = localtime(&t);
}
#include <io.h>
EXPORT_C void deleteFile(gchar * file)
{
_unlink(file);
}
#endif
| [
"shaochuan.yang@6c45ac76-16e4-11de-9d52-39b120432c5d"
]
| [
[
[
1,
117
]
]
]
|
be8a56b3c8bab768e2455cd0d763d8290e9b528b | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /AMXServer/include/EIBListener.h | 890196bcbb3a97112922b5e8d0d483c025421987 | []
| no_license | radtek/eibsuite | 0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd | 4504fcf4fa8c7df529177b3460d469b5770abf7a | refs/heads/master | 2021-05-29T08:34:08.764000 | 2011-12-06T20:42:06 | 2011-12-06T20:42:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #ifndef __EIB_LISTENER_HEADER__
#define __EIB_LISTENER_HEADER__
#include "JTC.h"
#include "EIBAddress.h"
#include "MsgTable.h"
#include "EibNetwork.h"
using namespace EibStack;
class CEIBListener : public JTCThread, public JTCMonitor
{
public:
CEIBListener();
virtual ~CEIBListener();
virtual void run();
void Close();
private:
bool _stop;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
26
]
]
]
|
8ff26724451dc05e65503aef63bfd5648984a5ef | 4d01363b089917facfef766868fb2b1a853605c7 | /src/Utils/Misc/Tokenizer.h | d0c8c801e2bfb9908c31fa3c50b20ec9fde870aa | []
| no_license | FardMan69420/aimbot-57 | 2bc7075e2f24dc35b224fcfb5623083edcd0c52b | 3f2b86a1f86e5a6da0605461e7ad81be2a91c49c | refs/heads/master | 2022-03-20T07:18:53.690175 | 2009-07-21T22:45:12 | 2009-07-21T22:45:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,524 | h | /**
* Adapted from code by James Fancy
*
* TODO: see if we can eliminate redundant start/end calls
*/
#ifndef tokenizer_h
#define tokenizer_h
#include <string>
#include <cstdlib>
#include <vector>
using std::vector;
using std::string;
class Tokenizer
{
protected:
int offset;
string text;
string delimiters;
public:
Tokenizer(const string& str) :
offset(0),
text(str),
delimiters(" \t\n\r")
{
}
Tokenizer(const string& str, const string& del) :
offset(0),
text(str),
delimiters(del)
{
}
string nextToken()
{
unsigned int start = text.find_first_not_of(delimiters, offset);
if(start == string::npos)
{
offset = text.length();
return "";
}
unsigned int end = text.find_first_of(delimiters, start);
if(end == string::npos)
{
offset = text.length();
return text.substr(start);
}
offset = end;
return text.substr(start, end - start);
}
int nextInt()
{
return atoi(nextToken().c_str());
}
float nextFloat()
{
return atof(nextToken().c_str());
}
vector<string> getStrings()
{
vector<string> tokens;
while(hasMoreTokens())
tokens.push_back(nextToken());
return tokens;
}
vector<int> getInts()
{
vector<int> tokens;
while(hasMoreTokens())
tokens.push_back(nextInt());
return tokens;
}
bool hasMoreTokens()
{
unsigned int start = text.find_first_not_of(delimiters, offset);
return start != string::npos;
}
};
#endif
| [
"daven.hughes@92c3b6dc-493d-11de-82d9-516ade3e46db"
]
| [
[
[
1,
94
]
]
]
|
80c6822c86e8d50f9dfba4d2f4b628d18b9f3b40 | 841e58a0ee1393ddd5053245793319c0069655ef | /Karma/Headers/Effects.h | 2c8ba623001e7be30a50e2f8394c61566d73ae49 | []
| no_license | dremerbuik/projectkarma | 425169d06dc00f867187839618c2d45865da8aaa | faf42e22b855fc76ed15347501dd817c57ec3630 | refs/heads/master | 2016-08-11T10:02:06.537467 | 2010-06-09T07:06:59 | 2010-06-09T07:06:59 | 35,989,873 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,862 | h | /*---------------------------------------------------------------------------------*/
/* File: Effects.h */
/* Author: Per Karlsson, [email protected] */
/* */
/* Description: Here all effects classes are collected. Info about each class */
/* is defined below in the file. */
/*---------------------------------------------------------------------------------*/
#ifndef EFFECTS_H
#define EFFECTS_H
#include <Ogre.h>
#include "Appstate.h"
#include <vector>
/* Effects is a superclass for all effects in the game with a timer. */
class Effects
{
public:
/* mtTimerReset is how long the effect will be shown. */
Effects(const double& timerReset) : mtTimer(0.0),mtTimerReset(timerReset){};
/* Abstract function. Every effect has its own way of starting. Particle Systems start emitting, Billboards->setVisible etc etc */
virtual void startTimer() = 0;
/* Updates the timer of the effect. If the timer is bigger or equal with the mtTimerReset, then the reset function will be called. */
virtual void update(const double& timeSinceLastFrame);
/* Static function that updates all dynamic effects (effects that aren't bound to any specific chunk). */
static void updateAll(const double& timeSinceLastFrame);
/* Adds an effect to the mtDynamicEffects vector. */
static void Effects::addDynamicEffect(Effects* e);
protected:
double mtTimer;
const double mtTimerReset;
/* See ::updateAll. */
static std::vector<Effects*> mtDynamicEffects;
/* Abstract function. See ::startTimer(). Every effect has its own way of resetting the effect. */
virtual void resetTimer() = 0; //Abstract
};
/* MuzzleFire is a simple Billboard (sprite, 2D texture) with a muzzle fire texture */
class MuzzleFire : public Effects
{
public:
/*
timerReset = how long the Muzzle Fire will be visible.
sceneMgr = the OGRE scenemanager
width = width of the billboard
height = height of the billboard
material = material of the texture
name = name of the billboardset
*/
MuzzleFire(const double& timerReset,Ogre::SceneManager* sceneMgr,const Ogre::Real width,
const Ogre::Real height, const Ogre::String& material,const Ogre::String& name);
/* Returns the BillboardSet of the Muzzle Fire. */
Ogre::BillboardSet* getBillboardSet(){return mvpMuzzleFire;};
/* Start the timer and makes the billboard visible. */
void startTimer();
private:
Ogre::BillboardSet* mvpMuzzleFire;
/* Sets the billboard visible or invisible. */
void setVisible(bool state);
/* Resets the timer and hides the billboard. */
void resetTimer();
};
/* The same as Muzzle Fire except this one only shows in First Person view. */
class MuzzleFireFirstPerson : public Effects
{
public:
/* TimerReset = how long the effect will be shown. */
MuzzleFireFirstPerson(const double& timerReset);
/* see MuzzleFire::startTimer() */
void startTimer();
private:
/* MuzzleFire::resetTimer() */
void resetTimer();
};
/* Blood is a particle system of redish textures. */
class Blood : public Effects
{
public:
/*
timerReset = how long the Muzzle Fire will be visible.
sceneMgr = the OGRE scenemanager.
name = name of the character of the spawns the blood effect.
particleSystem = name of the particleSystem ("blood" for example)
*/
Blood(const double& timerReset,Ogre::SceneManager* sceneMgr,const Ogre::String& name,const Ogre::String& particleSystem);
/* setPosition is called everytime a character has been shot. The position of the particle system is the hit point in the world. */
void setPosition(const Ogre::Vector3& p){mvpBloodNode->setPosition(p);};
/* The particle system starts emitting particles. */
void startTimer();
private:
Ogre::ParticleSystem* mvpBloodPS;
Ogre::SceneNode* mvpBloodNode;
/* The particle system stops emitting. */
void resetTimer();
};
/* ManuallyControlledParticles is a class for particle systems that don't have specific length.
PowerUp_MoveBox and PowerUp_RocketBoots are examples of such particle systems. The length here depends on the users input.*/
class ManuallyControlledParticles : public Effects
{
public:
/*
sceneMgr = OGRE scene manager.
name = "name" of the particle system.
particleSystem = name of the particleSystem template.
*/
ManuallyControlledParticles(Ogre::SceneManager *sceneMgr,const Ogre::String &name, const Ogre::String &particleSystem);
/* Returns the particle system */
Ogre::ParticleSystem* getParticleSystem(){return mvpPS;};
/* Resets the particle system. */
void setManualReset(){resetTimer();};
/* Start emitting particles. */
void startTimer();
/* Needs to overwrite the update function so the resetTimer() isn't called. */
void update(const double& timeSinceLastFrame){};
private:
Ogre::ParticleSystem* mvpPS;
/* Stops emitting particles. */
void resetTimer();
};
/* BulletHoles is an alone class for creating bullet holes on the static enviroment.
A bullet hole is a simple plane with a texture on it.*/
class BulletHoles
{
private:
/* Singleton, easier to use. */
static BulletHoles singleton;
BulletHoles(): mvBulletHoles(0){};
int mvBulletHoles;
Ogre::SceneManager* mvpSceneMgr;
public:
/* Get the singleton */
static BulletHoles getSingleton(){return singleton;};
static BulletHoles* getSingletonPtr(){return &singleton;};
/* Adds a plane with normal and of position. */
void addBulletHole(const Ogre::Vector3 &normal,const Ogre::Vector3 &pos);
/* Sets the OGRE scene manager. Needs to be done in the createScene() of every level. */
void setSceneManager(Ogre::SceneManager* s) {mvpSceneMgr = s;};
/* Resets the amount of bulletHoles. */
void resetBulletHoles(){mvBulletHoles = 0;};
};
#endif
| [
"perkarlsson89@0a7da93c-2c89-6d21-fed9-0a9a637d9411"
]
| [
[
[
1,
173
]
]
]
|
27ecceaac688097458875de16b5b285e128c6703 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/interprocess/example/doc_intrusive.cpp | 421772cea0962b75620a0d45652c861c2273bb6c | [
"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 | 4,136 | cpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
//[doc_intrusive
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/smart_ptr/intrusive_ptr.hpp>
//<-
#include "../test/get_process_id_name.hpp"
//->
using namespace boost::interprocess;
namespace N {
//A class that has an internal reference count
class reference_counted_class
{
private:
//Non-copyable
reference_counted_class(const reference_counted_class &);
//Non-assignable
reference_counted_class & operator=(const reference_counted_class &);
//A typedef to save typing
typedef managed_shared_memory::segment_manager segment_manager;
//This is the reference count
unsigned int m_use_count;
//The segment manager allows deletion from shared memory segment
offset_ptr<segment_manager> mp_segment_manager;
public:
//Constructor
reference_counted_class(segment_manager *s_mngr)
: m_use_count(0), mp_segment_manager(s_mngr){}
//Destructor
~reference_counted_class(){}
public:
//Returns the reference count
unsigned int use_count() const
{ return m_use_count; }
//Adds a reference
inline friend void intrusive_ptr_add_ref(reference_counted_class * p)
{ ++p->m_use_count; }
//Releases a reference
inline friend void intrusive_ptr_release(reference_counted_class * p)
{ if(--p->m_use_count == 0) p->mp_segment_manager->destroy_ptr(p); }
};
} //namespace N {
//A class that has an intrusive pointer to reference_counted_class
class intrusive_ptr_owner
{
typedef intrusive_ptr<N::reference_counted_class,
offset_ptr<void> > intrusive_ptr_t;
intrusive_ptr_t m_intrusive_ptr;
public:
//Takes a pointer to the reference counted class
intrusive_ptr_owner(N::reference_counted_class *ptr)
: m_intrusive_ptr(ptr){}
};
int main()
{
//Remove shared memory on construction and destruction
struct shm_remove
{
//<-
#if 1
shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
#else
//->
shm_remove() { shared_memory_object::remove("MySharedMemory"); }
~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
//<-
#endif
//->
} remover;
//Create shared memory
//<-
#if 1
managed_shared_memory shmem(create_only, test::get_process_id_name(), 10000);
#else
//->
managed_shared_memory shmem(create_only, "MySharedMemory", 10000);
//<-
#endif
//->
//Create the unique reference counted object in shared memory
N::reference_counted_class *ref_counted =
shmem.construct<N::reference_counted_class>
("ref_counted")(shmem.get_segment_manager());
//Create an array of ten intrusive pointer owners in shared memory
intrusive_ptr_owner *intrusive_owner_array =
shmem.construct<intrusive_ptr_owner>
(anonymous_instance)[10](ref_counted);
//Now test that reference count is ten
if(ref_counted->use_count() != 10)
return 1;
//Now destroy the array of intrusive pointer owners
//This should destroy every intrusive_ptr and because of
//that reference_counted_class will be destroyed
shmem.destroy_ptr(intrusive_owner_array);
//Now the reference counted object should have been destroyed
if(shmem.find<intrusive_ptr_owner>("ref_counted").first)
return 1;
//Success!
return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
130
]
]
]
|
07e16479486f67f47bbc1884f909ffea082f15e2 | c63685bfe2d1ecfdfebcda0eab70642f6fcf4634 | /HDRRendering/HDRRendering/JupiterUI/SHDRRender.h | d799a2ce3800ff077cb65d4cb14f7733e17e60e5 | []
| no_license | Shell64/cgdemos | 8afa9272cef51e6d0544d672caa0142154e231fc | d34094d372fea0536a5b3a17a861bb1a1bfac8c4 | refs/heads/master | 2021-01-22T23:26:19.112999 | 2011-10-13T12:38:10 | 2011-10-13T12:38:10 | 35,008,078 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | #ifndef __SHDR_RENDER_H__
#define __SHDR_RENDER_H__
class SHDRRender : public GLWidget
{
public:
SHDRRender( HWND hParentWnd );
~SHDRRender();
virtual bool Initialize();
protected:
virtual bool OnResize( WPARAM wParam, LPARAM lParam );
virtual bool OnPaint( WPARAM wParam, LPARAM lParam );
bool InitTexture( void );
bool InitShaders( void );
bool InitRenderTagets( void );
float GetExposure( void );
private:
EffectGLSL _downSampleEffect;
EffectGLSL _blurXEffect;
EffectGLSL _blurYEffect;
EffectGLSL _toneEffect;
GLTexInput _hdrTex;
GLTexFBO _rtDownsample;
GLTexFBO _rtBlurX;
GLTexFBO _rtBlurY;
float* m_GK;
};
#endif//__SHDR_RENDER_H__
| [
"hpsoar@6e3944b4-cba9-11de-a8df-5d31f88aefc0"
]
| [
[
[
1,
39
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.