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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8f1e762f3385bb6c817d76999e5b6dcfeeb6611f | 9907be749dc7553f97c9e51c5f35e69f55bd02c0 | /FrameworkMenu/FrameworkMenu/engine.cpp | 3052f09f26d3f7ea6247d9720709de881b43ec27 | []
| no_license | jdeering/csci476winthrop | bc8907b9cc0406826de76aca05e6758810377813 | 2bc485781f819c8fd82393ac86de33404e7ad6d3 | refs/heads/master | 2021-01-10T19:53:14.853438 | 2009-04-24T14:26:36 | 2009-04-24T14:26:36 | 32,223,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,738 | cpp | #include "engine.h"
#include "GameFramework.h"
// Set inst to NULL to begin
Framework* Framework::inst = NULL;
Game Framework::games[MAXGAMES];
int Framework::gameCount = 0;
/******************************************************
Provides a pointer to the Singleton instance of the
Framework class. If there is not an instance, it calls
the constructor.
@param user The username that the score of the game
will be posted for.
@return A pointer to the single Framework instance.
******************************************************/
Framework* Framework::Instance(std::string user)
{
if(!inst)
{
inst = new Framework(user);
// Hide console window
HWND hWnd = GetConsoleWindow();
if(hWnd)
ShowWindow(hWnd, SW_HIDE);
}
return inst;
}
/******************************************************
Default constructor.
******************************************************/
Framework::Framework()
{
gameRunning = false;
username = "Anonymous";
active = true;
gameCount = 0;
options.VOLUME = 50;
options.MUTE = false;
options.TTS = false;
menuRunning = true;
}
/******************************************************
Protected constructor
@param user The username that the score of the game
will be posted for.
******************************************************/
Framework::Framework(std::string user)
{
gameRunning = false;
username = user;
active = true;
gameCount = 0;
options.VOLUME = 50;
options.MUTE = false;
options.TTS = false;
if(GAMENUM != -1) // If this is a game and not the main menu
// load the side menu
LoadSideMenu();
LoadGames();
menuRunning = true;
if(GAMENUM != -1)
LaunchGame(GAMENUM);
buffer = create_bitmap(800, 600);
}
/******************************************************
Default destructor. Destroys all pointers used by
Allegro.
******************************************************/
Framework::~Framework()
{
show_mouse(NULL);
destroy_bitmap(buffer);
active = false;
inst = NULL;
}
/******************************************************
Clears the current screen and calls the sprite handler's
draw method.
******************************************************/
void Framework::UpdateSprites()
{
clear_to_color(buffer, makecol(255, 255, 255));
sprites.DrawSprites(buffer);
// Draw mouse pointer
if(mouse_x >= 0 && mouse_x <= 800 && mouse_y >= 0 && mouse_y <= 600)
draw_sprite(buffer, mouse_sprite, mouse_x, mouse_y);
}
/******************************************************
Calls the text handler's draw method to show all text
objects that are visible and reads all visible and
invisible text.
******************************************************/
void Framework::UpdateText()
{
textObjects.ShowAllVisible(buffer);
}
/******************************************************
The Framework's main method calls for each iteration.
******************************************************/
bool Framework::MessageLoop(bool pause)
{
if(key[KEY_ESC] || !active)
{
//Kill Program
active = false;
}
UpdateSprites();
UpdateText();
UpdateMouse();
UpdateKeyboard();
UpdateOptions(pause);
//if(gameRunning)
//{
//GetMessages();
//}
//CheckErrors();
return active;
}
/******************************************************
The Framework's public method to provide iterative
calls to its main loop method.
******************************************************/
bool Framework::MainLoop(bool pause)
{
if(pause) return true;
// Process normally if not paused
bool retVal = MessageLoop(pause);
acquire_screen();
blit(buffer, screen, 0, 0, 0, 0, 800, 600);
release_screen();
return retVal;
}
/******************************************************
Creates anonymous pipes via the operating system
by which modules and the framework will communicate.
This is not currently being used.
******************************************************/
void Framework::CreateMessagePipes()
{
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
// Create a pipe for the child process's STDOUT.
if ( ! CreatePipe(&hStdIn_Parent, &hStdOut_Child, &saAttr, 0) )
{
allegro_message("Error creating output pipe.");
active = false;
}
// Ensure the read handle to the pipe for STDOUT is not inherited.
if ( ! SetHandleInformation(hStdIn_Parent, HANDLE_FLAG_INHERIT, 0) )
{
allegro_message("Error setting handle information.");
active = false;
}
// Create a pipe for the child process's STDIN.
if ( ! CreatePipe(&hStdIn_Child, &hStdOut_Parent, &saAttr, 0) )
{
allegro_message("Error creating input pipe.");
active = false;
}
// Ensure the write handle to the pipe for STDIN is not inherited.
if ( ! SetHandleInformation(hStdOut_Parent, HANDLE_FLAG_INHERIT, 0) )
{
allegro_message("Error setting handle information.");
active = false;
}
SetNamedPipeHandleState(hStdOut_Parent, PIPE_WAIT, NULL, NULL);
}
/******************************************************
Launches the game at the given index. If the framework
and modules become separate EXE files, this will be used
to create the message pipes and create the module's process.
@param gameNum A zero-based index value that represents
a game's information's relative position
in the Games.XML file.
******************************************************/
void Framework::LaunchGame(int gameNum)
{
LoadGameAssets(gameNum);
//CreateMessagePipes();
//std::string gameExe = "modules/"+games[gameNum].path + games[gameNum].name + ".exe";
//std::wstring gameToLaunch(gameExe.begin(), gameExe.end());
//TCHAR szCmdline[]=TEXT("modules\\Wordplay\\Wordplay.exe");
//CreateGameProcess(gameToLaunch);
}
/******************************************************
Loads the information for all the games specified in
the Games.XML file and stores the information in a
game struct.
******************************************************/
void Framework::LoadGames()
{
gameList.Load(TEXT("data/Games.xml"));
gameList.FindElem();
while(gameList.FindChildElem(TEXT("game")) && gameCount < 4)
{
gameList.IntoElem();
// Get attributes
std::wstring atPath = gameList.GetAttrib(TEXT("path"));
std::wstring atName = gameList.GetAttrib(TEXT("name"));
// Get Asset XML File Paths
gameList.FindChildElem(TEXT("imageFile"));
std::wstring atImageXMLPath = gameList.GetChildData();
gameList.FindChildElem(TEXT("audioFile"));
std::wstring atAudioXMLPath = gameList.GetChildData();
gameList.FindChildElem(TEXT("textFile"));
std::wstring atTextXMLPath = gameList.GetChildData();
gameList.FindChildElem(TEXT("icon"));
std::wstring atIconWidth = gameList.GetChildAttrib(TEXT("width"));
std::wstring atIconHeight = gameList.GetChildAttrib(TEXT("height"));
std::wstring atIconPath = gameList.GetChildData();
gameList.OutOfElem();
// Set variables for attributes
std::string path(atPath.begin(), atPath.end());
std::string name(atName.begin(), atName.end());
std::string image(atImageXMLPath.begin(), atImageXMLPath.end());
std::string audio(atAudioXMLPath.begin(), atAudioXMLPath.end());
std::string text(atTextXMLPath.begin(), atTextXMLPath.end());
std::string iconPath(atIconPath.begin(), atIconPath.end());
std::string iconWidth(atIconWidth.begin(), atIconWidth.end());
std::string iconHeight(atIconHeight.begin(), atIconHeight.end());
games[gameCount].path = path;
games[gameCount].name = name;
games[gameCount].imageFile = image;
games[gameCount].audioFile = audio;
games[gameCount].textFile = text;
if(strcmp(iconPath.c_str(), "Default") != 0)
{
games[gameCount].icon.path = iconPath;
games[gameCount].icon.width = atoi(iconWidth.c_str());
games[gameCount].icon.height = atoi(iconHeight.c_str());
}
else
{
games[gameCount].icon.path = "data/images/default_icon.bmp";
games[gameCount].icon.width = 100;
games[gameCount].icon.height = 100;
}
gameCount++;
}
// This is needed to load the game icons in the case
// that this program is the main menu responsible for
// launching the game modules.
if(GAMENUM == -1)
LoadMenuImages();
}
/******************************************************
Reads the inbound pipe to receive messages from the
currently active module.
******************************************************/
void Framework::GetMessages()
{
DWORD bytesRead, bytesAvail;
std::stringstream msgStream;
msgStream.clear();
PeekNamedPipe(hStdIn_Parent, incMessage, MAX_MESSAGE_SIZE, &bytesRead, &bytesAvail, NULL);
if (bytesRead != 0)
{
clearBuffer();
if (bytesAvail > MAX_MESSAGE_SIZE)
{
while (bytesRead >= MAX_MESSAGE_SIZE)
{
clearBuffer();
// input handle, buffer, max message size, DWORD for bytesRead
ReadFile(hStdIn_Parent, incMessage, MAX_MESSAGE_SIZE, &bytesRead, NULL);
msgStream.write(incMessage, bytesRead); // copy message to std::stringstream
ParseMessage(msgStream);
}
}
else
{
// input handle, buffer, max message size, DWORD for bytesRead
ReadFile(hStdIn_Parent, incMessage, MAX_MESSAGE_SIZE, &bytesRead, NULL);
msgStream.write(incMessage, bytesRead); // copy message to std::stringstream
ParseMessage(msgStream);
}
}
clearBuffer(); // clears incMessage
}
/******************************************************
Adds a message to the outbound pipe for retrieval
by the currently active module.
@param msg The message to be sent to the module.
******************************************************/
void Framework::sendMessage(const char *msg)
{
DWORD bytesWritten;
std::string message(msg);
WriteFile(hStdOut_Parent, message.c_str(), message.size(), &bytesWritten, NULL);
}
/******************************************************
Adds a new sprite object to the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::CreateSprite(char *msg)
{
int x, y, w, h;
char reference[25], imageReference[25];
sscanf(msg, "%*d %s %s %d %d %d %d", reference, imageReference, &x, &y, &w, &h);
std::string str_reference = reference;
std::string str_imageReference = imageReference;
sprites.AddSprite(str_reference, str_imageReference, x+XOFFSET, y, w, h);
}
/******************************************************
Adds a new sprite object to the sprite handler based
on information received via a message from the module.
This message does not contain width or height information.
The sprite's width and height will be based on the associated
bitmap file's loaded dimensions.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework:: CreateSpriteRefDimensions(char *msg)
{
int x, y;
char reference[25], imageReference[25];
sscanf(msg, "%*d %s %s %d %d", reference, imageReference, &x, &y);
std::string str_reference = reference;
std::string str_imageReference = imageReference;
sprites.AddSprite(str_reference, str_imageReference, x+XOFFSET, y);
}
/******************************************************
Removes a specified sprite object from the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::KillSprite(char *msg)
{
char reference[10];
sscanf(msg, "%*d %s", reference);
std::string str_reference = reference;
if(!sprites.RemoveSprite(str_reference))
allegro_message("Sprite %s could not be removed", str_reference.c_str());
}
/******************************************************
Changes the visibility of an active sprite object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetSpriteVisible(char *msg)
{
char refName[5];
int visible;
sscanf(msg, "%*d %s %d", refName, &visible);
sprites.SetVisible(refName, visible);
UpdateSprites();
}
/******************************************************
Changes the size of a sprite in the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetSpriteSize(char *msg)
{
char reference[10];
int w, h;
sscanf(msg, "%*d %s %d %d", reference, &w, &h);
sprites.SetSpriteSize(reference, w, h);
}
/******************************************************
Changes the screen location of a sprite in the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetSpriteLocation(char *msg)
{
char reference[10];
int x, y;
sscanf(msg, "%*d %s %d %d", reference, &x, &y);
printf("Setting location for %s at %d , %d\n", reference, x, y);
sprites.SetSpriteLocation(reference, x+XOFFSET, y);
}
/******************************************************
Changes the animation frame delay of a sprite in the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetFrameDelay(char *msg)
{
char reference[10];
int delay;
sscanf(msg, "%*d %s %d", reference, &delay);
sprites.SetFrameDelay(reference, delay);
}
/******************************************************
Changes whether or not a sprite should be animated based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetAnimation(char *msg)
{
char reference[10];
int animate;
sscanf(msg, "%*d %s %d", reference, &animate);
sprites.SetAnimation(reference, animate);
}
/******************************************************
Changes the current animation frame of a sprite in the sprite handler based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetFrame(char *msg)
{
char reference[10];
int frame;
sscanf(msg, "%*d %s %d", reference, &frame);
printf("Getting frame for %s\n", reference);
sprites.SetFrame(reference, frame);
}
/******************************************************
Moves a sprite to a new screen location based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::MoveSprite(char *msg)
{
char reference[10];
int x, y, speed;
sscanf(msg, "%*d %s %d %d %d", reference, &x, &y, &speed);
sprites.MoveSprite(reference, x+XOFFSET, y, speed);
}
/******************************************************
Changes the associated bitmap file for a sprite
based on information received via a message from the
module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::ChangeBitmap(char* msg)
{
char refName[5], fileRef[25];
sscanf(msg, "%*d %s %s", refName, fileRef);
sprites.ChangeBitmap(refName, fileRef);
}
/******************************************************
Changes the screen location of a text object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetTextPosition(char *msg)
{
char reference[10];
int x, y;
sscanf(msg, "%*d %s %d %d", reference, &x, &y);
textObjects.SetTextPosition(reference, x, y);
}
/******************************************************
Changes the size of a text object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetTextSize(char *msg)
{
char reference[10];
int size;
sscanf(msg, "%*d %s %d", reference, &size);
textObjects.SetSize(reference, size);
}
/******************************************************
Changes the foreground color of a text object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetTextColor(char *msg)
{
char reference[10];
int r, g, b;
sscanf(msg, "%*d %s %d %d %d", reference, &r, &g, &b);
textObjects.SetColor(reference, r, g, b);
}
/******************************************************
Changes the background color of a text object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetTextBackgroundColor(char *msg)
{
char reference[10];
int r, g, b;
sscanf(msg, "%*d %s %d %d %d", reference, &r, &g, &b);
textObjects.SetBackgroundColor(reference, r, g, b);
}
/******************************************************
Changes the visibility of an active text object based
on information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::SetTextVisible(char *msg)
{
char refName[5];
int visible;
sscanf(msg, "%*d %s %d", refName, &visible);
textObjects.SetVisible(refName, visible);
}
/******************************************************
Creates a new text object from a text asset reference in the
XML file based on information received via a message from the
module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::CreateTextFromRef(char *msg)
{
int x, y;
std::string refName, assetName;
sscanf(msg, "%*d %s %d %d %s", refName, &x, &y, assetName);
textObjects.AddTextByRef(refName, assetName, x, y, true);
}
/******************************************************
Creates a new text object for a given text string
based on information received via a message from the
module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::CreateTextFromString(char *msg)
{
char c;
char *currStr = "";
int code, x, y, length;
std::string refName;
//sscanf(msg, "%*d %s %d %d %d", refName, &x, &y);
std::stringstream stream;
stream << msg; // put msg into stream
stream >> code >> refName >> length >> x >> y;
// get hanging space
stream.get(c);
char *string = new char[length+1];
// remainder of the stream is the string
stream.getline(string, length+1);
textObjects.AddText(refName, string, x, y, true);
}
/******************************************************
Removes a text object from the text handler
based on information received via a message from the
module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::RemoveText(char *msg)
{
std::string refName;
sscanf(msg, "%*d %s", refName);
}
/******************************************************
Changes the string of a text object
based on information received via a message from the
module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::ChangeText(char *msg)
{
char c;
char *currStr = "";
int code, length;
std::string refName;
std::stringstream stream;
stream << msg; // put msg into stream
stream >> code >> refName >> length;
stream.get(c); // Get hanging space
char *string = new char[length+1];
stream.getline(string, length+1);
textObjects.ChangeText(refName, string);
}
/******************************************************
Reads a string of text without displaying it to the
screen. This does not create a text object.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::ReadText(char *msg)
{
// only do if text-to-speech is enabled
// and sound is not muted
if(!options.TTS && !options.MUTE) return;
char c;
int code, length;
std::stringstream stream;
stream << msg; // put msg into stream
stream >> code >> length;
stream.get(c); // Get hanging space
char *string = new char[length+1];
stream.getline(string, length+1);
std::string stringToRead = string;
Text::ReadText(stringToRead, options.VOLUME);
}
/******************************************************
Creates an audio object reference for use by the API to
stop and play audio files.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::CreateAudioObject(char *msg)
{
char reference[10], assetName[50];
sscanf(msg, "%*d %s %s", reference, assetName);
audioObjects.MapSample(reference, assetName); // EDIT volume
}
/******************************************************
Plays a loaded audio file specified by information received
via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::PlayFile(char *msg)
{
char reference[10];
sscanf(msg, "%*d %s", reference);
audioObjects.PlaySample(reference, options.VOLUME); // EDIT volume
}
/******************************************************
Updates the loop variable of a loaded audio file specified
by information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::ResetLoop(char *msg)
{
char reference[10];
int loop;
sscanf(msg, "%*d %s %d", reference, &loop);
audioObjects.ResetLoopFlag(reference, loop);
}
/******************************************************
Stops a loaded audio file specified by information received
via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::StopFile(char *msg)
{
char reference[10];
sscanf(msg, "%*d %s", reference);
audioObjects.StopSample(reference);
}
/******************************************************
Posts the players score upon exiting the game based on
information received via a message from the module.
@param msg The message that has been received from the module
containing information needed for the function call.
******************************************************/
void Framework::PostScore(char *msg)
{
int score;
sscanf(msg, "%*d %d", &score);
gameRunning = false;
}
/******************************************************
Handles the sending of mouse events and location changes
to the module as well as Framework-only events (i.e. side menu
interaction).
******************************************************/
void Framework::UpdateMouse()
{
std::string mouse_message = "";
std::stringstream message;
int button, state, x, y;
mouse.Update(x, y);
message.clear();
message << "101 " << x << " " << y;
mouse_message = message.str();
//sendMessage(mouse_message.c_str());
GameFramework::mouseMessage(mouse_message.c_str());
message.clear();
message.str("");
mouse_message.clear();
if(mouse.StateChange(button, state, x, y))
{
std::string sprite_name = sprites.CheckClicks(mouse.GetPointer());
if(x >= 0 && x <= 600 && y >= 0 && y <= 600/* && gameRunning*/) // Game event
{
cout << "Click at ("<< x << "," << y << ")." << endl;
message.clear();
message.str("");
message << "102 " << button << " " << state << " " << x << " " << y << endl;
mouse_message = message.str();
//sendMessage(mouse_message.c_str());
GameFramework::mouseMessage(mouse_message.c_str());
message.clear();
mouse_message.clear();
if(strcmp(sprite_name.c_str(), "") != 0)
{
message.clear();
message.str("");
message << "103 " << button << " " << state << " " << sprite_name.c_str() << endl;
mouse_message = message.str();
//sendMessage(mouse_message.c_str());
GameFramework::mouseMessage(mouse_message.c_str());
message.clear();
mouse_message.clear();
}
}
else // Framework event
{
x += XOFFSET; // Reset mouse's x position to reflect entire screen
// instead of only the game window
std::string sprite_name = sprites.CheckClicks(mouse.GetPointer());
if(button == 1 && state == 1 && strcmp(sprite_name.c_str(), "") != 0) // see if a sprite is clicked
{
// change Text-to-Speech boolean value
if(strcmp(sprite_name.c_str(), "tts_box") == 0
|| strcmp(sprite_name.c_str(), "tts_banner") == 0)
{
options.TTS ^= true;
sprites.SetFrame("tts_box", options.TTS);
}
// change mute boolean value
if(strcmp(sprite_name.c_str(), "mute_box") == 0
|| strcmp(sprite_name.c_str(), "mute_banner") == 0)
{
options.MUTE ^= true;
sprites.SetFrame("mute_box", options.MUTE); // checked
}
// adjust volume
if(strcmp(sprite_name.c_str(), "vol_bar") == 0
|| strcmp(sprite_name.c_str(), "vol_pointer") == 0)
{
x -= 3;
if(x < 42) x = 42;
if(x > 150) x = 150;
sprites.SetSpriteLocation("vol_pointer", x, 465);
options.VOLUME = ((x - 45) * 100) / 110.0;
}
}
}
}
}
/******************************************************
Handles the sending of keyboard events and to the module
as well as Framework-only events (i.e. side menu interaction).
******************************************************/
void Framework::UpdateKeyboard()
{
int key, state;
std::string key_message;
std::stringstream message;
while(keyboard.StateChange(key, state))
{
key_message.clear();
message.clear();
message.str("");
message << "201 " << key << " " << state << endl;
key_message = message.str();
//sendMessage(key_message.c_str());
GameFramework::kybdMessage(key_message.c_str());
}
}
/******************************************************
Returns the state (running or not running) of the Framework.
@return true if the Framework loop is still running, false otherwise
******************************************************/
bool Framework::isActive()
{
return active;
}
/******************************************************
Returns the state (running or not running) of modules.
@return true if a module is running, false otherwise
******************************************************/
bool Framework::gameIsRunning()
{
return gameRunning;
}
/******************************************************
Handles the passing of the current desire Text-to-Speech
option and volume states to the objects that need them
(text handler and audio handler).
******************************************************/
void Framework::UpdateOptions(bool pause)
{
if(options.VOLUME < 0) options.VOLUME = 0;
if(options.VOLUME > 100) options.VOLUME = 100;
if(options.MUTE || pause)
audioObjects.Mute();
else
audioObjects.Unmute();
audioObjects.SetVolume(options.VOLUME);
textObjects.SetTTS(options.TTS);
}
/******************************************************
Creates a new operating system process to run a game
module's program. This is not currently in use but is
available if separation between the modules and Framework
is desired.
@param szCmdline The command line string specifying the
module's EXE location and any command line
options.
******************************************************/
void Framework::CreateGameProcess(std::wstring szCmdline)
// Create a child process that uses the previously created pipes for STDIN and STDOUT.
{
STARTUPINFO siStartInfo;
BOOL bSuccess = FALSE;
// Set up members of the PROCESS_INFORMATION structure.
ZeroMemory( &piProcInfo, sizeof(PROCESS_INFORMATION) );
// Set up members of the STARTUPINFO structure.
// This structure specifies the STDIN and STDOUT handles for redirection.
ZeroMemory( &siStartInfo, sizeof(STARTUPINFO) );
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.hStdOutput = hStdOut_Child;
siStartInfo.hStdInput = hStdIn_Child;
siStartInfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
// set the window display to HIDE
//if(!DEBUG)
siStartInfo.wShowWindow = SW_HIDE;
// Create the child process.
bSuccess = CreateProcess(NULL,
const_cast<LPWSTR>(szCmdline.c_str()), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&siStartInfo, // STARTUPINFO pointer
&piProcInfo); // receives PROCESS_INFORMATION
// If an error occurs, exit the application.
if ( ! bSuccess )
{
//LPWSTR cTemp = new WCHAR[100];
//memset(cTemp, 0, 100);
DWORD dTemp = GetLastError();
//FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, dTemp, 0, cTemp, 100, NULL);
std::string appPath(szCmdline.begin(), szCmdline.end());
allegro_message("Game Launch failed. Could not launch %s\n", appPath.c_str());
//MessageBox(NULL, cTemp, NULL, MB_OK);
active = false;
}
else
{
// Close handles to the child process and its primary thread.
// Some applications might keep these handles to monitor the status
// of the child process, for example.
CloseHandle(piProcInfo.hProcess);
CloseHandle(piProcInfo.hThread);
// Set game running flag
gameRunning = true;
}
}
/******************************************************
Loads the image, audio, and text assets specified in
a module's XML files.
@param gameNum The zero-based index into the games array.
This also represents a game's information's
relative location in the Games.XML file.
******************************************************/
void Framework::LoadGameAssets(int gameIndex)
{
std::string gamePath = "";
std::string imageFilePath = games[gameIndex].imageFile;
std::string audioFilePath = games[gameIndex].audioFile;
std::string textFilePath = games[gameIndex].textFile;
LoadImages(imageFilePath, gamePath);
LoadAudio(audioFilePath, gamePath);
LoadText(textFilePath, gamePath);
}
/******************************************************
Loads the image assets from an XML file at the specified
path and file name.
@param file_name The path to the XML file relative to the
module's EXE location.
@param gamePath The path to the module's EXE location relative
to the Framework's location.
******************************************************/
void Framework::LoadImages(std::string file_name, std::string gamePath)
{
std::string file = gamePath + file_name;
std::wstring w_file(file.begin(), file.end());
if(imgXML.Load(w_file.c_str()))
LoadGameImages(gamePath);
else
{
allegro_message("Image asset XML file not found at %s.", file.c_str());
active = false;
}
}
/******************************************************
Loads the audio assets from an XML file at the specified
path and file name.
@param file_name The path to the XML file relative to the
module's EXE location.
@param gamePath The path to the module's EXE location relative
to the Framework's location.
******************************************************/
void Framework::LoadAudio(std::string file_name, std::string gamePath)
{
std::string file = gamePath + file_name;
std::wstring w_file(file.begin(), file.end());
if(audXML.Load(w_file.c_str()))
LoadGameAudio(gamePath);
else
{
file_name.erase(0, 8);
allegro_message("Audio asset XML file not found at %s.", file.c_str());
active = false;
}
}
/******************************************************
Loads the text assets from an XML file at the specified
path and file name.
@param file_name The path to the XML file relative to the
module's EXE location.
@param gamePath The path to the module's EXE location relative
to the Framework's location.
******************************************************/
void Framework::LoadText(std::string file_name, std::string gamePath)
{
std::string file = gamePath + file_name;
std::wstring w_file(file.begin(), file.end());
if(txtXML.Load(w_file.c_str()))
LoadGameText(gamePath);
else
{
file_name.erase(0, 8);
allegro_message("Text asset XML file not found at %s.", file.c_str());
active = false;
}
}
/******************************************************
Loads the image asset files that are currently specified
in the loaded imgXML variable.
@param gamePath The path relative to the Framework's EXE
needed to concatenate module relative
asset paths onto.
******************************************************/
void Framework::LoadGameImages(std::string gamePath)
{
imgXML.FindElem();
while(imgXML.FindChildElem(TEXT("image")))
{
imgXML.IntoElem();
// Get attributes
std::wstring atFile = imgXML.GetAttrib(TEXT("file"));
std::wstring atRef = imgXML.GetAttrib(TEXT("ref"));
std::wstring atNumFrames = imgXML.GetAttrib(TEXT("numFrames"));
std::wstring atNumFrameCol = imgXML.GetAttrib(TEXT("numFrameCol"));
std::wstring atWidth = imgXML.GetAttrib(TEXT("spriteWidth"));
std::wstring atHeight = imgXML.GetAttrib(TEXT("spriteHeight"));
// Set variables for attributes
std::string file(atFile.begin(), atFile.end());
file = gamePath + file;
std::string ref(atRef.begin(), atRef.end());
std::string numFrames(atNumFrames.begin(), atNumFrames.end());
std::string numFrameCol(atNumFrameCol.begin(), atNumFrameCol.end());
std::string width(atWidth.begin(), atWidth.end());
std::string height(atHeight.begin(), atHeight.end());
imgXML.OutOfElem();
// Add file to sprite handler
bool ret = sprites.AddFile(ref, file, atoi(numFrames.c_str()), atoi(numFrameCol.c_str()), atoi(width.c_str()), atoi(height.c_str()));
if(!ret)
allegro_message("%s not loaded.", file.c_str());
}
}
/******************************************************
Loads the audio asset files that are currently specified
in the loaded audXML variable.
@param gamePath The path relative to the Framework's EXE
needed to concatenate module relative
asset paths onto.
******************************************************/
void Framework::LoadGameAudio(std::string gamePath)
{
SAMPLE *temp = NULL;
audXML.FindElem();
bool loopVal = false;
while(audXML.FindChildElem(TEXT("audio")))
{
audXML.IntoElem();
// Get attributes
std::wstring atFile = audXML.GetAttrib(TEXT("file"));
std::wstring atRef = audXML.GetAttrib(TEXT("ref"));
std::wstring atLoop = audXML.GetAttrib(TEXT("loop"));
// Set variables for attributes
std::string file(atFile.begin(), atFile.end());
file = gamePath + file;
std::string ref(atRef.begin(), atRef.end());
std::string loop(atLoop.begin(), atLoop.end());
audXML.OutOfElem();
if(strcmp(loop.c_str(), "true") == 0)
loopVal = true;
else if(strcmp(loop.c_str(), "false") == 0)
loopVal = false;
else
{
allegro_message("Error in Audio XML file (loop value).");
active = false;
return;
}
temp = load_sample(file.c_str());
if(!temp)
{
allegro_message("File not found at \"%s\". Audio Sample \"%s\" not added.", file.c_str(), ref.c_str());
active = false;
}
else
audioObjects.AddSample(ref, temp, loopVal);
}
}
/******************************************************
Loads the text asset files that are currently specified
in the loaded txtXML variable.
@param gamePath The path relative to the Framework's EXE
needed to concatenate module relative
asset paths onto.
******************************************************/
void Framework::LoadGameText(std::string gamePath)
{
txtXML.FindElem();
int x, y;
bool visVal = false;
while(txtXML.FindChildElem(TEXT("text")))
{
x=0; y=0;
txtXML.IntoElem();
// Get attributes
std::wstring atString = txtXML.GetAttrib(TEXT("std::string"));
std::wstring atRef = txtXML.GetAttrib(TEXT("ref"));
std::wstring atX = txtXML.GetAttrib(TEXT("x"));
std::wstring atY = txtXML.GetAttrib(TEXT("y"));
std::wstring atVisible = txtXML.GetAttrib(TEXT("visible"));
// Set variables for attributes
std::string textString(atString.begin(), atString.end());
std::string ref(atRef.begin(), atRef.end());
std::string xLoc(atX.begin(), atX.end());
std::string yLoc(atY.begin(), atY.end());
std::string visible(atVisible.begin(), atVisible.end());
txtXML.OutOfElem();
x = atoi(xLoc.c_str());
y = atoi(yLoc.c_str());
if(strcmp(visible.c_str(), "true") == 0)
visVal = true;
else if(strcmp(visible.c_str(), "false") == 0)
visVal = false;
else
{
allegro_message("Error in Text XML file (visible value).");
active = false;
return;
}
textObjects.AddText(ref, textString, x, y, visVal);
}
}
/******************************************************
Stops the module's process and closes the anonymous
pipes.
******************************************************/
void Framework::KillModule()
{
if(gameRunning)
{
gameRunning = false;
menuRunning = true;
// Kill game
// Launch menu
}
else if(menuRunning)
{
menuRunning = false; // Kill menu
active = false; // Exit framework
}
DWORD access = PROCESS_ALL_ACCESS;
HANDLE pHandle = OpenProcess(access, false, piProcInfo.dwProcessId);
TerminateProcess(pHandle, 0);
CloseHandle(pHandle);
CloseHandle(hStdIn_Parent);
CloseHandle(hStdOut_Parent);
CloseHandle(hStdIn_Child);
CloseHandle(hStdOut_Child);
}
/******************************************************
Clears the incoming/outgoing message buffer by setting
the all values in the buffer to zero.
******************************************************/
void Framework::clearBuffer()
{ memset(incMessage, 0, MAX_MESSAGE_SIZE); }
/******************************************************
Parses an incoming message stream. Determines the code
of the incoming message and calls the related function.
@param msgStream The incoming message string stream being
parsed for some number of distinct messages.
******************************************************/
void Framework::ParseMessage(std::stringstream &msgStream)
{
char message[MAX_MESSAGE_SIZE];
int code;
while(!msgStream.eof())
{
memset(message, 0, MAX_MESSAGE_SIZE);
msgStream.getline(message, MAX_MESSAGE_SIZE);
code = 0;
sscanf(message, "%d", &code);
if(!code)
{
if(strlen(message))
printf("Debug Message : %s\n", message);
continue;
}
switch(code)
{
// Sprites
case SPRITE_CREATE : CreateSprite(message); break;
case SPRITE_CREATE_FROM_ASSET : CreateSpriteRefDimensions(message); break;
case SPRITE_REMOVE : KillSprite(message); break;
case SPRITE_VISIBILITY_CHANGE : SetSpriteVisible(message); break;
case SPRITE_SET_SIZE : SetSpriteSize(message); break;
case SPRITE_SET_LOCATION : SetSpriteLocation(message); break;
case SPRITE_SET_FRAME_DELAY : SetFrameDelay(message); break;
case SPRITE_SET_ANIMATION : SetAnimation(message); break;
case SPRITE_SET_FRAME : SetFrame(message); break;
case SPRITE_MOVE_TO : MoveSprite(message); break;
case SPRITE_CHANGE_BITMAP : ChangeBitmap(message); break;
// Text
case TEXT_CREATE_FROM_ASSET : CreateTextFromRef(message); break;
case TEXT_CREATE_FROM_STRING : CreateTextFromString(message); break;
case TEXT_REMOVE : RemoveText(message); break;
case TEXT_CHANGE_CONTENT : ChangeText(message); break;
case TEXT_CHANGE_LOCATION : SetTextPosition(message); break;
case TEXT_VISIBILITY_CHANGE : SetTextVisible(message); break;
case TEXT_SIZE_CHANGE : SetTextSize(message); break;
case TEXT_COLOR_CHANGE : SetTextColor(message); break;
case TEXT_BGCOLOR_CHANGE : SetTextBackgroundColor(message); break;
case TEXT_READ : ReadText(message); break;
// Audio
case AUDIO_CREATE : CreateAudioObject(message);
case AUDIO_PLAY : PlayFile(message); break;
case AUDIO_SET_LOOP_COUNT : ResetLoop(message); break;
case AUDIO_STOP : StopFile(message); break;
// Score
case POST_SCORE : PostScore(message); break;
default : printf("Debug Message : %s\n", message);
break;
}
}
}
/******************************************************
Loads and displays the sprites for the side menu to
allow changing the volume and text-to-speech on/off
setting.
******************************************************/
void Framework::LoadSideMenu()
{
int w = 0, h = 0;
// Load the side menu sprite files
sprites.AddFile("CheckBox", "data/images/CheckBox.bmp", 2, 2, 40, 40);
sprites.AddFile("TTSBanner", "data/images/TTSBanner.bmp", 1, 1, 140, 30);
sprites.AddFile("VolumeBar", "data/images/VolumeBar.bmp", 1, 1, 110, 30);
sprites.AddFile("VolumePointer", "data/images/VolumePointer.bmp", 1, 1, 7, 44);
sprites.AddFile("VolumeBanner", "data/images/VolumeBanner.bmp", 1, 1, 110, 30);
sprites.AddFile("MuteBanner", "data/images/MuteBanner.bmp", 1, 1, 70, 30);
// Create the side menu sprites
sprites.AddSprite("tts_box", "CheckBox", 5, 70);
sprites.AddSprite("tts_banner", "TTSBanner", 55, 75);
sprites.AddSprite("vol_bar", "VolumeBar", 45, 465);
sprites.AddSprite("vol_pointer", "VolumePointer", 97, 465);
sprites.AddSprite("vol_banner", "VolumeBanner", 45, 520);
sprites.AddSprite("mute_banner", "MuteBanner", 75, 253);
sprites.AddSprite("mute_box", "CheckBox", 35, 250);
// Display them
sprites.SetVisible("tts_box", 1);
sprites.SetVisible("tts_banner", 1);
sprites.SetVisible("vol_bar", 1);
sprites.SetVisible("vol_pointer", 1);
sprites.SetVisible("vol_banner", 1);
sprites.SetVisible("mute_box", 1);
sprites.SetVisible("mute_banner", 1);
}
void Framework::LoadMenuImages()
{
sprites.AddFile("mainmenu_bkg", "data/images/mainmenu_bkg.bmp", 1, 1, 600, 600);
sprites.AddFile("leftarrow", "data/images/leftarrow.bmp", 1, 1, 100, 100);
sprites.AddFile("rightarrow", "data/images/rightarrow.bmp", 1, 1, 100, 100);
for(int i = 0; i < gameCount; i++)
{
char temp[3];
itoa(i, temp, 10);
std::string iconName(temp);
if(strcmp(games[i].icon.path.c_str(), "") != 0)
{
iconName = "gameicon." + iconName;
if(strcmp(games[i].icon.path.c_str(), "data/images/default_icon.bmp") != 0)
sprites.AddFile(iconName, games[i].path + games[i].icon.path, 1, 1, games[gameCount].icon.width, games[gameCount].icon.height);
else
sprites.AddFile(iconName, games[i].icon.path, 1, 1, games[gameCount].icon.width, games[gameCount].icon.height);
}
}
} | [
"deeringj2@2656ef14-ecf4-11dd-8fb1-9960f2a117f8"
]
| [
[
[
1,
1352
]
]
]
|
4b5cf8858fa5591018258200c0f68eecba50b5e0 | 070c58893ddb68626557793241b4c9c960737d86 | /dEspresso/dEspresso/dEspresso.cpp | 092c0cc7743fff2b27d8a3ecc46f909b737503a3 | []
| no_license | jongha/despresso | f84f328f77b0a338b31e8cf8debcda07ef49154d | 8986bbd6e710ee68fa341218c02f9b2aa7d1866d | refs/heads/master | 2020-05-18T07:16:32.144386 | 2010-09-28T05:14:56 | 2010-09-28T05:14:56 | 32,111,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,217 | cpp | // dEspresso.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "dEspresso.h"
#include "dEspressoDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CdEspressoApp
BEGIN_MESSAGE_MAP(CdEspressoApp, CWinApp)
ON_COMMAND(ID_HELP, &CWinApp::OnHelp)
END_MESSAGE_MAP()
// CdEspressoApp construction
CdEspressoApp::CdEspressoApp()
{
// TODO: add construction code here,
// Place all significant initialization in InitInstance
}
// The one and only CdEspressoApp object
CdEspressoApp theApp;
// CdEspressoApp initialization
BOOL CdEspressoApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
if (!AfxSocketInit())
{
AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
CdEspressoDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
84
]
]
]
|
4d7c998a0631fed05087790259f58d2337f76f60 | 90e001b00ae30ef22a3b07f6c9c374b0f2a1ee65 | /Computer Code/RobotPartProcessor.h | 9ba851425b3de762d66c100564b337cd00287c36 | []
| no_license | yazaddaruvala/2010W_UBC_EECE_375_450_Team6 | 6ca20eacef048a770e4422b45b49cedac8d6efe9 | e87918415ac41c7953f67247d6b9d3ce12f6e95a | refs/heads/master | 2016-09-11T04:20:55.171140 | 2011-05-29T08:32:43 | 2011-05-29T08:32:43 | 1,816,632 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 729 | h | /*
* Written by Yazad Daruvala
*/
#ifndef EECE375_ROBOTPARTPROCESSOR_H
#define EECE375_ROBOTPARTPROCESSOR_H
#include <cv.h>
#include <highgui.h>
#include <string>
#include <boost/thread.hpp>
#include "Processor.h"
class RobotPartProcessor: public Processor
{
public:
RobotPartProcessor( char* name_p, CvScalar color_p, const int hl, const int sl, const int vl, const int hh, const int sh, const int vh );
~RobotPartProcessor( void );
void process( vector<IplImage *> *input );
void configure( vector<IplImage *> *input );
private:
int hueLower, hueUpper;
int satLower, satUpper;
int valLower, valUpper;
int minRadius, maxRadius;
char* name;
boost::mutex bounds_Mutex;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
97373ad2b913080b6144ff55ffe9983af6aba2f6 | 9b575a11ef9652d78a93f71f5a61a01ae46ef7d0 | /Box2D2EngineReflexingBalls/sourcecode/MyContactListener.cpp | 901411e0e409ede87b1e9ee30735f35fe1d82361 | []
| no_license | vanminhle246/Physics2Engine | f9133786868a8c33d3919ef069372f4b1f9f6eb4 | cd6f0e6d90e02b16dcc397a1f99e0858812dc494 | refs/heads/master | 2021-01-10T19:09:09.757772 | 2011-12-22T10:43:32 | 2011-12-22T10:43:32 | 2,913,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | #include "MyContactListener.h"
#include "LinkerAgent.h"
void HandleContact(LinkerAgent* la1, LinkerAgent* la2)
{
/**/
djbool isSeed = la1->m_isSeed;
la1->m_isSeed = la2->m_isSeed;
la2->m_isSeed = isSeed;
/**/
/**
if (la1->m_isSeed) la2->m_isSeed = la1->m_isSeed;
if (la2->m_isSeed) la1->m_isSeed = la2->m_isSeed;
/**/
}
MyContactListener::MyContactListener(void)
{
}
MyContactListener::~MyContactListener(void)
{
}
void MyContactListener::BeginContact(b2Contact* contact)
{
b2Body* body1 = contact->GetFixtureA()->GetBody();
b2Body* body2 = contact->GetFixtureB()->GetBody();
if ((body1->GetType() == b2_dynamicBody) && (body2->GetType() == b2_dynamicBody))
{
void* linkerAgent1 = body1->GetUserData();
void* linkerAgent2 = body2->GetUserData();
if (linkerAgent1 && linkerAgent2)
HandleContact(static_cast<LinkerAgent*>(linkerAgent1), static_cast<LinkerAgent*>(linkerAgent2));
}
}
void MyContactListener::EndContact(b2Contact* contact)
{
} | [
"[email protected]"
]
| [
[
[
1,
39
]
]
]
|
c0fb905765c2000522e63ac93a481445981a3fc9 | 967868cbef4914f2bade9ef8f6c300eb5d14bc57 | /Server/Connection.hpp | 5a87f45b2f3fba629384df670627dd6a1b02d82b | []
| 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 | 1,404 | hpp | /*
© Vestris Inc., Geneva, Switzerland
http://www.vestris.com, 1994-1999 All Rights Reserved
______________________________________________
written by Daniel Doubrovkine - [email protected]
*/
#ifndef BASE_CONNECTION_HPP
#define BASE_CONNECTION_HPP
#include <platform/include.hpp>
#include <String/String.hpp>
#include <Vector/Vector.hpp>
#include <Socket/Socket.hpp>
class CConnection : public CObject {
private:
readonly_property(CSocket, Socket);
copy_property(void *, Server);
inline void MakePeerInformation(void) { m_Socket.MakePeerInformation(); }
public:
inline void Close(void) { m_Socket.Close(); }
inline int Write(const CString& Value) const { return m_Socket.Write(Value); }
inline int WriteLine(const CString& Value) const { return m_Socket.WriteLine(Value); }
inline int ReadLine(CString * pResult) const { return m_Socket.ReadLine(pResult); }
inline int Read(CString * pResult, const int MaxLength = -1) const { return m_Socket.Read(pResult, MaxLength); }
virtual void Execute(void *);
CConnection(void);
virtual ~CConnection(void);
inline void SetPeerSocket(int PeerSocket) { m_Socket.SetPeerSocket(PeerSocket); }
inline void SetPeerAddrIn(struct sockaddr_in PeerAddrIn) { m_Socket.SetPeerAddrIn(PeerAddrIn); }
inline void SetTimeout(int Timeout) { m_Socket.SetTimeout(Timeout); }
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
a35aae741446f44620439de4f87d4627599ad826 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/Include/CSpecialEffect.h | 8acda2bface59a46ff76ae84f54bf2377facf457 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | ISO-8859-10 | C++ | false | false | 1,658 | h | /*!
@file
@author Pablo Nuņez
@date 13/2009
@module
*//*
This file is part of the Nebula Engine.
Nebula Engine is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Nebula Engine is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Nebula Engine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _CPOSITION_H_
#define _CPOSITION_H_
#include "EnginePrerequisites.h"
namespace Nebula {
using namespace Ogre;
class IGameComponent;
struct CPositionDesc
{
CPositionDesc()
{
}
};
class NebulaDllPrivate CPosition : public IGameComponent,
public Ogre::Vector3
{
public:
CPosition();
CPosition(const CPositionDesc&);
~CPosition();
void update();
void setup();
//virtual const std::string& familyID() const {
// return mFamilyID;
//}
virtual const std::string& componentID() const {
return mComponentID;
}
private:
//static const std::string mFamilyID;
std::string mComponentID;
CPositionDesc mDesc;
};
//const std::string CPosition::mFamilyID = "CPosition";
//const std::string CPosition::mComponentID = "CPosition";
} //end namespace
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
72
]
]
]
|
0b32ef58802afcac3f6e66dfd8117793ea8a87fb | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-shared/Auth/Sha1.cpp | 40fd2fed6d7614f45e8d2b574d2b3b01533af402 | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,465 | cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "Sha1.h"
#include <stdarg.h>
Sha1Hash::Sha1Hash()
{
SHA1_Init(&mC);
}
Sha1Hash::~Sha1Hash()
{
// nothing.. lol
}
void Sha1Hash::UpdateData(const uint8 *dta, int len)
{
SHA1_Update(&mC, dta, len);
}
void Sha1Hash::UpdateData(const std::string &str)
{
UpdateData((uint8 *)str.c_str(), (int)str.length());
}
void Sha1Hash::UpdateBigNumbers(BigNumber *bn0, ...)
{
va_list v;
BigNumber *bn;
va_start(v, bn0);
bn = bn0;
while (bn)
{
UpdateData(bn->AsByteArray(), bn->GetNumBytes());
bn = va_arg(v, BigNumber *);
}
va_end(v);
}
void Sha1Hash::Initialize()
{
SHA1_Init(&mC);
}
void Sha1Hash::Finalize(void)
{
SHA1_Final(mDigest, &mC);
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1
],
[
4,
66
]
],
[
[
2,
3
]
]
]
|
47c88a64eee74b188a47a65552fb7925c93dabda | 80959be98b57106e6bd41c33c5bfb7dd5e9c88cd | /MD2Model.cpp | ab9ce54991539788c5d07389142ffbb7f5eddf46 | []
| no_license | dalorin/FPSDemo | e9ab067cfad73d404cc0ea01190212d5192405b0 | cf29b61a9654652a3f8d60d742072e1a8eaa3ca7 | refs/heads/master | 2020-07-26T17:42:10.801273 | 2010-12-27T00:16:55 | 2010-12-27T00:16:55 | 1,199,462 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,115 | cpp | #include "MD2Model.h"
#include <fstream>
#include <sstream>
#include "targa.h"
#include "Shader.h"
#include "Utils.h"
#include <map>
#define NUMVERTEXNORMALS 162
GLfloat vertexNormals[NUMVERTEXNORMALS][3] = {
#include "anorms.h"
};
using namespace std;
using namespace MD2;
MD2Model::MD2Model(void)
{
}
MD2Model::MD2Model(const char* modelFilename, const char* textureFilename)
{
load(modelFilename, textureFilename);
}
bool MD2Model::load(const char* modelFilename, const char* textureFilename)
{
// Open the file
ifstream modelFile(modelFilename, ios::binary);
if (!modelFile)
{
stringstream str;
str << "Invalid filename: " << modelFilename;
MessageBox(NULL, str.str().c_str(), "Model error", MB_ICONERROR | MB_OK);
exit(-1);
}
// Read the model header into m_header
modelFile.read(reinterpret_cast<char*>(&m_header), sizeof(MD2Header));
// Resize data structures according to figures supplied in header
m_skins.resize(m_header.numSkins);
m_md2Texcoords.resize(m_header.numTextureCoords);
m_texcoords.resize(m_header.numTextureCoords);
m_triangles.resize(m_header.numTriangles);
m_keyframes.resize(m_header.numFrames);
for (vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
it->vertices.resize(m_header.numVertices);
it->normals.resize(m_header.numVertices);
it->md2Vertices.resize(m_header.numVertices);
}
// Read skin data into memory
modelFile.seekg(m_header.skinOffset);
modelFile.read(reinterpret_cast<char*>(&m_skins[0]), sizeof(Skin) * m_header.numSkins);
// Read texture coordinate data into memory
modelFile.seekg(m_header.texCoordOffset);
modelFile.read(reinterpret_cast<char*>(&m_md2Texcoords[0]), sizeof(MD2TexCoord) * m_header.numTextureCoords);
// Read triangles into memory
modelFile.seekg(m_header.triangleOffset);
modelFile.read(reinterpret_cast<char*>(&m_triangles[0]), sizeof(Triangle) * m_header.numTriangles);
// Read keyframes into memory
modelFile.seekg(m_header.frameOffset);
for (vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
modelFile.read(reinterpret_cast<char*>(it->scale), sizeof(float) * 3);
modelFile.read(reinterpret_cast<char*>(it->translate), sizeof(float) * 3);
modelFile.read(reinterpret_cast<char*>(it->name), sizeof(char) * 16);
modelFile.read(reinterpret_cast<char*>(&it->md2Vertices[0]), sizeof(MD2Vertex) * m_header.numVertices);
}
// Convert MD2 texture coords to OpenGL coordinate system
for (unsigned int i = 0; i < m_md2Texcoords.size(); ++i)
{
m_texcoords[i].s = (GLfloat)m_md2Texcoords[i].s / (GLfloat)m_header.skinWidth;
m_texcoords[i].t = 1.0f - ((GLfloat)m_md2Texcoords[i].t / (GLfloat)m_header.skinHeight);
}
// Decompress keyframe vertices and swap Y and Z axes
for (vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
for (int i = 0; i < m_header.numVertices; ++i)
{
it->vertices[i].v[0] = (it->scale[0] * it->md2Vertices[i].v[0]) + it->translate[0];
it->vertices[i].v[2] = (it->scale[1] * it->md2Vertices[i].v[1]) + it->translate[1];
it->vertices[i].v[1] = (it->scale[2] * it->md2Vertices[i].v[2]) + it->translate[2];
it->normals[i].v[0] = vertexNormals[it->md2Vertices[i].lightNormalIndex][0];
it->normals[i].v[2] = vertexNormals[it->md2Vertices[i].lightNormalIndex][1];
it->normals[i].v[1] = vertexNormals[it->md2Vertices[i].lightNormalIndex][2];
}
}
//calculateNormals();
reorganiseVertices();
Utils::loadTexture(textureFilename, m_texture);
m_interpolatedKeyFrame = m_keyframes[0];
// Load vertex data into buffer.
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, m_interpolatedKeyFrame.vertices.size() * sizeof(Vertex), &m_interpolatedKeyFrame.vertices[0], GL_DYNAMIC_DRAW);
// Load texcoord data into buffer.
glGenBuffers(1, &m_texCoordBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer);
glBufferData(GL_ARRAY_BUFFER, m_texcoords.size() * sizeof(TexCoord), &m_texcoords[0], GL_STATIC_DRAW);
// Load vertex normal data into buffer.
glGenBuffers(1, &m_normalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_normalBuffer);
glBufferData(GL_ARRAY_BUFFER, m_interpolatedKeyFrame.normals.size() * sizeof(Vertex), &m_interpolatedKeyFrame.normals[0], GL_DYNAMIC_DRAW);
return true;
}
// Iterate through keyframes rebuilding vertices from triangle index info
void MD2Model::reorganiseVertices()
{
vector<Vertex> tempVertices;
vector<TexCoord> tempTexCoords;
vector<Vertex> tempNormals;
bool texCoordsDone = false;
for (vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
for (unsigned int i = 0; i < m_triangles.size(); ++i)
{
for (unsigned int j = 0; j < 3; ++j)
{
tempVertices.push_back(it->vertices[m_triangles[i].vertexIndex[j]]);
tempNormals.push_back(it->normals[m_triangles[i].vertexIndex[j]]);
if (!texCoordsDone)
tempTexCoords.push_back(m_texcoords[m_triangles[i].texCoordIndex[j]]);
}
}
texCoordsDone = true;
it->vertices = tempVertices;
it->normals = tempNormals;
}
m_texcoords = tempTexCoords;
}
/*void MD2Model::calculateNormals()
{
for (std::vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
KeyFrame* keyframe = &(*it);
for (unsigned int i = 0; i < keyframe->vertices.size(); i += 3)
{
Vertex* v1 = &keyframe->vertices[i];
Vertex* v2 = &keyframe->vertices[i+1];
Vertex* v3 = &keyframe->vertices[i+2];
Vector3 faceNormal;
Vector3 a(v2->v[0] - v1->v[0], v2->v[1] - v1->v[1], v2->v[2] - v1->v[2]);
Vector3 b(v3->v[0] - v1->v[0], v3->v[1] - v1->v[1], v3->v[2] - v1->v[2]);
faceNormal = a.cross(b);
faceNormal.normalize();
Vertex normal;
normal.v[0] = faceNormal.x;
normal.v[1] = faceNormal.y;
normal.v[2] = faceNormal.z;
for (int i = 0; i < 3; i++)
keyframe->normals.push_back(normal);
}
}
}*/
void MD2Model::calculateNormals()
{
std::map<short, int> vertexIncidences; //Stores number of triangles in which a vertex appears.
std::map<short, std::vector<Triangle*>> vertexTriangles; //Stores references to triangles in which a vertex appears.
std::map<Triangle*, Vector3> surfaceNormals; //Stores surface normals of triangles.
//For each keyframe
for (std::vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
KeyFrame* keyframe = &(*it);
//For each triangle
for (unsigned int i = 0; i < m_triangles.size(); i++)
{
Triangle* triangle = &m_triangles[i];
//For each triangle vertex
for (int j = 0; j < 3; j++)
{
// Increment incidence count for each vertex index
short vertexIndex = triangle->vertexIndex[j];
if (vertexIncidences.find(vertexIndex) != vertexIncidences.end())
vertexIncidences[vertexIndex]++;
else
vertexIncidences[vertexIndex] = 1;
// Store reference to triangle in each vertex
vertexTriangles[vertexIndex].push_back(triangle);
}
// Calculate and store surface normal
Vertex* v1 = &keyframe->vertices[triangle->vertexIndex[0]];
Vertex* v2 = &keyframe->vertices[triangle->vertexIndex[1]];
Vertex* v3 = &keyframe->vertices[triangle->vertexIndex[2]];
Vector3 faceNormal;
Vector3 a(v2->v[0] - v1->v[0], v2->v[1] - v1->v[1], v2->v[2] - v1->v[2]);
Vector3 b(v3->v[0] - v1->v[0], v3->v[1] - v1->v[1], v3->v[2] - v1->v[2]);
faceNormal = a.cross(b);
faceNormal.normalize();
surfaceNormals[triangle] = faceNormal;
}
}
//For each keyframe
for (std::vector<KeyFrame>::iterator it = m_keyframes.begin();
it != m_keyframes.end();
++it)
{
KeyFrame* keyframe = &(*it);
// For each vertex
for (unsigned short i = 0; i < keyframe->md2Vertices.size(); i++)
{
Vector3 sum(0.0f, 0.0f, 0.0f);
std::vector<Triangle*> triangles = vertexTriangles[i];
// For each triangle to which this vertex belongs
for (std::vector<Triangle*>::iterator triangle_it = triangles.begin();
triangle_it != triangles.end();
++triangle_it)
{
Triangle* triangle = *triangle_it;
// Sum surface normals
sum = sum + surfaceNormals[triangle];
}
// Divide by incidence count to get vertex normal and store it
sum = sum / (GLfloat)vertexIncidences[i];
sum.normalize();
Vertex normal;
normal.v[0] = sum.x;
normal.v[1] = sum.y;
normal.v[2] = sum.z;
keyframe->normals.push_back(normal);
}
}
}
void MD2Model::setMaterialProperties(MaterialProps props)
{
m_materialProps = props;
}
void MD2Model::onPrepare(float dt)
{
m_interpolatedKeyFrame = m_keyframes[0];
}
void MD2Model::onRender(ShaderProgram *shaderProgram)
{
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, m_texCoordBuffer);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, m_normalBuffer);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(3);
glBindTexture(GL_TEXTURE_2D, m_texture);
shaderProgram->bind();
shaderProgram->sendMatrices();
shaderProgram->sendUniform("texture0", 0);
shaderProgram->sendUniform("lerp_value", 0.0f);
shaderProgram->sendMaterialProps(m_materialProps);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
glDrawArrays(GL_TRIANGLES, 0, m_interpolatedKeyFrame.vertices.size());
glDisableVertexAttribArray(3);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(0);
//renderNormals(shaderProgram);
}
void MD2Model::renderNormals(ShaderProgram *shaderProgram)
{
glPushMatrix();
glBegin(GL_LINES);
for (unsigned int i = 0; i < m_interpolatedKeyFrame.vertices.size(); i++)
{
glVertex3f(
m_interpolatedKeyFrame.vertices[i].v[0],
m_interpolatedKeyFrame.vertices[i].v[1],
m_interpolatedKeyFrame.vertices[i].v[2]
);
glVertex3f(
m_interpolatedKeyFrame.vertices[i].v[0] + m_interpolatedKeyFrame.normals[i].v[0],
m_interpolatedKeyFrame.vertices[i].v[1] + m_interpolatedKeyFrame.normals[i].v[1],
m_interpolatedKeyFrame.vertices[i].v[2] + m_interpolatedKeyFrame.normals[i].v[2]
);
}
glEnd();
glPopMatrix();
}
GLfloat MD2Model::getBoundingSphereRadius()
{
GLfloat radius = 0.0f;
for (unsigned int i = 0; i < m_interpolatedKeyFrame.vertices.size(); i++)
{
Vector3 vec(
m_interpolatedKeyFrame.vertices[i].v[0],
m_interpolatedKeyFrame.vertices[i].v[1],
m_interpolatedKeyFrame.vertices[i].v[2]
);
GLfloat vecLength = vec.length();
if (vecLength > radius)
radius = vecLength;
}
return radius;
}
MD2Model::~MD2Model(void)
{
}
| [
"[email protected]"
]
| [
[
[
1,
363
]
]
]
|
91af0fcfbc88661e6ff192fafd30001c64ef11c1 | d76a67033e3abf492ff2f22d38fb80de804c4269 | /src/box2d/PrismaticJoint.cpp | e0bce5e1b5dc524b8582fb14a8f19dd122ec4976 | [
"Zlib"
]
| permissive | truthwzl/lov8 | 869a6be317b7d963600f2f88edaefdf9b5996f2d | 579163941593bae481212148041e0db78270c21d | refs/heads/master | 2021-01-10T01:58:59.103256 | 2009-12-16T16:00:09 | 2009-12-16T16:00:09 | 36,340,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | cpp | #include "PrismaticJoint.h"
// Module
#include "Body.h"
namespace love_box2d
{
PrismaticJoint::PrismaticJoint(boost::shared_ptr<Body> body1, boost::shared_ptr<Body> body2, b2PrismaticJointDef * def)
: Joint(body1, body2)
{
def->Initialize(body1->body, body2->body, def->localAnchor2, def->localAxis1);
def->lowerTranslation = 0.0f;
def->upperTranslation = 100.0f;
def->enableLimit = true;
joint = (b2PrismaticJoint*)createJoint(def);
}
PrismaticJoint::~PrismaticJoint()
{
destroyJoint(joint);
joint = 0;
}
float PrismaticJoint::getTranslation() const
{
return joint->GetJointTranslation();
}
float PrismaticJoint::getSpeed() const
{
return joint->GetJointSpeed();
}
void PrismaticJoint::setMotorEnabled(bool motor)
{
return joint->EnableMotor(true);
}
bool PrismaticJoint::isMotorEnabled() const
{
return joint->IsMotorEnabled();
}
void PrismaticJoint::setMaxMotorForce(float force)
{
joint->SetMaxMotorForce(force);
}
float PrismaticJoint::getMaxMotorForce() const
{
return joint->GetMotorForce();
}
void PrismaticJoint::setMotorSpeed(float speed)
{
joint->SetMotorSpeed(speed);
}
float PrismaticJoint::getMotorSpeed() const
{
return joint->GetMotorSpeed();
}
float PrismaticJoint::getMotorForce() const
{
return joint->GetMotorForce();
}
void PrismaticJoint::setLimitsEnabled(bool limit)
{
joint->EnableLimit(limit);
}
bool PrismaticJoint::isLimitsEnabled() const
{
return joint->IsLimitEnabled();
}
void PrismaticJoint::setUpperLimit(float limit)
{
joint->SetLimits(joint->GetLowerLimit(), limit);
}
void PrismaticJoint::setLowerLimit(float limit)
{
joint->SetLimits(limit, joint->GetUpperLimit());
}
void PrismaticJoint::setLimits(float lower, float upper)
{
joint->SetLimits(lower, upper);
}
float PrismaticJoint::getLowerLimit() const
{
return joint->GetLowerLimit();
}
float PrismaticJoint::getUpperLimit() const
{
return joint->GetUpperLimit();
}
int PrismaticJoint::getLimits(lua_State * L)
{
lua_pushnumber(L, joint->GetLowerLimit());
lua_pushnumber(L, joint->GetUpperLimit());
return 2;
}
} // love_box2d
| [
"m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162"
]
| [
[
[
1,
112
]
]
]
|
6cdced17cd2a24e273be842d1e44f9a30fcca4b0 | cdd5db763cad87ad5579ceb53a5fab002063bd73 | /Wirefree.h | a5cb0d2e12fce5b403a99640b3daaaf560ad4568 | []
| no_license | PersianP/Wirefree | 669ed6b842668aeee0ce307a6dad89bca2ed2622 | 74caf59c0f7be30067f4bd19be66770f446a74f9 | refs/heads/master | 2021-01-25T02:38:02.312629 | 2011-11-19T21:02:37 | 2011-11-19T21:02:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,983 | h | /*
Wirefree.h - interface class to talk with DIYSandbox Arduino devices
Copyright (C) 2011 DIYSandbox LLC
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _wirefree_h_
#define _wirefree_h_
#include <avr/pgmspace.h>
#include <WString.h>
#include "Client.h"
#include "Server.h"
#define MAX_SOCK_NUM 4
// LED Color definitions
#define LED_BLUE 0
#define LED_GREEN 1
#define LED_RED 2
#define LED_CYAN 3
#define LED_MAGENTA 4
#define LED_YELLOW 5
#define LED_WHITE 6
#define LED_OFF 7
#define NORMAL_MODE 0
#define ADHOC_MODE 1
#define AP_MODE 2
typedef struct _WIFI_PROFILE {
String ssid;
String security_key;
String ip;
String subnet;
String gateway;
} WIFI_PROFILE;
class Wirefree {
private:
void initLED();
public:
void setLED(int color);
static uint16_t _server_port[MAX_SOCK_NUM];
void begin(WIFI_PROFILE*, void (*rxDataHndlr)(String data));
void begin(WIFI_PROFILE*, void (*rxDataHndlr)(String data), uint8_t mode);
void process();
uint8_t connected();
uint8_t socketOpen(String url, String port);
void sendDeviceID();
void sendResponse(String data);
friend class Client;
friend class Server;
};
extern Wirefree Wireless;
#endif // _wirefree_h_
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
41
],
[
45,
61
],
[
63,
78
]
],
[
[
42,
44
],
[
62,
62
]
]
]
|
b4d4ddf34e18de7f6adf573b1e0d8c5524e48d2f | a7513d1fb4865ea56dbc1fcf4584fb552e642241 | /shiftable_files/osal/osal.hpp | 6ea57c04b279231517c7e1c94ff115aaadcc2568 | [
"MIT"
]
| permissive | det/avl_array | f0cab062fa94dd94cdf12bea4321c5488fb5cdcc | d57524a623af9cfeeff060b479cc47285486d741 | refs/heads/master | 2021-01-15T19:40:10.287367 | 2010-05-06T13:13:35 | 2010-05-06T13:13:35 | 35,425,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | hpp | ///////////////////////////////////////////////////////////////////
// //
// Copyright (c) 2010, Universidad de Alcala //
// //
// See accompanying LICENSE.TXT //
// //
///////////////////////////////////////////////////////////////////
/*
osal.hpp
--------
Interface definition of an OSAL (Operating System Abstraction
Layer) that must provide the basic services for the usage of
memory-mapped files.
*/
#ifndef _OS_ABSTRACTION_LAYER_HPP_
#define _OS_ABSTRACTION_LAYER_HPP_
#include "../shiftable_files.hpp"
namespace shiftable_files
{
namespace detail
{
class file
{
private:
file (const file &)
{}
const file & operator= (const file &)
{ return *this; }
public:
file () {}
virtual ~file () {}
virtual bool open (const char * name, open_mode mode) = 0;
virtual void close () = 0;
virtual uint32_t size () = 0;
virtual bool resize (uint32_t size) = 0;
virtual int8_t * map () = 0;
virtual void unmap () = 0;
static file * new_file (file_type type);
};
} // namespace detail
} // namespace shiftable_files
#endif
| [
"martin@ROBOTITO"
]
| [
[
[
1,
58
]
]
]
|
da3a5cf2d4fab5d76d51e975023bcda6a27cccad | 85c93419769170bb411bb28e3ad4790bc5d98181 | /ui/guiparam.cpp | c3deb9bb8f8f8fb8c4dc5669fdd93ebd44ed1b8b | []
| no_license | hirikesh/gorgoneye | 68d6a5774474cf541a7870fe35d0893ad54e99dd | fb81a4a059839bdf2d070dbda0ecde1ec7599f3a | refs/heads/master | 2021-01-10T10:00:43.506555 | 2010-11-04T23:09:31 | 2010-11-04T23:09:31 | 49,187,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,047 | cpp | #include <QDebug>
#include <QCheckBox>
#include <QSpinBox>
#include <QGridLayout>
#include <QLabel>
#include <QSlider>
#include <QRadioButton>
#include "guiparam.h"
GUICheckBox::GUICheckBox(const std::string& title, bool* value) :
QCheckBox(title.c_str()),
pValue(value)
{
init();
}
GUICheckBox::GUICheckBox(ModeParam* mp) :
QCheckBox(mp->name()),
pValue(static_cast<bool*>(mp->value()))
{
init();
}
void GUICheckBox::init()
{
setChecked(*pValue);
connect(this, SIGNAL(toggled(bool)), this, SLOT(setParamValue(bool)));
}
void GUICheckBox::setParamValue(bool value)
{
*pValue = value;
}
GUISlider::GUISlider(RangeParam<int>* rp) :
QFrame(),
slider(new QSlider(Qt::Horizontal, this)),
spinbox(new QSpinBox(this)),
title(new QLabel(rp->name())),
layout(new QGridLayout(this)),
pValue(static_cast<int*>(rp->value()))
{
slider->setRange(rp->getMinimum(), rp->getMaximum());
slider->setSingleStep(rp->getStep());
slider->setValue(*pValue);
spinbox->setRange(rp->getMinimum(), rp->getMaximum());
spinbox->setSingleStep(rp->getStep());
spinbox->setValue(slider->value());
layout->addWidget(title, 0, 0, 1, 2);
layout->addWidget(slider, 1, 0);
layout->addWidget(spinbox, 1, 1);
layout->setMargin(0);
layout->setSpacing(2);
connect(spinbox, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int)));
connect(slider, SIGNAL(valueChanged(int)), spinbox, SLOT(setValue(int)));
connect(slider, SIGNAL(valueChanged(int)), this, SLOT(setParamValue(int)));
}
void GUISlider::setParamValue(int value)
{
*pValue = value;
}
GUIDSpinBox::GUIDSpinBox(RangeParam<double>* rp) :
QFrame(),
spinbox(new QDoubleSpinBox(this)),
title(new QLabel(rp->name())),
layout(new QGridLayout(this)),
pValue(static_cast<double*>(rp->value()))
{
spinbox->setRange(rp->getMinimum(), rp->getMaximum());
spinbox->setSingleStep(rp->getStep());
spinbox->setDecimals(3);
spinbox->setValue(*pValue);
layout->addWidget(title, 0, 0);
layout->addWidget(spinbox, 1, 0);
layout->setMargin(0);
layout->setSpacing(2);
connect(spinbox, SIGNAL(valueChanged(double)), this, SLOT(setParamValue(double)));
}
void GUIDSpinBox::setParamValue(double value)
{
*pValue = value;
}
GUIRadioButton::GUIRadioButton(ImageModeParam* imp) :
QRadioButton(imp->name()),
pValue(static_cast<cv::Mat*>(imp->value())),
enPValue(static_cast<bool*>(imp->getPtrEnabled())),
dispImg(imp->getDstImgPtr())
{
if (*dispImg == pValue)
{
this->setChecked(true);
}
else
{
this->setChecked(false);
}
connect(this, SIGNAL(toggled(bool)), this, SLOT(setParamValues(bool)));
}
void GUIRadioButton::setParamValues(bool state)
{
*enPValue = state;
if (state)
{
*dispImg = pValue;
}
}
| [
"malcoholic@a09ac5dc-a04a-0975-72ff-3257ca587d63",
"justcme@a09ac5dc-a04a-0975-72ff-3257ca587d63"
]
| [
[
[
1,
11
],
[
13,
18
],
[
20,
26
],
[
29,
48
],
[
50,
51
],
[
53,
55
],
[
62,
77
],
[
79,
81
],
[
83,
83
],
[
87,
100
],
[
110,
119
]
],
[
[
12,
12
],
[
19,
19
],
[
27,
28
],
[
49,
49
],
[
52,
52
],
[
56,
61
],
[
78,
78
],
[
82,
82
],
[
84,
86
],
[
101,
109
]
]
]
|
65ad0d51ccea3462a7f013f1ac762f06742bcb9a | 815c8fa070af9fc8914acc4d54fb27be54e5e14b | /Foundation/Singleton.h | 00a80306efbc88cfcb8a12b252461d5b4313e986 | []
| no_license | abhean/Braintonic | ec7c2aa309d4f082f4783d16b3716381488caee4 | 820bf671bd15de45608e8fc40fa6d4aaef8df1ef | refs/heads/master | 2020-12-24T13:20:12.591248 | 2010-11-27T21:41:17 | 2010-11-27T21:41:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | h | #pragma once
#ifndef _SINGLETON_H_
#define _SINGLETON_H_
#include <boost/utility.hpp>
#include <cassert>
namespace Foundation
{
template <typename T>
class CSingleton : public boost::noncopyable
{
public:
virtual ~CSingleton() { assert(m_pInstance != NULL); m_pInstance = NULL; }
static void Done()
{
}
static T* Instance();
protected:
CSingleton()
{
assert(m_pInstance == NULL);
m_pInstance = static_cast<T*>(this);
}
private:
static T* m_pInstance;
};
template<typename T> T* CSingleton<T>::m_pInstance = NULL;
template <typename T>
T* CSingleton<T>::Instance()
{
assert(m_pInstance != NULL);
return m_pInstance;
}
} // namespace Foundation
#define INITIALIZE_SINGLETON(T) new T();
#endif // _SINGLETON_H_
| [
"[email protected]"
]
| [
[
[
1,
55
]
]
]
|
92271417be2b42c4751478e7e52f0092e86024a3 | 1c4a1cd805be8bc6f32b0a616de751ad75509e8d | /jacknero/src/pku_src/1029/3584212_CE.c | 8bcd731ed44a22e80b4c5607237a18d69070e71d | []
| no_license | jacknero/mycode | 30313261d7e059832613f26fa453abf7fcde88a0 | 44783a744bb5a78cee403d50eb6b4a384daccf57 | refs/heads/master | 2016-09-06T18:47:12.947474 | 2010-05-02T10:16:30 | 2010-05-02T10:16:30 | 180,950 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,620 | c | #include <stdio.h>
#include <string.h>
#define maxn 1001
int main()
{
int tt,n;
int num,i,j,k,t,total;
char c[maxn];
int d[maxn];
int b[maxn];
int a[101][maxn];
int jg[maxn];
bool p;
int sign,sign1;
//freopen("in.txt","r",stdin);
while (scanf("%d%d",&n,&k)==2)
{
tt=0;
bool q=false;
total=0;
memset(d,0,sizeof(d));
memset(b,0,sizeof(b));
for (i=1;i<=k;i++)
{
scanf("%d",&num);
a[i][0]=0;
for (j=1;j<=num*2;j++)
{
a[i][0]++;
scanf("%d",&a[i][a[i][0]]);
}
scanf("\n");
scanf("%c",&c[i]);
if (c[i]=='=')
{
for (j=1;j<=num*2;j++)
b[a[i][j]]=1;
}
else
{
total++;
d[total]=i;
}
}
if (total==0)
{
for (i=1;i<=n;i++)
if (b[i]!=1)
{
tt++;
jg[tt]=i;
}
}
else
{
for (i=1;i<=n;i++)
if (b[i]!=1)
{
p=true;
sign=1;
for (t=1;t<=a[d[1]][0];t++)
if (i==a[d[1]][t]) break;
if (i!=a[d[1]][a[d[1]][0]]&&t-1==a[d[1]][0])
{
p=false;
continue;
}
if (t<=a[d[1]][0]/2&&c[d[1]]=='<')
sign=-1;
else
if (t>a[d[1]][0]/2&&c[d[1]]=='>')
sign=-1;
if (p==false) continue;
for (j=2;j<=total;j++)
{
p=true;
sign1=1;
for (t=1;t<=a[d[j]][0];t++)
if (i==a[d[j]][t]) break;
if (i!=a[d[j]][a[d[j]][0]]&&t-1==a[d[j]][0])
{
p=false;
break;
}
if (t<=a[d[j]][0]/2&&c[d[j]]=='<')
sign1=-1;
else
if (t>a[d[j]][0]/2&&c[d[j]]=='>')
sign1=-1;
if (p==false) break;
if (sign1!=sign)
{
p=false;
break;
}
}
if (p==true)
{
tt++;
jg[tt]=i;
continue;
}
}
}
if (tt==1) printf("%d\n",jg[tt]);
else printf("0\n");
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
117
]
]
]
|
fd845d909fc9cf8ac73e3ffc4e7fe7e5e7f7fe7b | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/PatchClient/DlgOption.h | 88474783e39c981ea1a0d69a153954b26e622e8b | []
| no_license | 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 | UHC | C++ | false | false | 1,810 | h | #if !defined(AFX_DLGOPTION_H__3D38DC06_76E7_4F5A_9F94_A49970837AF0__INCLUDED_)
#define AFX_DLGOPTION_H__3D38DC06_76E7_4F5A_9F94_A49970837AF0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DlgOption.h : header file
//
#include "BtnST.h"
#include "Picture.h"
/////////////////////////////////////////////////////////////////////////////
// CDlgOption dialog
class CDlgOption : public CDialog
{
// Construction
public:
CDlgOption(CWnd* pParent = NULL); // standard constructor
CFont m_font;
CPicture m_pic;
int m_nResWidth; // 선택한 해상도
int m_nResHeight;
BOOL m_bStartFullScreen;
#if __VER >= 9 // __CSC_VER9_RESOLUTION
int m_nNormalRCount;
int m_nWideRCount;
#endif //__CSC_VER9_RESOLUTION
// Dialog Data
//{{AFX_DATA(CDlgOption)
enum { IDD = IDD_OPTION };
CButtonST m_BtnCANCEL;
CButtonST m_BtnOK;
CComboBox m_cbRes;
int m_nTexQual;
int m_nViewArea;
int m_nObjectDetail;
int m_nShadow;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlgOption)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
void LoadButton();
void LoadSkin();
// Generated message map functions
//{{AFX_MSG(CDlgOption)
virtual BOOL OnInitDialog();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
virtual void OnOK();
virtual void OnCancel();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLGOPTION_H__3D38DC06_76E7_4F5A_9F94_A49970837AF0__INCLUDED_)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
69
]
]
]
|
6450b25197bcaff5414a040519b0fec8b8687a6b | 670c614fea64d683cd517bf973559217a4b8d4b6 | / mindmap-search/mindmap-search/SimpleIndexBuilder.h | a116ebd5d54d9d6e2c22142e8d20a58048d09b91 | []
| no_license | mcpanic/mindmap-search | 5ce3e9a75d9a91224c38d7c0faa4089d9ea2487b | 67fd93be5f60c61a33d84f18cbaa1c5dd7ae7166 | refs/heads/master | 2021-01-18T13:33:19.390091 | 2009-04-06T11:42:07 | 2009-04-06T11:42:07 | 32,127,402 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | h | #pragma once
#include "indexbuilder.h"
class SimpleIndexBuilder: public IIndexBuilder
{
public:
SimpleIndexBuilder();
virtual ~SimpleIndexBuilder();
void Release();
void Build();
};
| [
"truepanic@ba4b31b2-0743-0410-801d-7d2edeec4cc6"
]
| [
[
[
1,
12
]
]
]
|
da59381ec35e99c60d8ee2c81df20a2ed0fa8dcf | a0949237db33b47ad927140915636d5c7221e5f1 | /Timer.h | a8edb9e12802a5797e5ebcbb4d6ab2d10ac4fd4a | []
| no_license | moozilla/mmbnonline | 6fa43595467c58bda8746027a950835949b1bdee | e5f74e84aab9775ab2d3b972466e40f458e51920 | refs/heads/master | 2021-01-10T06:10:21.527544 | 2007-08-17T23:31:14 | 2007-08-17T23:31:14 | 36,790,671 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,223 | h | #include <SDL/SDL.h>
class Timer
{
private:
//The clock time when the timer started
int startTicks;
//The ticks stored when the timer was paused
int pausedTicks;
//The timer status
bool paused;
bool started;
public:
//Initializes variables
Timer();
//The various clock actions
void start();
void stop();
void pause();
void unpause();
//Gets the timer's time
int get_ticks();
//Checks the status of the timer
bool is_started();
bool is_paused();
};
Timer::Timer()
{
//Initialize the variables
startTicks = 0;
pausedTicks = 0;
paused = false;
started = false;
}
void Timer::start()
{
//Start the timer
started = true;
//Unpause the timer
paused = false;
//Get the current clock time
startTicks = SDL_GetTicks();
}
void Timer::stop()
{
//Stop the timer
started = false;
//Unpause the timer
paused = false;
}
void Timer::pause()
{
//If the timer is running and isn't already paused
if( ( started == true ) && ( paused == false ) )
{
//Pause the timer
paused = true;
//Calculate the paused ticks
pausedTicks = SDL_GetTicks() - startTicks;
}
}
void Timer::unpause()
{
//If the timer is paused
if( paused == true )
{
//Unpause the timer
paused = false;
//Reset the starting ticks
startTicks = SDL_GetTicks() - pausedTicks;
//Reset the paused ticks
pausedTicks = 0;
}
}
int Timer::get_ticks()
{
//If the timer is running
if( started == true )
{
//If the timer is paused
if( paused == true )
{
//Return the number of ticks when the the timer was paused
return pausedTicks;
}
else
{
//Return the current time minus the start time
return SDL_GetTicks() - startTicks;
}
}
//If the timer isn't running
return 0;
}
bool Timer::is_started()
{
return started;
}
bool Timer::is_paused()
{
return paused;
}
| [
"nareion@8bee0d91-8a1e-0410-b811-83a365e83f77"
]
| [
[
[
1,
122
]
]
]
|
ef870198125908897b1e4047245c063733d88c37 | 8a8873b129313b24341e8fa88a49052e09c3fa51 | /src/DownLoadNet.cpp | dac125e7e50a5a020538480e927ce6ef80c7ef99 | []
| no_license | flaithbheartaigh/wapbrowser | ba09f7aa981d65df810dba2156a3f153df071dcf | b0d93ce8517916d23104be608548e93740bace4e | refs/heads/master | 2021-01-10T11:29:49.555342 | 2010-03-08T09:36:03 | 2010-03-08T09:36:03 | 50,261,329 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,154 | cpp | // BrowserDownLoadState.cpp: implementation of the CDownLoadNet class.
//
//////////////////////////////////////////////////////////////////////
#include <COEMAIN.H>
#include "DownLoadNet.h"
#include "HTTPEngine.h"
#include "MainEngine.h"
#include "utf.h"
#include "StaticCommonTools.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define KMAXTIMER (5000)
CDownLoadNet::CDownLoadNet(CMainEngine& aMainEngine)
:iMainEngine(aMainEngine),
iStatus(ENone),
iBeginPos(0),
iEndPos(0),
iTaskID(-1),
iThreadID(-1),
iContentType(0),
iBeyondTimeNum(0),
iReceivedData(NULL),
iReceivedTextData(NULL),
iDownLoadServer(NULL),
iStream(NULL)
{
iHttpBinary=CHTTPEngine::NewL(*this);
iHttpBinary->SetupConnectionL(iMainEngine.GetIAPValue());
ifs.Connect();
}
CDownLoadNet::~CDownLoadNet()
{
delete iStream;
ifs.Close() ;
iSaveFile.Close();
if(iReceivedData)
delete iReceivedData;
if(iReceivedTextData)
delete iReceivedTextData;
}
TInt CDownLoadNet::Activate()
{
iStatus = ENone;
iNewGetFile = 0;
return TRUE;
}
TInt CDownLoadNet::CancelDownLoad(TInt aType)
{
//aType:0-终止下载
// 2-文件打开失败终止下载;3-下载URL错误终止下载
iHttpBinary->CancelTransaction();
if(iStream)
{
if(iReceivedData)
{
iStream->WriteL (*iReceivedData);
iStream->CommitL ();
delete iReceivedData;
iReceivedData=NULL;
}
iStream->Close ();
iSaveFile.Close();
delete iStream;
iStream=NULL;
}
iSaveFileName.Zero ();
iBeginPos=0;
iEndPos=0;
iBeyondTimeNum=0;
if (iDownLoadServer)
{
if(aType==0 || aType==1)
iDownLoadServer->DownLoadEvent(iTaskID,iThreadID,0);
else
iDownLoadServer->DownLoadEvent(iTaskID,iThreadID,aType);
iTaskID=-1;
}
iStatus = ENone;
return TRUE;
}
void CDownLoadNet::GetFile()
{
if (NULL == iStream)
{
HttpBinaryGet();
}
}
void CDownLoadNet::HttpBinaryGet()
{
iHttpBinary->CancelTransaction();
iOldURL.Zero();
iOldURL.Copy(iUrl);
TBuf8<350> url8(0);
url8.Copy(iUrl);
TBuf8<100> nBeginPos;
nBeginPos.Zero ();
nBeginPos.Append (_L8("bytes="));
nBeginPos.AppendNum (iBeginPos);
nBeginPos.Append (_L8("-"));
if(iEndPos>0)
{
nBeginPos.AppendNum (iEndPos);
}
if(iHandleType==0)
{
//正常下载
iHttpBinary->IssueHTTPGetL(url8,nBeginPos);
}
else if(iHandleType==1)
{
//获取文件大小
iHttpBinary->IssueHTTPHeadL (url8);
}
}
void CDownLoadNet::HttpBinaryGet(TDesC& aURL)
{
iHttpBinary->CancelTransaction();
TBuf8<350> url8(0);
url8.Copy(aURL);
TBuf8<100> nBeginPos;
nBeginPos.Zero ();
nBeginPos.Append (_L8("bytes="));
nBeginPos.AppendNum (iBeginPos);
nBeginPos.Append (_L8("-"));
if(iEndPos>0)
{
nBeginPos.AppendNum (iEndPos);
}
if(iHandleType==0)
{
iHttpBinary->IssueHTTPGetL(url8,nBeginPos);
}
else if(iHandleType==1)
{
iHttpBinary->IssueHTTPHeadL (url8);
}
}
void CDownLoadNet::ClientEvent(const TDesC& aEventDescription,TInt aIndex)
{
UtilityTools::WriteLogsL(_L("CDownLoadNet::ClientEvent"));
if (aEventDescription.Compare (_L("Connecting..."))==0)
{
iMainEngine.SetCurrentTraffice_Rev((TInt64)iHttpBinary->GetSendSize());
}
switch(iHttpBinary->GetNetState())
{
case THTTPEvent::EGotResponseHeaders:
{
if(!iStream)
{
//20070601张晖增加判断是否为真正的下载内容
TBuf<100> nContentType;
nContentType.Zero ();
nContentType.Append (aEventDescription);
//iMainEngine.WriteLog16(nContentType);
#ifdef __WINS__
if(nContentType.Find(_L("application/vnd.oma.dd"))!=KErrNotFound || iHttpBinary->GetContentLength()<2048)
#else
if(nContentType.Find(_L("application/vnd.oma.dd"))!=KErrNotFound )
#endif
{
//DD下载文件
iContentType=2;
//iMainEngine.WriteLog16(_L("nContentType=2"));
return;
}
#ifdef __WINS__
else if(nContentType.Find(_L("text/vnd.sun.j2me.app-descriptor"))!=KErrNotFound)
#else
if(nContentType.Find(_L("text/vnd.sun.j2me.app-descriptor"))!=KErrNotFound )
#endif
{
//JAD下载文件
iContentType=3;
//iMainEngine.WriteLog16(_L("nContentType=3"));
return;
}
else if(nContentType.Find(_L("Content-Type:text"))!=KErrNotFound && nContentType.Find (_L("Content-Type:text/plain"))==KErrNotFound)
{
iContentType=1;
//iMainEngine.WriteLog16(_L("nContentType=1"));
return;
}
else
{
//iMainEngine.WriteLog16(_L("nContentType=0"));
iContentType=0;
}
if(iHandleType==1)
{
//如果是获取文件大小则返回结果
if (iDownLoadServer && iTaskID!=-1 && iThreadID!=-1)
{
TInt nTotalSize = iHttpBinary->GetContentLength();
iDownLoadServer->DownLoadReceived(iTaskID,iThreadID,nTotalSize,0);
}
return;
}
TInt err=iSaveFile.Open(ifs,iSaveFileName,EFileWrite|EFileShareAny);
if (err==KErrNotFound) // file does not exist - create it
{
iSaveFile.Close();
CancelDownLoad(5);
return;
}
iStream=new(ELeave) RFileWriteStream(iSaveFile,iBeginPos);
}
break;
}
case THTTPEvent::EGotResponseBodyData:
{
break;
}
case -888: // sign : now is the last data
{
//iMainEngine.WriteLog16(_L("888-1"));
::WriteLogsTemp(_L("ClientEvent-888-1"));
if(iContentType==1)
{
//移动推送页面判读
if (iReceivedTextData)
{
HBufC* newUrl = HBufC::NewLC(500);
TInt gErr=iMainEngine.ParseMobiWapPage(iOldURL,*iReceivedTextData,newUrl);
if(gErr==1) //处理推送页面
{
iOldURL.Zero();
iOldURL.Append(*newUrl);
HttpBinaryGet(iOldURL);
CleanupStack::PopAndDestroy(newUrl);
delete iReceivedTextData;
iReceivedTextData=NULL;
return;
}
else
{
//保存结果
TFileName nSaveFile;
nSaveFile.Zero();
nSaveFile.Append(_L("c:\\httperr.txt"));
WriteFile(nSaveFile,*iReceivedTextData);
CancelDownLoad(3);
}
CleanupStack::PopAndDestroy(newUrl);
delete iReceivedTextData;
iReceivedTextData=NULL;
return;
}
}
else if (iContentType==2)
{
//iMainEngine.WriteLog16(_L("888-2"));
HandleDDFile(*iReceivedTextData);
delete iReceivedTextData;
iReceivedTextData=NULL;
return;
}
else if (iContentType==3)
{
//iMainEngine.WriteLog16(_L("888-3"));
HandleJADFile(*iReceivedTextData);
delete iReceivedTextData;
iReceivedTextData=NULL;
return;
}
//iMainEngine.WriteLog16(_L("888-4"));
if(iStream)
{
if (iReceivedData)
{
//::WriteLogsL(_L("ClientEvent-X-1"));
iStream->WriteL(*iReceivedData);
iStream->CommitL();
//::WriteLogsL(_L("ClientEvent-X-2"));
delete iReceivedData;
iReceivedData=NULL;
}
if (iReceivedTextData)
{
delete iReceivedTextData;
iReceivedTextData=NULL;
}
iStream->Close();
iSaveFile.Close();
delete iStream;
iStream=NULL;
iStatus=EConnectOver;
if (iDownLoadServer)
{
iDownLoadServer->DownLoadEvent(iTaskID,iThreadID,1);
iTaskID=-1;
iThreadID=-1;
}
}
//iMainEngine.WriteLog16(_L("888-5"));
break;
}
case -999:
{
//iMainEngine.WriteLog16(_L("999-1"));
//20070708张晖增加超时自动重连
::WriteLogsTemp(_L("ClientEvent-999-1"));
iBeyondTimeNum++;
iHttpBinary->CancelTransaction();
//::WriteLogsL(_L("ClientEvent-999-2"));
if(iBeyondTimeNum<5)
{
//::WriteLogsL(_L("ClientEvent-999-3"));
::WriteLogsTemp(_L("ClientEvent-999-2"));
if(iStream && iReceivedData)
{
iStream->WriteL (*iReceivedData);
iStream->CommitL ();
}
//::WriteLogsL(_L("ClientEvent-999-4"));
if(iReceivedData)
{
delete iReceivedData;
iReceivedData=NULL;
}
if (iReceivedTextData)
{
delete iReceivedTextData;
iReceivedTextData=NULL;
}
//::WriteLogsL(_L("ClientEvent-999-5"));
HttpBinaryGet();
//::WriteLogsL(_L("ClientEvent-999-6"));
::WriteLogsTemp(_L("ClientEvent-999-3"));
}
else
{
//大于5次则认为是错误链接!
//::WriteLogsL(_L("ClientEvent-999-7"));
//iMainEngine.WriteLog16(_L("999-2"));
::WriteLogsTemp(_L("ClientEvent-999-4"));
if (iReceivedTextData)
{
delete iReceivedTextData;
iReceivedTextData=NULL;
}
CancelDownLoad(3);
::WriteLogsTemp(_L("ClientEvent-999-5"));
//::WriteLogsL(_L("ClientEvent-999-8"));
return;
}
//iMainEngine.WriteLog16(_L("999-3"));
}
}
UtilityTools::WriteLogsL(_L("CDownLoadNet::ClientEvent End"));
}
void CDownLoadNet::ClientBodyReceived(const TDesC8& aBodyData,TInt aIndex)
{
UtilityTools::WriteLogsL(_L("CDownLoadNet::ClientBodyReceived"));
iMainEngine.SetCurrentTraffice_Rev((TInt64)aBodyData.Length());
if(iContentType>=1)
{
//文本信息
HBufC* newData = HBufC::NewLC(aBodyData.Length());
TPtr16 ptr = newData->Des();
CnvUtfConverter::ConvertToUnicodeFromUtf8(ptr,aBodyData);
if (iReceivedTextData)
{
iReceivedTextData = iReceivedTextData->ReAllocL(iReceivedTextData->Length() + aBodyData.Length());
iReceivedTextData->Des() += newData->Des();
}
else
{
iReceivedTextData = HBufC::NewL(aBodyData.Length());
iReceivedTextData->Des().Copy(*newData);
}
//tmp
/*TFileName nSaveFile;
nSaveFile.Zero();
nSaveFile.Append(_L("c:\\httpbody.txt"));
WriteFile(nSaveFile,*newData);*/
CleanupStack::PopAndDestroy(newData);
}
else
{
//正常下载内容信息
iBeyondTimeNum=0;
if(iStream && iTaskID!=-1)
{
if (iReceivedData)
{
iReceivedData = iReceivedData->ReAllocL(iReceivedData->Length() + aBodyData.Length());
HBufC8* newData = HBufC8::NewLC(aBodyData.Length());
newData->Des().Copy(aBodyData);
iReceivedData->Des() += newData->Des();
CleanupStack::PopAndDestroy(newData);
}
// no data yet received.
else
{
iReceivedData = HBufC8::NewL(aBodyData.Length());
iReceivedData->Des().Copy(aBodyData);
}
if(iReceivedData->Length()> 60480)
{
iStream->WriteL(*iReceivedData);
iStream->CommitL();
delete iReceivedData;
iReceivedData=NULL;
}
//20070708张晖增加
iBeginPos=iBeginPos+aBodyData.Length();
if (iDownLoadServer && iTaskID!=-1 && iThreadID!=-1)
{
TInt nReservedSize = aBodyData.Length();
TInt nTotalSize = iHttpBinary->GetContentLength();
iDownLoadServer->DownLoadReceived(iTaskID,iThreadID,nTotalSize,nReservedSize);
}
}
}
UtilityTools::WriteLogsL(_L("CDownLoadNet::ClientBodyReceived End"));
}
void CDownLoadNet::GetDownLoadFileSize(TInt aTaskID,TInt aThreadID,const TDesC& aUrl)
{
//利用HTTP Head协议获取文件大小
iHandleType=1;
iBeyondTimeNum=0;
iTaskID=aTaskID;
iThreadID=aThreadID;
iUrl.Delete(0, iUrl.Length());
iUrl.Append(aUrl);
HttpBinaryGet();
}
void CDownLoadNet::SetUrl(TInt aTaskID,TInt aThreadID,const TDesC& aUrl, const TDesC& aName,TInt aBeginPos,TInt aEndPos)
{
if (iNewGetFile == -1)
iNewGetFile = 1;
iBeyondTimeNum=0;
iHandleType=0;
iBeginPos=aBeginPos;
iEndPos=aEndPos;
iTaskID=aTaskID;
iThreadID=aThreadID;
iSaveFileName.Delete(0, iSaveFileName.Length());
iSaveFileName.Append(aName);
iUrl.Delete(0, iUrl.Length());
iUrl.Append(aUrl);
GetFile();
}
void CDownLoadNet::HandleDDFile(TDesC& aContent)
{
//解析DD文件
TInt i=0;
TInt j=0;
TBuf<50> nType;
TBuf<255> nFileName;
TBuf<255> nDownLoadURL;
TBuf<255> nDownLoadResponseURL;
TInt nFileSize;
//获取文件类型
i=aContent.Find(_L("<type>"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=aContent.Find(_L("</type>"));
nType.Zero();
nType.Append(aContent.Mid(i+6,j-i-6));
//获取文件名称
i=aContent.Find(_L("<name>"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=aContent.Find(_L("</name>"));
nFileName.Zero();
nFileName.Append(aContent.Mid(i+6,j-i-6));
//获取文件大小
i=aContent.Find(_L("<size>"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=aContent.Find(_L("</size>"));
TLex temp(aContent.Mid(i+6,j-i-6));
temp.Val( nFileSize);
//获取文件下载URL
i=aContent.Find(_L("<objectURI>"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=aContent.Find(_L("</objectURI>"));
nDownLoadURL=aContent.Mid(i+11,j-i-11);
//获取文件下载成功返回URL
i=aContent.Find(_L("<installNotifyURI>"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=aContent.Find(_L("</installNotifyURI>"));
nDownLoadResponseURL=aContent.Mid(i+18,j-i-18);
//iMainEngine.WriteLog16(_L("HandleDDFile"));
//iMainEngine.WriteLog16(nDownLoadURL);
//iMainEngine.WriteLog16(nDownLoadResponseURL);
iDownLoadServer->DownLoadReceived(iTaskID,iThreadID,nFileSize,nFileName,nDownLoadURL,nDownLoadResponseURL);
}
void CDownLoadNet::HandleJADFile(TDesC& aContent)
{
//解析JAD文件
TInt i=0;
TInt j=0;
TBuf<500> nInfo;
TBuf<255> nFileName;
TBuf<255> nDownLoadURL;
TBuf<255> nDownLoadResponseURL;
TInt nFileSize;
nInfo.Zero();
nInfo.Append(aContent);
//获取文件名称
i=nInfo.Find(_L("MIDlet-Name:"));
j=nInfo.Find(_L("\n"));
if (i==KErrNotFound || j==KErrNotFound)
{
CancelDownLoad(3);
return;
}
nFileName.Zero();
nFileName.Append(nInfo.Mid(i+12,j-i-12));
nInfo.Delete(0,j+1);
//获取文件大小
i=nInfo.Find(_L("MIDlet-Jar-Size:"));
j=nInfo.Find(_L("\n"));
if (i==KErrNotFound || j==KErrNotFound)
{
CancelDownLoad(3);
return;
}
TLex temp(nInfo.Mid(i+16,j-i-16));
temp.Val( nFileSize);
nInfo.Delete(0,j+1);
//获取文件下载URL
i=nInfo.Find(_L("MIDlet-Jar-URL:"));
j=nInfo.Find(_L("\n"));
if (i==KErrNotFound || j==KErrNotFound)
{
CancelDownLoad(3);
return;
}
nDownLoadURL=nInfo.Mid(i+15,j-i-15);
nInfo.Delete(0,j+1);
//获取文件下载成功返回URL
i=nInfo.Find(_L("MIDlet-Install-Notify:"));
if (i==KErrNotFound)
{
CancelDownLoad(3);
return;
}
j=nInfo.Find(_L("\n"));
if (j!=KErrNotFound)
{
nDownLoadResponseURL=nInfo.Mid(i+22,j-i-22);
}
else
{
nDownLoadResponseURL=nInfo.Mid(i+22);
}
iDownLoadServer->DownLoadReceived(iTaskID,iThreadID,nFileSize,nFileName,nDownLoadURL,nDownLoadResponseURL);
}
void CDownLoadNet::SetHttpIndex(TInt aIndex)
{
if (iHttpBinary)
{
iHttpBinary->SetThreadIndex(aIndex);
}
} | [
"sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f"
]
| [
[
[
1,
728
]
]
]
|
15dc414a35ef01279e6b71fbfc36f059e42847f0 | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/skin_lite/src/SkinLite/PollStatsDialog.cpp | 850e95c894482eee3764238d51186231a3687182 | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,322 | cpp | #include <wx/wx.h>
#include <vector>
using namespace std;
#include "PollStatsDialog.h"
#include "PollGraphicFrame.h"
/** PollStatsDialog default constructor.
*
*/
PollStatsDialog::PollStatsDialog() : wxDialog()
{
m_controlsCreated = false;
}
/** PollStatsDialog constructor.
* @param[in] info. Receive the statistics in this parameter.
*/
PollStatsDialog::PollStatsDialog(const PollInfo &info) : wxDialog()
{
m_controlsCreated = false;
m_info = info;
}
/** PollStatsDialog constructor.
* @param[in] parent. Parent window.
* @param[in] id. Window id. Default wxID_ANY.
* @param[in] title. Window title. Default _("Poll Statistics").
* @param[in] pos. Window position. Default wxDefaultPosition.
* @param[in] size. Window size. Default wxDefaultSize.
* @param[in] style. Window style. Default wxDEFAULT_DIALOG_STYLE.
* @param[in] name. Window name. Default wxT("dialogBox")
*/
PollStatsDialog::PollStatsDialog(wxWindow *parent,
wxWindowID id, const wxString &title,
const wxPoint &pos, const wxSize &size,
long style, const wxString &name)
{
m_controlsCreated = false;
Create(parent, id, title, pos, size, style, name);
}
/** PollStatsDialog constructor.
* @param[in] info. Receive the statistics in this parameter.
* @param[in] parent. Parent window.
* @param[in] id. Window id. Default wxID_ANY.
* @param[in] title. Window title. Default _("Poll Statistics").
* @param[in] pos. Window position. Default wxDefaultPosition.
* @param[in] size. Window size. Default wxDefaultSize.
* @param[in] style. Window style. Default wxDEFAULT_DIALOG_STYLE.
* @param[in] name. Window name. Default wxT("dialogBox")
*/
PollStatsDialog::PollStatsDialog(const PollInfo &info, wxWindow *parent,
wxWindowID id, const wxString &title,
const wxPoint &pos, const wxSize &size,
long style, const wxString &name)
{
m_controlsCreated = false;
m_info = info;
Create(parent, id, title, pos, size, style, name);
}
/** PollAnswerDialog constructor.
* @param[in] parent. Parent window.
* @param[in] id. Window id. Default wxID_ANY.
* @param[in] title. Window title. Default _("Poll").
* @param[in] pos. Window position. Default wxDefaultPosition.
* @param[in] size. Window size. Default wxDefaultSize.
* @param[in] style. Window style. Default wxDEFAULT_DIALOG_STYLE.
* @param[in] name. Window name. Default wxT("PollAnswerDialog")
* @return Return true if controls were created or false if an error occurred.
*/
bool PollStatsDialog::Create(wxWindow *parent,
wxWindowID id, const wxString &title,
const wxPoint &pos, const wxSize &size,
long style, const wxString &name)
{
bool ret = wxDialog::Create(parent, id, title, pos, size, style, name);
if(ret)
{
CreateControls();
Connect(ID_POLL_STATS_DIALOG_BTN_GRAPHIC, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(PollStatsDialog::OnGraphicButtonClick), NULL, this);
Connect(wxID_CLOSE, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(PollStatsDialog::OnCloseButtonClick), NULL, this);
}
return ret;
}
/** Sets informations of the poll.
* @param[in] info. Receive the statistics in this parameter.
*/
void PollStatsDialog::SetPollInfo(const PollInfo &info)
{
m_info = info;
UpdateInfo();
}
/** Updates the fields with the statistics passed from info in instantiation or SetPollInfo.
*
*/
void PollStatsDialog::UpdateInfo()
{
if(m_info.IsValid())
{
m_lblQuestionText->SetLabel(m_info.GetQuestionText());
bool hasOptionLabels = !m_lblOptions.empty();
float votePercent;
int totalVotes = m_info.GetTotalVotes();
int blankVotes = m_info.GetNumberOfVotes(-1);
m_lblBlankVoteText->SetLabel(wxString(wxT("(-)")) << m_info.GetAnswerItem(-1).GetText());
if(totalVotes != 0)
{
votePercent = 100.0f * (blankVotes / (float)totalVotes);
m_btnGraphic->Enable(true);
}
else
{
votePercent = 0.0f;
m_btnGraphic->Enable(false);
}
m_lblTotalVotes->SetLabel(wxString() << totalVotes);
m_lblBlankVotes->SetLabel(wxString::Format(_("%d votes (%0.02f%%)"), blankVotes, votePercent));
for(int i = 0; i < m_info.GetAnswerItemCount(); i++)
{
const PollItem &item = m_info.GetAnswerItem(i);
if(!hasOptionLabels)
{
m_lblOptions.push_back(new wxStaticText(this, wxID_ANY, wxT("")));
m_lblStatValues.push_back(new wxStaticText(this, wxID_ANY, wxT("")));
m_optionsGridSizer->Add(m_lblOptions[i], 0, wxLEFT | wxEXPAND | wxALIGN_LEFT);
m_optionsGridSizer->Add(m_lblStatValues[i], 1, wxEXPAND | wxALIGN_RIGHT);
}
wxChar optionChar = 'A' + i;
m_lblOptions[i]->SetLabel(wxString(wxT("(")) << wxString(optionChar) << wxT(") ") << item.GetText());
if(m_info.GetTotalVotes() != 0)
votePercent = 100.0f * (item.GetAnswerCount() / (float)totalVotes);
else
votePercent = 0.0f;
m_lblStatValues[i]->SetLabel(wxString::Format(_("%d votes (%0.02f%%)"), item.GetAnswerCount(), votePercent));
}
SetMaxSize(POLL_STATS_DIALOG_MAX_SIZE);
m_optionsGridSizer->Layout();
GetSizer()->Layout();
Fit();
}
}
void PollStatsDialog::CreateControls()
{
wxBoxSizer *controlsSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *textSizer = new wxBoxSizer(wxVERTICAL);
m_optionsGridSizer = new wxFlexGridSizer(0, 2, 4, 4); // variable rows, 2 columns, 4 pixels gap (H, V)
wxBoxSizer *buttonsSizer = new wxBoxSizer(wxHORIZONTAL);
m_lblQuestionText = new wxStaticText(this, wxID_ANY, wxT(""));
m_lblTotalVotes = new wxStaticText(this, wxID_ANY, wxT("0"));
m_lblBlankVotes = new wxStaticText(this, wxID_ANY, wxT(""));
m_lblBlankVoteText = new wxStaticText(this, wxID_ANY, wxT(""));
m_btnGraphic = new wxButton(this, ID_POLL_STATS_DIALOG_BTN_GRAPHIC, _("Graphic"));
m_btnClose = new wxButton(this, wxID_CLOSE, _("Close"));
m_optionsGridSizer->AddGrowableCol(0); // first column holds the option text labels
// Total
m_optionsGridSizer->Add(new wxStaticText(this, wxID_ANY, _("Total votes")), 0, wxLEFT | wxEXPAND, wxALIGN_LEFT);
m_optionsGridSizer->Add(m_lblTotalVotes, 0, wxEXPAND | wxALIGN_RIGHT);
// Spacer. Must add a spacer to each column
for(int j = 0; j < m_optionsGridSizer->GetCols(); j++)
m_optionsGridSizer->AddSpacer(4);
// Blank votes
m_optionsGridSizer->Add(m_lblBlankVoteText, 0, wxLEFT | wxEXPAND | wxALIGN_LEFT);
m_optionsGridSizer->Add(m_lblBlankVotes, 0, wxEXPAND | wxALIGN_RIGHT);
textSizer->Add(m_lblQuestionText, 0, wxALL | wxEXPAND, 4);
textSizer->AddSpacer(16);
textSizer->Add(m_optionsGridSizer, 1, wxLEFT | wxEXPAND, 16);
buttonsSizer->Add(m_btnGraphic, 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 8);
buttonsSizer->Add(m_btnClose, 0, wxALL | wxALIGN_CENTER_HORIZONTAL, 8);
controlsSizer->Add(textSizer, 1, wxALL | wxEXPAND, 8);
controlsSizer->Add(buttonsSizer, 1, wxALL | wxEXPAND, 8);
SetSizer(controlsSizer);
UpdateInfo();
m_controlsCreated = true;
}
void PollStatsDialog::OnGraphicButtonClick(wxCommandEvent &event)
{
if(m_info.IsValid())
{
std::vector<wxString> vecAnswerLabels;
std::vector<double> vecAnswerTotalVotes;
wxString question = m_info.GetQuestionText();
int totalVotes = m_info.GetTotalVotes();
int blankVotes = m_info.GetNumberOfVotes(-1);
vecAnswerLabels.push_back(m_info.GetAnswerItem(-1).GetText());
vecAnswerTotalVotes.push_back((double)blankVotes);
for(int i = 0; i < m_info.GetAnswerItemCount(); i++)
{
const PollItem &item = m_info.GetAnswerItem(i);
wxChar optionChar = 'A' + i;
wxString answerLabel = wxString(wxT("(")) << wxString(optionChar) << wxT(")");
int answerVoteCount = item.GetAnswerCount();
vecAnswerLabels.push_back(answerLabel);
vecAnswerTotalVotes.push_back((double)answerVoteCount);
}
PollGraphicFrame *pollGraphicFrame = (PollGraphicFrame *)FindWindowById(ID_POLLGRAPHICFRAME, this);
if (pollGraphicFrame == NULL)
pollGraphicFrame = new PollGraphicFrame(this, ID_POLLGRAPHICFRAME, _("Poll Graphic result"));
pollGraphicFrame->DrawChart(POLL_STATS_DIALOG_PNG_PATH, question, vecAnswerLabels, vecAnswerTotalVotes);
pollGraphicFrame->Show();
}
}
void PollStatsDialog::OnCloseButtonClick(wxCommandEvent &event)
{
Close();
}
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
236
]
]
]
|
530b18031ed1faa03a76f95503abb1c7ed48ebd9 | 1e299bdc79bdc75fc5039f4c7498d58f246ed197 | /ServerLib/FileIndexObject.h | 7b3d1600a55f1bc16acf76d8a8e2b9506de6a706 | []
| no_license | moosethemooche/Certificate-Server | 5b066b5756fc44151b53841482b7fa603c26bf3e | 887578cc2126bae04c09b2a9499b88cb8c7419d4 | refs/heads/master | 2021-01-17T06:24:52.178106 | 2011-07-13T13:27:09 | 2011-07-13T13:27:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,585 | h | //--------------------------------------------------------------------------------
// Copyright (c) 2001 MarkCare Medical Solutions, Inc.
// Created...: 6/11/01
// Author....: Rich Schonthal
//--------------------------------------------------------------------------------
#if !defined(AFX_FILEINDEXOBJECT_H__B66F74A9_E5CF_11D3_B10F_00A0CC271D0D__INCLUDED_)
#define AFX_FILEINDEXOBJECT_H__B66F74A9_E5CF_11D3_B10F_00A0CC271D0D__INCLUDED_
//--------------------------------------------------------------------------------
#include <ReadWriteObject.h>
#ifndef __AFXTEMPL_H__
#include <afxtempl.h>
#endif
//--------------------------------------------------------------------------------
class CFileIndexObject
{
public:
CMutex m_mutex;
LONG m_nRefCount;
protected:
CString m_sName;
public:
CFileIndexObject(LPCTSTR pName);
virtual ~CFileIndexObject();
LPCTSTR GetName();
void SetName(LPCTSTR pName);
virtual UINT GetObjectId();
virtual bool Write(CFile&, bool bResetPosOnError = true);
virtual bool Read(CFile&, bool bResetPosOnError = true);
};
//--------------------------------------------------------------------------------
class CFileIndexObjMap : public CReadWriteObject, public CMap<LPCTSTR, LPCTSTR, CFileIndexObject*, CFileIndexObject*>
{
public:
CFileIndexObjMap();
virtual bool Write(CFile&);
virtual bool Read(CFile&);
virtual CFileIndexObject* CreateNewIndexObject(LPCTSTR pName = NULL);
};
#endif//AFX_FILEINDEXOBJECT_H__B66F74A9_E5CF_11D3_B10F_00A0CC271D0D__INCLUDED_
| [
"[email protected]"
]
| [
[
[
1,
53
]
]
]
|
91e42a8982a63d9d2e41ecd02aad37dff1d1b09a | df238aa31eb8c74e2c208188109813272472beec | /BCGInclude/BCGPPlannerViewMonth.h | 6632407a1a6c0cd8284e133a5f0339bb221df245 | []
| no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,660 | h | //*******************************************************************************
// COPYRIGHT NOTES
// ---------------
// This is a part of BCGControlBar Library Professional Edition
// Copyright (C) 1998-2008 BCGSoft Ltd.
// All rights reserved.
//
// This source code can be used, distributed or modified
// only under terms and conditions
// of the accompanying license agreement.
//*******************************************************************************
//
// BCGPPlannerViewMonth.h: interface for the CBCGPPlannerViewMonth class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_BCGPPLANNERVIEWMONTH_H__BEAF25DC_41EC_4DA2_B94D_500C660AEFFF__INCLUDED_)
#define AFX_BCGPPLANNERVIEWMONTH_H__BEAF25DC_41EC_4DA2_B94D_500C660AEFFF__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "BCGCBPro.h"
#ifndef BCGP_EXCLUDE_PLANNER
#include "BCGPPlannerView.h"
class BCGCBPRODLLEXPORT CBCGPPlannerViewMonth : public CBCGPPlannerView
{
friend class CBCGPPlannerManagerCtrl;
DECLARE_DYNCREATE(CBCGPPlannerViewMonth)
public:
virtual ~CBCGPPlannerViewMonth();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
virtual void SetDate (const COleDateTime& date);
virtual void SetDateInterval (const COleDateTime& date1, const COleDateTime& date2);
virtual COleDateTime CalculateDateStart (const COleDateTime& date) const;
virtual void SetDrawTimeFinish (BOOL bDraw);
virtual BOOL IsDrawTimeFinish () const;
virtual void SetDrawTimeAsIcons (BOOL bDraw);
virtual BOOL IsDrawTimeAsIcons () const;
virtual void SetCompressWeekend (BOOL bCompress);
virtual BOOL IsCompressWeekend () const;
virtual COleDateTime GetDateFromPoint (const CPoint& point) const;
virtual int GetWeekFromPoint (const CPoint& point) const;
virtual void SetSelection (const COleDateTime& sel1, const COleDateTime& sel2, BOOL bRedraw = TRUE);
virtual BOOL CanCaptureAppointment (BCGP_PLANNER_HITTEST hitCapturedAppointment) const;
protected:
CBCGPPlannerViewMonth();
virtual void GetCaptionFormatStrings (CStringArray& sa);
virtual void AdjustScrollSizes ();
virtual void AdjustLayout (CDC* pDC, const CRect& rectClient);
virtual void AdjustRects ();
virtual void AdjustAppointments ();
virtual BCGP_PLANNER_HITTEST HitTestArea (const CPoint& point) const;
virtual DROPEFFECT HitTestDrag (DWORD dwKeyState, const CPoint& point) const;
virtual void DrawHeader (CDC* pDC, const CRect& rect, int dxColumn);
virtual void OnPaint (CDC* pDC, const CRect& rectClient);
virtual void OnDrawClient (CDC* pDC, const CRect& rect);
virtual void OnDrawHeader (CDC* pDC, const CRect& rectHeader);
virtual void OnDrawWeekBar (CDC* pDC, const CRect& rectBar);
virtual BOOL OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
virtual BOOL OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
virtual BOOL OnScroll(UINT nScrollCode, UINT nPos, BOOL bDoScroll);
virtual void OnActivate(CBCGPPlannerManagerCtrl* pPlanner, const CBCGPPlannerView* pOldView);
COleDateTime GetFirstWeekDay2 (const COleDateTime& date, int nWeekStart) const;
virtual void AddUpDownRect(BYTE nType, const CRect& rect);
int m_nHeaderHeight;
int m_nWeekBarWidth;
int m_nDuration;
BOOL m_bDrawTimeFinish;
BOOL m_bDrawTimeAsIcons;
BOOL m_bCompressWeekend;
CArray<CRect, CRect&>
m_WeekRects;
};
#endif // BCGP_EXCLUDE_PLANNER
#endif // !defined(AFX_BCGPPLANNERVIEWMONTH_H__BEAF25DC_41EC_4DA2_B94D_500C660AEFFF__INCLUDED_)
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
]
| [
[
[
1,
110
]
]
]
|
943bd9129a475ef94a9d3dd67894b66634f97826 | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizer/ParameterGUI_Base.cpp | 772b2ea9ec9b771004850065147ce236d2e3c1eb | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,401 | cpp | #ifdef PRECOMPILED_HEADER
#include "common.h"
#endif
#include "ParameterGUI_Base.h"
#include "Widgets.h"
#include "dds_pulse_info.h"
using namespace std;
ParameterGUI_Base::ParameterGUI_Base(std::vector<ParameterGUI_Base*> * pv,
unsigned flags) :
Parameter_Base(""),
label(0),
parent(0),
gui_revision(-2),
bottom(-2e9),
top(2e9),
precision(3),
increment(0.01),
input_width(0),
label_width(0),
new_row(false),
bLinked(false),
flags(flags),
bInit(true),
fpga_id(-1)
{
if (pv)
pv->push_back(this);
palBSB2.setColor(QPalette::WindowText, QColor(100, 100, 200));
palBSB1.setColor(QPalette::WindowText, QColor(50, 50, 200));
palRSB1.setColor(QPalette::WindowText, QColor(200, 50, 50));
palRSB2.setColor(QPalette::WindowText, QColor(200, 100, 100));
palCarrier.setColor(QPalette::WindowText, QColor(50, 170, 50));
QObject::connect(this, SIGNAL(sig_UpdateGUI()), this, SLOT(UpdateGUI()), Qt::QueuedConnection);
}
ParameterGUI_Base::ParameterGUI_Base(std::vector<ParameterGUI_Base*> * pv,
const std::string& sIni) :
Parameter_Base(""),
label(0),
parent(0),
gui_revision(-2),
bottom(-2e9),
top(2e9),
precision(3),
increment(0.01),
input_width(0),
label_width(0),
new_row(false),
bLinked(false),
flags(0),
bInit(true),
fpga_id(-1)
{
extract_val<double>(sIni, "min=", &bottom);
extract_val<double>(sIni, "max=", &top);
extract_val<unsigned>(sIni, "flags=", &flags);
flags = flags & (~pulse_info::flag_disabled);
if (pv)
pv->push_back(this);
palBSB2.setColor(QPalette::WindowText, QColor(100, 100, 200));
palBSB1.setColor(QPalette::WindowText, QColor(50, 50, 200));
palRSB1.setColor(QPalette::WindowText, QColor(200, 50, 50));
palRSB2.setColor(QPalette::WindowText, QColor(200, 100, 100));
palCarrier.setColor(QPalette::WindowText, QColor(50, 170, 50));
QObject::connect(this, SIGNAL(sig_UpdateGUI()), this, SLOT(UpdateGUI()), Qt::QueuedConnection);
}
void ParameterGUI_Base::selectScanTarget(const std::string&, bool)
{
}
void ParameterGUI_Base::PostUpdateGUI()
{
emit sig_UpdateGUI();
}
void ParameterGUI_Base::setLinked(bool bLinked)
{
this->bLinked = bLinked;
if (bLinked)
{
QColor bkg(Qt::lightGray);
palBSB2.setColor(QPalette::Window, bkg);
palBSB1.setColor(QPalette::Window, bkg);
palRSB1.setColor(QPalette::Window, bkg);
palRSB2.setColor(QPalette::Window, bkg);
palCarrier.setColor(QPalette::Window, bkg);
palOther.setColor(QPalette::Window, bkg);
}
}
QWidget* ParameterGUI_Base::MakeLabelControl(QWidget* parent, unsigned)
{
this->parent = parent;
if (HasLabel())
{
label = new QLabel(parent);
label->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
label->setAutoFillBackground(true);
UpdateGUI_Label();
}
return label;
}
void ParameterGUI_Base::GUI_button_press()
{
emit GUI_button_was_pressed(this);
}
void ParameterGUI_Base::GUI_value_change()
{
if (flags & RP_FLAG_READ_ONLY)
return;
gui_revision++;
UpdateFromGUI();
emit GUI_user_value_change(this);
}
void ParameterGUI_Base::Show(bool bShow)
{
setFlag(RP_FLAG_HIDDEN, !bShow);
}
void ParameterGUI_Base::setFlag(unsigned f, bool bOn)
{
if (bOn)
flags |= f;
else
flags &= ~f;
}
const std::string& ParameterGUI_Base::GetName() const
{
//return get_display_label();
return IGetName();
}
bool ParameterGUI_Base::SetName(const std::string& name)
{
gui_revision = -2;
return ISetName(name);
}
void ParameterGUI_Base::setInputPalette(const QPalette& p)
{
if (input_widget())
input_widget()->setPalette(p);
}
void ParameterGUI_Base::UpdateGUI()
{
if (label)
UpdateGUI_Label();
if (input_widget())
UpdateGUI_Value();
gui_revision = revision;
}
QPalette* ParameterGUI_Base::GetLabelPalette(const std::string& s)
{
if (s.find("bsb") != string::npos || s.find("BSB") != string::npos)
{
if (s.find("COM") != string::npos)
return &palBSB1;
else
return &palBSB2;
}
if (s.find("rsb") != string::npos || s.find("RSB") != string::npos)
{
if (s.find("COM") != string::npos)
return &palRSB1;
else
return &palRSB2;
}
if (s.find("carrier") != string::npos)
return &palCarrier;
return &palOther;
}
void ParameterGUI_Base::UpdateGUI_Label()
{
if (label)
{
if (flags & RP_FLAG_HIDDEN)
label->hide();
else
label->show();
QPalette* pal = GetLabelPalette(get_display_label().c_str());
if (pal)
label->setPalette(*pal);
label->setText(get_display_label().c_str());
if (ttip.length())
label->setToolTip(ttip.c_str());
}
if (input_widget() && ttip.length())
{
input_widget()->setToolTip(ttip.c_str());
ttip = "";
}
}
bool ParameterGUI_Base::UpdateFromGUI()
{
bool bResult = false;
if (input_widget())
if (gui_revision > revision)
{
bResult = SetValueFromString( GetGUIString() );
gui_revision = revision;
}
return false;
}
bool ParameterGUI_Base::OwnsWindow(QWidget* p)
{
return p && ((p == input_widget()) || (p == label));
}
QPoint ParameterGUI_Base::GetInputSize()
{
return QPoint(200, 30);
}
QPoint ParameterGUI_Base::GetLabelSize()
{
return IsPacked() ? QPoint(100, 30) : QPoint(200, 30);
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
262
]
]
]
|
7df380e888866ccbf4f1e969ff1e172a71d97615 | 0b55a33f4df7593378f58b60faff6bac01ec27f3 | /Konstruct/Common/Utility/kpuFixedArray.h | 421ed34146f7b74c035f4c54af498253271eda9c | []
| no_license | RonOHara-GG/dimgame | 8d149ffac1b1176432a3cae4643ba2d07011dd8e | bbde89435683244133dca9743d652dabb9edf1a4 | refs/heads/master | 2021-01-10T21:05:40.480392 | 2010-09-01T20:46:40 | 2010-09-01T20:46:40 | 32,113,739 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | h | #pragma once
template <typename T>
class kpuFixedArray
{
public:
kpuFixedArray()
{
m_iNumElements = 0;
m_iNumUsedElements = 0;
m_pElements = 0;
}
kpuFixedArray(int iNumElements)
{
m_iNumElements = 0;
m_iNumUsedElements = 0;
m_pElements = 0;
SetSize(iNumElements);
}
~kpuFixedArray(void)
{
if( m_pElements )
free(m_pElements);
}
void SetSize(int iNumElements)
{
if( m_pElements )
{
T* pNewData = (T*)malloc(sizeof(T) * iNumElements);
int iCopyCount = MIN(iNumElements, m_iNumElements);
memcpy(pNewData, m_pElements, sizeof(T) * iCopyCount);
int iDiff = iNumElements - m_iNumElements;
if( iDiff > 0 )
memset(&pNewData[iCopyCount], 0, sizeof(T) * iDiff);
}
else
{
m_pElements = (T*)malloc(sizeof(T) * iNumElements);
memset(m_pElements, 0, sizeof(T) * iNumElements);
}
m_iNumElements = iNumElements;
m_iNumUsedElements = 0;
}
const int GetNumElements()
{
return m_iNumElements;
}
const int GetNumElementsUsed()
{
return m_iNumUsedElements;
}
T& operator[](const int iIndex)
{
return m_pElements[iIndex];
}
T& GetElement(const int iIndex)
{
return m_pElements[iIndex];
}
int Add(const T& element)
{
if( m_iNumUsedElements < m_iNumElements )
{
int iIndex = m_iNumUsedElements;
m_iNumUsedElements++;
m_pElements[iIndex] = element;
return iIndex;
}
return -1;
}
int RemoveAt(int i)
{
m_pElements[i] = 0;
m_iNumUsedElements--;
}
protected:
int m_iNumElements;
int m_iNumUsedElements;
T* m_pElements;
};
| [
"acid1789@0c57dbdb-4d19-7b8c-568b-3fe73d88484e",
"bflassing@0c57dbdb-4d19-7b8c-568b-3fe73d88484e"
]
| [
[
[
1,
53
],
[
59,
82
],
[
89,
93
]
],
[
[
54,
58
],
[
83,
88
]
]
]
|
74e2043da29193d9069a3c9e1291e8b1287c1c4f | b6cdddcfcd908188888a3864b1f0becf0ee2ceee | /QtApp/SaWatch/src/DirectoryChanges.cpp | ab90ea89d08258c5e8eb9fe80d30d7d82e701f49 | []
| no_license | himanshu2090/syncany | 698c37c51a72309154dd454365ffc498e767d450 | f60bb2266fc1e99de390171edea890292beee467 | refs/heads/master | 2021-01-21T07:53:47.966909 | 2009-05-18T13:13:44 | 2009-05-18T13:13:44 | 34,249,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74,939 | cpp | // DirectoryChanges.cpp: implementation of the CDirectoryChangeWatcher and CDirectoryChangeHandler classes.
//
///////////////////////////////////////////////////////////////////
///
/***********************************************************
Author: Wes Jones [email protected]
File: DirectoryChanges.cpp
Latest Changes:
11/22/2001 -- Fixed bug causing file name's to be truncated if
longer than 130 characters. Fixed CFileNotifyInformation::GetFileName()
Thanks to Edric([email protected]) for pointing this out.
Added code to enable process privileges when CDirectoryChangeWatcher::WatchDirectory()
is first called. See docuementation API for ReadDirectoryChangesW() for more information of required privileges.
Currently enables these privileges: (11/22/2001)
SE_BACKUP_NAME
SE_CHANGE_NOTIFY_NAME
SE_RESTORE_NAME(02/09/2002)
Implemented w/ helper class CPrivilegeEnabler.
11/23/2001 Added classes so that all notifications are handled by the
same thread that called CDirectoryChangeWatcher::WatchDirectory(),
ie: the main thread.
CDirectoryChangeHandler::On_Filexxxx() functions are now called in the
context of the main thread instead of the worker thread.
This is good for two reasons:
1: The worker thread spends less time handling each notification.
The worker thread simply passes the notification to the main thread,
which does the processing.
This means that each file change notification is handled as fast as possible
and ReadDirectoryChangesW() can be called again to receive more notifications
faster.
2: This makes it easier to make an ActiveX or ATL object with this class
because the events that are fired, fire in the context of the main thread.
The fact that I'm using a worker thread w/ this class is totally
transparent to a client user.
If I decide to turn this app into an ActiveX or ATL object
I don't have to worry about wierd COM rules and multithreading issues,
and neither does the client, be the client a VB app, C++ app, Delphi app, or whatever.
Implemented with CDelayedDirectoryChangeHandler in DirectoryChangeHandler.h/.cpp
02/06/2002 Fixed a bug that would cause an application to hang.
If ReadDirectoryChangesW was to fail during normal operation,
the short story is that the application would hang
when it called CDirectoryChangeWatcher::UnwatchDirectory(const CString & )
One way to reproduce this behavior on the old code
is to watch a directory using a UNC path, and then change the IP
address of that machine while the watch was running. Exitting
the app after this would cause it to hang.
Steps to reproduce it:
1) Assume that the computer running the code is
named 'ThisComputer' and there is a shared folder named 'FolderName'
2) Start a watch on a folder using a UNC path: ie: \\ThisComputer\FolderName
eg: CDirectoryChangeWatcher watcher;
watcher.WatchDirectory(_T("\\\\ThisComputer\\FolderName",/ * other parameters * /)
3) Change the IP address of 'ThisComputer'
** ReadDirectoryChangesW() will fail some point after this.
4) Exit the application... it may hang.
Anyways, that's what the bug fix is for.
02/06/2002 New side effects for CDirectoryChangeHandler::On_ReadDirectoryChangeError()
If CDirectoryChangeHandler::On_ReadDirectoryChangeError() is ever executed
the directory that you are watching will have been unwatched automatically due
to the error condition.
A call to CDirectoryChangeWatcher::IsWatchingDirectory() will fail because the directory
is no longer being watched. You'll need to re-watch that directory.
02/09/2002 Added a parameter to CDirectoryChangeHandler::On_ReadDirectoryChangeError()
Added the parameter: const CString & strDirectoryName
The new signature is now:
virtual void CDirectoryChangeHandler::On_ReadDirectoryChangeError(DWORD dwError, const CString & strDirectoryName);
This new parameter gives you the name of the directory that the error occurred on.
04/25/2002 Provided a way to get around the requirement of a message pump.
A console app can now use this w/out problems by passing false
to the constructor of CDirectoryChangeWatcher.
An app w/ a message pump can also pass false if it so desires w/out problems.
04/25/2002 Added two new virtual functions to CDirectoryChangeHandler
Added:
On_WatchStarted(DWORD dwError, const CString & strDirectoryName)
On_WatchStopped(const CString & strDirectoryName);
See header file for details.
04/27/2002 Added new function to CDirectoryChangeHandler:
Added virtual bool On_FilterNotification(DWORD dwNotifyAction, LPCTSTR szFileName, LPCTSTR szNewFileName)
This function is called before any notification function, and allows the
CDirectoryChangeHandler derived class to ignore file notifications
by performing a programmer defined test.
By ignore, i mean that
On_FileAdded(), On_FileRemoved(), On_FileModified(), or On_FileNameChanged()
will NOT be called if this function returns false.
The default implementation always returns true, signifying that ALL notifications
are to be called.
04/27/2002 Added new Parameters to CDirectoryChangeWatcher::WatchDirectory()
The new parameters are:
LPCTSTR szIncludeFilter
LPCTSTR szExcludeFilter
Both parameters are defaulted to NULL.
Signature is now:
CDirectoryChangeWatcher::WatchDirectory(const CString & strDirToWatch,
DWORD dwChangesToWatchFor,
CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs = FALSE,
LPCTSTR szIncludeFilter = NULL,
LPCTSTR szExcludeFilter = NULL)
04/27/2002 Added support for include and exclude filters.
These filters allow you to receive notifications for just the files you
want... ie: you can specify that you only want to receive notifications
for changes to "*.txt" files or some other such file filter.
NOTE: This feature is implemented w/ the PathMatchSpec() api function
which is only available on NT4.0 if Internet Explorer 4.0 or above is installed.
See MSDN for PathMatchSpec(). Win2000, and XP do not have to worry about it.
Filter specifications:
Accepts wild card characters * and ?, just as you're used to for the DOS dir command.
It is possible to specify multiple extenstions in the filter by separating each filter spec
with a semi-colon.
eg: "*.txt;*.tmp;*.log" <-- this filter specifies all .txt, .tmp, & .log files
Filters are passed as parameters to CDirectoryChangeWatcher::WatchDirectory()
NOTE: The filters you specify take precedence over CDirectoryChangeHandler::On_FilterNotification().
This means that if the file name does not pass the filters that you specify
when the watch is started, On_FilterNotification() will not be called.
Filter specifications are case insensitive, ie: ".tmp" and ".TMP" are the same
FILTER TYPES:
Include Filter:
If you specify an include filter, you are specifying that you
only want to receive notifications for specific file types.
eg: "*.log" means that you only want notifications for changes
to files w/ an exention of ".log".
Changes to ALL OTHER other file types are ignored.
An empty, or not specified include filter means that you want
notifications for changes of ALL file types.
Exclude filter:
If you specify an exclude filter, you are specifying that
you do not wish to receive notifications for a specific type of file or files.
eg: "*.tmp" would mean that you do not want any notifications
regarding files that end w/ ".tmp"
An empty, or not specified exclude filter means that
you do not wish to exclude any file notifications.
************************************************************/
#define _WIN32_WINNT 0x500 //so that I can use ReadDirectoryChanges
#include <afxwin.h> // MFC core and standard components
#include <afxext.h>
#include "DWLib.h"
#include "DirectoryChanges.h"
#include "DelayedDirectoryChangeHandler.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//
//
// Fwd Declares & #define's
//
//
//
// Helper classes
class CPrivilegeEnabler; //for use w/ enabling process priveledges when this code is first used. It's a singleton.
class CFileNotifyInformation;//helps CDirectoryChangeWatcher class notify CDirectoryChangeHandler class of changes to files.
class CDelayedDirectoryChangeHandler; // Helps all notifications become handled by the main
// thread, or a worker thread depending upon a value passed to the
// constructor of CDirectoryChangeWatcher.
//
// For notifications to fire in the main thread, your app must have a message pump.
//
// The 'main' thread is the one that called CDirectoryChangeWatcher::WatchDirectory()
// Helper functions
static BOOL EnablePrivilege(LPCTSTR pszPrivName, BOOL fEnable = TRUE);
static bool IsDirectory(const CString & strPath);
/////////////////////////////////////////////////////////////////////
// Helper functions.
BOOL EnablePrivilege(LPCTSTR pszPrivName, BOOL fEnable /*= TRUE*/)
//
// I think this code is from a Jeffrey Richter book...
//
// Enables user priviledges to be set for this process.
//
// Process needs to have access to certain priviledges in order
// to use the ReadDirectoryChangesW() API. See documentation.
{
BOOL fOk = FALSE;
// Assume function fails
HANDLE hToken;
// Try to open this process's access token
if (OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES, &hToken))
{
// privilege
TOKEN_PRIVILEGES tp = { 1 };
if( LookupPrivilegeValue(NULL, pszPrivName, &tp.Privileges[0].Luid) )
{
tp.Privileges[0].Attributes = fEnable ? SE_PRIVILEGE_ENABLED : 0;
AdjustTokenPrivileges(hToken, FALSE, &tp,
sizeof(tp), NULL, NULL);
fOk = (GetLastError() == ERROR_SUCCESS);
}
CloseHandle(hToken);
}
return(fOk);
}
static bool IsDirectory(const CString & strPath)
//
// Returns: bool
// true if strPath is a path to a directory
// false otherwise.
//
{
DWORD dwAttrib = GetFileAttributes( strPath );
return static_cast<bool>( ( dwAttrib != 0xffffffff
&& (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) );
}
///////////////////////////////////////////////
//Helper class:
class CFileNotifyInformation
/*******************************
A Class to more easily traverse the FILE_NOTIFY_INFORMATION records returned
by ReadDirectoryChangesW().
FILE_NOTIFY_INFORMATION is defined in Winnt.h as:
typedef struct _FILE_NOTIFY_INFORMATION {
DWORD NextEntryOffset;
DWORD Action;
DWORD FileNameLength;
WCHAR FileName[1];
} FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION;
ReadDirectoryChangesW basically puts x amount of these records in a
buffer that you specify.
The FILE_NOTIFY_INFORMATION structure is a 'dynamically sized' structure (size depends on length
of the file name (+ sizeof the DWORDs in the struct))
Because each structure contains an offset to the 'next' file notification
it is basically a singly linked list. This class treats the structure in that way.
Sample Usage:
BYTE Read_Buffer[ 4096 ];
...
ReadDirectoryChangesW(...Read_Buffer, 4096,...);
...
CFileNotifyInformation notify_info( Read_Buffer, 4096);
do{
switch( notify_info.GetAction() )
{
case xx:
notify_info.GetFileName();
}
while( notify_info.GetNextNotifyInformation() );
********************************/
{
public:
CFileNotifyInformation( BYTE * lpFileNotifyInfoBuffer, DWORD dwBuffSize)
: m_pBuffer( lpFileNotifyInfoBuffer ),
m_dwBufferSize( dwBuffSize )
{
ASSERT( lpFileNotifyInfoBuffer && dwBuffSize );
m_pCurrentRecord = (PFILE_NOTIFY_INFORMATION) m_pBuffer;
}
BOOL GetNextNotifyInformation();
BOOL CopyCurrentRecordToBeginningOfBuffer(OUT DWORD & ref_dwSizeOfCurrentRecord);
DWORD GetAction() const;//gets the type of file change notifiation
CString GetFileName()const;//gets the file name from the FILE_NOTIFY_INFORMATION record
CString GetFileNameWithPath(const CString & strRootPath) const;//same as GetFileName() only it prefixes the strRootPath into the file name
protected:
BYTE * m_pBuffer;//<--all of the FILE_NOTIFY_INFORMATION records 'live' in the buffer this points to...
DWORD m_dwBufferSize;
PFILE_NOTIFY_INFORMATION m_pCurrentRecord;//this points to the current FILE_NOTIFY_INFORMATION record in m_pBuffer
};
BOOL CFileNotifyInformation::GetNextNotifyInformation()
/***************
Sets the m_pCurrentRecord to the next FILE_NOTIFY_INFORMATION record.
Even if this return FALSE, (unless m_pCurrentRecord is NULL)
m_pCurrentRecord will still point to the last record in the buffer.
****************/
{
if( m_pCurrentRecord
&& m_pCurrentRecord->NextEntryOffset != 0UL)//is there another record after this one?
{
//set the current record to point to the 'next' record
PFILE_NOTIFY_INFORMATION pOld = m_pCurrentRecord;
m_pCurrentRecord = (PFILE_NOTIFY_INFORMATION) ((LPBYTE)m_pCurrentRecord + m_pCurrentRecord->NextEntryOffset);
ASSERT( (DWORD)((BYTE*)m_pCurrentRecord - m_pBuffer) < m_dwBufferSize);//make sure we haven't gone too far
if( (DWORD)((BYTE*)m_pCurrentRecord - m_pBuffer) > m_dwBufferSize )
{
//we've gone too far.... this data is hosed.
//
// This sometimes happens if the watched directory becomes deleted... remove the FILE_SHARE_DELETE flag when using CreateFile() to get the handle to the directory...
m_pCurrentRecord = pOld;
}
return (BOOL)(m_pCurrentRecord != pOld);
}
return FALSE;
}
BOOL CFileNotifyInformation::CopyCurrentRecordToBeginningOfBuffer(OUT DWORD & ref_dwSizeOfCurrentRecord)
/*****************************************
Copies the FILE_NOTIFY_INFORMATION record to the beginning of the buffer
specified in the constructor.
The size of the current record is returned in DWORD & dwSizeOfCurrentRecord.
*****************************************/
{
ASSERT( m_pBuffer && m_pCurrentRecord );
if( !m_pCurrentRecord ) return FALSE;
BOOL bRetVal = TRUE;
//determine the size of the current record.
ref_dwSizeOfCurrentRecord = sizeof( FILE_NOTIFY_INFORMATION );
//subtract out sizeof FILE_NOTIFY_INFORMATION::FileName[1]
WCHAR FileName[1];//same as is defined for FILE_NOTIFY_INFORMATION::FileName
UNREFERENCED_PARAMETER(FileName);
ref_dwSizeOfCurrentRecord -= sizeof(FileName);
//and replace it w/ value of FILE_NOTIFY_INFORMATION::FileNameLength
ref_dwSizeOfCurrentRecord += m_pCurrentRecord->FileNameLength;
ASSERT( (DWORD)((LPBYTE)m_pCurrentRecord + ref_dwSizeOfCurrentRecord) <= m_dwBufferSize );
ASSERT( (void*)m_pBuffer != (void*)m_pCurrentRecord );//if this is the case, your buffer is way too small
if( (void*)m_pBuffer != (void*) m_pCurrentRecord )
{//copy the m_pCurrentRecord to the beginning of m_pBuffer
ASSERT( (DWORD)m_pCurrentRecord > (DWORD)m_pBuffer + ref_dwSizeOfCurrentRecord);//will it overlap?
__try{
memcpy(m_pBuffer, m_pCurrentRecord, ref_dwSizeOfCurrentRecord);
bRetVal = TRUE;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
TRACE(_T("EXCEPTION! CFileNotifyInformation::CopyCurrentRecordToBeginningOfBuffer() -- probably because bytes overlapped in a call to memcpy()"));
bRetVal = FALSE;
}
}
//else
//there was only one record in this buffer, and m_pCurrentRecord is already at the beginning of the buffer
return bRetVal;
}
DWORD CFileNotifyInformation::GetAction() const
{
ASSERT( m_pCurrentRecord );
if( m_pCurrentRecord )
return m_pCurrentRecord->Action;
return 0UL;
}
CString CFileNotifyInformation::GetFileName() const
{
//
//BUG FIX:
// File Name's longer than 130 characters are truncated
//
// Thanks Edric @ [email protected] for pointing this out.
if( m_pCurrentRecord )
{
WCHAR wcFileName[ MAX_PATH + 1] = {0};//L"";
memcpy( wcFileName,
m_pCurrentRecord->FileName,
//min( MAX_PATH, m_pCurrentRecord->FileNameLength) <-- buggy line
min( (MAX_PATH * sizeof(WCHAR)), m_pCurrentRecord->FileNameLength));
return CString( wcFileName );
}
return CString();
}
static inline bool HasTrailingBackslash(const CString & str )
{
if( str.GetLength() > 0
&& str[ str.GetLength() - 1 ] == _T('\\') )
return true;
return false;
}
CString CFileNotifyInformation::GetFileNameWithPath(const CString & strRootPath) const
{
CString strFileName( strRootPath );
//if( strFileName.Right(1) != _T("\\") )
if( !HasTrailingBackslash( strRootPath ) )
strFileName += _T("\\");
strFileName += GetFileName();
return strFileName;
}
/////////////////////////////////////////////////////////////////////////////////
class CPrivilegeEnabler
//
// Enables privileges for this process
// first time CDirectoryChangeWatcher::WatchDirectory() is called.
//
// It's a singleton.
//
{
private:
CPrivilegeEnabler();//ctor
public:
~CPrivilegeEnabler(){};
static CPrivilegeEnabler & Instance();
//friend static CPrivilegeEnabler & Instance();
};
CPrivilegeEnabler::CPrivilegeEnabler()
{
LPCTSTR arPrivelegeNames[] = {
SE_BACKUP_NAME, // these two are required for the FILE_FLAG_BACKUP_SEMANTICS flag used in the call to
SE_RESTORE_NAME,// CreateFile() to open the directory handle for ReadDirectoryChangesW
SE_CHANGE_NOTIFY_NAME //just to make sure...it's on by default for all users.
//<others here as needed>
};
for(int i = 0; i < sizeof(arPrivelegeNames) / sizeof(arPrivelegeNames[0]); ++i)
{
if( !EnablePrivilege(arPrivelegeNames[i], TRUE) )
{
TRACE(_T("Unable to enable privilege: %s -- GetLastError(): %d\n"), arPrivelegeNames[i], GetLastError());
TRACE(_T("CDirectoryChangeWatcher notifications may not work as intended due to insufficient access rights/process privileges.\n"));
TRACE(_T("File: %s Line: %d\n"), _T(__FILE__), __LINE__);
}
}
}
CPrivilegeEnabler & CPrivilegeEnabler::Instance()
{
static CPrivilegeEnabler theInstance;//constructs this first time it's called.
return theInstance;
}
//
//
//
///////////////////////////////////////////////////////////
//
//
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CDirectoryChangeHandler::CDirectoryChangeHandler()
: m_nRefCnt( 1 ),
m_pDirChangeWatcher( NULL ),
m_nWatcherRefCnt( 0L )
{
}
CDirectoryChangeHandler::~CDirectoryChangeHandler()
{
UnwatchDirectory();
}
long CDirectoryChangeHandler::AddRef()
{
return InterlockedIncrement(&m_nRefCnt);
}
long CDirectoryChangeHandler::Release()
{
long nRefCnt = -1;
if( (nRefCnt = InterlockedDecrement(&m_nRefCnt)) == 0 )
delete this;
return nRefCnt;
}
long CDirectoryChangeHandler::CurRefCnt()const
{
return m_nRefCnt;
}
BOOL CDirectoryChangeHandler::UnwatchDirectory()
{
CSingleLock lock(&m_csWatcher, TRUE);
ASSERT( lock.IsLocked() );
if( m_pDirChangeWatcher )
return m_pDirChangeWatcher->UnwatchDirectory( this );
return TRUE;
}
long CDirectoryChangeHandler::ReferencesWatcher(CDirectoryChangeWatcher * pDirChangeWatcher)
{
ASSERT( pDirChangeWatcher );
CSingleLock lock(&m_csWatcher, TRUE);
if( m_pDirChangeWatcher
&& m_pDirChangeWatcher != pDirChangeWatcher )
{
TRACE(_T("CDirectoryChangeHandler...is becoming used by a different CDirectoryChangeWatcher!\n"));
TRACE(_T("Directories being handled by this object will now be unwatched.\nThis object is now being used to ")
_T("handle changes to a directory watched by different CDirectoryChangeWatcher object, probably on a different directory"));
if( UnwatchDirectory() )
{
m_pDirChangeWatcher = pDirChangeWatcher;
m_nWatcherRefCnt = 1; //when this reaches 0, set m_pDirChangeWatcher to NULL
return m_nWatcherRefCnt;
}
else
{
ASSERT( FALSE );//shouldn't get here!
}
}
else
{
ASSERT( !m_pDirChangeWatcher || m_pDirChangeWatcher == pDirChangeWatcher );
m_pDirChangeWatcher = pDirChangeWatcher;
if( m_pDirChangeWatcher )
return InterlockedIncrement(&m_nWatcherRefCnt);
}
return m_nWatcherRefCnt;
}
long CDirectoryChangeHandler::ReleaseReferenceToWatcher(CDirectoryChangeWatcher * pDirChangeWatcher)
{
ASSERT( m_pDirChangeWatcher == pDirChangeWatcher );
CSingleLock lock(&m_csWatcher, TRUE);
long nRef;
if( (nRef = InterlockedDecrement(&m_nWatcherRefCnt)) <= 0L )
{
m_pDirChangeWatcher = NULL; //Setting this to NULL so that this->UnwatchDirectory() which is called in the dtor
//won't call m_pDirChangeWatcher->UnwatchDirecotry(this).
//m_pDirChangeWatcher may point to a destructed object depending on how
//these classes are being used.
m_nWatcherRefCnt = 0L;
}
return nRef;
}
//
//
// Default implmentations for CDirectoryChangeHandler's virtual functions.
//
//
void CDirectoryChangeHandler::On_FileAdded(const CString & strFileName)
{
TRACE(_T("The following file was added: %s\n"), strFileName);
if(IsDirectory(strFileName))
OnDirChanged((char*)(LPCSTR)strFileName,'A');
else
OnFileChanged((char*)(LPCSTR)strFileName,'A');
}
void CDirectoryChangeHandler::On_FileRemoved(const CString & strFileName)
{
TRACE(_T("The following file was removed: %s\n"), strFileName);
if(IsDirectory(strFileName))
OnDirChanged((char*)(LPCSTR)strFileName,'R');
else
OnFileChanged((char*)(LPCSTR)strFileName,'R');
}
void CDirectoryChangeHandler::On_FileModified(const CString & strFileName)
{
TRACE(_T("The following file was modified: %s\n"), strFileName);
if(!IsDirectory(strFileName))
OnFileChanged((char*)(LPCSTR)strFileName,'M');
}
void CDirectoryChangeHandler::On_FileNameChanged(const CString & strOldFileName, const CString & strNewFileName)
{
TRACE(_T("The file %s was RENAMED to %s\n"), strOldFileName, strNewFileName);
if(IsDirectory(strOldFileName))
OnDirRenamed((char*)(LPCSTR)strOldFileName,(char*)(LPCSTR)strNewFileName);
else
OnFileRenamed((char*)(LPCSTR)strOldFileName,(char*)(LPCSTR)strNewFileName);
}
void CDirectoryChangeHandler::On_ReadDirectoryChangesError(DWORD dwError, const CString & strDirectoryName)
{
TRACE(_T("WARNING!!!!!\n") );
TRACE(_T("An error has occurred on a watched directory!\n"));
TRACE(_T("This directory has become unwatched! -- %s \n"), strDirectoryName);
TRACE(_T("ReadDirectoryChangesW has failed! %d"), dwError);
ASSERT( FALSE );//you should override this function no matter what. an error will occur someday.
}
void CDirectoryChangeHandler::On_WatchStarted(DWORD dwError, const CString & strDirectoryName)
{
if( dwError == 0 )
TRACE(_T("A watch has begun on the following directory: %s\n"), strDirectoryName);
else
TRACE(_T("A watch failed to start on the following directory: (Error: %d) %s\n"),dwError, strDirectoryName);
}
void CDirectoryChangeHandler::On_WatchStopped(const CString & strDirectoryName)
{
TRACE(_T("The watch on the following directory has stopped: %s\n"), strDirectoryName);
}
bool CDirectoryChangeHandler::On_FilterNotification(DWORD /*dwNotifyAction*/, LPCTSTR /*szFileName*/, LPCTSTR /*szNewFileName*/)
//
// bool On_FilterNotification(DWORD dwNotifyAction, LPCTSTR szFileName, LPCTSTR szNewFileName);
//
// This function gives your class a chance to filter unwanted notifications.
//
// PARAMETERS:
// DWORD dwNotifyAction -- specifies the event to filter
// LPCTSTR szFileName -- specifies the name of the file for the event.
// LPCTSTR szNewFileName -- specifies the new file name of a file that has been renamed.
//
// RETURN VALUE:
// return true from this function, and you will receive the notification.
// return false from this function, and your class will NOT receive the notification.
//
// Valid values of dwNotifyAction:
// FILE_ACTION_ADDED -- On_FileAdded() is about to be called.
// FILE_ACTION_REMOVED -- On_FileRemoved() is about to be called.
// FILE_ACTION_MODIFIED -- On_FileModified() is about to be called.
// FILE_ACTION_RENAMED_OLD_NAME-- On_FileNameChanged() is about to be call.
//
//
// NOTE: When the value of dwNotifyAction is FILE_ACTION_RENAMED_OLD_NAME,
// szFileName will be the old name of the file, and szNewFileName will
// be the new name of the renamed file.
//
// The default implementation always returns true, indicating that all notifications will
// be sent.
//
{
return true;
}
void CDirectoryChangeHandler::SetChangedDirectoryName(const CString & strChangedDirName)
{
m_strChangedDirectoryName = strChangedDirName;
}
////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////
CDirectoryChangeWatcher::CDirectoryChangeWatcher(bool bAppHasGUI /*= true*/, DWORD dwFilterFlags/*=FILTERS_CHECK_FILE_NAME_ONLY*/)
: m_hCompPort( NULL )
,m_hThread( NULL )
,m_dwThreadID( 0UL )
,m_bAppHasGUI( bAppHasGUI )
,m_dwFilterFlags( dwFilterFlags == 0? FILTERS_DEFAULT_BEHAVIOR : dwFilterFlags)
{
//NOTE:
// The bAppHasGUI variable indicates that you have a message pump associated
// with the main thread(or the thread that first calls CDirectoryChangeWatcher::WatchDirectory() ).
// Directory change notifications are dispatched to your main thread.
//
// If your app doesn't have a gui, then pass false. Doing so causes a worker thread
// to be created that implements a message pump where it dispatches/executes the notifications.
// It's ok to pass false even if your app does have a GUI.
// Passing false is required for Console applications, or applications without a message pump.
// Note that notifications are fired in a worker thread.
//
//NOTE:
//
//
}
CDirectoryChangeWatcher::~CDirectoryChangeWatcher()
{
UnwatchAllDirectories();
if( m_hCompPort )
{
CloseHandle( m_hCompPort );
m_hCompPort = NULL;
}
}
DWORD CDirectoryChangeWatcher::SetFilterFlags(DWORD dwFilterFlags)
//
// SetFilterFlags()
//
// sets filter behavior for directories watched AFTER this function has been called.
//
//
//
{
DWORD dwOld = m_dwFilterFlags;
m_dwFilterFlags = dwFilterFlags;
if( m_dwFilterFlags == 0 )
m_dwFilterFlags = FILTERS_DEFAULT_BEHAVIOR;//the default.
return dwOld;
}
BOOL CDirectoryChangeWatcher::IsWatchingDirectory(const CString & strDirName)const
/*********************************************
Determines whether or not a directory is being watched
be carefull that you have the same name path name, including the backslash
as was used in the call to WatchDirectory().
ie:
"C:\\Temp"
is different than
"C:\\Temp\\"
**********************************************/
{
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT( lock.IsLocked() );
int i;
if( GetDirWatchInfo(strDirName, i) )
return TRUE;
return FALSE;
}
int CDirectoryChangeWatcher::NumWatchedDirectories()const
{
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
ASSERT( lock.IsLocked() );
int nCnt(0),max = m_DirectoriesToWatch.GetSize();
for(int i(0); i < max; ++i)
{
if( m_DirectoriesToWatch[i] != NULL )//array may contain NULL elements.
nCnt++;
}
return nCnt;
}
DWORD CDirectoryChangeWatcher::WatchDirectory(const CString & strDirToWatch,
DWORD dwChangesToWatchFor,
CDirectoryChangeHandler * pChangeHandler,
BOOL bWatchSubDirs /*=FALSE*/,
LPCTSTR szIncludeFilter /*=NULL*/,
LPCTSTR szExcludeFilter /*=NULL*/
)
/*************************************************************
FUNCTION: WatchDirectory(const CString & strDirToWatch, --the name of the directory to watch
DWORD dwChangesToWatchFor, --the changes to watch for see dsk docs..for ReadDirectoryChangesW
CDirectoryChangeHandler * pChangeHandler -- handles changes in specified directory
BOOL bWatchSubDirs --specified to watch sub directories of the directory that you want to watch
)
PARAMETERS:
const CString & strDirToWatch -- specifies the path of the directory to watch.
DWORD dwChangesToWatchFor -- specifies flags to be passed to ReadDirectoryChangesW()
CDirectoryChangeHandler * -- ptr to an object which will handle notifications of file changes.
BOOL bWatchSubDirs -- specifies to watch subdirectories.
LPCTSTR szIncludeFilter -- A file pattern string for files that you wish to receive notifications
for. See Remarks.
LPCTSTR szExcludeFilter -- A file pattern string for files that you do not wish to receive notifications for. See Remarks
Starts watching the specified directory(and optionally subdirectories) for the specified changes
When specified changes take place the appropriate CDirectoryChangeHandler::On_Filexxx() function is called.
dwChangesToWatchFor can be a combination of the following flags, and changes map out to the
following functions:
FILE_NOTIFY_CHANGE_FILE_NAME -- CDirectoryChangeHandler::On_FileAdded()
CDirectoryChangeHandler::On_FileNameChanged,
CDirectoryChangeHandler::On_FileRemoved
FILE_NOTIFY_CHANGE_DIR_NAME -- CDirectoryChangeHandler::On_FileNameAdded(),
CDirectoryChangeHandler::On_FileRemoved
FILE_NOTIFY_CHANGE_ATTRIBUTES -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_SIZE -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_LAST_WRITE -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_LAST_ACCESS -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_CREATION -- CDirectoryChangeHandler::On_FileModified
FILE_NOTIFY_CHANGE_SECURITY -- CDirectoryChangeHandler::On_FileModified?
Returns ERROR_SUCCESS if the directory will be watched,
or a windows error code if the directory couldn't be watched.
The error code will most likely be related to a call to CreateFile(), or
from the initial call to ReadDirectoryChangesW(). It's also possible to get an
error code related to being unable to create an io completion port or being unable
to start the worker thread.
This function will fail if the directory to be watched resides on a
computer that is not a Windows NT/2000/XP machine.
You can only have one watch specified at a time for any particular directory.
Calling this function with the same directory name will cause the directory to be
unwatched, and then watched again(w/ the new parameters that have been passed in).
**************************************************************/
{
ASSERT( dwChangesToWatchFor != 0);
if( strDirToWatch.IsEmpty()
|| dwChangesToWatchFor == 0
|| pChangeHandler == NULL )
{
TRACE(_T("ERROR: You've passed invalid parameters to CDirectoryChangeWatcher::WatchDirectory()\n"));
::SetLastError(ERROR_INVALID_PARAMETER);
return ERROR_INVALID_PARAMETER;
}
//double check that it's really a directory
if( !IsDirectory( strDirToWatch ) )
{
TRACE(_T("ERROR: CDirectoryChangeWatcher::WatchDirectory() -- %s is not a directory!\n"), strDirToWatch);
::SetLastError(ERROR_BAD_PATHNAME);
return ERROR_BAD_PATHNAME;
}
//double check that this directory is not already being watched....
//if it is, then unwatch it before restarting it...
if( IsWatchingDirectory( strDirToWatch) )
{
VERIFY(
UnwatchDirectory( strDirToWatch )
);
}
//
//
// Reference this singleton so that privileges for this process are enabled
// so that it has required permissions to use the ReadDirectoryChangesW API, etc.
//
CPrivilegeEnabler::Instance();
//
//open the directory to watch....
HANDLE hDir = CreateFile(strDirToWatch,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE ,//| FILE_SHARE_DELETE, <-- removing FILE_SHARE_DELETE prevents the user or someone else from renaming or deleting the watched directory. This is a good thing to prevent.
NULL, //security attributes
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | //<- the required priviliges for this flag are: SE_BACKUP_NAME and SE_RESTORE_NAME. CPrivilegeEnabler takes care of that.
FILE_FLAG_OVERLAPPED, //OVERLAPPED!
NULL);
if( hDir == INVALID_HANDLE_VALUE )
{
DWORD dwError = GetLastError();
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory() -- Couldn't open directory for monitoring. %d\n"), dwError);
::SetLastError(dwError);//who knows if TRACE will cause GetLastError() to return success...probably won't, but set it manually just for fun.
return dwError;
}
//opened the dir!
CDirWatchInfo * pDirInfo = new CDirWatchInfo( hDir, strDirToWatch, pChangeHandler, dwChangesToWatchFor, bWatchSubDirs, m_bAppHasGUI, szIncludeFilter, szExcludeFilter, m_dwFilterFlags);
if( !pDirInfo )
{
TRACE(_T("WARNING: Couldn't allocate a new CDirWatchInfo() object --- File: %s Line: %d\n"), _T( __FILE__ ), __LINE__);
CloseHandle( hDir );
::SetLastError(ERROR_OUTOFMEMORY);
return ERROR_OUTOFMEMORY;
}
//create a IO completion port/or associate this key with
//the existing IO completion port
m_hCompPort = CreateIoCompletionPort(hDir,
m_hCompPort, //if m_hCompPort is NULL, hDir is associated with a NEW completion port,
//if m_hCompPort is NON-NULL, hDir is associated with the existing completion port that the handle m_hCompPort references
(DWORD)pDirInfo, //the completion 'key'... this ptr is returned from GetQueuedCompletionStatus() when one of the events in the dwChangesToWatchFor filter takes place
0);
if( m_hCompPort == NULL )
{
TRACE(_T("ERROR -- Unable to create I/O Completion port! GetLastError(): %d File: %s Line: %d"), GetLastError(), _T( __FILE__ ), __LINE__ );
DWORD dwError = GetLastError();
pDirInfo->DeleteSelf( NULL );
::SetLastError(dwError);//who knows what the last error will be after i call pDirInfo->DeleteSelf(), so set it just to make sure
return dwError;
}
else
{//completion port created/directory associated w/ it successfully
//if the thread isn't running start it....
//when the thread starts, it will call ReadDirectoryChangesW and wait
//for changes to take place
if( m_hThread == NULL )
{
//start the thread
CWinThread * pThread = AfxBeginThread(MonitorDirectoryChanges, this);
if( !pThread )
{//couldn't create the thread!
TRACE(_T("CDirectoryChangeWatcher::WatchDirectory()-- AfxBeginThread failed!\n"));
pDirInfo->DeleteSelf( NULL );
return (GetLastError() == ERROR_SUCCESS)? ERROR_MAX_THRDS_REACHED : GetLastError();
}
else
{
m_hThread = pThread->m_hThread;
m_dwThreadID = pThread->m_nThreadID;
pThread->m_bAutoDelete = TRUE;//pThread is deleted when thread ends....it's TRUE by default(for CWinThread ptrs returned by AfxBeginThread(threadproc, void*)), but just makin sure.
}
}
if( m_hThread != NULL )
{//thread is running,
//signal the thread to issue the initial call to
//ReadDirectoryChangesW()
DWORD dwStarted = pDirInfo->StartMonitor( m_hCompPort );
if( dwStarted != ERROR_SUCCESS )
{//there was a problem!
TRACE(_T("Unable to watch directory: %s -- GetLastError(): %d\n"), dwStarted);
pDirInfo->DeleteSelf( NULL );
::SetLastError(dwStarted);//I think this'll set the Err object in a VB app.....
return dwStarted;
}
else
{//ReadDirectoryChangesW was successfull!
//add the directory info to the first empty slot in the array
//associate the pChangeHandler with this object
pChangeHandler->ReferencesWatcher( this );//reference is removed when directory is unwatched.
//CDirWatchInfo::DeleteSelf() must now be called w/ this CDirectoryChangeWatcher pointer becuse
//of a reference count
//save the CDirWatchInfo* so I'll be able to use it later.
VERIFY( AddToWatchInfo( pDirInfo ) );
SetLastError(dwStarted);
return dwStarted;
}
}
else
{
ASSERT(FALSE);//control path shouldn't get here
::SetLastError(ERROR_MAX_THRDS_REACHED);
return ERROR_MAX_THRDS_REACHED;
}
}
ASSERT( FALSE );//shouldn't get here.
}
BOOL CDirectoryChangeWatcher::UnwatchAllDirectories()
{
//unwatch all of the watched directories
//delete all of the CDirWatchInfo objects,
//kill off the worker thread
if( m_hThread != NULL )
{
ASSERT( m_hCompPort != NULL );
CSingleLock lock( &m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
CDirWatchInfo * pDirInfo;
//Unwatch each of the watched directories
//and delete the CDirWatchInfo associated w/ that directory...
int max = m_DirectoriesToWatch.GetSize();
for(int i = 0; i < max; ++i)
{
if( (pDirInfo = m_DirectoriesToWatch[i]) != NULL )
{
VERIFY( pDirInfo->UnwatchDirectory( m_hCompPort ) );
m_DirectoriesToWatch.SetAt(i, NULL) ;
pDirInfo->DeleteSelf(this);
}
}
m_DirectoriesToWatch.RemoveAll();
//kill off the thread
PostQueuedCompletionStatus(m_hCompPort, 0, 0, NULL);//The thread will catch this and exit the thread
//wait for it to exit
WaitForSingleObject(m_hThread, INFINITE);
//CloseHandle( m_hThread );//Since thread was started w/ AfxBeginThread() this handle is closed automatically, closing it again will raise an exception
m_hThread = NULL;
m_dwThreadID = 0UL;
//close the completion port...
CloseHandle( m_hCompPort );
m_hCompPort = NULL;
return TRUE;
}
else
{
#ifdef _DEBUG
//make sure that there aren't any
//CDirWatchInfo objects laying around... they should have all been destroyed
//and removed from the array m_DirectoriesToWatch
if( m_DirectoriesToWatch.GetSize() > 0 )
{
for(int i = 0; i < m_DirectoriesToWatch.GetSize(); ++i)
{
ASSERT( m_DirectoriesToWatch[i] == NULL );
}
}
#endif
}
return FALSE;
}
BOOL CDirectoryChangeWatcher::UnwatchDirectory(const CString & strDirToStopWatching)
/***************************************************************
FUNCTION: UnwatchDirectory(const CString & strDirToStopWatching -- if this directory is being watched, the watch is stopped
****************************************************************/
{
BOOL bRetVal = FALSE;
if( m_hCompPort != NULL )//The io completion port must be open
{
ASSERT( !strDirToStopWatching.IsEmpty() );
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nIdx = -1;
CDirWatchInfo * pDirInfo = GetDirWatchInfo(strDirToStopWatching, nIdx);
if( pDirInfo != NULL
&& nIdx != -1 )
{
//stop watching this directory
VERIFY( pDirInfo->UnwatchDirectory( m_hCompPort ) );
//cleanup the object used to watch the directory
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
bRetVal = TRUE;
}
}
return bRetVal;
}
BOOL CDirectoryChangeWatcher::UnwatchDirectory(CDirectoryChangeHandler * pChangeHandler)
/************************************
This function is called from the dtor of CDirectoryChangeHandler automatically,
but may also be called by a programmer because it's public...
A single CDirectoryChangeHandler may be used for any number of watched directories.
Unwatch any directories that may be using this
CDirectoryChangeHandler * pChangeHandler to handle changes to a watched directory...
The CDirWatchInfo::m_pChangeHandler member of objects in the m_DirectoriesToWatch
array will == pChangeHandler if that handler is being used to handle changes to a directory....
************************************/
{
ASSERT( pChangeHandler );
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nUnwatched = 0;
int nIdx = -1;
CDirWatchInfo * pDirInfo;
//
// go through and unwatch any directory that is
// that is using this pChangeHandler as it's file change notification handler.
//
while( (pDirInfo = GetDirWatchInfo( pChangeHandler, nIdx )) != NULL )
{
VERIFY( pDirInfo->UnwatchDirectory( m_hCompPort ) );
nUnwatched++;
m_DirectoriesToWatch.SetAt(nIdx, NULL);
pDirInfo->DeleteSelf(this);
}
return (BOOL)(nUnwatched != 0);
}
BOOL CDirectoryChangeWatcher::UnwatchDirectoryBecauseOfError(CDirWatchInfo * pWatchInfo)
//
// Called in the worker thread in the case that ReadDirectoryChangesW() fails
// during normal operation. One way to force this to happen is to watch a folder
// using a UNC path and changing that computer's IP address.
//
{
ASSERT( pWatchInfo );
ASSERT( m_dwThreadID == GetCurrentThreadId() );//this should be called from the worker thread only.
BOOL bRetVal = FALSE;
if( pWatchInfo )
{
CSingleLock lock(&m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
int nIdx = -1;
if( GetDirWatchInfo(pWatchInfo, nIdx) == pWatchInfo )
{
// we are actually watching this....
//
// Remove this CDirWatchInfo object from the list of watched directories.
//
m_DirectoriesToWatch.SetAt(nIdx, NULL);//mark the space as free for the next watch...
//
// and delete it...
//
pWatchInfo->DeleteSelf(this);
}
}
return bRetVal;
}
int CDirectoryChangeWatcher::AddToWatchInfo(CDirectoryChangeWatcher::CDirWatchInfo * pWatchInfo)
//
//
// To add the CDirWatchInfo * to an array.
// The array is used to keep track of which directories
// are being watched.
//
// Add the ptr to the first non-null slot in the array.
{
CSingleLock lock( &m_csDirWatchInfo, TRUE);
ASSERT( lock.IsLocked() );
//first try to add it to the first empty slot in m_DirectoriesToWatch
int max = m_DirectoriesToWatch.GetSize();
int i =0;
for(; i < max; ++i)
{
if( m_DirectoriesToWatch[i] == NULL )
{
m_DirectoriesToWatch[i] = pWatchInfo;
break;
}
}
if( i == max )
{
// there where no empty slots, add it to the end of the array
try{
i = m_DirectoriesToWatch.Add( pWatchInfo );
}
catch(CMemoryException * e){
e->ReportError();
e->Delete();//??? delete this? I thought CMemoryException objects where pre allocated in mfc? -- sample code in msdn does, so will i
i = -1;
}
}
return (BOOL)(i != -1);
}
//
// functions for retrieving the directory watch info based on different parameters
//
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(const CString & strDirName, int & ref_nIdx)const
{
if( strDirName.IsEmpty() )// can't be watching a directory if it's you don't pass in the name of it...
return FALSE; //
CSingleLock lock(const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p = NULL;
for(int i = 0; i < max; ++i )
{
if( (p = m_DirectoriesToWatch[i]) != NULL
&& p->m_strDirName.CompareNoCase( strDirName ) == 0 )
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirectoryChangeWatcher::CDirWatchInfo * pWatchInfo, int & ref_nIdx)const
{
ASSERT( pWatchInfo != NULL );
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int i(0), max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p;
for(; i < max; ++i)
{
if( (p = m_DirectoriesToWatch[i]) != NULL
&& p == pWatchInfo )
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
CDirectoryChangeWatcher::CDirWatchInfo * CDirectoryChangeWatcher::GetDirWatchInfo(CDirectoryChangeHandler * pChangeHandler, int & ref_nIdx)const
{
ASSERT( pChangeHandler != NULL );
CSingleLock lock( const_cast<CCriticalSection*>(&m_csDirWatchInfo), TRUE);
int i(0),max = m_DirectoriesToWatch.GetSize();
CDirWatchInfo * p;
for( ; i < max; ++i)
{
if( (p = m_DirectoriesToWatch[i]) != NULL
&& p->GetRealChangeHandler() == pChangeHandler )
{
ref_nIdx = i;
return p;
}
}
return NULL;//NOT FOUND
}
long CDirectoryChangeWatcher::ReleaseReferenceToWatcher(CDirectoryChangeHandler * pChangeHandler)
{
ASSERT( pChangeHandler );
return pChangeHandler->ReleaseReferenceToWatcher(this);
}
CDirectoryChangeWatcher::CDirWatchInfo::CDirWatchInfo(HANDLE hDir,
const CString & strDirectoryName,
CDirectoryChangeHandler * pChangeHandler,
DWORD dwChangeFilter,
BOOL bWatchSubDir,
bool bAppHasGUI,
LPCTSTR szIncludeFilter,
LPCTSTR szExcludeFilter,
DWORD dwFilterFlags)
: m_pChangeHandler( NULL ),
m_hDir(hDir),
m_dwChangeFilter( dwChangeFilter ),
m_bWatchSubDir( bWatchSubDir ),
m_strDirName( strDirectoryName ),
m_dwBufLength(0),
m_dwReadDirError(ERROR_SUCCESS),
m_StartStopEvent(FALSE, TRUE), //NOT SIGNALLED, MANUAL RESET
m_RunningState( RUNNING_STATE_NOT_SET )
{
ASSERT( hDir != INVALID_HANDLE_VALUE
&& !strDirectoryName.IsEmpty() );
//
// This object 'decorates' the pChangeHandler passed in
// so that notifications fire in the context a thread other than
// CDirectoryChangeWatcher::MonitorDirectoryChanges()
//
// Supports the include and exclude filters
//
//
m_pChangeHandler = new CDelayedDirectoryChangeHandler( pChangeHandler, bAppHasGUI, szIncludeFilter, szExcludeFilter, dwFilterFlags );
if( m_pChangeHandler )
m_pChangeHandler->SetPartialPathOffset( m_strDirName );//to support FILTERS_CHECK_PARTIAL_PATH..this won't change for the duration of the watch, so set it once... HERE!
ASSERT( m_pChangeHandler );
ASSERT( GetChangeHandler() );
ASSERT( GetRealChangeHandler() );
if( GetRealChangeHandler() )
GetRealChangeHandler()->AddRef();
memset(&m_Overlapped, 0, sizeof(m_Overlapped));
//memset(m_Buffer, 0, sizeof(m_Buffer));
}
CDirectoryChangeWatcher::CDirWatchInfo::~CDirWatchInfo()
{
if( GetChangeHandler() )
{//If this call to CDirectoryChangeHandler::Release() causes m_pChangeHandler to delete itself,
//the dtor for CDirectoryChangeHandler will call CDirectoryChangeWatcher::UnwatchDirectory( CDirectoryChangeHandler * ),
//which will make try to delete this object again.
//if m_pChangeHandler is NULL, it won't try to delete this object again...
CDirectoryChangeHandler * pTmp = SetRealDirectoryChangeHandler( NULL );
if( pTmp )
pTmp->Release();
else{
ASSERT( FALSE );
}
}
CloseDirectoryHandle();
delete m_pChangeHandler;
m_pChangeHandler = NULL;
}
void CDirectoryChangeWatcher::CDirWatchInfo::DeleteSelf(CDirectoryChangeWatcher * pWatcher)
//
// There's a reason for this function!
//
// the dtor is private to enforce that it is used.
//
//
// pWatcher can be NULL only if CDirecotryChangeHandler::ReferencesWatcher() has NOT been called.
// ie: in certain sections of WatchDirectory() it's ok to pass this w/ NULL, but no where else.
//
{
//ASSERT( pWatcher != NULL );
ASSERT( GetRealChangeHandler() );
if( pWatcher )
{
//
//
// Before this object is deleted, the CDirectoryChangeHandler object
// needs to release it's reference count to the CDirectoryChangeWatcher object.
// I might forget to do this since I getting rid of CDirWatchInfo objects
// in more than one place...hence the reason for this function.
//
pWatcher->ReleaseReferenceToWatcher( GetRealChangeHandler() );
}
delete this;
}
CDelayedDirectoryChangeHandler* CDirectoryChangeWatcher::CDirWatchInfo::GetChangeHandler() const
{
return m_pChangeHandler;
}
CDirectoryChangeHandler * CDirectoryChangeWatcher::CDirWatchInfo::GetRealChangeHandler() const
//
// The 'real' change handler is the CDirectoryChangeHandler object
// passed to CDirectoryChangeWatcher::WatchDirectory() -- this is the object
// that really handles the changes.
//
{
ASSERT( m_pChangeHandler );
return m_pChangeHandler->GetRealChangeHandler();
}
CDirectoryChangeHandler * CDirectoryChangeWatcher::CDirWatchInfo::SetRealDirectoryChangeHandler(CDirectoryChangeHandler * pChangeHandler)
//
// Allows you to switch out, at run time, which object really handles the change notifications.
//
{
CDirectoryChangeHandler * pOld = GetRealChangeHandler();
m_pChangeHandler->GetRealChangeHandler() = pChangeHandler;
return pOld;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::CloseDirectoryHandle()
//
// Closes the directory handle that was opened in CDirectoryChangeWatcher::WatchDirecotry()
//
//
{
BOOL b = TRUE;
if( m_hDir != INVALID_HANDLE_VALUE )
{
b = CloseHandle(m_hDir);
m_hDir = INVALID_HANDLE_VALUE;
}
return b;
}
DWORD CDirectoryChangeWatcher::CDirWatchInfo::StartMonitor(HANDLE hCompPort)
/*********************************************
Sets the running state of the object to perform the initial call to ReadDirectoryChangesW()
, wakes up the thread waiting on GetQueuedCompletionStatus()
and waits for an event to be set before returning....
The return value is either ERROR_SUCCESS if ReadDirectoryChangesW is successfull,
or is the value of GetLastError() for when ReadDirectoryChangesW() failed.
**********************************************/
{
ASSERT( hCompPort );
//Guard the properties of this object
VERIFY( LockProperties() );
m_RunningState = RUNNING_STATE_START_MONITORING;//set the state member to indicate that the object is to START monitoring the specified directory
PostQueuedCompletionStatus(hCompPort, sizeof(this), (DWORD)this, &m_Overlapped);//make the thread waiting on GetQueuedCompletionStatus() wake up
VERIFY( UnlockProperties() );//unlock this object so that the thread can get at them...
//wait for signal that the initial call
//to ReadDirectoryChanges has been made
DWORD dwWait = 0;
do{
dwWait = WaitForSingleObject(m_StartStopEvent, 10 * 1000);
if( dwWait != WAIT_OBJECT_0 )
{
//
// shouldn't ever see this one....but just in case you do, notify me of the problem [email protected].
//
TRACE(_T("WARNING! Possible lockup detected. FILE: %s Line: %d\n"), _T( __FILE__ ), __LINE__);
}
} while( dwWait != WAIT_OBJECT_0 );
ASSERT( dwWait == WAIT_OBJECT_0 );
m_StartStopEvent.ResetEvent();
return m_dwReadDirError;//This value is set in the worker thread when it first calls ReadDirectoryChangesW().
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::UnwatchDirectory(HANDLE hCompPort)
/*******************************************
Sets the running state of the object to stop monitoring a directory,
Causes the worker thread to wake up and to stop monitoring the dierctory
********************************************/
{
ASSERT( hCompPort );
//
// Signal that the worker thread is to stop watching the directory
//
if( SignalShutdown(hCompPort) )
{
//and wait for the thread to signal that it has shutdown
return WaitForShutdown();
}
return FALSE;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::SignalShutdown( HANDLE hCompPort )
//added to fix a bug -- this will be called normally by UnwatchDirectory(HANDLE)
// and abnormally by the worker thread in the case that ReadDirectoryChangesW fails -- see code.
//
// Signals the worker thread(via the I/O completion port) that it is to stop watching the
// directory for this object, and then returns.
//
{
BOOL bRetVal = FALSE;
ASSERT( hCompPort );
ASSERT( m_hDir != INVALID_HANDLE_VALUE );
//Lock the properties so that they aren't modified by another thread
VERIFY( LockProperties() ); //unlikey to fail...
//set the state member to indicate that the object is to stop monitoring the
//directory that this CDirWatchInfo is responsible for...
m_RunningState = CDirectoryChangeWatcher::CDirWatchInfo::RUNNING_STATE_STOP;
//put this object in the I/O completion port... GetQueuedCompletionStatus() will return it inside the worker thread.
bRetVal = PostQueuedCompletionStatus(hCompPort, sizeof(CDirWatchInfo*), (DWORD)this, &m_Overlapped);
if( !bRetVal )
{
TRACE(_T("PostQueuedCompletionStatus() failed! GetLastError(): %d\n"), GetLastError());
}
VERIFY( UnlockProperties() );
return bRetVal;
}
BOOL CDirectoryChangeWatcher::CDirWatchInfo::WaitForShutdown()
//
// This is to be called some time after SignalShutdown().
//
//
{
ASSERT_VALID(&m_StartStopEvent);
//Wait for the Worker thread to indicate that the watch has been stopped
DWORD dwWait;
bool bWMQuitReceived = false;
do{
dwWait = MsgWaitForMultipleObjects(1, &m_StartStopEvent.m_hObject, FALSE, 5000, QS_ALLINPUT);//wait five seconds
switch( dwWait )
{
case WAIT_OBJECT_0:
//handle became signalled!
break;
case WAIT_OBJECT_0 + 1:
{
//This thread awoke due to sent/posted message
//process the message Q
//
// There is a message in this thread's queue, so
// MsgWaitForMultipleObjects returned.
// Process those messages, and wait again.
MSG msg;
while( PeekMessage(&msg, NULL, 0,0, PM_REMOVE ) )
{
if( msg.message != WM_QUIT)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
/****
This appears to be causing quite a lot of pain, to quote Mustafa.
//it's the WM_QUIT message, put it back in the Q and
// exit this function
PostMessage(msg.hwnd, msg.message, msg.wParam, msg.lParam );
bWMQuitReceived = true;
****/
break;
}
}
}break;
case WAIT_TIMEOUT:
{
TRACE(_T("WARNING: Possible Deadlock detected! ThreadID: %d File: %s Line: %d\n"), GetCurrentThreadId(), _T(__FILE__), __LINE__);
}break;
}//end switch(dwWait)
}while( dwWait != WAIT_OBJECT_0 && !bWMQuitReceived );
ASSERT( dwWait == WAIT_OBJECT_0 || bWMQuitReceived);
m_StartStopEvent.ResetEvent();
return (BOOL) (dwWait == WAIT_OBJECT_0 || bWMQuitReceived);
}
UINT CDirectoryChangeWatcher::MonitorDirectoryChanges(LPVOID lpvThis)
/********************************************
The worker thread function which monitors directory changes....
********************************************/
{
DWORD numBytes;
CDirWatchInfo * pdi;
LPOVERLAPPED lpOverlapped;
CDirectoryChangeWatcher * pThis = reinterpret_cast<CDirectoryChangeWatcher*>(lpvThis);
ASSERT( pThis );
pThis->On_ThreadInitialize();
do
{
// Retrieve the directory info for this directory
// through the io port's completion key
if( !GetQueuedCompletionStatus( pThis->m_hCompPort,
&numBytes,
(LPDWORD) &pdi,//<-- completion Key
&lpOverlapped,
INFINITE) )
{//The io completion request failed...
//probably because the handle to the directory that
//was used in a call to ReadDirectoryChangesW has been closed.
//
// calling pdi->CloseDirectoryHandle() will cause GetQueuedCompletionStatus() to return false.
//
//
if( !pdi
|| ( pdi && AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo)))
&& pdi->m_hDir != INVALID_HANDLE_VALUE //the directory handle is still open! (we expect this when after we close the directory handle )
)
{
#ifdef _DEBUG
TRACE(_T("GetQueuedCompletionStatus() returned FALSE\nGetLastError(): %d Completion Key: %p lpOverlapped: %p\n"), GetLastError(), pdi, lpOverlapped);
MessageBeep( static_cast<UINT>(-1) );
#endif
}
}
if ( pdi )//pdi will be null if I call PostQueuedCompletionStatus(m_hCompPort, 0,0,NULL);
{
//
// The following check to AfxIsValidAddress() should go off in the case
// that I have deleted this CDirWatchInfo object, but it was still in
// "in the Queue" of the i/o completion port from a previous overlapped operation.
//
ASSERT( AfxIsValidAddress(pdi,
sizeof(CDirectoryChangeWatcher::CDirWatchInfo)) );
/***********************************
The CDirWatchInfo::m_RunningState is pretty much the only member
of CDirWatchInfo that can be modified from the other thread.
The functions StartMonitor() and UnwatchDirecotry() are the functions that
can modify that variable.
So that I'm sure that I'm getting the right value,
I'm using a critical section to guard against another thread modyfying it when I want
to read it...
************************************/
bool bObjectShouldBeOk = true;
try{
VERIFY( pdi->LockProperties() );//don't give the main thread a chance to change this object
}
catch(...){
//any sort of exception here indicates I've
//got a hosed object.
TRACE(_T("CDirectoryChangeWatcher::MonitorDirectoryChanges() -- pdi->LockProperties() raised an exception!\n"));
bObjectShouldBeOk = false;
}
if( bObjectShouldBeOk )
{
//while we're working with this object...
CDirWatchInfo::eRunningState Run_State = pdi->m_RunningState ;
VERIFY( pdi->UnlockProperties() );//let another thread back at the properties...
/***********************************
Unlock it so that there isn't a DEADLOCK if
somebody tries to call a function which will
cause CDirWatchInfo::UnwatchDirectory() to be called
from within the context of this thread (eg: a function called because of
the handler for one of the CDirectoryChangeHandler::On_Filexxx() functions)
************************************/
ASSERT( pdi->GetChangeHandler() );
switch( Run_State )
{
case CDirWatchInfo::RUNNING_STATE_START_MONITORING:
{
//Issue the initial call to ReadDirectoryChangesW()
if( !ReadDirectoryChangesW( pdi->m_hDir,
pdi->m_Buffer,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE,
pdi->m_bWatchSubDir,
pdi->m_dwChangeFilter,
&pdi->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pdi->m_Overlapped,
NULL) )//no completion routine!
{
pdi->m_dwReadDirError = GetLastError();
if( pdi->GetChangeHandler() )
pdi->GetChangeHandler()->On_WatchStarted(pdi->m_dwReadDirError, pdi->m_strDirName);
}
else
{//read directory changes was successful!
//allow it to run normally
pdi->m_RunningState = CDirWatchInfo::RUNNING_STATE_NORMAL;
pdi->m_dwReadDirError = ERROR_SUCCESS;
if( pdi->GetChangeHandler() )
pdi->GetChangeHandler()->On_WatchStarted(ERROR_SUCCESS, pdi->m_strDirName );
}
pdi->m_StartStopEvent.SetEvent();//signall that the ReadDirectoryChangesW has been called
//check CDirWatchInfo::m_dwReadDirError to see whether or not ReadDirectoryChangesW succeeded...
//
// note that pdi->m_dwReadDirError is the value returned by WatchDirectory()
//
}break;
case CDirWatchInfo::RUNNING_STATE_STOP:
{
//We want to shut down the monitoring of the directory
//that pdi is managing...
if( pdi->m_hDir != INVALID_HANDLE_VALUE )
{
//Since I've previously called ReadDirectoryChangesW() asynchronously, I am waiting
//for it to return via GetQueuedCompletionStatus(). When I close the
//handle that ReadDirectoryChangesW() is waiting on, it will
//cause GetQueuedCompletionStatus() to return again with this pdi object....
// Close the handle, and then wait for the call to GetQueuedCompletionStatus()
//to return again by breaking out of the switch, and letting GetQueuedCompletionStatus()
//get called again
pdi->CloseDirectoryHandle();
pdi->m_RunningState = CDirWatchInfo::RUNNING_STATE_STOP_STEP2;//back up step...GetQueuedCompletionStatus() will still need to return from the last time that ReadDirectoryChangesW() was called.....
//
// The watch has been stopped, tell the client about it
// if( pdi->GetChangeHandler() )
pdi->GetChangeHandler()->On_WatchStopped( pdi->m_strDirName );
}
else
{
//either we weren't watching this direcotry in the first place,
//or we've already stopped monitoring it....
pdi->m_StartStopEvent.SetEvent();//set the event that ReadDirectoryChangesW has returned and no further calls to it will be made...
}
}break;
case CDirWatchInfo::RUNNING_STATE_STOP_STEP2:
{
//GetQueuedCompletionStatus() has returned from the last
//time that ReadDirectoryChangesW was called...
//Using CloseHandle() on the directory handle used by
//ReadDirectoryChangesW will cause it to return via GetQueuedCompletionStatus()....
if( pdi->m_hDir == INVALID_HANDLE_VALUE )
pdi->m_StartStopEvent.SetEvent();//signal that no further calls to ReadDirectoryChangesW will be made
//and this pdi can be deleted
else
{//for some reason, the handle is still open..
pdi->CloseDirectoryHandle();
//wait for GetQueuedCompletionStatus() to return this pdi object again
}
}break;
case CDirWatchInfo::RUNNING_STATE_NORMAL:
{
if( pdi->GetChangeHandler() )
pdi->GetChangeHandler()->SetChangedDirectoryName( pdi->m_strDirName );
DWORD dwReadBuffer_Offset = 0UL;
//process the FILE_NOTIFY_INFORMATION records:
CFileNotifyInformation notify_info( (LPBYTE)pdi->m_Buffer, READ_DIR_CHANGE_BUFFER_SIZE);
pThis->ProcessChangeNotifications(notify_info, pdi, dwReadBuffer_Offset);
// Changes have been processed,
// Reissue the watch command
//
if( !ReadDirectoryChangesW( pdi->m_hDir,
pdi->m_Buffer + dwReadBuffer_Offset,//<--FILE_NOTIFY_INFORMATION records are put into this buffer
READ_DIR_CHANGE_BUFFER_SIZE - dwReadBuffer_Offset,
pdi->m_bWatchSubDir,
pdi->m_dwChangeFilter,
&pdi->m_dwBufLength,//this var not set when using asynchronous mechanisms...
&pdi->m_Overlapped,
NULL) )//no completion routine!
{
//
// NOTE:
// In this case the thread will not wake up for
// this pdi object because it is no longer associated w/
// the I/O completion port...there will be no more outstanding calls to ReadDirectoryChangesW
// so I have to skip the normal shutdown routines(normal being what happens when CDirectoryChangeWatcher::UnwatchDirectory() is called.
// and close this up, & cause it to be freed.
//
TRACE(_T("WARNING: ReadDirectoryChangesW has failed during normal operations...failed on directory: %s\n"), pdi->m_strDirName);
ASSERT( pThis );
//
// To help insure that this has been unwatched by the time
// the main thread processes the On_ReadDirectoryChangesError() notification
// bump the thread priority up temporarily. The reason this works is because the notification
// is really posted to another thread's message queue,...by setting this thread's priority
// to highest, this thread will get to shutdown the watch by the time the other thread has a chance
// to handle it. *note* not technically guaranteed 100% to be the case, but in practice it'll work.
int nOldThreadPriority = GetThreadPriority( GetCurrentThread() );
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
//
// Notify the client object....(a CDirectoryChangeHandler derived class)
//
try{
pdi->m_dwReadDirError = GetLastError();
pdi->GetChangeHandler()->On_ReadDirectoryChangesError( pdi->m_dwReadDirError, pdi->m_strDirName );
//Do the shutdown
pThis->UnwatchDirectoryBecauseOfError( pdi );
//pdi = NULL; <-- DO NOT set this to NULL, it will cause this worker thread to exit.
//pdi is INVALID at this point!!
}
catch(...)
{
//just in case of exception, this thread will be set back to
//normal priority.
}
//
// Set the thread priority back to normal.
//
SetThreadPriority(GetCurrentThread(), nOldThreadPriority);
}
else
{//success, continue as normal
pdi->m_dwReadDirError = ERROR_SUCCESS;
}
}break;
default:
TRACE(_T("MonitorDirectoryChanges() -- how did I get here?\n"));
break;//how did I get here?
}//end switch( pdi->m_RunningState )
}//end if( bObjectShouldBeOk )
}//end if( pdi )
} while( pdi );
pThis->On_ThreadExit();
return 0; //thread is ending
}
void CDirectoryChangeWatcher::ProcessChangeNotifications(IN CFileNotifyInformation & notify_info,
IN CDirectoryChangeWatcher::CDirWatchInfo * pdi,
OUT DWORD & ref_dwReadBuffer_Offset//used in case ...see case for FILE_ACTION_RENAMED_OLD_NAME
)
/////////////////////////////////////////////////////////////
//
// Processes the change notifications and dispatches the handling of the
// notifications to the CDirectoryChangeHandler object passed to WatchDirectory()
//
/////////////////////////////////////////////////////////////
{
//
// Sanity check...
// this function should only be called by the worker thread.
//
ASSERT( m_dwThreadID == GetCurrentThreadId() );
// Validate parameters...
//
ASSERT( pdi );
ASSERT( AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo) ) );
if( !pdi || !AfxIsValidAddress(pdi, sizeof(CDirectoryChangeWatcher::CDirWatchInfo)) )
{
TRACE(_T("Invalid arguments to CDirectoryChangeWatcher::ProcessChangeNotifications() -- pdi is invalid!\n"));
TRACE(_T("File: %s Line: %d"), _T( __FILE__ ), __LINE__ );
return;
}
DWORD dwLastAction = 0;
ref_dwReadBuffer_Offset = 0UL;
CDirectoryChangeHandler * pChangeHandler = pdi->GetChangeHandler();
//CDelayedDirectoryChangeHandler * pChangeHandler = pdi->GetChangeHandler();
ASSERT( pChangeHandler );
ASSERT( AfxIsValidAddress(pChangeHandler, sizeof(CDirectoryChangeHandler)) );
//ASSERT( AfxIsValidAddress(pChangeHandler, sizeof(CDelayedDirectoryChangeHandler)) );
if( !pChangeHandler )
{
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() Unable to continue, pdi->GetChangeHandler() returned NULL!\n"));
TRACE(_T("File: %s Line: %d\n"), _T( __FILE__ ), __LINE__ );
return;
}
//
// go through and process the notifications contained in the
// CFileChangeNotification object( CFileChangeNotification is a wrapper for the FILE_NOTIFY_INFORMATION structure
// returned by ReadDirectoryChangesW)
//
do
{
//The FileName member of the FILE_NOTIFY_INFORMATION
//structure contains the NAME of the file RELATIVE to the
//directory that is being watched...
//ie, if watching C:\Temp and the file C:\Temp\MyFile.txt is changed,
//the file name will be "MyFile.txt"
//If watching C:\Temp, AND you're also watching subdirectories
//and the file C:\Temp\OtherFolder\MyOtherFile.txt is modified,
//the file name will be "OtherFolder\MyOtherFile.txt
//The CDirectoryChangeHandler::On_Filexxx() functions will receive the name of the file
//which includes the full path to the directory being watched
//
// See what the change was
//
switch( notify_info.GetAction() )
{
case FILE_ACTION_ADDED: // a file was added!
pChangeHandler->On_FileAdded( notify_info.GetFileNameWithPath( pdi->m_strDirName ) ); break;
case FILE_ACTION_REMOVED: //a file was removed
pChangeHandler->On_FileRemoved( notify_info.GetFileNameWithPath( pdi->m_strDirName ) ); break;
case FILE_ACTION_MODIFIED:
//a file was changed
//pdi->m_pChangeHandler->On_FileModified( strLastFileName ); break;
pChangeHandler->On_FileModified( notify_info.GetFileNameWithPath( pdi->m_strDirName ) ); break;
case FILE_ACTION_RENAMED_OLD_NAME:
{//a file name has changed, and this is the OLD name
//This record is followed by another one w/
//the action set to FILE_ACTION_RENAMED_NEW_NAME (contains the new name of the file
CString strOldFileName = notify_info.GetFileNameWithPath( pdi->m_strDirName );
if( notify_info.GetNextNotifyInformation() )
{//there is another PFILE_NOTIFY_INFORMATION record following the one we're working on now...
//it will be the record for the FILE_ACTION_RENAMED_NEW_NAME record
ASSERT( notify_info.GetAction() == FILE_ACTION_RENAMED_NEW_NAME );//making sure that the next record after the OLD_NAME record is the NEW_NAME record
//get the new file name
CString strNewFileName = notify_info.GetFileNameWithPath( pdi->m_strDirName );
pChangeHandler->On_FileNameChanged( strOldFileName, strNewFileName);
}
else
{
//this OLD_NAME was the last record returned by ReadDirectoryChangesW
//I will have to call ReadDirectoryChangesW again so that I will get
//the record for FILE_ACTION_RENAMED_NEW_NAME
//Adjust an offset so that when I call ReadDirectoryChangesW again,
//the FILE_NOTIFY_INFORMATION will be placed after
//the record that we are currently working on.
/***************
Let's say that 200 files all had their names changed at about the same time
There will be 400 FILE_NOTIFY_INFORMATION records (one for OLD_NAME and one for NEW_NAME for EACH file which had it's name changed)
that ReadDirectoryChangesW will have to report to
me. There might not be enough room in the buffer
and the last record that we DID get was an OLD_NAME record,
I will need to call ReadDirectoryChangesW again so that I will get the NEW_NAME
record. This way I'll always have to strOldFileName and strNewFileName to pass
to CDirectoryChangeHandler::On_FileRenamed().
After ReadDirecotryChangesW has filled out our buffer with
FILE_NOTIFY_INFORMATION records,
our read buffer would look something like this:
End Of Buffer
|
\-/
|_________________________________________________________________________
| |
|file1 OLD name record|file1 NEW name record|...|fileX+1 OLD_name record| |(the record we want would be here, but we've ran out of room, so we adjust an offset and call ReadDirecotryChangesW again to get it)
|_________________________________________________________________________|
Since the record I need is still waiting to be returned to me,
and I need the current 'OLD_NAME' record,
I'm copying the current FILE_NOTIFY_INFORMATION record
to the beginning of the buffer used by ReadDirectoryChangesW()
and I adjust the offset into the read buffer so the the NEW_NAME record
will be placed into the buffer after the OLD_NAME record now at the beginning of the buffer.
Before we call ReadDirecotryChangesW again,
modify the buffer to contain the current OLD_NAME record...
|_______________________________________________________
| |
|fileX old name record(saved)|<this is now garbage>.....|
|_______________________________________________________|
/-\
|
Offset for Read
Re-issue the watch command to get the rest of the records...
ReadDirectoryChangesW(..., pBuffer + (an Offset),
After GetQueuedCompletionStatus() returns,
our buffer will look like this:
|__________________________________________________________________________________________________________
| |
|fileX old name record(saved)|fileX new name record(the record we've been waiting for)| <other records>... |
|__________________________________________________________________________________________________________|
Then I'll be able to know that a file name was changed
and I will have the OLD and the NEW name of the file to pass to CDirectoryChangeHandler::On_FileNameChanged
****************/
//NOTE that this case has never happened to me in my testing
//so I can only hope that the code works correctly.
//It would be a good idea to set a breakpoint on this line of code:
VERIFY( notify_info.CopyCurrentRecordToBeginningOfBuffer( ref_dwReadBuffer_Offset ) );
}
break;
}
case FILE_ACTION_RENAMED_NEW_NAME:
{
//This should have been handled in FILE_ACTION_RENAMED_OLD_NAME
ASSERT( dwLastAction == FILE_ACTION_RENAMED_OLD_NAME );
ASSERT( FALSE );//this shouldn't get here
}
default:
TRACE(_T("CDirectoryChangeWatcher::ProcessChangeNotifications() -- unknown FILE_ACTION_ value! : %d\n"), notify_info.GetAction() );
break;//unknown action
}
dwLastAction = notify_info.GetAction();
} while( notify_info.GetNextNotifyInformation() );
} | [
"ttylikl@1da26e48-1f5d-11de-b56b-c9554f25afe1"
]
| [
[
[
1,
2043
]
]
]
|
5030dd853e4079c09a4b5d8bd7f1eb6949b5f4e6 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/WayFinder/symbian-r6/IAPObserver_old.h | 3fdac5e2c97a0e1d71eb7012fea33ac4e6d36313 | [
"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 | 2,141 | h | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "arch.h"
/**
* Interface for objects using the IAPSearcher class.
*/
class IAPObserver
{
public:
virtual void SetIAP(TInt aIAP) = 0;
virtual int32 GetIAP() = 0;
virtual void ReportProgressIAP(TInt aVal, TInt aMax, HBufC* aName) = 0;
virtual TBool ShowIAPMenu() = 0;
virtual void CheckIAPChosen(TInt ch) = 0;
virtual void ReportFailureIAP(TInt error, TBool temporary = EFalse) = 0;
virtual void SendIAP(int32 aIAPid, TBool isReal = EFalse, TBool aShow = ETrue) = 0;
virtual void SendSyncParameters() = 0;
virtual void SendNop() = 0;
};
| [
"[email protected]"
]
| [
[
[
1,
33
]
]
]
|
cd5c6fd58f76f0dd72a38de5ee9208dbf36b9ee1 | 7dd2dbb15df45024e4c3f555da6d9ca6fc2c4d8b | /maelstrom/maelstromproject.h | bc6e933bf2fd9b381964b43cb5a0298d495844d7 | []
| no_license | wangscript/maelstrom-editor | c9f761e1f9e5f4e64d7e37834a7a63e04f57ae31 | 5bfab31bf444f44b9f8209f4deaed8715c305426 | refs/heads/master | 2021-01-10T01:37:00.619456 | 2011-11-21T23:17:08 | 2011-11-21T23:17:08 | 50,160,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | h | #ifndef MAELSTROMPROJECT_H
#define MAELSTROMPROJECT_H
#include <QObject>
#include <QString>
class MaelstromProject : public QObject
{
Q_OBJECT
private:
QString name;
QString projectPath;
QString assetDbPath;
QString databaseDriver;
bool synched;
MaelstromProject();
public:
static MaelstromProject *create(const QString& projectDirectory, const QString& projectName, bool createDirectory, const QString assetDbPath);
static MaelstromProject *open(const QString&);
QString getAssetDbPath() const;
QString getDatabaseDriver() const;
bool getInSync() const;
QString getName() const;
QString getProjectPath() const;
void resetAssetDatabase();
void setAssetDbPath(const QString);
void setDatabaseDriver(const QString);
void setName(const QString);
void setProjectPath(const QString);
void save();
void addAssetPackage(const QString name);
void deleteAssetPackage(const int id);
~MaelstromProject();
signals:
void nameChanged();
void projectPathChanged();
};
QDataStream &operator<<(QDataStream &out, const MaelstromProject &project);
QDataStream &operator>>(QDataStream &in, MaelstromProject &project);
#endif // MAELSTROMPROJECT_H
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
5c018d3f0df0b534b4b974ab7430edbbaffc2cc4 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Graphics/WmlVersion.cpp | 34a8126dd7774667e4ea8c3604b1fe1bc9bc68b0 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,523 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlVersion.h"
using namespace Wml;
const int Version::MAJOR = 1;
const int Version::MINOR = 7;
const char Version::CURRENT[] = "Magic3D Version 1.07";
const int Version::LENGTH = 21;
//----------------------------------------------------------------------------
Version::Version (int iMajorVersion, int iMinorVersion)
{
m_iMajor = iMajorVersion;
m_iMinor = iMinorVersion;
}
//----------------------------------------------------------------------------
Version::Version (const char* acString)
{
m_iMajor = -1;
m_iMinor = -1;
if ( acString
&& strlen(acString) >= LENGTH-1
&& acString[LENGTH-1] == 0
&& strncmp(acString,CURRENT,LENGTH-5) == 0 )
{
int iArgs = sscanf(acString+LENGTH-5,"%1d.%2d",&m_iMajor,&m_iMinor);
if ( iArgs != 2 )
{
m_iMajor = -1;
m_iMinor = -1;
}
}
}
//----------------------------------------------------------------------------
bool Version::IsValid () const
{
return 0 < m_iMajor && m_iMajor < 10
&& 0 <= m_iMinor && m_iMinor < 100;
}
//----------------------------------------------------------------------------
int Version::GetMajor () const
{
return m_iMajor;
}
//----------------------------------------------------------------------------
int Version::GetMinor () const
{
return m_iMinor;
}
//----------------------------------------------------------------------------
int Version::GetCombined () const
{
return 100*m_iMajor + m_iMinor;
}
//----------------------------------------------------------------------------
bool Version::operator== (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() == rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
bool Version::operator!= (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() != rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
bool Version::operator< (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() < rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
bool Version::operator<= (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() <= rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
bool Version::operator> (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() > rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
bool Version::operator>= (const Version& rkVersion) const
{
assert( IsValid() && rkVersion.IsValid() );
return GetCombined() >= rkVersion.GetCombined();
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
103
]
]
]
|
eca3ad4a23067ba6542414e66af45d78dc298a57 | ffadac985f616b08e142033e7acb1aa240f82fd4 | /src/ProjectionMatrix.h | 24d2fb1303e513c44282625374da167c393dd719 | []
| no_license | jfischoff/obido_math | 9184aea6e975db4164b6e973d0e4fd5b21d024ba | 5b892bf5c0615912613ef9719cb4e9944ab2c444 | refs/heads/master | 2016-09-06T06:18:49.577093 | 2011-10-11T14:53:37 | 2011-10-11T14:53:37 | 2,555,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | h | #ifndef PROJECTIONMATRIX_H
#define PROJECTIONMATRIX_H
#include "Matrix4x4.h"
#include "Vector3.h"
#include <iostream>
using namespace std;
class ProjectionMatrix
{
public:
static void* Constructor();
ProjectionMatrix();
ProjectionMatrix(const Vector3& near, const Vector3& far);
ProjectionMatrix(const ProjectionMatrix& other);
ProjectionMatrix& operator=(const ProjectionMatrix& other);
void copy(const ProjectionMatrix& other);
void setFrustrum(const Vector3& near, const Vector3& far);
void setFrustrum(Float nearX, Float nearY, Float nearZ,
Float farX, Float farY, Float farZ);
Matrix4x4 getMatrix() const;
Float getNearZ() const;
Vector3 getNear();
Vector3 getFar();
private:
Vector3 m_Near;
Vector3 m_Far;
};
#endif //PROJECTIONMATRIX_H
| [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
83fe7661e3108545f4e074968d4987215e2be6c2 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/shortlinksrv/Bluetooth/T_BTSdpAPI/inc/T_DataSdpAttrValueString.h | f3a68b7a5b5416a8a9916ce1da40ab952b0bb5a7 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,436 | h | /*
* Copyright (c) 2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#if (!defined __T_DATA_SDP_ATTR_VALUE_STRING_H__ )
#define __T_DATA_SDP_ATTR_VALUE_STRING_H__
// User Includes
#include "T_DataSdpAttrValue.h"
/**
* Test Active Notification class
*
*/
class CT_DataSdpAttrValueString : public CT_DataSdpAttrValue
{
public:
/**
* Two phase constructor
*/
static CT_DataSdpAttrValueString* NewL();
/**
* Public destructor
*/
~CT_DataSdpAttrValueString();
/**
* Process a command read from the ini file
*
* @param aCommand The command to process
* @param aSection The section in the ini containing data for the command
* @param aAsyncErrorIndex Command index for async calls to return errors to
*
* @return ETrue if the command is processed
*
* @leave System wide error
*/
virtual TBool DoCommandL(const TTEFFunction& aCommand, const TTEFSectionName& aSection, const TInt aAsyncErrorIndex);
/**
* Return a pointer to the object that the data wraps
*
* @return pointer to the object that the data wraps
*/
virtual TAny* GetObject() { return iAttrValString; }
/**
* Set the object that the data wraps
*
* @param aObject object that the wrapper is testing
*
*/
virtual void SetObjectL(TAny* aAny);
/**
* The object will no longer be owned by this
*
* @leave KErrNotSupported if the the function is not supported
*/
virtual void DisownObjectL();
inline virtual TCleanupOperation CleanupOperation();
protected:
/**
* Protected constructor. First phase construction
*/
CT_DataSdpAttrValueString();
/**
* Second phase construction
*/
void ConstructL();
virtual CSdpAttrValue* GetSdpAttrValue() const;
private:
/**
* Helper methods
*/
void DestroyData();
inline void DoCmdNewStringL(const TDesC& aSection);
inline void DoCmdDestructor();
static void CleanupOperation(TAny* aAny);
private:
CSdpAttrValueString* iAttrValString;
};
#endif /* __T_DATA_SDP_ATTR_VALUE_STRING_H__ */
| [
"none@none"
]
| [
[
[
1,
106
]
]
]
|
5545b327db53fa2dda6aac248efd4961fcd002ab | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-16/pcbnew/plothpgl.cpp | 27e7385dc04c323111f5aebd8c7fc36da26876b5 | []
| 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 | UTF-8 | C++ | false | false | 26,295 | cpp | /*******************************/
/**** Routine de trace HPGL ****/
/*******************************/
#include "fctsys.h"
#include "common.h"
#include "plot_common.h"
#include "pcbnew.h"
#include "pcbplot.h"
#include "trigo.h"
#include "protos.h"
/* Variables locales : */
static int pen_rayon; /* Rayon de la plume en unites pcb */
static int pen_diam; /* Diametre de la plume en unites pcb */
static int pen_recouvrement; /* recouvrement en remplissage en unites pcb */
/* Routines Locales */
/*****************************************************************************/
void WinEDA_BasePcbFrame::Genere_HPGL(const wxString & FullFileName, int Layer)
/*****************************************************************************/
{
int modetrace;
wxSize SheetSize;
wxSize BoardSize;
wxPoint BoardCenter;
double scale_x, scale_y;
int marge = 0 * U_PCB; // Extra margin (set to 0)
bool Center = FALSE;
modetrace = Plot_Mode;
/* Calcul des echelles de conversion */
scale_x = Scale_X * SCALE_HPGL;
scale_y = Scale_Y * SCALE_HPGL;
// calcul en unites internes des dimensions de la feuille ( connues en 1/1000 pouce )
SheetSize.x = m_CurrentScreen->m_CurrentSheet->m_Size.x * U_PCB;
SheetSize.y = m_CurrentScreen->m_CurrentSheet->m_Size.y * U_PCB;
g_PlotOffset.x = 0 ;
g_PlotOffset.y = (int)(SheetSize.y * scale_y) ;
// Compute pen_dim (from g_HPGL_Pen_Diam in mils) in pcb units,
// with plot scale (if Scale is 2, pen diametre is always g_HPGL_Pen_Diam
// so apparent pen diam is real pen diam / Scale
pen_diam = (int) round((g_HPGL_Pen_Diam * 10.0) / Scale_X); // Assume Scale_X # Scale_Y
pen_rayon = pen_diam / 2;
nb_plot_erreur = 0 ;
// compute pen_recouvrement (from g_HPGL_Pen_Recouvrement in mils)
// with plot scale
if(g_HPGL_Pen_Recouvrement < 0 ) g_HPGL_Pen_Recouvrement = 0 ;
if(g_HPGL_Pen_Recouvrement >= g_HPGL_Pen_Diam )
g_HPGL_Pen_Recouvrement = g_HPGL_Pen_Diam - 1 ;
pen_recouvrement = (int) round(g_HPGL_Pen_Recouvrement * 10.0/Scale_X);
dest = wxFopen(FullFileName, wxT("wt"));
if (dest == NULL)
{
wxString msg = _("Unable to create ") + FullFileName;
DisplayError(this, msg);
return ;
}
Affiche_1_Parametre(this, 0,_("File"),FullFileName,CYAN) ;
PrintHeaderHPGL(dest, g_HPGL_Pen_Speed,g_HPGL_Pen_Num);
if ( Plot_Sheet_Ref && (g_PlotScaleOpt == 1) )
{
int tmp = g_PlotOrient; g_PlotOrient = 0;
InitPlotParametresHPGL(g_PlotOffset, scale_x, scale_y, g_PlotOrient);
PlotWorkSheet( PLOT_FORMAT_HPGL, m_CurrentScreen);
g_PlotOrient = tmp;
}
/* calcul des dimensions et centre du PCB */
m_Pcb->ComputeBoundaryBox();
BoardSize = m_Pcb->m_BoundaryBox.GetSize();
BoardCenter = m_Pcb->m_BoundaryBox.Centre();
if( g_PlotScaleOpt == 0 ) // Optimum scale
{
float Xscale, Yscale;
Xscale = (float) (SheetSize.x - ( 2 * marge)) / BoardSize.x;
Yscale = (float) (SheetSize.y - ( 2 * marge)) / BoardSize.y;
scale_x = scale_y = min( Xscale, Yscale) * SCALE_HPGL;
}
BoardCenter.x = (int)(BoardCenter.x * scale_x);
BoardCenter.y = (int)(BoardCenter.y * scale_y);
if( g_PlotScaleOpt != 1 ) Center = TRUE; // Echelle != 1
/* Calcul du cadrage */
marge = (int)(marge * SCALE_HPGL);
if ( Center )
g_PlotOffset.x = (int)(- SheetSize.x/2 * SCALE_HPGL) +
BoardCenter.x + marge;
switch ( g_PlotOrient)
{
default :
if ( Center )
{
g_PlotOffset.y = (int)(SheetSize.y/2 * SCALE_HPGL) +
BoardCenter.y + marge;
}
break ;
case PLOT_MIROIR :
if ( Center )
g_PlotOffset.y = (int)(- SheetSize.y/2 * SCALE_HPGL) + BoardCenter.y;
else g_PlotOffset.y = (int)((- SheetSize.y +
m_Pcb->m_BoundaryBox.GetBottom() + m_Pcb->m_BoundaryBox.GetY()) * SCALE_HPGL);
break ;
}
InitPlotParametresHPGL(g_PlotOffset, scale_x, scale_y, g_PlotOrient);
switch( Layer )
{
case CUIVRE_N :
case LAYER_N_2 :
case LAYER_N_3 :
case LAYER_N_4 :
case LAYER_N_5 :
case LAYER_N_6 :
case LAYER_N_7 :
case LAYER_N_8 :
case LAYER_N_9 :
case LAYER_N_10 :
case LAYER_N_11:
case LAYER_N_12:
case LAYER_N_13 :
case LAYER_N_14 :
case LAYER_N_15 :
case CMP_N : Plot_Layer_HPGL(dest,g_TabOneLayerMask[Layer], 0, 1, modetrace);
break;
case SILKSCREEN_N_CU :
case SILKSCREEN_N_CMP :
Plot_Serigraphie(PLOT_FORMAT_HPGL,dest, g_TabOneLayerMask[Layer]);
break;
case SOLDERMASK_N_CU :
case SOLDERMASK_N_CMP : /* Trace du vernis epargne */
{
int tracevia;
if (g_DrawViaOnMaskLayer) tracevia = 1;
else tracevia = 0;
Plot_Layer_HPGL(dest,g_TabOneLayerMask[Layer],
g_DesignSettings.m_MaskMargin, tracevia, modetrace);
}
break;
case SOLDERPASTE_N_CU :
case SOLDERPASTE_N_CMP : /* Trace du masque de pate de soudure */
Plot_Layer_HPGL(dest,g_TabOneLayerMask[Layer], 0, 0, modetrace);
break;
default : /* Trace des autres couches (dessin, adhesives,eco,comment) */
Plot_Serigraphie(PLOT_FORMAT_HPGL,dest, g_TabOneLayerMask[Layer]);
break;
}
/* fin */
CloseFileHPGL(dest) ;
}
/*********************************************************************/
void WinEDA_BasePcbFrame::Plot_Layer_HPGL(FILE * File,int masque_layer,
int garde, int tracevia, int modetrace)
/*********************************************************************/
/* Trace en format HPGL. d'une couche cuivre ou masque
1 unite HPGL = 0.98 mils ( 1 mil = 1.02041 unite HPGL ) .
*/
{
wxSize size;
wxPoint start, end;
MODULE * Module;
D_PAD * PtPad;
TRACK * pts ;
EDA_BaseStruct * PtStruct;
wxString msg;
masque_layer |= EDGE_LAYER; /* Les elements de la couche EDGE sont tj traces */
/* trace des elements type Drawings Pcb : */
PtStruct = m_Pcb->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext )
{
switch( PtStruct->m_StructType )
{
case TYPEDRAWSEGMENT:
PlotDrawSegment( (DRAWSEGMENT*) PtStruct, PLOT_FORMAT_HPGL,
masque_layer);
break;
case TYPETEXTE:
PlotTextePcb((TEXTE_PCB*) PtStruct,PLOT_FORMAT_HPGL,
masque_layer);
break;
case TYPECOTATION:
PlotCotation((COTATION*) PtStruct, PLOT_FORMAT_HPGL,
masque_layer);
break;
case TYPEMIRE:
PlotMirePcb((MIREPCB*) PtStruct, PLOT_FORMAT_HPGL,
masque_layer);
break;
case TYPEMARQUEUR:
break;
default:
DisplayError(this, wxT("Type Draw non gere"));
break;
}
}
/* Trace des Elements des modules autres que pads */
nb_items = 0 ;
Affiche_1_Parametre(this, 48, wxT("DrawMod"),wxEmptyString,GREEN) ;
Module = m_Pcb->m_Modules;
for( ; Module != NULL ;Module = (MODULE *)Module->Pnext )
{
PtStruct = Module->m_Drawings;
for( ; PtStruct != NULL; PtStruct = PtStruct->Pnext )
{
switch( PtStruct->m_StructType )
{
case TYPEEDGEMODULE:
if( masque_layer &
g_TabOneLayerMask[((EDGE_MODULE*)PtStruct)->m_Layer] )
Plot_1_EdgeModule(PLOT_FORMAT_HPGL, (EDGE_MODULE*) PtStruct);
break;
default: break;
}
}
}
/* Trace des Elements des modules : Pastilles */
nb_items = 0 ;
Affiche_1_Parametre(this, 48, wxT("Pads "), wxEmptyString,GREEN) ;
Module = m_Pcb->m_Modules;
for( ; Module != NULL ; Module = (MODULE*) Module->Pnext)
{
PtPad = (D_PAD*) Module->m_Pads;
for ( ; PtPad != NULL ;PtPad = (D_PAD*)PtPad->Pnext )
{
wxPoint shape_pos;
if( (PtPad->m_Masque_Layer & masque_layer) == 0)
continue ;
shape_pos = PtPad->ReturnShapePos();
start = shape_pos;
size = PtPad->m_Size;
size.x += garde*2; size.y += garde*2;
nb_items++ ;
switch (PtPad->m_PadShape & 0x7F)
{
case CIRCLE :
trace_1_pastille_RONDE_HPGL(start,size.x,modetrace) ;
break ;
case OVALE :
{
trace_1_pastille_OVALE_HPGL(start,size, PtPad->m_Orient,modetrace) ;
break ;
}
case TRAPEZE :
{
wxSize delta;
delta = PtPad->m_DeltaSize;
trace_1_pad_TRAPEZE_HPGL(start,size,delta,
PtPad->m_Orient, modetrace) ;
break ;
}
case RECT :
default:
PlotRectangularPad_HPGL(start,size,
PtPad->m_Orient,modetrace) ;
break ;
}
msg.Printf( wxT("%d"),nb_items) ;
Affiche_1_Parametre(this, 48, wxT("Pads"), msg,GREEN) ;
}
}
/* trace des VIAS : */
if(tracevia)
{
TRACK * pts ;
nb_items = 0 ;
Affiche_1_Parametre(this, 56, wxT("Vias"), wxEmptyString, RED) ;
for(pts = m_Pcb->m_Track ;pts != NULL; pts = (TRACK*)pts->Pnext )
{
if( pts->m_StructType != TYPEVIA ) continue;
SEGVIA * Via = (SEGVIA *) pts;
/* vias not plotted if not on selected layer, but if layer
== SOLDERMASK_LAYER_CU or SOLDERMASK_LAYER_CMP, vias are drawn ,
if they are on a external copper layer
*/
int via_mask_layer = Via->ReturnMaskLayer();
if ( (via_mask_layer & CUIVRE_LAYER ) ) via_mask_layer |= SOLDERMASK_LAYER_CU;
if ( (via_mask_layer & CMP_LAYER ) ) via_mask_layer |= SOLDERMASK_LAYER_CMP;
if( (via_mask_layer & masque_layer) == 0 ) continue;
start = Via->m_Start;
size.x = Via->m_Width + (garde*2);
trace_1_pastille_RONDE_HPGL(start, size.x, modetrace) ;
nb_items++ ; msg.Printf( wxT("%d"), nb_items) ;
Affiche_1_Parametre(this, 56, wxT("Vias"), msg,RED) ;
}
fputs("PU;\n",dest) ;
}
/* trace des segments pistes */
nb_items = 0 ;
Affiche_1_Parametre(this, 64, wxT("Tracks "),wxEmptyString,YELLOW) ;
for(pts = m_Pcb->m_Track ;pts != NULL; pts = (TRACK*)pts->Pnext )
{
if ( pts->m_StructType == TYPEVIA ) continue ;
if( (g_TabOneLayerMask[pts->m_Layer] & masque_layer) == 0 ) continue;
size.x = size.y = pts->m_Width;
start = pts->m_Start;
end = pts->m_End;
if ( size.x > pen_diam )/* c.a.d si largeur piste > diam plume */
trace_1_pastille_RONDE_HPGL(start, size.x, modetrace) ;
/* Trace d'un segment de piste */
trace_1_segment_HPGL(start.x,start.y,end.x,end.y,size.x) ;
/* Complement de Trace en mode Remplissage */
if( (Plot_Mode == FILLED) && (pen_diam <= size.x ) )
{
while( (size.x -= (int)((pen_rayon - pen_recouvrement)*2) ) > 0 )
{
trace_1_segment_HPGL(start.x,start.y,end.x,end.y,
max(size.x,pen_diam) ) ;
}
}
if ( size.x > pen_diam)
trace_1_pastille_RONDE_HPGL(end, size.x, modetrace) ;
nb_items++ ; msg.Printf( wxT("%d"),nb_items) ;
Affiche_1_Parametre(this, 64,wxEmptyString, msg,YELLOW) ;
}
/* trace des segments pistes et zones */
nb_items = 0 ;
Affiche_1_Parametre(this, 64, wxT("Zones "), wxEmptyString,YELLOW) ;
for(pts = m_Pcb->m_Zone ;pts != NULL; pts = (TRACK*)pts->Pnext )
{
if( g_TabOneLayerMask[pts->m_Layer] & masque_layer)
{
size.x = size.y = pts->m_Width;
start = pts->m_Start;
end = pts->m_End;
if ( size.x > pen_diam )/* c.a.d si largeur piste > diam plume */
trace_1_pastille_RONDE_HPGL(start, size.x,modetrace) ;
/* Trace d'un segment de piste */
trace_1_segment_HPGL(start.x,start.y,end.x,end.y,size.x) ;
/* Complement de Trace en mode Remplissage */
if( (Plot_Mode == FILLED) && (pen_diam <= size.x ) )
{
while( (size.x -= (int)((pen_rayon - pen_recouvrement)*2) ) > 0 )
{
trace_1_segment_HPGL(start.x,start.y,end.x,end.y,
max(size.x,pen_diam)) ;
}
}
if ( size.x > pen_diam)
trace_1_pastille_RONDE_HPGL(end, size.x, modetrace) ;
nb_items++ ; msg.Printf( wxT("%d"),nb_items) ;
Affiche_1_Parametre(this, 64,wxEmptyString, msg,YELLOW) ;
}
}
}
/************************************************************************************/
void trace_1_pastille_OVALE_HPGL(wxPoint pos, wxSize size, int orient, int modetrace)
/************************************************************************************/
/* Trace 1 pastille OVALE en position pos_X,Y , de dim size.x, size.y */
{
int rayon, deltaxy , cx, cy;
int trace_orient = orient;
/* la pastille est ramenee a une pastille ovale avec size.y > size.x
( ovale vertical en orientation 0 ) */
if(size.x > size.y )
{
EXCHG(size.x,size.y); trace_orient += 900;
if ( orient >= 3600 ) trace_orient -= 3600;
}
deltaxy = size.y - size.x; /* = distance entre centres de l'ovale */
rayon = size.x / 2;
if ( modetrace == FILLED )
{
PlotRectangularPad_HPGL(pos, wxSize(size.x,deltaxy),
orient,modetrace) ;
cx = 0; cy = deltaxy/2;
RotatePoint(&cx, &cy, trace_orient);
trace_1_pastille_RONDE_HPGL(wxPoint(cx + pos.x, cy + pos.y), size.x, modetrace) ;
Plume_HPGL('U') ;
cx = 0; cy = -deltaxy/2;
RotatePoint(&cx, &cy, trace_orient);
trace_1_pastille_RONDE_HPGL(wxPoint(cx + pos.x, cy + pos.y), size.x, modetrace) ;
}
else /* Trace en mode FILAIRE */
{
cx = -rayon; cy = -deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
Move_Plume_HPGL( wxPoint(cx + pos.x, cy + pos.y), 'U');
cx = -rayon; cy = deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
Move_Plume_HPGL( wxPoint(cx + pos.x, cy + pos.y), 'D');
cx = rayon; cy = - deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
Move_Plume_HPGL( wxPoint(cx + pos.x, cy + pos.y), 'U');
cx = rayon; cy = deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
Move_Plume_HPGL( wxPoint(cx + pos.x, cy + pos.y), 'D');
Plume_HPGL('U');
cx = 0; cy = - deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
PlotArc(PLOT_FORMAT_HPGL, wxPoint(cx + pos.x, cy + pos.y),
trace_orient, trace_orient + 1800,
size.x / 2, pen_diam);
cx = 0; cy = deltaxy / 2;
RotatePoint(&cx, &cy, trace_orient);
PlotArc(PLOT_FORMAT_HPGL, wxPoint(cx + pos.x, cy + pos.y),
trace_orient + 1800, trace_orient,
size.x / 2, pen_diam);
}
Plume_HPGL('U') ;
}
/**************************************************************************/
void trace_1_pastille_RONDE_HPGL(wxPoint pos, int diametre, int modetrace)
/**************************************************************************/
/* Trace 1 pastille RONDE (via,pad rond) en position pos */
{
int rayon, delta;
UserToDeviceCoordinate(pos);
delta = pen_diam - pen_recouvrement;
rayon = diametre / 2 ;
if(modetrace != FILAIRE)
{
rayon = (diametre - pen_diam ) /2 ;
}
if(rayon < 0 )
{
rayon = 0 ; nb_plot_erreur++ ; Affiche_erreur(nb_plot_erreur) ;
}
wxSize rsize(rayon, rayon);
UserToDeviceSize( rsize );
Plume_HPGL('U');
sprintf(cbuf,"PA %d,%d;CI %d;\n", pos.x, pos.y, rsize.x);
fputs(cbuf,dest) ;
if(modetrace == FILLED ) /* Trace en mode Remplissage */
{
if(delta > 0 )
{
while ( (rayon -= delta ) >= 0 )
{
rsize.x = rsize.y = rayon;
UserToDeviceSize( rsize );
sprintf(cbuf,"PA %d,%d; CI %d;\n", pos.x, pos.y, rsize.x);
fputs(cbuf,dest) ;
}
}
}
Plume_HPGL('U'); return ;
}
/***************************************************************/
void PlotRectangularPad_HPGL(wxPoint padpos, wxSize padsize,
int orient,int modetrace)
/****************************************************************/
/*
Trace 1 pad rectangulaire vertical ou horizontal ( Pad rectangulaire )
donne par son centre et ses dimensions X et Y
Units are user units
*/
{
wxSize size;
int delta;
int ox, oy, fx, fy;
size.x = padsize.x / 2; size.y = padsize.y / 2 ;
if(modetrace != FILAIRE)
{
size.x = (padsize.x - (int)pen_diam) / 2 ;
size.y = (padsize.y - (int)pen_diam) / 2 ;
}
if ( (size.x < 0 ) || (size.y < 0) )
{
nb_plot_erreur++ ; Affiche_erreur(nb_plot_erreur) ;
}
if ( size.x < 0 ) size.x = 0 ; if ( size.y < 0 ) size.y = 0 ;
/* Si une des dimensions est nulle, le trace se reduit a 1 trait */
if(size.x == 0 )
{
ox = padpos.x; oy = padpos.y-size.y;
RotatePoint(&ox,&oy,padpos.x,padpos.y,orient);
fx = padpos.x; fy = padpos.y+size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(ox, oy), 'U');
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
Plume_HPGL('U'); return ;
}
if(size.y == 0 )
{
ox = padpos.x - size.x; oy = padpos.y;
RotatePoint(&ox,&oy,padpos.x,padpos.y,orient);
fx = padpos.x + size.x; fy = padpos.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(ox, oy), 'U');
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
Plume_HPGL('U') ; return ;
}
ox = padpos.x - size.x; oy = padpos.y - size.y;
RotatePoint(&ox,&oy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(ox, oy), 'U');
fx = padpos.x - size.x; fy = padpos.y + size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
fx = padpos.x + size.x; fy = padpos.y + size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
fx = padpos.x + size.x; fy = padpos.y - size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
Move_Plume_HPGL( wxPoint(ox, oy), 'D');
if(modetrace != FILLED )
{
Plume_HPGL('U'); return ;
}
/* Trace en mode Remplissage */
delta = (int)(pen_diam - pen_recouvrement) ;
if(delta > 0 )
while( (size.x > 0) && (size.y > 0) )
{
size.x -= delta; size.y -= delta ;
if ( size.x < 0 ) size.x = 0 ; if ( size.y < 0 ) size.y = 0 ;
ox = padpos.x - size.x; oy = padpos.y - size.y;
RotatePoint(&ox,&oy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(ox, oy), 'D');
fx = padpos.x - size.x; fy = padpos.y + size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
fx = padpos.x + size.x; fy = padpos.y + size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
fx = padpos.x + size.x; fy = padpos.y - size.y;
RotatePoint(&fx,&fy,padpos.x,padpos.y,orient);
Move_Plume_HPGL( wxPoint(fx, fy), 'D');
Move_Plume_HPGL( wxPoint(ox, oy), 'D');
}
Plume_HPGL('U');
}
/********************************************************************/
void trace_1_pad_TRAPEZE_HPGL(wxPoint padpos, wxSize size,wxSize delta,
int orient,int modetrace)
/********************************************************************/
/*
Trace 1 pad trapezoidal donne par :
son centre padpos.x,padpos.y
ses dimensions dimX et dimY
les variations deltaX et deltaY
son orientation orient et 0.1 degres
le mode de trace (FILLED, SKETCH, FILAIRE)
Le trace n'est fait que pour un trapeze, c.a.d que deltaX ou deltaY
= 0.
les notation des sommets sont ( vis a vis de la table tracante )
0 ------------- 3
. .
. .
. .
1 --- 2
*/
{
int ii , jj;
wxPoint polygone[4]; /* coord des sommets / centre du pad */
wxPoint coord[4]; /* coord reelles des sommets du trapeze a tracer */
float fangle; /* angle d'inclinaison des cotes du trapeze */
int rayon; /* rayon de la plume */
int moveX, moveY; /* variation de position plume selon axe X et Y , lors
du remplissage du trapeze */
rayon = (int) pen_rayon; if (modetrace == FILAIRE) rayon = 0;
moveX = moveY = rayon;
size.x /= 2; size.y /= 2;
delta.x /= 2; delta.y /= 2;
polygone[0].x = - size.x - delta.y; polygone[0].y = + size.y + delta.x;
polygone[1].x = - size.x + delta.y; polygone[1].y = - size.y - delta.x;
polygone[2].x = + size.x - delta.y; polygone[2].y = - size.y + delta.x;
polygone[3].x = + size.x + delta.y; polygone[3].y = + size.y - delta.x;
/* Calcul du demi angle d'inclinaison des cotes du trapeze */
if( delta.y ) /* Trapeze horizontal */
{
fangle = atan2( (float)(polygone[1].y - polygone[0].y),
(float)(polygone[1].x - polygone[0].x) ) / 2 ;
}
else
{
fangle = atan2( (float)(polygone[3].y - polygone[0].y),
(float)(polygone[3].x - polygone[0].x) ) / 2 ;
}
/* Trace du contour */
polygone[0].x += moveX; polygone[0].y -= moveY;
polygone[1].x += moveX; polygone[1].y += moveY;
polygone[2].x -= moveX; polygone[2].y += moveY;
polygone[3].x -= moveX; polygone[3].y -= moveY;
for (ii = 0; ii < 4; ii++)
{
coord[ii].x = polygone[ii].x + padpos.x;
coord[ii].y = polygone[ii].y + padpos.y;
RotatePoint(&coord[ii], padpos, orient);
}
// Plot edge:
Move_Plume_HPGL( coord[0], 'U');
Move_Plume_HPGL( coord[1], 'D');
Move_Plume_HPGL( coord[2], 'D');
Move_Plume_HPGL( coord[3], 'D');
Move_Plume_HPGL( coord[0], 'D');
if(modetrace != FILLED )
{
Plume_HPGL('U'); return;
}
/* Fill the shape */
moveX = moveY = pen_diam - pen_recouvrement;
/* calcul de jj = hauteur du remplissage */
if( delta.y ) /* Trapeze horizontal */
{
jj = size.y - (int)( pen_diam + (2 * pen_recouvrement) );
}
else
{
jj = size.x - (int)( pen_diam + (2 * pen_recouvrement) );
}
/* Calcul de jj = nombre de segments a tracer pour le remplissage */
jj = jj / (int)(pen_diam - pen_recouvrement);
/* Trace du contour */
for( ; jj > 0 ; jj-- )
{
polygone[0].x += moveX; polygone[0].y -= moveY;
polygone[1].x += moveX; polygone[1].y += moveY;
polygone[2].x -= moveX; polygone[2].y += moveY;
polygone[3].x -= moveX; polygone[3].y -= moveY;
/* Test de limitation de variation des dimensions :
si les sommets se "croisent", il ne faut plus modifier les
coordonnees correspondantes */
if( polygone[0].x > polygone[3].x )
{ /* croisement sur axe X des 2 sommets 0 et 3 */
polygone[0].x = polygone[3].x = 0;
}
if( polygone[1].x > polygone[2].x )
{ /* croisement sur axe X des 2 sommets 1 et 2 */
polygone[1].x = polygone[2].x = 0;
}
if( polygone[1].y > polygone[0].y )
{ /* croisement sur axe Y des 2 sommets 0 et 1 */
polygone[0].y = polygone[1].y = 0;
}
if( polygone[2].y > polygone[3].y )
{ /* croisement sur axe Y des 2 sommets 2 et 3 */
polygone[2].y = polygone[3].y = 0;
}
for (ii = 0; ii < 4; ii++)
{
coord[ii].x = polygone[ii].x + padpos.x;
coord[ii].y = polygone[ii].y + padpos.y;
RotatePoint(&coord[ii], padpos, orient);
}
Move_Plume_HPGL( coord[0], 'U');
Move_Plume_HPGL( coord[1], 'D');
Move_Plume_HPGL( coord[2], 'D');
Move_Plume_HPGL( coord[3], 'D');
Move_Plume_HPGL( coord[0], 'D');
}
Plume_HPGL('U');
}
/********************************************************************/
void trace_1_segment_HPGL(int pos_X0,int pos_Y0,int pos_X1,int pos_Y1,
int epaisseur)
/********************************************************************/
/* Trace 1 rectangle donne par son axe et son epaisseur (piste rectangulaire)
en mode SKETCH
*/
{
float alpha ; /* angle de l'axe du rectangle */
wxSize size; /* coord relatives a l'origine du segment de sa fin */
int dh ; /* demi epaisseur du segment compte tenu de la
largeur de la plume */
int dx_rot; /* coord du segment en repere modifie ( size.y_rot etant nul )*/
float sin_alpha, cos_alpha ;
size.x = pos_X1 - pos_X0; size.y = pos_Y1 - pos_Y0 ;
dh = (epaisseur - (int)pen_diam ) / 2 ;
if ( dh < 0 )
{
dh = 0 ; nb_plot_erreur++ ; Affiche_erreur(nb_plot_erreur) ;
}
if ( (dh == 0) || (Plot_Mode == FILAIRE) ) /* Le trace se reduit a 1 trait */
{
Move_Plume_HPGL( wxPoint(pos_X0 , pos_Y0) , 'U');
Move_Plume_HPGL( wxPoint(pos_X1 , pos_Y1) , 'D');
Plume_HPGL('U');
return ;
}
if( size.x < 0 )
{
EXCHG( pos_X0, pos_X1 ) ; EXCHG( pos_Y0, pos_Y1 );
size.y = - size.y ;size.x = - size.x ;
}
if ( size.y == 0 ) /* segment horizontal */
{
Move_Plume_HPGL( wxPoint(pos_X0 , pos_Y0 - dh) , 'U');
Move_Plume_HPGL( wxPoint(pos_X1 , pos_Y1 - dh) , 'D');
Move_Plume_HPGL( wxPoint(pos_X1 , pos_Y1 + dh) , 'D');
Move_Plume_HPGL( wxPoint(pos_X0 , pos_Y0 + dh) , 'D');
Move_Plume_HPGL( wxPoint(pos_X0 , pos_Y0 - dh) , 'D');
}
else if ( size.x == 0 ) /* vertical */
{
if( size.y < 0 ) dh = -dh ;
Move_Plume_HPGL( wxPoint(pos_X0 - dh , pos_Y0) , 'U');
Move_Plume_HPGL( wxPoint(pos_X1 - dh , pos_Y1) , 'D');
Move_Plume_HPGL( wxPoint(pos_X1 + dh , pos_Y1) , 'D');
Move_Plume_HPGL( wxPoint(pos_X0 + dh , pos_Y0) , 'D');
Move_Plume_HPGL( wxPoint(pos_X0 - dh , pos_Y0) , 'D');
}
else /* piste inclinee */
{
/* On calcule les coord des extremites du rectangle dans le repere
a axe x confondu avec l'axe du rect. puis on revient dans le repere
de trace par 2 rotations inverses
coord : xrot = x*cos + y*sin
yrot = y*cos - x*sin
avec ici yrot = 0 puisque le segment est horizontal dans le nouveau repere
Transformee inverse :
coord : x = xrot*cos - yrot*sin
y = yrot*cos + xrot*sin
*/
int dx0,dy0, dx1,dy1;
if( size.x == size.y ) /* alpah = 45 degre */
{
sin_alpha = cos_alpha = 0.70711 ;
}
else if( size.x == -size.y ) /* alpah = -45 degre */
{
cos_alpha = 0.70711 ; sin_alpha = -0.70711 ;
}
else
{
alpha = atan2((float)size.y,(float)size.x) ;
sin_alpha = sin(alpha) ;
cos_alpha = cos(alpha) ;
}
dx_rot = (int)(size.x * cos_alpha + size.y * sin_alpha) ;
/* size.y_rot = (int)(size.y * cos_alpha - size.x * sin_alpha) ; doit etre NULL */
/* calcul du point de coord 0,-dh */
dx0 =(int) ( dh * sin_alpha) ;
dy0 =(int) (- dh*cos_alpha ) ;
Move_Plume_HPGL( wxPoint(pos_X0 + dx0 , pos_Y0 + dy0) , 'U');
/* calcul du point de coord size.xrot,-dh */
dx1 =(int) (dx_rot*cos_alpha + dh * sin_alpha) ;
dy1 =(int) (-dh*cos_alpha + dx_rot*sin_alpha ) ;
Move_Plume_HPGL( wxPoint(pos_X0 + dx1 , pos_Y0 + dy1) , 'D');
/* calcul du point de coord size.xrot,+dh */
dx1 =(int) (dx_rot*cos_alpha - dh * sin_alpha) ;
dy1 =(int) (dh*cos_alpha + dx_rot*sin_alpha ) ;
Move_Plume_HPGL( wxPoint(pos_X0 + dx1 , pos_Y0 + dy1) , 'D');
/* calcul du point de coord 0,+dh */
dx1 =(int) ( - dh * sin_alpha) ;
dy1 =(int) (dh*cos_alpha ) ;
Move_Plume_HPGL( wxPoint(pos_X0 + dx1 , pos_Y0 + dy1) , 'D');
/* retour au point de depart */
Move_Plume_HPGL( wxPoint(pos_X0 + dx0 , pos_Y0 + dy0) , 'D');
}
Plume_HPGL('U');
}
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
869
]
]
]
|
019210d192f978a18ae116f7259f33d1adec2e93 | 9907be749dc7553f97c9e51c5f35e69f55bd02c0 | /WordplaySingle/Wordplay/api_code/GFObject.h | ecfa80d14c8d48e1ee9ce99b208a060834c6f93c | []
| no_license | jdeering/csci476winthrop | bc8907b9cc0406826de76aca05e6758810377813 | 2bc485781f819c8fd82393ac86de33404e7ad6d3 | refs/heads/master | 2021-01-10T19:53:14.853438 | 2009-04-24T14:26:36 | 2009-04-24T14:26:36 | 32,223,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | h | /**
* @file GFObject.h
* @brief A template for any Framework object (GFSprite, GFAudio, GFText)
*/
#pragma once
#include "GameFramework.h"
class GFObject
{
/* SO THAT THE FRAMEWORK CAN ACCESS PROTECTED MEMBERS */
friend class GameFramework;
public:
/*
A QUICK COMMENT ABOUT THIS OPERATOR:
there should be no case where this operator is EVER true, except in the case
where a function return value is checked against null. for that reason, this
operator serves only to service the needs of error checking.
*/
bool operator==(const GFObject& o)
{ return _ref == o._ref; };
protected:
/* PROTECTED CONSTRUCTOR */
GFObject(int ref) : _ref(ref) { };
static int const GFW_BUFFER_SIZE = 128;
/* REFERENCE NUMBER FOR FRAMEWORK */
int _ref;
void _clrBuffer(char buffer[]){ memset(buffer, 0, GFW_BUFFER_SIZE); }
};
| [
"authorblues@2656ef14-ecf4-11dd-8fb1-9960f2a117f8",
"deeringj2@2656ef14-ecf4-11dd-8fb1-9960f2a117f8"
]
| [
[
[
1,
5
],
[
20,
20
]
],
[
[
6,
19
],
[
21,
34
]
]
]
|
9348cd04a3b20059fcb0f80326a8e72b637123b1 | accd6e4daa3fc1103c86d245c784182e31681ea4 | /HappyHunter/Effect/UnderWaterEffect.h | e073f011bc615e78a85169a4a7d4e669f8062b7c | []
| no_license | linfuqing/zero3d | d87ad6cf97069aea7861332a9ab8fc02b016d286 | cebb12c37fe0c9047fb5b8fd3c50157638764c24 | refs/heads/master | 2016-09-05T19:37:56.213992 | 2011-08-04T01:37:36 | 2011-08-04T01:37:36 | 34,048,942 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 500 | h | #pragma once
#include "FullScreenEffect.h"
#include "VertexBuffer.h"
#include "Texture.h"
namespace zerO
{
class CUnderWaterEffect :
public CFullScreenEffect
{
struct BUMPVERTEX
{
D3DXVECTOR4 p;
float tu1, tv1;
float tu2, tv2;
};
public:
CUnderWaterEffect(void);
~CUnderWaterEffect(void);
bool Restore();
bool Create();
void Render(CTexturePrinter& TexturePrinter);
private:
CVertexBuffer m_VertexBuffer;
CTexture m_Texture;
};
} | [
"[email protected]"
]
| [
[
[
1,
31
]
]
]
|
de55a1ac0f0c9f766993fb6a8dc9654759e8b623 | 5dc6c87a7e6459ef8e832774faa4b5ae4363da99 | /vis_avs/r_fadeout.cpp | 7b218e8a57c0f1c1077e69a3f71ec20786bd4093 | []
| no_license | aidinabedi/avs4unity | 407603d2fc44bc8b075b54cd0a808250582ee077 | 9b6327db1d092218e96d8907bd14d68b741dcc4d | refs/heads/master | 2021-01-20T15:27:32.449282 | 2010-12-24T03:28:09 | 2010-12-24T03:28:09 | 90,773,183 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,548 | cpp | /*
LICENSE
-------
Copyright 2005 Nullsoft, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Nullsoft 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 OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h"
// alphachannel safe 11/21/99
#include <windows.h>
#include <commctrl.h>
#include "r_defs.h"
#include "resource.h"
#include "timing.h"
#ifndef LASER
#define C_THISCLASS C_FadeOutClass
#define MOD_NAME "Trans / Fadeout"
class C_THISCLASS : public C_RBASE {
protected:
public:
C_THISCLASS();
virtual ~C_THISCLASS();
virtual int render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h);
virtual char *get_desc() { return MOD_NAME; }
virtual HWND conf(HINSTANCE hInstance, HWND hwndParent);
virtual void load_config(unsigned char *data, int len);
virtual int save_config(unsigned char *data);
void maketab(void);
unsigned char fadtab[3][256];
int fadelen, color;
};
void C_THISCLASS::maketab(void)
{
int rseek=color&0xff;
int gseek=(color>>8)&0xff;
int bseek=(color>>16)&0xff;
int x;
for (x = 0; x < 256; x ++)
{
int r=x;
int g=x;
int b=x;
if (r <= rseek-fadelen) r+=fadelen;
else if (r >= rseek+fadelen) r-=fadelen;
else r=rseek;
if (g <= gseek-fadelen) g+=fadelen;
else if (g >= gseek+fadelen) g-=fadelen;
else g=gseek;
if (b <= bseek-fadelen) b+=fadelen;
else if (b >= bseek+fadelen) b-=fadelen;
else b=bseek;
fadtab[0][x]=r;
fadtab[1][x]=g;
fadtab[2][x]=b;
}
}
#define PUT_INT(y) data[pos]=(y)&255; data[pos+1]=(y>>8)&255; data[pos+2]=(y>>16)&255; data[pos+3]=(y>>24)&255
#define GET_INT() (data[pos]|(data[pos+1]<<8)|(data[pos+2]<<16)|(data[pos+3]<<24))
void C_THISCLASS::load_config(unsigned char *data, int len)
{
int pos=0;
if (len-pos >= 4) { fadelen=GET_INT(); pos+=4; }
if (len-pos >= 4) { color=GET_INT(); pos+=4; }
maketab();
}
int C_THISCLASS::save_config(unsigned char *data)
{
int pos=0;
PUT_INT(fadelen); pos+=4;
PUT_INT(color); pos+=4;
return pos;
}
C_THISCLASS::C_THISCLASS()
{
color=0;
fadelen=16;
maketab();
}
C_THISCLASS::~C_THISCLASS()
{
}
int C_THISCLASS::render(char visdata[2][2][SAMPLES], int isBeat, int *framebuffer, int *fbout, int w, int h)
{
if (isBeat&0x80000000) return 0;
if (!fadelen) return 0;
timingEnter(1);
if (
#ifdef NO_MMX
1
#else
color
#endif
)
{
unsigned char *t=(unsigned char *)framebuffer;
int x=w*h;
while (x--)
{
t[0]=fadtab[0][t[0]];
t[1]=fadtab[1][t[1]];
t[2]=fadtab[2][t[2]];
t+=4;
}
}
#ifndef NO_MMX
else
{
int l=(w*h);
char fadj[8];
int x;
unsigned char *t=fadtab[0];
for (x = 0; x < 8; x ++) fadj[x]=this->fadelen;
__asm
{
mov edx, l
mov edi, framebuffer
movq mm7, [fadj]
shr edx, 3
align 16
_l1:
movq mm0, [edi]
movq mm1, [edi+8]
movq mm2, [edi+16]
psubusb mm0, mm7
movq mm3, [edi+24]
psubusb mm1, mm7
movq [edi], mm0
psubusb mm2, mm7
movq [edi+8], mm1
psubusb mm3, mm7
movq [edi+16], mm2
movq [edi+24], mm3
add edi, 8*4
dec edx
jnz _l1
mov edx, l
sub eax, eax
and edx, 7
jz _l3
sub ebx, ebx
sub ecx, ecx
mov esi, t
_l2:
mov al, [edi]
mov bl, [edi+1]
mov cl, [edi+2]
sub al, [esi+eax]
sub bl, [esi+ebx]
sub cl, [esi+ecx]
mov [edi], al
mov [edi+1], bl
mov [edi+2], cl
add edi, 4
dec edx
jnz _l2
_l3:
emms
}
}
#endif
timingLeave(1);
return 0;
}
C_RBASE *R_FadeOut(char *desc)
{
if (desc) { strcpy(desc,MOD_NAME); return NULL; }
return (C_RBASE *) new C_THISCLASS();
}
static C_THISCLASS *g_this;
static BOOL CALLBACK g_DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam,LPARAM lParam)
{
int *a=NULL;
switch (uMsg)
{
case WM_DRAWITEM:
{
DRAWITEMSTRUCT *di=(DRAWITEMSTRUCT *)lParam;
switch (di->CtlID)
{
case IDC_LC:
GR_DrawColoredButton(di,g_this->color);
break;
}
}
return 0;
case WM_INITDIALOG:
SendDlgItemMessage(hwndDlg,IDC_SLIDER1,TBM_SETRANGEMIN,0,0);
SendDlgItemMessage(hwndDlg,IDC_SLIDER1,TBM_SETRANGEMAX,0,92);
SendDlgItemMessage(hwndDlg,IDC_SLIDER1,TBM_SETPOS,1,g_this->fadelen);
return 1;
case WM_HSCROLL:
{
HWND swnd = (HWND) lParam;
int t = (int) SendMessage(swnd,TBM_GETPOS,0,0);
if (swnd == GetDlgItem(hwndDlg,IDC_SLIDER1))
{
g_this->fadelen=t;
g_this->maketab();
}
}
case WM_COMMAND:
switch (LOWORD(wParam))
{
case IDC_LC:
GR_SelectColor(hwndDlg,&g_this->color);
InvalidateRect(GetDlgItem(hwndDlg,LOWORD(wParam)),NULL,FALSE);
g_this->maketab();
return 0;
}
return 0;
}
return 0;
}
HWND C_THISCLASS::conf(HINSTANCE hInstance, HWND hwndParent)
{
g_this = this;
return CreateDialog(hInstance,MAKEINTRESOURCE(IDD_CFG_FADE),hwndParent,g_DlgProc);
}
#else
C_RBASE *R_FadeOut(char *desc) { return NULL; }
#endif | [
"[email protected]"
]
| [
[
[
1,
277
]
]
]
|
10232ff586058721b564699136fafcf4c778c226 | f90b1358325d5a4cfbc25fa6cccea56cbc40410c | /src/GUI/proRataMerge.cpp | c3599510c58a035635f3a8e7534032500aebbab9 | []
| no_license | ipodyaco/prorata | bd52105499c3fad25781d91952def89a9079b864 | 1f17015d304f204bd5f72b92d711a02490527fe6 | refs/heads/master | 2021-01-10T09:48:25.454887 | 2010-05-11T19:19:40 | 2010-05-11T19:19:40 | 48,766,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,398 | cpp |
#include "proRataMerge.h"
ProRataMerge::ProRataMerge( QWidget* qwParent )
: QDialog( qwParent )
/* : QWidget( qwParent, qwfFl ) */
{
buildUI();
setValues();
qsOutputDirectory = "";
setAttribute( Qt::WA_ShowModal );
setModal( true );
}
ProRataMerge::~ProRataMerge()
{
}
void ProRataMerge::buildUI()
{
qvbProRataMergeLayout = new QVBoxLayout;
qbgInput = new QGroupBox;
qbgInputLayout = new QGridLayout;
qbgInput->setLayout( qbgInputLayout );
qlwInput = new QListWidget;
qbgInputLayout->addWidget( qlwInput, 0, 0, 2, 1 );
qpbAddDir = new QPushButton;
connect( qpbAddDir, SIGNAL( clicked() ),
this, SLOT( addDirectory() ) );
qbgInputLayout->addWidget( qpbAddDir, 0, 1 );
qpbRemoveDir = new QPushButton;
connect( qpbRemoveDir, SIGNAL( clicked() ),
this, SLOT( removeDirectory() ) );
qbgInputLayout->addWidget( qpbRemoveDir, 1, 1 );
qvbProRataMergeLayout->addWidget( qbgInput );
qbgOutput = new QGroupBox;
qbgOutputLayout = new QHBoxLayout;
qbgOutput->setLayout( qbgOutputLayout );
qleOutput = new QLineEdit;
connect( qleOutput, SIGNAL( textChanged( const QString & ) ),
this, SLOT( validateOutputDir(const QString &) ) );
qbgOutputLayout->addWidget( qleOutput );
qpbOuputBrowse = new QPushButton;
connect( qpbOuputBrowse, SIGNAL( clicked() ),
this, SLOT( browseForOutputDirectory() ) );
qbgOutputLayout->addWidget( qpbOuputBrowse );
qvbProRataMergeLayout->addWidget( qbgOutput );
// Separator
qfLine1 = new QFrame;
qfLine1->setLineWidth( 1 );
qfLine1->setFrameStyle( QFrame::HLine | QFrame::Sunken );
qvbProRataMergeLayout->addWidget( qfLine1 );
// Controls
qpbCancelButton = new QPushButton(tr("Cancel"));
connect( qpbCancelButton, SIGNAL( clicked() ),
this, SLOT( close() ) );
qpbMergeButton = new QPushButton(tr("&Merge"));
qpbMergeButton->setEnabled(false);
connect( qpbMergeButton, SIGNAL( clicked() ),
this, SLOT( merge() ) );
qhblButtonLayout = new QHBoxLayout;
qhblButtonLayout->addStretch(1);
qhblButtonLayout->addWidget(qpbCancelButton);
qhblButtonLayout->addWidget(qpbMergeButton);
qvbProRataMergeLayout->addLayout( qhblButtonLayout );
setLayout( qvbProRataMergeLayout );
}
void ProRataMerge::setValues()
{
qbgInput->setTitle( tr( "Input Directories" ) );
qlwInput->clear();
qpbAddDir->setText( tr( "Add Directory.." ) );
qpbRemoveDir->setText( tr( "Remove Directory" ) );
qbgOutput->setTitle( tr( "Output Directory" ) );
qpbOuputBrowse->setText( tr( "Browse.." ) );
setWindowTitle( tr( "Merge Directories - ProRata" ) );
setFixedHeight( sizeHint().height() );
}
void ProRataMerge::merge()
{
accept();
// Get the list of files.
for (int i = 0; i < qlwInput->count() ; i++ )
{
QString qsDir = (qlwInput->item( i ))->text();
QDir dir( qsDir );
QString qsBaseName = qsDir.section( '/', -1 );
dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
QFileInfoList list = dir.entryInfoList();
for (int j = 0; j < list.size(); ++j) {
QFileInfo fileInfo = list.at(j);
QString qsNewFile = qsOutputDirectory + "/" + qsBaseName + "_" + fileInfo.fileName();
//QFile::copy( fileInfo.absoluteFilePath(), qsNewFile );
QFile qfInputFile;
qfInputFile.setFileName( fileInfo.absoluteFilePath() );
qfInputFile.copy( qsNewFile );
}
dir.setFilter(QDir::AllDirs | QDir::NoSymLinks);
QFileInfoList qfileDirList = dir.entryInfoList();
QString qsDirList = "";
for (int j = 0; j < qfileDirList.size(); ++j)
{
QFileInfo dirInfo = qfileDirList.at(j);
if ( dirInfo.fileName() == "." || dirInfo.fileName() == ".." )
{
continue;
}
QDir qdCurrentPointer;
QString qsDestDirectory = qsOutputDirectory + "/" + qsBaseName + "_" + dirInfo.fileName();
qdCurrentPointer.mkdir( qsDestDirectory );
QDir sourceDir( dirInfo.absoluteFilePath() );
sourceDir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
QFileInfoList list = sourceDir.entryInfoList();
for (int j = 0; j < list.size(); ++j) {
QFileInfo dirInfo = list.at(j);
QString qsNewFile = qsDestDirectory + "/" + qsBaseName + "_" + dirInfo.fileName();
//QFile::copy( dirInfo.absoluteFilePath(), qsNewFile );
QFile qfInputFile;
qfInputFile.setFileName( dirInfo.absoluteFilePath() );
qfInputFile.copy( qsNewFile );
}
}
//QMessageBox::information(this, "dir list ", qsDirList );
}
}
void ProRataMerge::addDirectory()
{
QString qsDirName = QFileDialog::getExistingDirectory(
this,
"Choose a directory to merge.",
QDir::rootPath());
if ( !qsDirName.isEmpty() )
{
qlwInput->addItem( new QListWidgetItem( qsDirName ) );
}
}
void ProRataMerge::removeDirectory()
{
qlwInput->takeItem( qlwInput->currentRow() );
}
void ProRataMerge::browseForOutputDirectory()
{
QString qsDirName = QFileDialog::getExistingDirectory(
this,
"Choose a directory to save the merge output.",
QDir::rootPath());
if ( !qsDirName.isEmpty() )
{
qleOutput->setText( qsDirName );
}
}
void ProRataMerge::validateOutputDir( const QString & qsDir)
{
QDir qdTemp2( qsDir );
if ( qdTemp2.exists() )
{
qpbMergeButton->setEnabled(true);
qsOutputDirectory = qleOutput->text();
}
else
{
qsOutputDirectory = "";
}
}
| [
"chongle.pan@c58cc1ec-c975-bb1e-ac29-6983d7497d3a"
]
| [
[
[
1,
209
]
]
]
|
bb06f43abcef168b445268f8d8861c287c83234a | f177b64040f6e70ff885ca6911babf647103ddaa | /source/Drawable.h | bd51dcf5df542ceaf9f1bc03407fb8d333cdae63 | []
| no_license | xflash/redraid | b7b662853a09e529e20b5ceee74b4f51ba6d6689 | 1d6b010bbadc2586232ec92df99be7ec49adb43d | refs/heads/master | 2016-09-10T03:57:18.746840 | 2008-06-07T16:11:18 | 2008-06-07T16:11:18 | 32,315,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,305 | h | #ifndef Drawable_h
#define Drawable_h
#include <ulib/ulib.h>
#include "ResourceLoader.h"
// Base class for Drawable objects
class Drawable {
private:
UL_IMAGE *img;
private:
int width, height;
protected:
u16 color;
public:
Drawable():img(NULL) { }
virtual ~Drawable() { }
void initDraw(int imageID) {
img = (UL_IMAGE*)ResourceLoader::Get()->getResource(imageID);
//White by default
color = 0x7fff;
}
void draw(){
//Set the ball color
ulSetImageTint(img, getColor());
//rotate the image
img->angle = getDrawAngle();
// move the image center and the rotation center
// img->centerX = getDrawFrameX() + getDrawFrameW()>>1;
// img->centerY = getDrawFrameY() + getDrawFrameH()>>1;
img->centerX = getDrawFrameW()>>1;
img->centerY = getDrawFrameH()>>1;
//draw only the frame in the sprite sheet
ulSetImageTileSize(img,
getDrawFrameX(), getDrawFrameY(),
getDrawFrameW(), getDrawFrameH());
//Draw the image
/*
ulDrawFillRect(getDrawUpX(), getDrawUpY(),
getDrawLowX(), getDrawLowY(),
RGB15(16, 0, 0));
*/
ulDrawImageXY(img, getDrawCenterX(), getDrawCenterY());
//ulPrintf_xy(getDrawCenterX(), getDrawCenterY(), "%d", getDrawAngle());
}
public:
inline void setColor(u16 c) { color=c; }
inline u16 getColor() { return color; }
virtual int getDrawUpX() { return getDrawCenterX()-(getDrawFrameW()>>1); }
virtual int getDrawUpY() { return getDrawCenterY()-(getDrawFrameH()>>1); }
virtual int getDrawLowX() { return getDrawCenterX()+(getDrawFrameW()>>1); }
virtual int getDrawLowY() { return getDrawCenterY()+(getDrawFrameH()>>1); }
protected:
//override those to position the drawing
virtual int getDrawFrameX() { return 0; }
virtual int getDrawFrameY() { return 0; }
// implement those to position the image center
virtual int getDrawCenterX()=0;
virtual int getDrawCenterY()=0;
virtual int getDrawAngle()=0;
// Default dimensions are determined with the image size
// may be overriden
virtual int getDrawFrameW() { return getDrawW(); }
virtual int getDrawFrameH() { return getDrawH(); }
private:
int getDrawW() { return img->sizeX; }
int getDrawH() { return img->sizeY; }
};
#endif
| [
"rcoqueugniot@c32521c4-154f-0410-b136-dfa89fbbf926"
]
| [
[
[
1,
88
]
]
]
|
83225004bbb6b353ec0c7bd00b5ba02a552c7583 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libpthread/testsemwait/inc/tsemwaitserver.h | fe0691bc1703a64657fc319a9461c32c725f0582 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | h | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
#ifndef __TSEMWAITSERVER_H__
#define __TSEMWAITSERVER_H__
#include <f32file.h>
#include <test/TestExecuteServerBase.h>
class CSemwaitTestServer : public CTestServer
{
public:
static CSemwaitTestServer* NewL();
virtual CTestStep* CreateTestStep(const TDesC& aStepName);
RFs& Fs() {return iFs;}
private:
RFs iFs;
};
#endif //
| [
"none@none"
]
| [
[
[
1,
36
]
]
]
|
fc5bd84d31834a97db7146ff7cd83b647f71aaff | e4bad8b090b8f2fd1ea44b681e3ac41981f50220 | /trunk/Abeetles/Abeetles/StatisticsEnv.cpp | 42bd86b401377da35c1527909efbac1afa293ffa | []
| no_license | BackupTheBerlios/abeetles-svn | 92d1ce228b8627116ae3104b4698fc5873466aff | 803f916bab7148290f55542c20af29367ef2d125 | refs/heads/master | 2021-01-22T12:02:24.457339 | 2007-08-15T11:18:14 | 2007-08-15T11:18:14 | 40,670,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,056 | cpp | #include "StdAfx.h"
#include "StatisticsEnv.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Grid.h"
#include "assert.h"
CStatisticsEnv::CStatisticsEnv(void)
{
MakeEmpty();
FILE * statTimeFile;
errno_t err;
if ((err= fopen_s(&statTimeFile,STAT_TIME_FILE,"w"))!=0)
{
printf("Creation of file for time statistics was not successful - Error No.%d.\n",err);
return; //It is not a reason to finnish the program.
//exit (EXIT_FAILURE);
}
else
{ //adding to rows
/*
fprintf(statTimeFile,"Number of beetles;\n");
fprintf(statTimeFile,"Number of births;\n");
fprintf(statTimeFile,"Number of flowers;\n");
fprintf(statTimeFile,"Density of population;\n");*/
//adding to columns
fprintf(statTimeFile,"Number of beetles;Number of births;Number of flowers\n");
}
fclose(statTimeFile);
}
CStatisticsEnv::~CStatisticsEnv(void)
{
}
void CStatisticsEnv::NextTime(int Time)
{
PastNumBeetles[Time%BUF_SIZE]=NumBeetles;
PastNumBirths[Time%BUF_SIZE]=NumBirths;
PastNumFlowers[Time%BUF_SIZE]=NumFlowers;
//After 1000 time slices add all time values into file.
if (Time% BUF_SIZE == (BUF_SIZE-1))
{
//SaveTimeStatist_InRowsAppend();
SaveTimeStatist_InColumnsAppend();
}
NumBirths=0;
SumAge=0;
SumEnergy=0;
SumNumChildren=0;
}
void CStatisticsEnv::MakeEmpty(void)
{
SumAge=0;
SumEnergy=0;
SumHungryThreshold =0;
SumInvInChild=0;
SumLearnAbility=0;
SumNumChildren=0;
NumBeetles=0;
NumBirths=0;
NumFlowers=0;
}
double CStatisticsEnv::GetAvgAge(void)
{
return (double)SumAge/NumBeetles;
}
double CStatisticsEnv::GetAvgEnergy(void)
{
return (double)SumEnergy/NumBeetles;
}
double CStatisticsEnv::GetAvgHungryThreshold(void)
{
return (double)SumHungryThreshold/NumBeetles;
}
double CStatisticsEnv::GetAvgInvInChild(void)
{
return (double)SumInvInChild/NumBeetles;
}
double CStatisticsEnv::GetAvgLearnAbility(void)
{
return (double)SumLearnAbility/NumBeetles;
}
double CStatisticsEnv::GetAvgNumChildren(void)
{
return (double)SumNumChildren/NumBeetles;
}
/**
* Public method <br>
* Description: Saves {@link Abeetles.CStatisticsEnv} actual and agregated statistics<br>
* System dependence: no<br>
* Usage comments:<br>
* @return true - if successful, false - otherwise
* @param filename [name for file, where the statistics will be saved]
* @param time [Actual time to be writte](Parameters - meaning):
* @throws name [descrip](Exceptions - meaning)
* @see Abeetles.CStatisticsEnv #SaveTimeStatist_InColumnsAppend
* @see Abeetles.CStatisticsEnv #SaveTimeStatist_InRowsAppend
*/
bool CStatisticsEnv::SaveActAgrStatist(char * filename, int time)
{
FILE * statFile;
errno_t err;
if ((err= fopen_s(&statFile,filename,"w"))!=0)
{
printf("%d",err);
return false;
}
fprintf(statFile," ---------- \n");
fprintf(statFile,"Time=%d\n",time);
fprintf(statFile,"NumBeetles=%d;\n",NumBeetles);
fprintf(statFile,"NumBirths=%d;\n",NumBirths);
fprintf(statFile,"NumFlowers=%d;\n",NumFlowers);
fprintf(statFile,"AvgAge=%f;\n",GetAvgAge());
fprintf(statFile,"AvgEnergy=%f;\n",GetAvgEnergy());
fprintf(statFile,"AvgHungryThreshold=%f;\n",GetAvgHungryThreshold());
fprintf(statFile,"AvgInvInChild=%f;\n",GetAvgInvInChild());
fprintf(statFile,"AvgLearnAbility=%f;\n",GetAvgLearnAbility());
fprintf(statFile,"AvgNumChildren=%f;\n",GetAvgNumChildren());
fprintf(statFile," ---------- \n");
fclose(statFile);
return true;
}
bool CStatisticsEnv::SaveTimeStatist_InRowsAppend()
{
FILE * stTFOld;FILE * stTF;
errno_t err;
char chr=0;
//rename file to some other name
rename(STAT_TIME_FILE,STAT_TIME_FILE_OLD);
//open old file for reading and new file for writing
if ((err= fopen_s(&stTFOld,STAT_TIME_FILE_OLD,"r"))!=0)
{
printf("Error No.%d occured, opening of file %s unsuccessful.",err,STAT_TIME_FILE);
return false;
}
if ((err= fopen_s(&stTF,STAT_TIME_FILE,"w"))!=0)
{
printf("Error No.%d occured, opening of file %s unsuccessful.",err,STAT_TIME_FILE);
return false;
}
//rewrite old to new up to the end of the first line
chr=getc(stTFOld);
while(chr!='\n')
{
putc(chr,stTF);chr=getc(stTFOld);
}
int I;
for (I=0;I<BUF_SIZE;I++)
fprintf(stTF,"%d;",PastNumBeetles[I]);
fprintf(stTF,"\n");
chr=getc(stTFOld);
while(chr!='\n')
{
putc(chr,stTF);chr=getc(stTFOld);
}
for (I=0;I<BUF_SIZE;I++)
fprintf(stTF,"%d;",PastNumBirths[I]);
fprintf(stTF,"\n");
chr=getc(stTFOld);
while(chr!='\n')
{
putc(chr,stTF);chr=getc(stTFOld);
}
for (I=0;I<BUF_SIZE;I++)
fprintf(stTF,"%d;",PastNumFlowers[I]);
fprintf(stTF,"\n");
fclose(stTF);fclose(stTFOld);
remove (STAT_TIME_FILE_OLD);
return true;
}
/**
* Public method <br>
* Description: Writes last n value to a .csv file. The n is defined by constant BUF_SIZE. The name of the file is STAT_TIME_FILE. It adds every monitored variable into separate column. <br>
* System dependence: no<br>
* Usage comments:<br>
* @return True - if saving was successful and false, if opening of the file failed.
*/
bool CStatisticsEnv::SaveTimeStatist_InColumnsAppend()
{
FILE * stTF;
errno_t err;
int I;
if ((err= fopen_s(&stTF,STAT_TIME_FILE,"a+"))!=0)
{
printf_s("Error No.%d occured: %s, opening of file %s unsuccessful.",err,strerror(err),STAT_TIME_FILE);
return false;
}
for (I=0;I<BUF_SIZE;I++)
fprintf(stTF,"%d;%d;%d\n",PastNumBeetles[I],PastNumBirths[I],PastNumFlowers[I]);
fclose(stTF);
return true;
}
bool CStatisticsEnv::SaveActHistStatist(char * filename, int time,CGrid * grid)
{
FILE * statFile;
errno_t err;
int I,J;
int Ages [MAX_HIST];
for (I=0;I<MAX_HIST;I++) Ages[I]=0;
int LearnAbilities[MAX_HIST];
for (I=0;I<MAX_HIST;I++) LearnAbilities[I]=0;
int InvInChilds[MAX_HIST];
for (I=0;I<MAX_HIST;I++) InvInChilds[I]=0;
int Energies[MAX_HIST];
for (I=0;I<MAX_HIST;I++) Energies[I]=0;
CBeetle * beetle=NULL;
for(I=0;I<grid->G_Width;I++)
for(J=0;J<grid->G_Height;J++)
{
if (grid->GetCellContent(I,J,&beetle)==BEETLE)
{
if (beetle->Age <MAX_HIST)
Ages[beetle->Age]++;
assert(beetle->LearnAbility<MAX_HIST);
LearnAbilities[beetle->LearnAbility]++;
assert(beetle->InvInChild<MAX_HIST);
InvInChilds[beetle->InvInChild]++;
assert(beetle->Energy<MAX_HIST);
Energies[beetle->Energy]++;
}
}
if ((err= fopen_s(&statFile,filename,"w"))!=0)
{
printf_s("Error No.%d occured: %s, opening of file %s unsuccessful.",err,strerror(err),filename);
return false;
}
fprintf(statFile,"Ages;LearnAbilities;InvInChilds;Energies\n");
for (I=0;I<MAX_HIST;I++)
{
fprintf(statFile,"%d;%d;%d;%d\n",Ages[I],LearnAbilities[I],InvInChilds[I],Energies[I]);
}
fclose(statFile);
return true;
}
| [
"ibart@60a5a0de-1a2f-0410-942a-f28f22aea592"
]
| [
[
[
1,
286
]
]
]
|
73d2205040af51bd284190785ef5c0768fd231e6 | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /EIBStdLib/src/XGetopt.cpp | 25de3b7c57d03f40cb3458a3e0d83a44f6ba44ee | []
| 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 | 5,571 | cpp | #ifdef WIN32
#include "XGetopt.h"
///////////////////////////////////////////////////////////////////////////////
//
// X G e t o p t . c p p
//
//
// NAME
// getopt -- parse command line options
//
// SYNOPSIS
// int getopt(int argc, TCHAR *argv[], TCHAR *optstring)
//
// extern TCHAR *optarg;
// extern int optind;
//
// DESCRIPTION
// The getopt() function parses the command line arguments. Its
// arguments argc and argv are the argument count and array as
// passed into the application on program invocation. In the case
// of Visual C++ programs, argc and argv are available via the
// variables __argc and __argv (double underscores), respectively.
// getopt returns the next option letter in argv that matches a
// letter in optstring. (Note: Unicode programs should use
// __targv instead of __argv. Also, all character and string
// literals should be enclosed in _T( ) ).
//
// optstring is a string of recognized option letters; if a letter
// is followed by a colon, the option is expected to have an argument
// that may or may not be separated from it by white space. optarg
// is set to point to the start of the option argument on return from
// getopt.
//
// Option letters may be combined, e.g., "-ab" is equivalent to
// "-a -b". Option letters are case sensitive.
//
// getopt places in the external variable optind the argv index
// of the next argument to be processed. optind is initialized
// to 0 before the first call to getopt.
//
// When all options have been processed (i.e., up to the first
// non-option argument), getopt returns EOF, optarg will point
// to the argument, and optind will be set to the argv index of
// the argument. If there are no non-option arguments, optarg
// will be set to NULL.
//
// The special option "--" may be used to delimit the end of the
// options; EOF will be returned, and "--" (and everything after it)
// will be skipped.
//
// RETURN VALUE
// For option letters contained in the string optstring, getopt
// will return the option letter. getopt returns a question mark (?)
// when it encounters an option letter not included in optstring.
// EOF is returned when processing is finished.
//
// BUGS
// 1) Long options are not supported.
// 2) The GNU double-colon extension is not supported.
// 3) The environment variable POSIXLY_CORRECT is not supported.
// 4) The + syntax is not supported.
// 5) The automatic permutation of arguments is not supported.
// 6) This implementation of getopt() returns EOF if an error is
// encountered, instead of -1 as the latest standard requires.
//
// EXAMPLE
// BOOL CMyApp::ProcessCommandLine(int argc, TCHAR *argv[])
// {
// int c;
//
// while ((c = getopt(argc, argv, _T("aBn:"))) != EOF)
// {
// switch (c)
// {
// case _T('a'):
// TRACE(_T("option a\n"));
// //
// // set some flag here
// //
// break;
//
// case _T('B'):
// TRACE( _T("option B\n"));
// //
// // set some other flag here
// //
// break;
//
// case _T('n'):
// TRACE(_T("option n: value=%d\n"), atoi(optarg));
// //
// // do something with value here
// //
// break;
//
// case _T('?'):
// TRACE(_T("ERROR: illegal option %s\n"), argv[optind-1]);
// return FALSE;
// break;
//
// default:
// TRACE(_T("WARNING: no handler for option %c\n"), c);
// return FALSE;
// break;
// }
// }
// //
// // check for non-option args here
// //
// return TRUE;
// }
//
///////////////////////////////////////////////////////////////////////////////
char *optarg; // global argument pointer
int optind = 0; // global argv index
int opterr = 0;
int getopt(int argc, char *argv[], char *optstring)
{
static char *next = NULL;
if (optind == 0)
next = NULL;
optarg = NULL;
if (next == NULL || *next == '\0')
{
if (optind == 0)
optind++;
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
{
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
if (strcmp(argv[optind], "--") == 0)
{
optind++;
optarg = NULL;
if (optind < argc)
optarg = argv[optind];
return EOF;
}
next = argv[optind];
next++; // skip past -
optind++;
}
char c = *next++;
char *cp = strchr(optstring, c);
if (cp == NULL || c == ':')
return '?';
cp++;
if (*cp == ':')
{
if (*next != '\0')
{
optarg = next;
next = NULL;
}
else if (optind < argc)
{
optarg = argv[optind];
optind++;
}
else
{
return '?';
}
}
return c;
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
184
]
]
]
|
99ead24b6a09aac422c7e3005643fa95bc4ff7eb | 3da0b0276bc8c3d7d1bcdbabfb0e763a38d3a24c | /unpassed/1411.cpp | 2fbbee3c17af13c125ee983854f1c3a1683d132e | []
| 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 | 1,780 | cpp | #include<iostream>
#include<vector>
using namespace std;
enum {
SIZ = 41,
};
struct Rect{
int h,l;
bool operator<(const Rect &r)const{
if(h != r.h) return h<r.h;
return l<r.l;
}
};
vector<Rect> tab[SIZ];
int num, S, side[SIZ];
bool fun(){
int i, t;
Rect one,cur;
for(i=0; i<SIZ; i++){
tab[i].clear();
}
one.h = one.l = S;
tab[S].push_back(one);
for(i=num-1; i>=0; i--){
for(t=side[i]; t<=S ; t++){
if(tab[t].size() == 0) continue;
one = tab[t].back();
tab[t].pop_back();
if(side[i] == one.l){
one.h -= side[i];
if(one.h < one.l){
swap(one.h, one.l);
}
if(one.l > 0){
tab[one.l].push_back(one);
}
} else {
cur.h = side[i], cur.l = one.l - side[i];
one.h -= side[i];
if(one.h<one.l) swap(one.h, one.l);
if(cur.h<cur.l) swap(cur.h, cur.l);
tab[one.l].push_back(one);
tab[cur.l].push_back(cur);
}
break;
}
if(t > S) return false;
}
return true;
}
bool readIn(){
int t = 0;
scanf("%d%d",&S, &num);
for(int i=0; i<num; i++){
scanf("%d", &side[i]);
t += side[i]*side[i];
}
sort(side, side+num);
return S*S==t;
}
int main(){
int tst;
bool t;
const char *ans[2] = {"HUTUTU!", "KHOOOOB!"};
scanf("%d", &tst);
while(tst--){
t = readIn();
if(t){
t = fun();
}
printf("%s\n", ans[t]);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
78
]
]
]
|
dc3000b3edd88c0fa331562f2cab55a2c4d8470d | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/packages/dContainers/dRefCounter.h | 38d23be16bf86ca410ac9bf6b7a608e2a7f6b5d9 | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 676 | h | /* Copyright (c) <2009> <Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely
*/
#ifndef __DREF_COUNTER_H__
#define __DREF_COUNTER_H__
class dRefCounter
{
public:
dRefCounter(void);
int GetRef() const;
int Release();
void AddRef() const;
protected:
virtual ~dRefCounter(void);
private:
mutable int m_refCount;
};
#endif | [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
32
]
]
]
|
e26490dc1c4684d1109a6dff40c30438f68952fb | d1382634d6e81672de95920a5a4bc8c275f1d512 | /NESOverFixUI/NESOverFixUI/NESOverFixUI.cpp | b61c5acb0f587bcd55373e8dc9b23315c1a0350d | []
| no_license | sinsinpub/nesoverfix | c963541918585ce499f1f1fe6e0b4ffbd7cad6e3 | ae2c0221915601d9a4737cc9a21339cdbe57de30 | refs/heads/master | 2021-01-10T03:20:05.336152 | 2007-11-23T01:38:47 | 2007-11-23T01:38:47 | 36,711,087 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 609 | cpp | // NESOverFixUI.cpp: 主项目文件。
#include "stdafx.h"
#include "frmDialog.h"
using namespace NESOverFixUI;
const unsigned long MaxRomFile = 4096;
//unsigned long RomFileCnt;
//array<System::String^> ^RomFileName[MaxRomFile];
//unsigned long RomFileSize[MaxRomFile];
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// 在创建任何控件之前启用 Windows XP 可视化效果
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// 创建主窗口并运行它
Application::Run(gcnew frmMainDlg());
return 0;
}
| [
"sinsinpub@2981e236-803f-0410-ade4-ab5c7a4432ec"
]
| [
[
[
1,
25
]
]
]
|
ae203fafbd0a43160f91852fed5931ab00de427e | 58ef4939342d5253f6fcb372c56513055d589eb8 | /SimulateMessage/Client/source/Views/inc/MainScreenContainer.h | 7d5894af0713378d336415ac87108e3d0ebff0f6 | []
| 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,873 | h | /*
============================================================================
Name : MainScreenContainer.h
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CMainScreenContainer declaration
============================================================================
*/
#ifndef MAINSCREENCONTAINER_H
#define MAINSCREENCONTAINER_H
// INCLUDES
#include <e32std.h>
#include <e32base.h>
#include <coecntrl.h>
#include <eikclb.h>
#include <eikfrlb.h>
#include "SimMsgStruct.h"
// CLASS DECLARATION
/**
* CMainScreenContainer
*
*/
class CMainScreenContainer : public CCoeControl, MCoeControlObserver
{
public:
// Constructors and destructor
/**
* Destructor.
*/
~CMainScreenContainer();
/**
* Two-phased constructor.
*/
static CMainScreenContainer* NewL(const TRect& aRect);
/**
* Two-phased constructor.
*/
static CMainScreenContainer* NewLC(const TRect& aRect);
private:
/**
* Constructor for performing 1st stage construction
*/
CMainScreenContainer();
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL(const TRect& aRect);
public:
// Functions from base classes
TKeyResponse OfferKeyEventL(const TKeyEvent& aKeyEvent, TEventCode aType);
void RemoveSelectedTask();
void EditSelectedTask();
private:
// Functions from base classes
void SizeChanged();
TInt CountComponentControls() const;
CCoeControl* ComponentControl(TInt aIndex) const;
void Draw(const TRect& aRect) const;
void HandleControlEventL(CCoeControl* aControl, TCoeEvent aEventType);
void UpdateDisplay();
void SetIconsL();
private:
//data
// CEikColumnListBox* iListBox;
CEikFormattedCellListBox* iListBox;
RSimMsgDataArray* iTaskArray;
};
#endif // MAINSCREENCONTAINER_H
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
85
]
]
]
|
f2e8707b61a6563fefbc17a25a8e2fa03f129a83 | 34a68e61a469b94063bc98465557072897a9aa88 | /libraries/gameswf/gameswf_as_classes/as_netstream.cpp | 05e00157c99349622c71eb563b9e1497970419b5 | []
| no_license | CneoC/shinzui | f83bfc9cbd9a05480d5323a21339d83e4d403dd9 | 5a2b79b430b207500766849bd58538e6a4aff2f8 | refs/heads/master | 2020-05-03T11:00:52.671613 | 2010-01-25T00:05:55 | 2010-01-25T00:05:55 | 377,430 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,133 | cpp | // as_netstream.cpp -- Vitaly Alexeev <[email protected]> 2007
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "gameswf/gameswf_as_classes/as_netstream.h"
#include "gameswf/gameswf_render.h"
#include "gameswf/gameswf_function.h"
#include "gameswf/gameswf_root.h"
#include "gameswf/base/tu_timer.h"
#if TU_CONFIG_LINK_TO_FFMPEG == 1
namespace gameswf
{
// it is running in decoder thread
static void netstream_server(void* arg)
{
as_netstream* ns = (as_netstream*) arg;
ns->run();
}
// audio callback is running in sound handler thread
static void audio_streamer(as_object* netstream, Uint8* stream, int len)
{
as_netstream* ns = cast_to<as_netstream>(netstream);
assert(ns);
ns->audio_callback(stream, len);
}
static hash<int, tu_string> s_netstream_event_level;
static hash<int, tu_string> s_netstream_event_code;
as_netstream::as_netstream(player* player):
as_object(player),
m_FormatCtx(NULL),
m_VCodecCtx(NULL),
m_video_stream(NULL),
m_ACodecCtx(NULL),
m_audio_stream(NULL),
m_start_time(0.0f),
m_video_time(0.0f),
m_video_index(-1),
m_audio_index(-1),
m_video_data(NULL),
m_convert_ctx(NULL),
m_status(STOP),
m_seek_time(-1.0f),
m_buffer_time(0.1f) // The default value is 0.1 second
{
// fill static hash once
if (s_netstream_event_level.size() == 0)
{
s_netstream_event_level.add(status, "status");
s_netstream_event_level.add(error, "error");
}
if (s_netstream_event_code.size() == 0)
{
s_netstream_event_code.add(playStreamNotFound, "NetStream.Play.StreamNotFound");
s_netstream_event_code.add(playStart, "NetStream.Play.Start");
s_netstream_event_code.add(playStop, "NetStream.Play.Stop");
s_netstream_event_code.add(seekNotify, "NetStream.Seek.Notify");
s_netstream_event_code.add(seekInvalidTime, "NetStream.Seek.InvalidTime");
s_netstream_event_code.add(bufferEmpty, "NetStream.Buffer.Empty");
s_netstream_event_code.add(bufferFull, "NetStream.Buffer.Full");
}
av_register_all();
}
as_netstream::~as_netstream()
{
switch (m_status)
{
default:
break;
case PLAY:
m_status = STOP;
m_thread->wait();
break;
case PAUSE:
m_status = STOP;
m_decoder.signal();
m_thread->wait();
break;
}
}
void as_netstream::play(const char* url)
{
switch (m_status)
{
default:
break;
case PAUSE:
m_status = PLAY;
m_decoder.signal();
break;
case STOP:
{
// is path relative ?
tu_string infile = get_player()->get_workdir();
if (strstr(url, ":") || url[0] == '/')
{
infile = "";
}
infile += url;
m_url = infile;
get_root()->add_listener(this);
if (open_stream(m_url.c_str()) == true)
{
sound_handler* sound = get_sound_handler();
if (sound)
{
sound->attach_aux_streamer(audio_streamer, this);
}
m_thread = new tu_thread(netstream_server, this);
}
break;
}
}
}
void as_netstream::close()
{
switch (m_status)
{
default:
break;
case PLAY:
m_status = STOP;
break;
case PAUSE:
m_status = STOP;
m_decoder.signal();
break;
}
}
// seek_time in sec
void as_netstream::seek(double seek_time)
{
switch (m_status)
{
default:
break;
case PLAY:
if (seek_time < 0)
{
seek_time = 0;
}
m_seek_time = seek_time;
break;
case PAUSE:
if (seek_time < 0)
{
seek_time = 0;
}
m_seek_time = seek_time;
m_status = PLAY;
m_decoder.signal();
break;
}
}
// return current time in sec
double as_netstream::now() const
{
return (double) tu_timer::get_ticks() / 1000.0;
}
// it is running in decoder thread
void as_netstream::run()
{
set_status(status, playStart);
m_start_time = now();
m_video_time = 0;
m_status = PLAY;
while (m_status == PLAY || m_status == PAUSE)
{
if (m_status == PAUSE)
{
double paused = now();
m_decoder.wait();
m_start_time += now() - paused;
continue;
}
// seek request
if (m_seek_time >= 0)
{
int64 timestamp = (int64) (m_seek_time * AV_TIME_BASE);
int flags = m_seek_time > m_video_time ? 0 : AVSEEK_FLAG_BACKWARD;
int ret = av_seek_frame(m_FormatCtx, -1, timestamp, flags);
if (ret == 0)
{
m_aq.clear();
m_vq.clear();
m_start_time += m_video_time - m_seek_time;
m_video_time = m_seek_time;
set_status(status, seekNotify);
}
else
{
set_status(error, seekInvalidTime);
}
m_seek_time = -1;
}
if (get_bufferlength() < m_buffer_time)
{
//printf("m_buffer_length=%f, queue_size=%d\n", get_bufferlength(), m_vq.size());
AVPacket pkt;
int rc = av_read_frame(m_FormatCtx, &pkt);
if (rc < 0)
{
if (m_vq.size() == 0)
{
break;
}
}
else
{
if (pkt.stream_index == m_video_index)
{
m_vq.push(new av_packet(pkt));
}
else
if (pkt.stream_index == m_audio_index)
{
if (get_sound_handler())
{
m_aq.push(new av_packet(pkt));
}
}
else
{
continue;
}
}
}
// skip expired video frames
double current_time = now() - m_start_time;
while (current_time >= m_video_time)
{
gc_ptr<av_packet> packet;
if (m_vq.pop(&packet))
{
const AVPacket& pkt = packet->get_packet();
// update video clock with pts, if present
if (pkt.dts > 0)
{
m_video_time = av_q2d(m_video_stream->time_base) * pkt.dts;
}
m_video_time += av_q2d(m_video_stream->codec->time_base); // +frame_delay
set_video_data(decode_video(pkt));
}
else
{
// no packets in queue
// set_status("status", "NetStream.Buffer.Empty");
break;
}
}
// Don't hog the CPU.
// Queues have filled, video frame have shown
// now it is possible and to have a rest
int delay = (int) (1000 * (m_video_time - current_time));
// hack, adjust m_start_time after seek
if (delay > 50)
{
m_start_time -= (m_video_time - current_time);
current_time = now() - m_start_time;
delay = (int) (1000 * (m_video_time - current_time));
}
assert(delay <= 50);
if (delay > 0)
{
if (get_bufferlength() >= m_buffer_time)
{
// set_status("status", "NetStream.Buffer.Full");
tu_timer::sleep(delay);
}
// printf("current_time=%f, video_time=%f, delay=%d\n", current_time, m_video_time, delay);
}
}
sound_handler* sound = get_sound_handler();
if (sound)
{
sound->detach_aux_streamer(this);
}
close_stream();
set_status(status, playStop);
m_status = STOP;
}
// it is running in sound mixer thread
void as_netstream::audio_callback(Uint8* stream, int len)
{
while (len > 0 && m_status == PLAY)
{
// decode sound
if (m_sound == NULL)
{
gc_ptr<av_packet> audio;
if (m_aq.pop(&audio))
{
Sint16* sample;
int size;
decode_audio(audio->get_packet(), &sample, &size);
m_sound = new decoded_sound(sample, size);
continue;
}
break;
}
else
{
int n = m_sound->extract(stream, len);
stream += n;
len -= n;
if (m_sound->size() == 0)
{
m_sound = NULL;
}
}
}
}
void as_netstream::advance(float delta_time)
{
stream_event ev;
while(m_event.pop(&ev))
{
// printf("pop status: %s %s\n", ev.level.c_str(), ev.code.c_str());
// keep this alive during execution!
gc_ptr<as_object> this_ptr(this);
as_value function;
if (get_member("onStatus", &function))
{
gc_ptr<as_object> infoObject = new as_object(get_player());
infoObject->set_member("level", s_netstream_event_level[ev.level].c_str());
infoObject->set_member("code", s_netstream_event_code[ev.code].c_str());
as_environment env(get_player());
env.push(infoObject.get_ptr());
call_method(function, &env, this, 1, env.get_top_index());
}
if (ev.code == playStop || ev.code == playStreamNotFound)
{
get_root()->remove_listener(this);
}
}
}
// it is running in decoder thread
void as_netstream::set_status(netstream_event_level level, netstream_event_code code)
{
// printf("push status: %s %s\n", level, code);
stream_event ev;
ev.level = level;
ev.code = code;
m_event.push(ev);
}
// it is running in decoder thread
void as_netstream::close_stream()
{
set_video_data(NULL);
m_vq.clear();
m_aq.clear();
if (m_VCodecCtx) avcodec_close(m_VCodecCtx);
m_VCodecCtx = NULL;
if (m_ACodecCtx) avcodec_close(m_ACodecCtx);
m_ACodecCtx = NULL;
if (m_FormatCtx) av_close_input_file(m_FormatCtx);
m_FormatCtx = NULL;
if (m_convert_ctx)
{
sws_freeContext(m_convert_ctx);
m_convert_ctx = NULL;
}
}
// it is running in decoder thread
bool as_netstream::open_stream(const char* c_url)
{
// This registers all available file formats and codecs
// with the library so they will be used automatically when
// a file with the corresponding format/codec is opened
// Open video file
// The last three parameters specify the file format, buffer size and format parameters;
// by simply specifying NULL or 0 we ask libavformat to auto-detect the format
// and use a default buffer size
if (av_open_input_file(&m_FormatCtx, c_url, NULL, 0, NULL) != 0)
{
// log_error("Couldn't open file '%s'\n", c_url);
set_status(error, playStreamNotFound);
return false;
}
// Next, we need to retrieve information about the streams contained in the file
// This fills the streams field of the AVFormatContext with valid information
if (av_find_stream_info(m_FormatCtx) < 0)
{
log_error("Couldn't find stream information from '%s'\n", c_url);
return false;
}
// Find the first video & audio stream
m_video_index = -1;
m_audio_index = -1;
for (int i = 0; i < m_FormatCtx->nb_streams; i++)
{
AVCodecContext* enc = m_FormatCtx->streams[i]->codec;
switch (enc->codec_type)
{
default:
break;
case CODEC_TYPE_AUDIO:
if (m_audio_index < 0)
{
m_audio_index = i;
m_audio_stream = m_FormatCtx->streams[i];
}
break;
case CODEC_TYPE_VIDEO:
if (m_video_index < 0)
{
m_video_index = i;
m_video_stream = m_FormatCtx->streams[i];
}
break;
case CODEC_TYPE_DATA:
case CODEC_TYPE_SUBTITLE:
case CODEC_TYPE_UNKNOWN:
break;
}
}
if (m_video_index < 0)
{
log_error("Didn't find a video stream from '%s'\n", c_url);
return false;
}
// Get a pointer to the codec context for the video stream
m_VCodecCtx = m_FormatCtx->streams[m_video_index]->codec;
// Find the decoder for the video stream
AVCodec* pCodec = avcodec_find_decoder(m_VCodecCtx->codec_id);
if (pCodec == NULL)
{
m_VCodecCtx = NULL;
log_error("Decoder not found\n");
return false;
}
// Open codec
if (avcodec_open(m_VCodecCtx, pCodec) < 0)
{
m_VCodecCtx = NULL;
log_error("Could not open codec\n");
return false;
}
if (m_audio_index >= 0 && get_sound_handler() != NULL)
{
// Get a pointer to the audio codec context for the video stream
m_ACodecCtx = m_FormatCtx->streams[m_audio_index]->codec;
// Find the decoder for the audio stream
AVCodec* pACodec = avcodec_find_decoder(m_ACodecCtx->codec_id);
if (pACodec == NULL)
{
log_error("No available AUDIO decoder to process MPEG file: '%s'\n", c_url);
return false;
}
// Open codec
if (avcodec_open(m_ACodecCtx, pACodec) < 0)
{
log_error("Could not open AUDIO codec\n");
return false;
}
}
m_convert_ctx = sws_getContext(
m_VCodecCtx->width, m_VCodecCtx->height, m_VCodecCtx->pix_fmt,
m_VCodecCtx->width, m_VCodecCtx->height, PIX_FMT_RGBA32,
SWS_BICUBIC, NULL, NULL, NULL);
assert(m_convert_ctx);
return true;
}
// it is running in sound mixer thread
bool as_netstream::decode_audio(const AVPacket& pkt, Sint16** data, int* size)
{
bool ok = false;
int frame_size;
Uint8* decoder_buf = (Uint8*) malloc((AVCODEC_MAX_AUDIO_FRAME_SIZE * 3) / 2);
if (avcodec_decode_audio(m_ACodecCtx, (Sint16*) decoder_buf, &frame_size, pkt.data, pkt.size) >= 0)
{
sound_handler* sh = get_sound_handler();
if (sh)
{
sh->cvt(data, size, decoder_buf, frame_size, m_ACodecCtx->channels, m_ACodecCtx->sample_rate);
ok = true;
}
}
free(decoder_buf);
return ok;
}
// it is running in decoder thread
Uint8* as_netstream::decode_video(const AVPacket& pkt)
{
int got = 0;
AVFrame frame;
avcodec_decode_video(m_VCodecCtx, &frame, &got, pkt.data, pkt.size);
if (got)
{
// get buf for rgba picture
// will be freed later in update_video()
int size = avpicture_get_size(PIX_FMT_RGBA32, m_VCodecCtx->width, m_VCodecCtx->height);
Uint8* data = (Uint8*) malloc(size);
AVPicture picture1;
avpicture_fill(&picture1, data, PIX_FMT_RGBA32, m_VCodecCtx->width, m_VCodecCtx->height);
sws_scale(m_convert_ctx, frame.data, frame.linesize, 0, 0,
picture1.data, picture1.linesize);
return data;
}
return NULL;
}
int as_netstream::get_width() const
{
if (m_VCodecCtx)
{
return m_VCodecCtx->width;
}
return 0;
}
int as_netstream::get_height() const
{
if (m_VCodecCtx)
{
return m_VCodecCtx->height;
}
return 0;
}
// pass video data in video_stream_instance()
Uint8* as_netstream::get_video_data()
{
tu_autolock locker(m_lock_video);
Uint8* video_data = m_video_data;
m_video_data = NULL;
return video_data;
}
void as_netstream::set_video_data(Uint8* data)
{
tu_autolock locker(m_lock_video);
if (m_video_data)
{
free(m_video_data);
}
m_video_data = data;
}
double as_netstream::get_duration() const
{
return (double) m_FormatCtx->duration / 1000000;
}
double as_netstream::get_bufferlength()
{
if (m_video_stream != NULL)
{
// hack,
// TODO: take account of PTS (presentaion time stamp)
return m_vq.size() * av_q2d(m_video_stream->codec->time_base); // frame_delay
}
return 0;
}
void netstream_close(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
ns->close();
}
// flag:Boolean [optional] - A Boolean value specifying whether to pause play (true) or resume play (false).
// If you omit this parameter, NetStream.pause() acts as a toggle: the first time it is called on a specified stream,
// it pauses play, and the next time it is called, it resumes play.
void netstream_pause(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
if (fn.nargs > 0)
{
bool pause = fn.arg(0).to_bool();
if (pause == false && ns->m_status == as_netstream::PAUSE) // play
{
ns->play(NULL);
}
else
if (pause == true && ns->m_status == as_netstream::PLAY) // pause
{
ns->m_status = as_netstream::PAUSE;
}
}
else
{
// toggle mode
if (ns->m_status == as_netstream::PAUSE) // play
{
ns->play(NULL);
}
else
if (ns->m_status == as_netstream::PLAY) // pause
{
ns->m_status = as_netstream::PAUSE;
}
}
}
void netstream_play(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
if (fn.nargs < 1)
{
log_error("NetStream play needs args\n");
return;
}
ns->play(fn.arg(0).to_tu_string());
}
// Seeks the keyframe closest to the specified number of seconds from the beginning
// of the stream.
void netstream_seek(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
if (fn.nargs < 1)
{
log_error("NetStream seek needs args\n");
return;
}
ns->seek(fn.arg(0).to_number());
}
// public setBufferTime(bufferTime:Number) : Void
// bufferTime:Number - The number of seconds of data to be buffered before
// Flash begins displaying data.
// The default value is 0.1 (one-tenth of a second).
void netstream_setbuffertime(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
if (fn.nargs < 1)
{
log_error("setBufferTime needs args\n");
return;
}
ns->set_buffertime(fn.arg(0).to_number());
}
void netstream_time(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
fn.result->set_double(ns->time());
}
void netstream_buffer_length(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
fn.result->set_double(ns->get_bufferlength());
}
void netstream_buffer_time(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
fn.result->set_double(ns->get_buffertime());
}
void netstream_video_width(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
fn.result->set_int(ns->get_width());
}
void netstream_video_height(const fn_call& fn)
{
as_netstream* ns = cast_to<as_netstream>(fn.this_ptr);
assert(ns);
fn.result->set_int(ns->get_height());
}
void as_global_netstream_ctor(const fn_call& fn)
// Constructor for ActionScript class NetStream.
{
as_object* netstream = new as_netstream(fn.get_player());
// properties
netstream->builtin_member("time", as_value(netstream_time, as_value()));
netstream->builtin_member("bufferLength", as_value(netstream_buffer_length, as_value()));
netstream->builtin_member("bufferTime", as_value(netstream_buffer_time, as_value()));
// methods
netstream->builtin_member("close", netstream_close);
netstream->builtin_member("pause", netstream_pause);
netstream->builtin_member("play", netstream_play);
netstream->builtin_member("seek", netstream_seek);
netstream->builtin_member("setbuffertime", netstream_setbuffertime);
// gameswf extension, video width & height
netstream->builtin_member("_width", as_value(netstream_video_width, as_value()));
netstream->builtin_member("_height", as_value(netstream_video_height, as_value()));
fn.result->set_as_object(netstream);
}
} // end of gameswf namespace
#else
#include "gameswf/gameswf_action.h"
#include "gameswf/gameswf_log.h"
namespace gameswf
{
void as_global_netstream_ctor(const fn_call& fn)
{
log_error("video requires FFMPEG library\n");
}
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
802
]
]
]
|
0593d60d598807d2dc9f7d4b32c2f37f972a0b26 | 62c9cb0899bbb36d3e742559831f84054b57d790 | /Test_MMCore_devkit/Test_MMCore_devkit.cpp | 13c249a8996473203b762c6c4ae078126f0928a3 | []
| no_license | astraw/micromanager1.3 | b1a245f676f32bbaf1cda7cecbaaf0a5c661ad6c | 6032a1916442dfd1847bef0ed1d5bd1895334c1d | refs/heads/master | 2020-06-05T02:37:31.526258 | 2009-04-28T16:58:58 | 2009-04-28T16:58:58 | 187,348 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,393 | cpp | ///////////////////////////////////////////////////////////////////////////////
// FILE: Test_MMCore_devkit.cpp
// PROJECT: Micro-Manager
// SUBSYSTEM: Device driver developer's kit
//-----------------------------------------------------------------------------
// DESCRIPTION: Command-line test program for MMCore and device drivers.
// This file is built for Win32 development and may require small
// modifications to compile on Mac or Linux.
//
// AUTHOR: Nenad Amodaj, [email protected], 10/01/2007
//
// COPYRIGHT: University of California, San Francisco, 2007
//
// LICENSE: This file is distributed under the BSD license.
// License text is included with the source distribution.
//
// This file 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.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// CVS: $Id: Test_MMCore.cpp 475 2007-09-27 19:44:59Z nenad $
#include "../MMCore/MMCore.h"
#ifdef WIN32
//#include <windows.h>
#endif
#include <iostream>
#include <iomanip>
#include <assert.h>
#include <string>
using namespace std;
// declaration of test methods
void TestDemoDevices(CMMCore& core);
void TestPixelSize(CMMCore& core);
/**
* Creates MMCore object, loads configuration, prints the status and performs
* a couple of basic tests.
*
* Modify to exercise specific devices in more detail.
*/
int main(int argc, char* argv[])
{
if (argc != 2)
{
cout << "Invalid number of command-line parameters." << endl;
cout << "Usage: Test_MMCore <configuration file name>" << endl;
return 1;
}
try {
// Create CMMCore object
CMMCore core;
// load system configuration
core.loadSystemConfiguration(argv[1]);
core.enableStderrLog(false); // supress console echo of log/debug messages
// print current device status
// (this should work for any configuration)
vector<string> devices = core.getLoadedDevices();
for (size_t i=0; i<devices.size(); i++)
{
cout << devices[i] << endl;
vector<string> props = core.getDevicePropertyNames(devices[i].c_str());
for (size_t j=0; j<props.size(); j++)
{
string val = core.getProperty(devices[i].c_str(), props[j].c_str());
cout << " " << props[j] << "=" << val << endl;
}
}
// add any testing routines here...
// TestDemoDevices is just an example for a testing rountine
// It assumes that specific demo configuration is already loaded
TestDemoDevices(core);
//TestPixelSize(core);
// clean-up before exiting
core.unloadAllDevices();
}
catch (CMMError& err)
{
cout << "Exception: " << err.getMsg() << endl;
cout << "Exiting now." << endl;
return 1;
}
cout << "Test_MMCore ended OK." << endl;
return 0;
}
/**
* Test routine for the MMConfig_Demo.cfg.
* Device names must match
*/
void TestDemoDevices(CMMCore& core)
{
const char* XYStageName = "XY";
const char* wheelName = "Emission";
// Example 1: move filter wheel to state(position) 3
// -------------------------------------------------
core.setState(wheelName, 3);
core.waitForDevice(wheelName);
long state = core.getState(wheelName);
cout << "State device " << wheelName << " in state " << state << endl;
// Example 2: move filter wheel to specific label (must be previously defined)
// ---------------------------------------------------------------------------
core.setStateLabel(wheelName, "Chroma-HQ620");
core.waitForDevice(wheelName);
state = core.getState(wheelName);
string stateLabel = core.getStateLabel(wheelName);
cout << "State device " << wheelName << " in state " << state << ", labeled as " << stateLabel << endl;
// Example 3: move multiple filters at once using one of the predefined configurations
// -----------------------------------------------------------------------------------
core.setConfig("Channel", "DAPI");
core.waitForSystem();
// print current status for all state devices
vector<string> stateDevices = core.getLoadedDevicesOfType(MM::StateDevice);
for (size_t i=0; i<stateDevices.size(); i++)
{
state = core.getState(stateDevices[i].c_str());
stateLabel = core.getStateLabel(stateDevices[i].c_str());
cout << "State device " << stateDevices[i] << " in state " << state << ", labeled as " << stateLabel << endl;
}
// Example 4: snap an image
// ------------------------
core.setExposure(100.0);
core.setProperty("Camera", "PixelType", "8bit");
core.snapImage();
cout << "Image snapped." << endl;
// Example 5: move XYStage
// -----------------------
core.setXYPosition(XYStageName, 0.0, 0.0);
core.waitForDevice(XYStageName);
core.setXYPosition(XYStageName, 10000.0, 10000.0);
core.waitForDevice(XYStageName);
double x,y;
core.getXYPosition(XYStageName, x, y);
cout << "XY position = " << x << "," << y << endl;
}
void TestPixelSize(CMMCore& core)
{
core.definePixelSizeConfig("Resolution10", "Objective", "State", "1");
core.definePixelSizeConfig("Resolution20", "Objective", "State", "3");
core.definePixelSizeConfig("Resolution40", "Objective", "State", "0");
core.setPixelSizeUm("Resolution10", 1.0);
core.setPixelSizeUm("Resolution20", 0.5);
core.setPixelSizeUm("Resolution40", 0.25);
core.setState("Objective", 2);
cout << "Pixel size = " << core.getPixelSizeUm() << " um" << endl;
core.setState("Objective", 1);
cout << "Pixel size = " << core.getPixelSizeUm() << " um" << endl;
core.setState("Objective", 3);
cout << "Pixel size = " << core.getPixelSizeUm() << " um" << endl;
core.setState("Objective", 0);
cout << "Pixel size = " << core.getPixelSizeUm() << " um" << endl;
}
| [
"nenad@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd",
"nico@d0ab736e-dc22-4aeb-8dc9-08def0aa14fd"
]
| [
[
[
1,
107
],
[
109,
184
]
],
[
[
108,
108
]
]
]
|
ece48e7145c321315673a1b8e51f6d3de398caa1 | a84b143f40d9e945b3ee81a2e4522706a381ca85 | /PGR2project/src/Grass.h | a730301543a46889be13652dafe978028b53b1e2 | []
| no_license | kucerad/natureal | ed076b87001104d2817ade8f64a34e1571f53fc8 | afa143975c54d406334dc1ee7af3f8ee26008334 | refs/heads/master | 2021-01-01T05:38:08.139120 | 2011-09-06T07:00:36 | 2011-09-06T07:00:36 | 35,802,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | h | #ifndef _GRASS_H
#define _GRASS_H
#include "Vegetation.h"
class Grass :
public Vegetation
{
public:
Grass(TextureManager *texManager, ShaderManager *shManager);
Grass(Grass* copy);
~Grass(void);
Vegetation* getCopy();
void draw();
void init();
void update(double time);
void bakeToVBO();
v3 transformTexCoords(v3 &origTexCoords);
void fixTexType();
int texPart_x;
int texPart_y;
int textureId;
int shaderId;
Shader* shader;
int textureWaveId;
};
#endif
| [
"kucera.ad@2c66c73b-3297-93fb-03e7-aeb916e281bd",
"[email protected]@2c66c73b-3297-93fb-03e7-aeb916e281bd"
]
| [
[
[
1,
22
],
[
24,
24
],
[
26,
38
]
],
[
[
23,
23
],
[
25,
25
]
]
]
|
bd691ac465599a5809995b7976ed81efb7f8ed6d | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /testLotsOfGuys/src/demo/IdlePlayer.h | 04d443e57c55e528fa20607b7bdcc05a75e75bd4 | [
"MIT"
]
| permissive | TomLeeLive/aras-p-dingus | ed91127790a604e0813cd4704acba742d3485400 | 22ef90c2bf01afd53c0b5b045f4dd0b59fe83009 | refs/heads/master | 2023-04-19T20:45:14.410448 | 2011-10-04T10:51:13 | 2011-10-04T10:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 739 | h | #ifndef __IDLE_PLAYER_H
#define __IDLE_PLAYER_H
class CComplexStuffEntity;
struct IdleConfig {
std::vector<CAnimationBunch*> mAnims;
};
void InitIdleConfig( IdleConfig& cfg );
// --------------------------------------------------------------------------
class IdlePlayer {
public:
IdlePlayer( const IdleConfig& cfg );
~IdlePlayer();
void update( CComplexStuffEntity& character, time_value demoTime );
private:
void startScrollerAnim( CComplexStuffEntity& character );
private:
std::vector<int> mAnimPlayCount;
const IdleConfig* mCfg;
// timing
time_value mStartTime;
time_value mLocalTime; // time since started
float mDefAnimPlayedTime;
float mDefAnimPlayTime;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
39
]
]
]
|
2e18c3cd38b11b22a114dd12304a615e5351a902 | 12ea67a9bd20cbeed3ed839e036187e3d5437504 | /winxgui/VisualWinx/Connect.h | a34fdcb703551c310b72605727f2a943a975dc4a | []
| no_license | cnsuhao/winxgui | e0025edec44b9c93e13a6c2884692da3773f9103 | 348bb48994f56bf55e96e040d561ec25642d0e46 | refs/heads/master | 2021-05-28T21:33:54.407837 | 2008-09-13T19:43:38 | 2008-09-13T19:43:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,907 | h | // Connect.h : Declaration of the CConnect
#pragma once
#include "resource.h" // main symbols
using namespace AddInDesignerObjects;
using namespace Microsoft_VisualStudio_CommandBars;
/// <summary>The object for implementing an Add-in.</summary>
/// <seealso class='IDTExtensibility2' />
class ATL_NO_VTABLE CConnect :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CConnect, &CLSID_Connect>,
public IDispatchImpl<EnvDTE::IDTCommandTarget, &EnvDTE::IID_IDTCommandTarget, &EnvDTE::LIBID_EnvDTE, 7, 0>,
public IDispatchImpl<_IDTExtensibility2, &IID__IDTExtensibility2, &LIBID_AddInDesignerObjects, 1, 0>
{
public:
/// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>
CConnect()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_ADDIN)
DECLARE_NOT_AGGREGATABLE(CConnect)
BEGIN_COM_MAP(CConnect)
COM_INTERFACE_ENTRY(IDTExtensibility2)
COM_INTERFACE_ENTRY(IDTCommandTarget)
COM_INTERFACE_ENTRY2(IDispatch, IDTExtensibility2)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
public:
//IDTExtensibility2 implementation:
/// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
/// <param term='application'>Root object of the host application.</param>
/// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
/// <param term='addInInst'>Object representing this Add-in.</param>
/// <seealso class='IDTExtensibility2' />
STDMETHOD(OnConnection)(IDispatch * Application, ext_ConnectMode ConnectMode, IDispatch *AddInInst, SAFEARRAY **custom);
/// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>
/// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
STDMETHOD(OnDisconnection)(ext_DisconnectMode RemoveMode, SAFEARRAY **custom );
/// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
STDMETHOD(OnAddInsUpdate)(SAFEARRAY **custom );
/// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
STDMETHOD(OnStartupComplete)(SAFEARRAY **custom );
/// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>
/// <param term='custom'>Array of parameters that are host application specific.</param>
/// <seealso class='IDTExtensibility2' />
STDMETHOD(OnBeginShutdown)(SAFEARRAY **custom );
//IDTCommandTarget implementation:
/// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>
/// <param term='commandName'>The name of the command to determine state for.</param>
/// <param term='neededText'>Text that is needed for the command.</param>
/// <param term='status'>The state of the command in the user interface.</param>
/// <param term='commandText'>Text requested by the neededText parameter.</param>
/// <seealso class='Exec' />
STDMETHOD(QueryStatus)(BSTR CmdName, EnvDTE::vsCommandStatusTextWanted NeededText, EnvDTE::vsCommandStatus *StatusOption, VARIANT *CommandText);
/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>
/// <param term='commandName'>The name of the command to execute.</param>
/// <param term='executeOption'>Describes how the command should be run.</param>
/// <param term='varIn'>Parameters passed from the caller to the command handler.</param>
/// <param term='varOut'>Parameters passed from the command handler to the caller.</param>
/// <param term='handled'>Informs the caller if the command was handled or not.</param>
/// <seealso class='Exec' />
STDMETHOD(Exec)(BSTR CmdName, EnvDTE::vsCommandExecOption ExecuteOption, VARIANT *VariantIn, VARIANT *VariantOut, VARIANT_BOOL *Handled);
private:
CComPtr<EnvDTE80::DTE2> m_pDTE;
CComPtr<EnvDTE::AddIn> m_pAddInInstance;
};
OBJECT_ENTRY_AUTO(__uuidof(Connect), CConnect)
| [
"xushiweizh@86f14454-5125-0410-a45d-e989635d7e98"
]
| [
[
[
1,
98
]
]
]
|
2f01c04ffee21ad98308c5c4226a89a275cf252b | fc4946d917dc2ea50798a03981b0274e403eb9b7 | /gentleman/gentleman/WindowsAPICodePack/WindowsAPICodePack/DirectX/DirectX/Direct3D10/D3D10Texture3D.cpp | eb3f2b5906162623d1ebfde30ef53f829c3eb4ed | []
| no_license | midnite8177/phever | f9a55a545322c9aff0c7d0c45be3d3ddd6088c97 | 45529e80ebf707e7299887165821ca360aa1907d | refs/heads/master | 2020-05-16T21:59:24.201346 | 2010-07-12T23:51:53 | 2010-07-12T23:51:53 | 34,965,829 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 933 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
#include "stdafx.h"
#include "D3D10Texture3D.h"
using namespace Microsoft::WindowsAPICodePack::DirectX::Direct3D10;
Texture3DDescription Texture3D::Description::get()
{
Texture3DDescription desc;
pin_ptr<Texture3DDescription> ptr = &desc;
GetInterface<ID3D10Texture3D>()->GetDesc((D3D10_TEXTURE3D_DESC*)ptr);
return desc;
}
MappedTexture3D Texture3D::Map(UInt32 subresourceIndex, D3D10::Map type, MapFlag flags)
{
D3D10_MAPPED_TEXTURE3D texture = {0};
CommonUtils::VerifyResult(GetInterface<ID3D10Texture3D>()->Map(
subresourceIndex,
static_cast<D3D10_MAP>(type),
static_cast<UINT>(flags),
&texture));
return MappedTexture3D(texture);
}
void Texture3D::Unmap(UInt32 subresourceIndex)
{
GetInterface<ID3D10Texture3D>()->Unmap(static_cast<UINT>(subresourceIndex));
}
| [
"lucemia@9e708c16-f4dd-11de-aa3c-59de0406b4f5"
]
| [
[
[
1,
32
]
]
]
|
31e0a208d3cea538f2926c0c362928327d286f65 | ebba8dfe112e93bad2be3551629d632ee4681de9 | /apps/examples/movieGrabberExample/src/testApp.h | a49d7a8aabe94bdeb341f58395b229aa76f9ea8e | []
| no_license | lucasdupin/28blobs | 8499a4c249b5ac4c7731313e0d418dc051610de4 | 5a6dd8a9b084468a38f5045a2367a1dbf6d21609 | refs/heads/master | 2016-08-03T12:27:08.348430 | 2009-06-20T04:39:03 | 2009-06-20T04:39:03 | 219,034 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | h | #ifndef _TEST_APP
#define _TEST_APP
#include "ofMain.h"
class testApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
ofVideoGrabber vidGrabber;
unsigned char * videoInverted;
ofTexture videoTexture;
int camWidth;
int camHeight;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
30
]
]
]
|
aa0a4db4a479ebd2a0c3e8ee7d608cae30cd7e88 | f7d8a85f9d0c1956d64efbe96d056e338b0e0641 | /lib/wxvcl/classes.h | 79da2d0f239ed55dd04fef0a62b320ecdab9570a | []
| no_license | thennequin/dlfm | 6183dfeb485f860396573eda125fd61dcd497660 | 0b122e7042ec3b48660722e2b41ef0a0551a70a9 | refs/heads/master | 2020-04-11T03:53:12.856319 | 2008-07-06T10:17:29 | 2008-07-06T10:17:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,173 | h | /*
Authors : Guru Kathiresan - [email protected] ,
FreePascal Team - http://www.freepascal.org
License :
Short Verion : wxVCL is distributed under Modified LGPL
(the same license used by FCL, LCL). In short,
this license allows you to use wxVCL in your application either
statically or dynamically linked (and keep your source code as
closed source) but you cannot sell wxVCL alone as a seperate
product or claim owner ship for it and when you make a change to
the wxVCL library (not your application code), you have to give
the changes (of the wxVCL library code) back to the community.
Long Version : The source code of wxVCL is distributed under the
Library GNU General Public License with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,
and to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a module
which is not derived from or based on this library. If you modify this
library, you may extend this exception to your version of the library, but you are
not obligated to do so. If you do not wish to do so, delete this exception
statement from your version.
*/
#pragma once
#ifndef ClassesH
#define ClassesH
#include <wx/wx.h>
#include <wx/datetime.h>
#include <wx/arrstr.h>
#include "sysconst.h"
#include "sysutils.h"
#include <vector>
#include <wx/tokenzr.h>
//Data types
typedef std::vector <wxThread*> wxThreadArray;
typedef std::vector <int> wxIntegerArray;
typedef std::vector <wxString> wxStringArray;
typedef std::vector <float> wxFloatArray;
typedef std::vector <double> wxDoubleArray;
typedef std::vector<wxArrayString*> wxArrayOfArrayString;
class TStringList : public wxArrayString
{
public:
TStringList(void);
virtual ~TStringList(void);
void Assign(const wxArrayString &strLst);
void AddStrings(const wxArrayString &strLst);
void SetText(const wxString & strValue);
wxString GetText(void);
bool SaveToFile(const wxString & fileName,bool bStripEmptyLine = false);
bool LoadFromFile(const wxString & fileName);
long Count(void);
void Delete(size_t itemNum);
long IndexOf(const wxString & strName,bool IgnoreCase = false);
void Insert(size_t Pos,const wxString & Value);
void BeginUpdate(void);
void EndUpdate(void);
};
typedef TStringList TStrings ;
wxString StringListToString(const wxArrayString &aryStr);
bool LoadFromFile(const wxString &strFileName,wxArrayString &aryStr);
bool SaveToFile(const wxString &strFileName,const wxArrayString &aryStr);
bool StripEmptyLinesFromStringList(wxArrayString &aryStr);
wxArrayString StringToTokens(const wxString &str1,const wxString &strDelimiter,wxStringTokenizerMode mode = wxTOKEN_RET_EMPTY);
wxString ArrayStringToString(const wxArrayString &aryStr);
#endif//DateUtilsH
| [
"CameleonTH@0c2b0ced-2a4c-0410-b056-e1a948518b24"
]
| [
[
[
1,
80
]
]
]
|
15946bed00f057097cf1d7ef495c0c3dff807acc | d752d83f8bd72d9b280a8c70e28e56e502ef096f | /Libraries/Random/Random.cpp | f285b5b4fe9342dad87d4130a6bc4e3208e83311 | []
| no_license | apoch/epoch-language.old | f87b4512ec6bb5591bc1610e21210e0ed6a82104 | b09701714d556442202fccb92405e6886064f4af | refs/heads/master | 2021-01-10T20:17:56.774468 | 2010-03-07T09:19:02 | 2010-03-07T09:19:02 | 34,307,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,701 | cpp | //
// The Epoch Language Project
// Auxiliary Libraries
//
// Library for working with random numbers
//
#include "stdlib.h"
#include "windows.h"
#include <vector>
#include "Utility/Types/IDTypes.h"
#include "Utility/Types/IntegerTypes.h"
#include "Utility/Types/RealTypes.h"
#include "Marshalling/LibraryImporting.h"
//
// Main entry/exit point for the DLL - initialization and cleanup should be done here
//
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID reserved)
{
if(reason == DLL_PROCESS_ATTACH)
{
// Initialize random number system
srand(::GetTickCount());
}
return TRUE;
}
//
// Callback that is invoked when a program starts running which loads this library.
// Our goal here is to register all of the functions in the library with the Epoch
// virtual machine, so that we can call the library from the program.
//
void __stdcall LinkToEpochVM(RegistrationTable registration, void* bindrecord)
{
std::vector<ParamData> params;
params.push_back(ParamData(L"maximum", VM::EpochVariableType_Integer));
registration.RegisterFunction(L"random", "GetRandomNumber", ¶ms[0], params.size(), VM::EpochVariableType_Integer, VM::EpochVariableType_Error, bindrecord);
}
//-------------------------------------------------------------------------------
// Routines exported by the DLL
//-------------------------------------------------------------------------------
//
// Simple standard C library random number generator
//
Integer32 __stdcall GetRandomNumber(Integer32 maximum)
{
return static_cast<Integer32>(static_cast<Real>(rand()) / static_cast<Real>(RAND_MAX) * static_cast<Real>(maximum));
}
| [
"[email protected]",
"don.apoch@localhost"
]
| [
[
[
1,
42
],
[
44,
59
]
],
[
[
43,
43
]
]
]
|
9fad2dedd4897842232a0538310c5fd1f5a85921 | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/sys/win32/file.cc | b0d009fb611a54fad34924e0c91056beba7b0efd | []
| no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,378 | cc | //
// file.cc for in
//
// Made by texane
// Login <[email protected]>
//
// Started on Sun Jan 22 14:10:39 2006 texane
// Last update Wed Apr 05 14:27:16 2006 texane
//
#include <string>
#include <sys/sysapi.hh>
#include <windows.h>
using std::string;
void sysapi::file::reset_handle(handle_t& file_handle)
{
file_handle = INVALID_HANDLE_VALUE;
}
bool sysapi::file::handle_isset(handle_t& file_handle)
{
return !(file_handle == INVALID_HANDLE_VALUE);
}
sysapi::error::handle_t sysapi::file::open(handle_t& hfile, const std::string& path, omode_t omode)
{
sysapi::error::handle_t herr;
DWORD shmode;
DWORD op_mod;
herr = error::SUCCESS;
shmode = 0;
op_mod = 0;
if (omode & O_READ)
{
op_mod |= GENERIC_READ;
shmode |= FILE_SHARE_READ;
}
if (omode & O_WRITE)
{
op_mod |= GENERIC_WRITE;
shmode |= FILE_SHARE_WRITE;
}
hfile = CreateFile(path.c_str(), op_mod, shmode, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hfile == INVALID_HANDLE_VALUE)
herr = error::OPEN_FAILED;
// herr = GetLastError();
return herr;
}
sysapi::error::handle_t sysapi::file::close(handle_t& hfile)
{
CloseHandle(hfile);
// + reset_handle(hfile);
return error::SUCCESS;
}
sysapi::error::handle_t sysapi::file::remove(const string& nm_file)
{
BOOL is_success;
is_success = DeleteFile(nm_file.c_str());
if (is_success == FALSE)
return error::DELETE_FAILED;
return error::SUCCESS;
}
sysapi::error::handle_t sysapi::file::read(handle_t& hfile, unsigned char* buf, unsigned int nbytes, unsigned int& nread)
{
DWORD nr_bytes;
BOOL ret;
nread = 0;
ret = ReadFile(hfile, static_cast<LPVOID>(buf), nbytes, &nr_bytes, NULL);
if (ret == FALSE)
return error::READ_FAILED;
nread = (unsigned int)nr_bytes;
return error::SUCCESS;
}
sysapi::error::handle_t sysapi::file::read_nonblock(handle_t& hfile, unsigned char* buf, unsigned int nbytes, unsigned int& nread)
{
unsigned char one_buf;
DWORD nr_bytes;
DWORD nr_avail;
BOOL ret;
// are there data pending in the pipe
ret = PeekNamedPipe(hfile, (LPVOID)&one_buf, sizeof(unsigned char), &nr_bytes, &nr_avail, 0);
if (ret == FALSE)
{
return sysapi::error::READ_FAILED;
}
if (nr_bytes == 0)
{
// no data to read
nread = 0;
return sysapi::error::OPERATION_WOULDBLOCK;
}
return sysapi::file::read(hfile, buf, nbytes, nread);
}
sysapi::error::handle_t sysapi::file::write(handle_t& hfile, unsigned char* buf, unsigned int nbytes, unsigned int& nwritten)
{
DWORD nr_bytes;
BOOL ret;
ret = WriteFile(hfile, reinterpret_cast<LPVOID>((void*)buf), nbytes, &nr_bytes, NULL);
if (ret == FALSE)
return error::WRITE_FAILED;
nwritten = nr_bytes;
return error::SUCCESS;
}
sysapi::error::handle_t sysapi::file::size(handle_t& hfile, unsigned long long& sz)
{
BY_HANDLE_FILE_INFORMATION info;
if (GetFileInformationByHandle(hfile, &info) == FALSE)
return error::UNKNOWN;
sz = info.nFileSizeLow;
return error::SUCCESS;
}
// Query about api
// Query informations about a given file
enum file_query
{
DOES_EXIST = 0,
GET_SIZE,
IS_DIRECTORY,
IS_READABLE,
IS_WRITTABLE,
IS_EXECUTABLE
};
static bool normalfile_query_about(const char* filename, enum file_query q, unsigned long* aux)
{
HANDLE hfile;
BY_HANDLE_FILE_INFORMATION info;
bool ret;
ret = false;
hfile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
if (hfile == INVALID_HANDLE_VALUE)
{
return false;
}
if (GetFileInformationByHandle(hfile, &info) == FALSE)
{
CloseHandle(hfile);
return false;
}
switch (q)
{
case DOES_EXIST:
ret = true;
break;
case IS_DIRECTORY:
if (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
ret = true;
break;
case GET_SIZE:
*aux = (unsigned long)info.nFileSizeLow;
ret = true;
break;
case IS_READABLE:
ret = true;
break;
case IS_WRITTABLE:
ret = true;
break;
case IS_EXECUTABLE:
ret = true;
break;
default:
ret = false;
break;
}
CloseHandle(hfile);
return ret;
}
static bool directory_query_about(const char* filename, enum file_query q, unsigned long* aux)
{
return true;
}
static bool file_query_about(const char* filename, enum file_query q, unsigned long* aux)
{
return normalfile_query_about(filename, q, aux);
}
bool sysapi::file::is_path_valid(const string& filename)
{
return file_query_about(filename.c_str(), DOES_EXIST, 0);
}
bool sysapi::file::is_directory(const string& filename)
{
return file_query_about(filename.c_str(), IS_DIRECTORY, 0);
}
bool sysapi::file::is_readable(const string& filename)
{
return file_query_about(filename.c_str(), IS_READABLE, 0);
}
bool sysapi::file::is_writable(const string& filename)
{
return file_query_about(filename.c_str(), IS_WRITTABLE, 0);
}
bool sysapi::file::is_executable(const string& filename)
{
return file_query_about(filename.c_str(), IS_EXECUTABLE, 0);
}
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
245
]
]
]
|
ec24290fb7c67c10f40cec08dd6322c17c807c5a | cd787383f4b4ffad1c6a1d45899ed16a8d12a18a | /CHoboCopyException.cpp | 38aa468c4c857c8c38f8068bd26e731b0732d928 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | brianly/hobocopy | f6d6277203422d0a757459bafa4856e47dab118d | 0450f1551a4df300829723048db0924b69ec7d96 | refs/heads/master | 2020-12-25T13:08:22.457084 | 2011-01-22T00:55:01 | 2011-01-22T00:55:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | cpp | /*
Copyright (c) 2006 Wangdera Corporation ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "stdafx.h"
#include "CHoboCopyException.h" | [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
3fef533b18fdc4ad0dba535d4316637ea010a2ea | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /InfoPaneCreator.h | cb33ab74266f6ae9e03893e6cc0147d5a75ec068 | []
| no_license | outcast1000/Jaangle | 062c7d8d06e058186cb65bdade68a2ad8d5e7e65 | 18feb537068f1f3be6ecaa8a4b663b917c429e3d | refs/heads/master | 2020-04-08T20:04:56.875651 | 2010-12-25T10:44:38 | 2010-12-25T10:44:38 | 19,334,292 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | h | // /*
// *
// * Copyright (C) 2003-2010 Alexandros Economou
// *
// * This file is part of Jaangle (http://www.jaangle.com)
// *
// * 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, 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 GNU Make; see the file COPYING. If not, write to
// * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
// * http://www.gnu.org/copyleft/gpl.html
// *
// */
#pragma once
#include "IPane.h"
class InfoPaneCreator:public IPaneCreator
{
public:
InfoPaneCreator() {}
virtual ~InfoPaneCreator() {}
virtual IPane* CreateInstance();
virtual const PaneInfo& GetPaneInfo();
virtual BOOL IsCreatable() {return TRUE;}
};
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
37
]
]
]
|
4b60d52692c7494d8b70f8c42dc68cbd6cb01b3b | 45c0d7927220c0607531d6a0d7ce49e6399c8785 | /GlobeFactory/src/useful/input_listener.hh | d2bca7606c7787a6ae4084891ea1f04e5d004687 | []
| no_license | wavs/pfe-2011-scia | 74e0fc04e30764ffd34ee7cee3866a26d1beb7e2 | a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a | refs/heads/master | 2021-01-25T07:08:36.552423 | 2011-01-17T20:23:43 | 2011-01-17T20:23:43 | 39,025,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,672 | hh | ////////////////////////////////////////////////////////////////////////////////
// Filename : input_listener.hh
// Authors : Creteur Clement
// Last edit : 01/11/09 - 19h34
// Comment : This listener registers itself on creation time. Then, each time
// the InputManager is updated, it sends the event to the listeners.
// The virtual methods return true if it did something with the
// input.
////////////////////////////////////////////////////////////////////////////////
#ifndef INPUT_LISTENER_HH
#define INPUT_LISTENER_HH
#include <string>
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class KeyboardEvent;
class MouseEvent;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
class InputListener
{
public:
InputListener(unsigned parPriority, const std::string& parName);
virtual ~InputListener();
virtual void OnQuit() {}
virtual bool OnKeyboardEvent(const KeyboardEvent&) {return false;}
virtual bool OnMouseEvent(const MouseEvent&) {return false;}
inline unsigned GetPriority() const {return MPriority;}
inline const std::string& GetName() const {return MName;}
private:
unsigned MPriority;
std::string MName;
};
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
#endif
| [
"creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc"
]
| [
[
[
1,
46
]
]
]
|
06025ea5da4393d84981b0064d9823bef705485b | 453607cc50d8e248e83472e81e8254c5d6997f64 | /packet/include/costbase.h | cf34b08b6403ebcf93efeae6bfef62ae1fa4e53d | []
| no_license | wbooze/test | 9242ba09b65547d422defec34405b843b289053f | 29e20eae9f1c1900bf4bb2433af43c351b9c531e | refs/heads/master | 2016-09-05T11:23:41.471171 | 2011-02-10T10:08:59 | 2011-02-10T10:08:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,606 | h |
#ifndef _COSTBASE_H_
#define _COSTBASE_H_
#include "packnode.h"
/** \file
The documentation in this file is formatted for doxygen
(see www.doxygen.org).
<h4>
Copyright and Use
</h4>
You may use this source code without limitation and without
fee as long as you include:
<blockquote>
This software was written and is copyrighted by Ian Kaplan, Bear
Products International, www.bearcave.com, 2002.
</blockquote>
This software is provided "as is", without any warranty or
claim as to its usefulness. Anyone who uses this source code
uses it at their own risk. Nor is any support provided by
Ian Kaplan and Bear Products International.
Please send any bug fixes or suggested source changes to:
<pre>
[email protected]
</pre>
@author Ian Kaplan
*/
/**
Base class for objects that define costs functions
for the wavelet packet transform.
The costbase base class provides a constructor that is passed the
root of a wavelet packet tree (which is built by packtree.cpp).
The wavelet packet tree is constructed from packnode objects
(which are a subclass of the packdata).
The cost function calculation invoked by the constructor traverses
the wavelet packet tree (top down) and calls costCalc on each node
in the tree. The cost function result is stored in the node. Note
that the cost function also calculates a cost value for the original
data, since in theory the original data may represent the minimal
representation for the data in terms of the cost function.
The pure virtual function costCalc, which calculates the cost
function, must be defined by the subclass.
A description of the cost functions associated with the wavelet
packet transform can be found in Chapter 8 of <i>Ripples in
Mathematics</i> by Jense and la Cour-Harbo.
\author Ian Kaplan
*/
class costbase
{
public:
/** disallow the copy constructor */
costbase( const costbase &rhs ) {}
public:
/**
Recursively traverse the wavelet packet tree and calculate the cost
function.
*/
void traverse( packnode<double> *node )
{
if (node != 0) {
double cost = costCalc( node );
node->cost( cost );
traverse( node->lhsChild() );
traverse( node->rhsChild() );
}
} // traverse
/** Cost function to be defined by the subclass */
virtual double costCalc(packnode<double> *node) = 0;
public:
/** The default constructor does nothing */
costbase() {}
}; // costbase
#endif
| [
"[email protected]"
]
| [
[
[
1,
99
]
]
]
|
661009b866e17b248878c7a3a39a73dd021ebbb7 | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ferrylibs/src/ferry/cv_geometry/RANSAC.cpp | 233301c804b88d45fc38596a64578da9a0dd9b29 | []
| 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 | 25 | cpp | #include ".\ransac.h"
| [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
2
]
]
]
|
ed6fb4de8ed871543e49dee7ad7ea42ee31b53ab | fac8de123987842827a68da1b580f1361926ab67 | /inc/math/HMMatrix4.cpp | 216fe2f76075d85f1e7a644fffb148ab41420b35 | []
| 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 | 21,548 | cpp | #include "math/HMath.h"
namespace hmath
{
const m4 m4::ZERO(
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0 );
const m4 m4::IDENTITY(
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1 );
const m4 m4::CLIPSPACE2DTOIMAGESPACE(
0.5, 0, 0, 0.5,
0, -0.5, 0, 0.5,
0, 0, 1, 0,
0, 0, 0, 1);
//-----------------------------------------------------------------------
inline static f64
MINOR(const m4& m, const size_t r0, const size_t r1, const size_t r2,
const size_t c0, const size_t c1, const size_t c2)
{
return m[r0][c0] * (m[r1][c1] * m[r2][c2] - m[r2][c1] * m[r1][c2]) -
m[r0][c1] * (m[r1][c0] * m[r2][c2] - m[r2][c0] * m[r1][c2]) +
m[r0][c2] * (m[r1][c0] * m[r2][c1] - m[r2][c0] * m[r1][c1]);
}
//-----------------------------------------------------------------------
m4::m4()
{
}
m4::m4(
f64 m00, f64 m01, f64 m02, f64 m03,
f64 m10, f64 m11, f64 m12, f64 m13,
f64 m20, f64 m21, f64 m22, f64 m23,
f64 m30, f64 m31, f64 m32, f64 m33 )
{
val[0][0] = m00;
val[0][1] = m01;
val[0][2] = m02;
val[0][3] = m03;
val[1][0] = m10;
val[1][1] = m11;
val[1][2] = m12;
val[1][3] = m13;
val[2][0] = m20;
val[2][1] = m21;
val[2][2] = m22;
val[2][3] = m23;
val[3][0] = m30;
val[3][1] = m31;
val[3][2] = m32;
val[3][3] = m33;
}
void m4::set( f64 m00, f64 m01, f64 m02, f64 m03,
f64 m10, f64 m11, f64 m12, f64 m13,
f64 m20, f64 m21, f64 m22, f64 m23,
f64 m30, f64 m31, f64 m32, f64 m33 )
{
val[0][0] = m00;
val[0][1] = m01;
val[0][2] = m02;
val[0][3] = m03;
val[1][0] = m10;
val[1][1] = m11;
val[1][2] = m12;
val[1][3] = m13;
val[2][0] = m20;
val[2][1] = m21;
val[2][2] = m22;
val[2][3] = m23;
val[3][0] = m30;
val[3][1] = m31;
val[3][2] = m32;
val[3][3] = m33;
}
m4::m4(const m3& m3x3)
{
operator=(IDENTITY);
operator=(m3x3);
}
m4::m4(const quat& rot)
{
m3 m3x3;
rot.ToRotationMatrix(m3x3);
operator=(IDENTITY);
operator=(m3x3);
}
f64* m4::operator [] ( size_t iRow )
{
assert( iRow < 4 );
return val[iRow];
}
const f64 *const m4::operator [] ( size_t iRow ) const
{
assert( iRow < 4 );
return val[iRow];
}
m4 m4::concatenate(const m4 &m2) const
{
m4 r;
r.val[0][0] = val[0][0] * m2.val[0][0] + val[0][1] * m2.val[1][0] + val[0][2] * m2.val[2][0] + val[0][3] * m2.val[3][0];
r.val[0][1] = val[0][0] * m2.val[0][1] + val[0][1] * m2.val[1][1] + val[0][2] * m2.val[2][1] + val[0][3] * m2.val[3][1];
r.val[0][2] = val[0][0] * m2.val[0][2] + val[0][1] * m2.val[1][2] + val[0][2] * m2.val[2][2] + val[0][3] * m2.val[3][2];
r.val[0][3] = val[0][0] * m2.val[0][3] + val[0][1] * m2.val[1][3] + val[0][2] * m2.val[2][3] + val[0][3] * m2.val[3][3];
r.val[1][0] = val[1][0] * m2.val[0][0] + val[1][1] * m2.val[1][0] + val[1][2] * m2.val[2][0] + val[1][3] * m2.val[3][0];
r.val[1][1] = val[1][0] * m2.val[0][1] + val[1][1] * m2.val[1][1] + val[1][2] * m2.val[2][1] + val[1][3] * m2.val[3][1];
r.val[1][2] = val[1][0] * m2.val[0][2] + val[1][1] * m2.val[1][2] + val[1][2] * m2.val[2][2] + val[1][3] * m2.val[3][2];
r.val[1][3] = val[1][0] * m2.val[0][3] + val[1][1] * m2.val[1][3] + val[1][2] * m2.val[2][3] + val[1][3] * m2.val[3][3];
r.val[2][0] = val[2][0] * m2.val[0][0] + val[2][1] * m2.val[1][0] + val[2][2] * m2.val[2][0] + val[2][3] * m2.val[3][0];
r.val[2][1] = val[2][0] * m2.val[0][1] + val[2][1] * m2.val[1][1] + val[2][2] * m2.val[2][1] + val[2][3] * m2.val[3][1];
r.val[2][2] = val[2][0] * m2.val[0][2] + val[2][1] * m2.val[1][2] + val[2][2] * m2.val[2][2] + val[2][3] * m2.val[3][2];
r.val[2][3] = val[2][0] * m2.val[0][3] + val[2][1] * m2.val[1][3] + val[2][2] * m2.val[2][3] + val[2][3] * m2.val[3][3];
r.val[3][0] = val[3][0] * m2.val[0][0] + val[3][1] * m2.val[1][0] + val[3][2] * m2.val[2][0] + val[3][3] * m2.val[3][0];
r.val[3][1] = val[3][0] * m2.val[0][1] + val[3][1] * m2.val[1][1] + val[3][2] * m2.val[2][1] + val[3][3] * m2.val[3][1];
r.val[3][2] = val[3][0] * m2.val[0][2] + val[3][1] * m2.val[1][2] + val[3][2] * m2.val[2][2] + val[3][3] * m2.val[3][2];
r.val[3][3] = val[3][0] * m2.val[0][3] + val[3][1] * m2.val[1][3] + val[3][2] * m2.val[2][3] + val[3][3] * m2.val[3][3];
return r;
}
m4 m4::operator * ( const m4 &m2 ) const
{
return concatenate( m2 );
}
v3 m4::operator * ( const v3 &v ) const
{
v3 r;
f64 fInvW = 1.0 / ( val[3][0] * v.x + val[3][1] * v.y + val[3][2] * v.z + val[3][3] );
r.x = ( (f32)val[0][0] * v.x + (f32)val[0][1] * v.y + (f32)val[0][2] * v.z + (f32)val[0][3] ) * (f32)fInvW;
r.y = ( (f32)val[1][0] * v.x + (f32)val[1][1] * v.y + (f32)val[1][2] * v.z + (f32)val[1][3] ) * (f32)fInvW;
r.z = ( (f32)val[2][0] * v.x + (f32)val[2][1] * v.y + (f32)val[2][2] * v.z + (f32)val[2][3] ) * (f32)fInvW;
return r;
}
v4 m4::operator * (const v4& v) const
{
return v4(
(f32)val[0][0] * v.x + (f32)val[0][1] * v.y + (f32)val[0][2] * v.z + (f32)val[0][3] * v.w,
(f32)val[1][0] * v.x + (f32)val[1][1] * v.y + (f32)val[1][2] * v.z + (f32)val[1][3] * v.w,
(f32)val[2][0] * v.x + (f32)val[2][1] * v.y + (f32)val[2][2] * v.z + (f32)val[2][3] * v.w,
(f32)val[3][0] * v.x + (f32)val[3][1] * v.y + (f32)val[3][2] * v.z + (f32)val[3][3] * v.w
);
}
m4 m4::operator + ( const m4 &m2 ) const
{
m4 r;
r.val[0][0] = val[0][0] + m2.val[0][0];
r.val[0][1] = val[0][1] + m2.val[0][1];
r.val[0][2] = val[0][2] + m2.val[0][2];
r.val[0][3] = val[0][3] + m2.val[0][3];
r.val[1][0] = val[1][0] + m2.val[1][0];
r.val[1][1] = val[1][1] + m2.val[1][1];
r.val[1][2] = val[1][2] + m2.val[1][2];
r.val[1][3] = val[1][3] + m2.val[1][3];
r.val[2][0] = val[2][0] + m2.val[2][0];
r.val[2][1] = val[2][1] + m2.val[2][1];
r.val[2][2] = val[2][2] + m2.val[2][2];
r.val[2][3] = val[2][3] + m2.val[2][3];
r.val[3][0] = val[3][0] + m2.val[3][0];
r.val[3][1] = val[3][1] + m2.val[3][1];
r.val[3][2] = val[3][2] + m2.val[3][2];
r.val[3][3] = val[3][3] + m2.val[3][3];
return r;
}
m4 m4::operator - ( const m4 &m2 ) const
{
m4 r;
r.val[0][0] = val[0][0] - m2.val[0][0];
r.val[0][1] = val[0][1] - m2.val[0][1];
r.val[0][2] = val[0][2] - m2.val[0][2];
r.val[0][3] = val[0][3] - m2.val[0][3];
r.val[1][0] = val[1][0] - m2.val[1][0];
r.val[1][1] = val[1][1] - m2.val[1][1];
r.val[1][2] = val[1][2] - m2.val[1][2];
r.val[1][3] = val[1][3] - m2.val[1][3];
r.val[2][0] = val[2][0] - m2.val[2][0];
r.val[2][1] = val[2][1] - m2.val[2][1];
r.val[2][2] = val[2][2] - m2.val[2][2];
r.val[2][3] = val[2][3] - m2.val[2][3];
r.val[3][0] = val[3][0] - m2.val[3][0];
r.val[3][1] = val[3][1] - m2.val[3][1];
r.val[3][2] = val[3][2] - m2.val[3][2];
r.val[3][3] = val[3][3] - m2.val[3][3];
return r;
}
bit m4::operator == ( const m4& m2 ) const
{
if(
val[0][0] != m2.val[0][0] || val[0][1] != m2.val[0][1] || val[0][2] != m2.val[0][2] || val[0][3] != m2.val[0][3] ||
val[1][0] != m2.val[1][0] || val[1][1] != m2.val[1][1] || val[1][2] != m2.val[1][2] || val[1][3] != m2.val[1][3] ||
val[2][0] != m2.val[2][0] || val[2][1] != m2.val[2][1] || val[2][2] != m2.val[2][2] || val[2][3] != m2.val[2][3] ||
val[3][0] != m2.val[3][0] || val[3][1] != m2.val[3][1] || val[3][2] != m2.val[3][2] || val[3][3] != m2.val[3][3] )
return false;
return true;
}
bit m4::operator != ( const m4& m2 ) const
{
if(
val[0][0] != m2.val[0][0] || val[0][1] != m2.val[0][1] || val[0][2] != m2.val[0][2] || val[0][3] != m2.val[0][3] ||
val[1][0] != m2.val[1][0] || val[1][1] != m2.val[1][1] || val[1][2] != m2.val[1][2] || val[1][3] != m2.val[1][3] ||
val[2][0] != m2.val[2][0] || val[2][1] != m2.val[2][1] || val[2][2] != m2.val[2][2] || val[2][3] != m2.val[2][3] ||
val[3][0] != m2.val[3][0] || val[3][1] != m2.val[3][1] || val[3][2] != m2.val[3][2] || val[3][3] != m2.val[3][3] )
return true;
return false;
}
void m4::operator = ( const m3& mat3 )
{
val[0][0] = mat3.val[0][0]; val[0][1] = mat3.val[0][1]; val[0][2] = mat3.val[0][2];
val[1][0] = mat3.val[1][0]; val[1][1] = mat3.val[1][1]; val[1][2] = mat3.val[1][2];
val[2][0] = mat3.val[2][0]; val[2][1] = mat3.val[2][1]; val[2][2] = mat3.val[2][2];
}
m4 m4::transpose(void) const
{
return m4(val[0][0], val[1][0], val[2][0], val[3][0],
val[0][1], val[1][1], val[2][1], val[3][1],
val[0][2], val[1][2], val[2][2], val[3][2],
val[0][3], val[1][3], val[2][3], val[3][3]);
}
void m4::setTrans( const v3& v )
{
val[0][3] = v.x;
val[1][3] = v.y;
val[2][3] = v.z;
}
v3 m4::getTrans() const
{
return v3((f32)val[0][3], (f32)val[1][3], (f32)val[2][3]);
}
void m4::makeTrans( const v3& v )
{
val[0][0] = 1.0; val[0][1] = 0.0; val[0][2] = 0.0; val[0][3] = v.x;
val[1][0] = 0.0; val[1][1] = 1.0; val[1][2] = 0.0; val[1][3] = v.y;
val[2][0] = 0.0; val[2][1] = 0.0; val[2][2] = 1.0; val[2][3] = v.z;
val[3][0] = 0.0; val[3][1] = 0.0; val[3][2] = 0.0; val[3][3] = 1.0;
}
void m4::makeTrans( f64 tx, f64 ty, f64 tz )
{
val[0][0] = 1.0; val[0][1] = 0.0; val[0][2] = 0.0; val[0][3] = tx;
val[1][0] = 0.0; val[1][1] = 1.0; val[1][2] = 0.0; val[1][3] = ty;
val[2][0] = 0.0; val[2][1] = 0.0; val[2][2] = 1.0; val[2][3] = tz;
val[3][0] = 0.0; val[3][1] = 0.0; val[3][2] = 0.0; val[3][3] = 1.0;
}
m4 m4::getTrans( const v3& v )
{
m4 r;
r.val[0][0] = 1.0; r.val[0][1] = 0.0; r.val[0][2] = 0.0; r.val[0][3] = v.x;
r.val[1][0] = 0.0; r.val[1][1] = 1.0; r.val[1][2] = 0.0; r.val[1][3] = v.y;
r.val[2][0] = 0.0; r.val[2][1] = 0.0; r.val[2][2] = 1.0; r.val[2][3] = v.z;
r.val[3][0] = 0.0; r.val[3][1] = 0.0; r.val[3][2] = 0.0; r.val[3][3] = 1.0;
return r;
}
m4 m4::getTrans( f64 t_x, f64 t_y, f64 t_z )
{
m4 r;
r.val[0][0] = 1.0; r.val[0][1] = 0.0; r.val[0][2] = 0.0; r.val[0][3] = t_x;
r.val[1][0] = 0.0; r.val[1][1] = 1.0; r.val[1][2] = 0.0; r.val[1][3] = t_y;
r.val[2][0] = 0.0; r.val[2][1] = 0.0; r.val[2][2] = 1.0; r.val[2][3] = t_z;
r.val[3][0] = 0.0; r.val[3][1] = 0.0; r.val[3][2] = 0.0; r.val[3][3] = 1.0;
return r;
}
void m4::setScale( const v3& v )
{
val[0][0] = v.x;
val[1][1] = v.y;
val[2][2] = v.z;
}
m4 m4::getScale( const v3& v )
{
m4 r;
r.val[0][0] = v.x; r.val[0][1] = 0.0; r.val[0][2] = 0.0; r.val[0][3] = 0.0;
r.val[1][0] = 0.0; r.val[1][1] = v.y; r.val[1][2] = 0.0; r.val[1][3] = 0.0;
r.val[2][0] = 0.0; r.val[2][1] = 0.0; r.val[2][2] = v.z; r.val[2][3] = 0.0;
r.val[3][0] = 0.0; r.val[3][1] = 0.0; r.val[3][2] = 0.0; r.val[3][3] = 1.0;
return r;
}
m4 m4::getScale( f64 s_x, f64 s_y, f64 s_z )
{
m4 r;
r.val[0][0] = s_x; r.val[0][1] = 0.0; r.val[0][2] = 0.0; r.val[0][3] = 0.0;
r.val[1][0] = 0.0; r.val[1][1] = s_y; r.val[1][2] = 0.0; r.val[1][3] = 0.0;
r.val[2][0] = 0.0; r.val[2][1] = 0.0; r.val[2][2] = s_z; r.val[2][3] = 0.0;
r.val[3][0] = 0.0; r.val[3][1] = 0.0; r.val[3][2] = 0.0; r.val[3][3] = 1.0;
return r;
}
void m4::extract3x3Matrix(m3& m3x3) const
{
m3x3.val[0][0] = (f32)val[0][0];
m3x3.val[0][1] = (f32)val[0][1];
m3x3.val[0][2] = (f32)val[0][2];
m3x3.val[1][0] = (f32)val[1][0];
m3x3.val[1][1] = (f32)val[1][1];
m3x3.val[1][2] = (f32)val[1][2];
m3x3.val[2][0] = (f32)val[2][0];
m3x3.val[2][1] = (f32)val[2][1];
m3x3.val[2][2] = (f32)val[2][2];
}
quat m4::extractQuaternion() const
{
m3 m3x3;
extract3x3Matrix(m3x3);
return quat(m3x3);
}
m4 m4::operator*(f64 scalar) const
{
return m4(
scalar*val[0][0], scalar*val[0][1], scalar*val[0][2], scalar*val[0][3],
scalar*val[1][0], scalar*val[1][1], scalar*val[1][2], scalar*val[1][3],
scalar*val[2][0], scalar*val[2][1], scalar*val[2][2], scalar*val[2][3],
scalar*val[3][0], scalar*val[3][1], scalar*val[3][2], scalar*val[3][3]);
}
m4 m4::adjoint() const
{
return m4( MINOR(*this, 1, 2, 3, 1, 2, 3),
-MINOR(*this, 0, 2, 3, 1, 2, 3),
MINOR(*this, 0, 1, 3, 1, 2, 3),
-MINOR(*this, 0, 1, 2, 1, 2, 3),
-MINOR(*this, 1, 2, 3, 0, 2, 3),
MINOR(*this, 0, 2, 3, 0, 2, 3),
-MINOR(*this, 0, 1, 3, 0, 2, 3),
MINOR(*this, 0, 1, 2, 0, 2, 3),
MINOR(*this, 1, 2, 3, 0, 1, 3),
-MINOR(*this, 0, 2, 3, 0, 1, 3),
MINOR(*this, 0, 1, 3, 0, 1, 3),
-MINOR(*this, 0, 1, 2, 0, 1, 3),
-MINOR(*this, 1, 2, 3, 0, 1, 2),
MINOR(*this, 0, 2, 3, 0, 1, 2),
-MINOR(*this, 0, 1, 3, 0, 1, 2),
MINOR(*this, 0, 1, 2, 0, 1, 2));
}
//-----------------------------------------------------------------------
f64 m4::determinant() const
{
return val[0][0] * MINOR(*this, 1, 2, 3, 1, 2, 3) -
val[0][1] * MINOR(*this, 1, 2, 3, 0, 2, 3) +
val[0][2] * MINOR(*this, 1, 2, 3, 0, 1, 3) -
val[0][3] * MINOR(*this, 1, 2, 3, 0, 1, 2);
}
//-----------------------------------------------------------------------
m4 m4::inverse() const
{
f64 m00 = val[0][0], m01 = val[0][1], m02 = val[0][2], m03 = val[0][3];
f64 m10 = val[1][0], m11 = val[1][1], m12 = val[1][2], m13 = val[1][3];
f64 m20 = val[2][0], m21 = val[2][1], m22 = val[2][2], m23 = val[2][3];
f64 m30 = val[3][0], m31 = val[3][1], m32 = val[3][2], m33 = val[3][3];
f64 v0 = m20 * m31 - m21 * m30;
f64 v1 = m20 * m32 - m22 * m30;
f64 v2 = m20 * m33 - m23 * m30;
f64 v3 = m21 * m32 - m22 * m31;
f64 v4 = m21 * m33 - m23 * m31;
f64 v5 = m22 * m33 - m23 * m32;
f64 t00 = + (v5 * m11 - v4 * m12 + v3 * m13);
f64 t10 = - (v5 * m10 - v2 * m12 + v1 * m13);
f64 t20 = + (v4 * m10 - v2 * m11 + v0 * m13);
f64 t30 = - (v3 * m10 - v1 * m11 + v0 * m12);
f64 invDet = 1 / (t00 * m00 + t10 * m01 + t20 * m02 + t30 * m03);
f64 d00 = t00 * invDet;
f64 d10 = t10 * invDet;
f64 d20 = t20 * invDet;
f64 d30 = t30 * invDet;
f64 d01 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
f64 d11 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
f64 d21 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
f64 d31 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m10 * m31 - m11 * m30;
v1 = m10 * m32 - m12 * m30;
v2 = m10 * m33 - m13 * m30;
v3 = m11 * m32 - m12 * m31;
v4 = m11 * m33 - m13 * m31;
v5 = m12 * m33 - m13 * m32;
f64 d02 = + (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
f64 d12 = - (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
f64 d22 = + (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
f64 d32 = - (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
v0 = m21 * m10 - m20 * m11;
v1 = m22 * m10 - m20 * m12;
v2 = m23 * m10 - m20 * m13;
v3 = m22 * m11 - m21 * m12;
v4 = m23 * m11 - m21 * m13;
v5 = m23 * m12 - m22 * m13;
f64 d03 = - (v5 * m01 - v4 * m02 + v3 * m03) * invDet;
f64 d13 = + (v5 * m00 - v2 * m02 + v1 * m03) * invDet;
f64 d23 = - (v4 * m00 - v2 * m01 + v0 * m03) * invDet;
f64 d33 = + (v3 * m00 - v1 * m01 + v0 * m02) * invDet;
return m4(
d00, d01, d02, d03,
d10, d11, d12, d13,
d20, d21, d22, d23,
d30, d31, d32, d33);
}
//-----------------------------------------------------------------------
m4 m4::inverseAffine(void) const
{
assert(isAffine());
f64 m10 = val[1][0], m11 = val[1][1], m12 = val[1][2];
f64 m20 = val[2][0], m21 = val[2][1], m22 = val[2][2];
f64 t00 = m22 * m11 - m21 * m12;
f64 t10 = m20 * m12 - m22 * m10;
f64 t20 = m21 * m10 - m20 * m11;
f64 m00 = val[0][0], m01 = val[0][1], m02 = val[0][2];
f64 invDet = 1 / (m00 * t00 + m01 * t10 + m02 * t20);
t00 *= invDet; t10 *= invDet; t20 *= invDet;
m00 *= invDet; m01 *= invDet; m02 *= invDet;
f64 r00 = t00;
f64 r01 = m02 * m21 - m01 * m22;
f64 r02 = m01 * m12 - m02 * m11;
f64 r10 = t10;
f64 r11 = m00 * m22 - m02 * m20;
f64 r12 = m02 * m10 - m00 * m12;
f64 r20 = t20;
f64 r21 = m01 * m20 - m00 * m21;
f64 r22 = m00 * m11 - m01 * m10;
f64 m03 = val[0][3], m13 = val[1][3], m23 = val[2][3];
f64 r03 = - (r00 * m03 + r01 * m13 + r02 * m23);
f64 r13 = - (r10 * m03 + r11 * m13 + r12 * m23);
f64 r23 = - (r20 * m03 + r21 * m13 + r22 * m23);
return m4(
r00, r01, r02, r03,
r10, r11, r12, r13,
r20, r21, r22, r23,
0, 0, 0, 1);
}
//-----------------------------------------------------------------------
void m4::makeTransform(const v3& position, const v3& scale, const quat& orientation)
{
// Ordering:
// 1. Scale
// 2. Rotate
// 3. Translate
m3 rot3x3, scale3x3;
orientation.ToRotationMatrix(rot3x3);
scale3x3 = m3::zero;
scale3x3[0][0] = scale.x;
scale3x3[1][1] = scale.y;
scale3x3[2][2] = scale.z;
// Set up final matrix with scale, rotation and translation
*this = rot3x3 * scale3x3;
this->setTrans(position);
// No projection term
val[3][0] = 0; val[3][1] = 0; val[3][2] = 0; val[3][3] = 1;
}
//-----------------------------------------------------------------------
void m4::makeInverseTransform(const v3& position, const v3& scale, const quat& orientation)
{
// Invert the parameters
v3 invTranslate = -position;
v3 invScale(1 / scale.x, 1 / scale.y, 1 / scale.z);
quat invRot = orientation.inv();
// Because we're inverting, order is translation, rotation, scale
// So make translation relative to scale & rotation
invTranslate *= invScale; // scale
invTranslate = invRot * invTranslate; // rotate
// Next, make a 3x3 rotation matrix and apply inverse scale
m3 rot3x3, scale3x3;
invRot.ToRotationMatrix(rot3x3);
scale3x3 = m3::zero;
scale3x3[0][0] = invScale.x;
scale3x3[1][1] = invScale.y;
scale3x3[2][2] = invScale.z;
// Set up final matrix with scale, rotation and translation
*this = scale3x3 * rot3x3;
this->setTrans(invTranslate);
// No projection term
val[3][0] = 0; val[3][1] = 0; val[3][2] = 0; val[3][3] = 1;
}
bit m4::isAffine(void) const
{
return val[3][0] == 0 && val[3][1] == 0 && val[3][2] == 0 && val[3][3] == 1;
}
m4 m4::concatenateAffine(const m4 &m2) const
{
assert(isAffine() && m2.isAffine());
return m4(
val[0][0] * m2.val[0][0] + val[0][1] * m2.val[1][0] + val[0][2] * m2.val[2][0],
val[0][0] * m2.val[0][1] + val[0][1] * m2.val[1][1] + val[0][2] * m2.val[2][1],
val[0][0] * m2.val[0][2] + val[0][1] * m2.val[1][2] + val[0][2] * m2.val[2][2],
val[0][0] * m2.val[0][3] + val[0][1] * m2.val[1][3] + val[0][2] * m2.val[2][3] + val[0][3],
val[1][0] * m2.val[0][0] + val[1][1] * m2.val[1][0] + val[1][2] * m2.val[2][0],
val[1][0] * m2.val[0][1] + val[1][1] * m2.val[1][1] + val[1][2] * m2.val[2][1],
val[1][0] * m2.val[0][2] + val[1][1] * m2.val[1][2] + val[1][2] * m2.val[2][2],
val[1][0] * m2.val[0][3] + val[1][1] * m2.val[1][3] + val[1][2] * m2.val[2][3] + val[1][3],
val[2][0] * m2.val[0][0] + val[2][1] * m2.val[1][0] + val[2][2] * m2.val[2][0],
val[2][0] * m2.val[0][1] + val[2][1] * m2.val[1][1] + val[2][2] * m2.val[2][1],
val[2][0] * m2.val[0][2] + val[2][1] * m2.val[1][2] + val[2][2] * m2.val[2][2],
val[2][0] * m2.val[0][3] + val[2][1] * m2.val[1][3] + val[2][2] * m2.val[2][3] + val[2][3],
0, 0, 0, 1);
}
v3 m4::transformAffine(const v3& v) const
{
assert(isAffine());
return v3(
(f32)val[0][0] * v.x + (f32)val[0][1] * v.y + (f32)val[0][2] * v.z + (f32)val[0][3],
(f32)val[1][0] * v.x + (f32)val[1][1] * v.y + (f32)val[1][2] * v.z + (f32)val[1][3],
(f32)val[2][0] * v.x + (f32)val[2][1] * v.y + (f32)val[2][2] * v.z + (f32)val[2][3]);
}
v4 m4::transformAffine(const v4& v) const
{
assert(isAffine());
return v4(
(f32)val[0][0] * v.x + (f32)val[0][1] * v.y + (f32)val[0][2] * v.z + (f32)val[0][3] * v.w,
(f32)val[1][0] * v.x + (f32)val[1][1] * v.y + (f32)val[1][2] * v.z + (f32)val[1][3] * v.w,
(f32)val[2][0] * v.x + (f32)val[2][1] * v.y + (f32)val[2][2] * v.z + (f32)val[2][3] * v.w,
v.w);
}
v4 operator * (const v4& v, const m4& mat)
{
return v4(
v.x*(f32)mat[0][0] + v.y*(f32)mat[1][0] + v.z*(f32)mat[2][0] + v.w*(f32)mat[3][0],
v.x*(f32)mat[0][1] + v.y*(f32)mat[1][1] + v.z*(f32)mat[2][1] + v.w*(f32)mat[3][1],
v.x*(f32)mat[0][2] + v.y*(f32)mat[1][2] + v.z*(f32)mat[2][2] + v.w*(f32)mat[3][2],
v.x*(f32)mat[0][3] + v.y*(f32)mat[1][3] + v.z*(f32)mat[2][3] + v.w*(f32)mat[3][3]
);
}
}
| [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
609
]
]
]
|
d8553e4432df1f97ba6f77b66917d978b66eb144 | c04ce4f22fc46c4d44fc425275403592bc6f067a | /wolf/src/game/engine/eWall.cpp | dba2d6b31647f3a37c52a184d5e4c691d24035f1 | []
| no_license | allenh1/wolfenstein-reloaded | 0161953173f053cc1ee4e03555def208ea98a34b | 4db98d1a9e5bf51f88c58d9acae6d7f6850baf1d | refs/heads/master | 2020-04-10T03:30:04.121502 | 2010-07-09T17:14:50 | 2010-07-09T17:14:50 | 32,124,233 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,163 | cpp | /*
**************************************************************************
Wolfenstein Reloaded
Developed by Hunter Allen <[email protected]>
File Description: Wall engine. (Detects collision and stuff)
**************************************************************************
Copyright © 2010 Hunter Allen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************
*/
#include "eWall.h"
/*!
* This function detects collision between the shooter and the wall.
* Runs for only one wall
*/
| [
"hunterallen40@14159fd0-a646-01e2-d422-a234b5f98ae5"
]
| [
[
[
1,
38
]
]
]
|
2dc49a22d86e85ee165b3f227e8d2c2f9877c7b7 | 1cc5720e245ca0d8083b0f12806a5c8b13b5cf98 | /archive/ok/2760/c.cpp | edc3b795820572d4817270defa60487b8cdda12d | []
| no_license | Emerson21/uva-problems | 399d82d93b563e3018921eaff12ca545415fd782 | 3079bdd1cd17087cf54b08c60e2d52dbd0118556 | refs/heads/master | 2021-01-18T09:12:23.069387 | 2010-12-15T00:38:34 | 2010-12-15T00:38:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,844 | cpp |
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
#define FOR(a,b) for(a=0;a<b;a++)
using namespace std;
#define MAXI (110)
int n,p,c,tr;
int target,source;
int fila[MAXI];
int capa[MAXI][MAXI], flux[MAXI][MAXI];
int pai[MAXI];
int min[MAXI];
int resid(int tor, int dest) {
return capa[tor][dest] - flux[tor][dest];
}
int bfs() {
int i,j,atual,ffila, ifila, r;
for(i=0;i<n;i++) {
pai[i]=-1; min[i]= 1 << 30;
}
pai[source] = source;
fila[0]=source;
ifila = 1; ffila = 0;
while(ffila<ifila) {
atual = fila[ffila++];
FOR(i,n) {
r = resid(atual,i);
if(pai[i]==-1 && r>0) {
fila[ifila++] = i;
pai[i] = atual;
min[i] = min[atual];
if(min[i]>r) min[i] = r;
}
}
}
return pai[target] != -1;
}
int main() {
int i,j,l;
long k;
int u,v,z;
while((scanf("%d %d %d %d",&n,&p,&c,&tr))==4) {
source = n; target = n + 1;
n += 2;
FOR(i,n) FOR(j,n) flux[i][j]=capa[i][j]=0;
// evita fluxos coincidentes
FOR(i,tr) {
scanf(" (%d,%d)%d",&u,&v,&z);
// conecta u para v com vazao z
capa[u][v] += z;
}
FOR(l,p) {
scanf(" (%d)%d",&i,&j);
capa[source][i] = j;
// cout << "source: " << i << " com " << j << endl;
}
//cout << c << endl;
FOR(l,c) {
scanf(" (%d)%d",&i,&j);
//cout << "sink: " << i << " com " << j << endl;
capa[i][target] = j;
}
while(1) {
if(bfs()==0) break;
// aumenta o fluxo no caminho
i = target;
k = min[target];
while(pai[i]!=i) {
j = pai[i];
flux[i][j] -= k;
flux[j][i] += k;
i = j;
}
}
k = 0;
for(i=0;i!=n;i++) k += flux[i][target];
cout << k << endl;
}
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
108
]
]
]
|
369481b7e5017328a7493644f681faa7ebc7918e | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/ParticleUniverse/include/ParticleUniverseRendererTokens.h | f4d33f1d884e972dbe943579fb9238bdf23319f9 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,585 | h | /*
-----------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2006-2008 Henry van Merode
Usage of this program is free for non-commercial use and licensed under the
the terms of the GNU Lesser General Public License.
You should have received a copy of the GNU Lesser 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, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
#ifndef __PU_RENDERER_TOKENS_H__
#define __PU_RENDERER_TOKENS_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseITokenInitialiser.h"
namespace ParticleUniverse
{
/** This class contains the tokens that are needed for a Renderer.
*/
class _ParticleUniverseExport ParticleRendererTokens : public ITokenInitialiser
{
protected:
public:
ParticleRendererTokens(void) {};
virtual ~ParticleRendererTokens(void) {};
/** @see
ITokenInitialiser::setupTokenDefinitions
*/
virtual void setupTokenDefinitions(ITokenRegister* tokenRegister);
protected:
// Tokens which get called during parsing.
class RenderQueueGroupToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mRenderQueueGroupToken;
class SortingToken : public IToken {virtual void parse(ParticleScriptParser* parser);} mSortingToken;
};
}
#endif
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
47
]
]
]
|
f6b4765fff0b525af6150e4df1e51d3a75004f3f | 08afd1531b4902e60767855d3bedef18ee46cb13 | /Camera/Prosilica/ProsilicaGigESDK_mac/examples/SampleViewer/src/Seeker.cpp | c128b6021df25e4f23679f80ddc9377a97a0fe74 | []
| no_license | zoccolan/eyetracker | 9482e75580e4e26ae5a2074d82154e313859c1b0 | e648a6acd6230025e422f15b0a3573a5439d5ab4 | refs/heads/master | 2021-01-17T10:22:31.485349 | 2011-05-19T13:33:46 | 2011-05-19T13:33:46 | 1,463,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,701 | cpp | /*
| ==============================================================================
| Copyright (C) 2006-2007 Prosilica. All Rights Reserved.
|
| Redistribution of this header file, in original or modified form, without
| prior written consent of Prosilica is prohibited.
|
|==============================================================================
|
| File: Seeker.cpp
|
| Project/lib: Linux Sample Viewer
|
| Target:
|
| Description: Implements the worker that seek a camera
|
| Notes:
|
|==============================================================================
|
| THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
| WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE,
| NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
| DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 FILES =========================================================
#include <Seeker.h>
#include <PvApi.h>
//===== CLASS IMPLEMENTATION ==================================================
/*
* Method: CSeeker()
* Purpose: constructor
* Comments: none
*/
CSeeker::CSeeker(tInt32 aId,wxEvtHandler* aHandler,tUint32 aAddr)
:PWorker(aId,aHandler) , iAddr(aAddr), iFound(false)
{
}
/*
* Method: ~CSeeker()
* Purpose: destructor
* Comments: none
*/
CSeeker::~CSeeker()
{
}
/*
* Method: OnEntry()
* Purpose: called when the thread is starting
* Comments: none
*/
void CSeeker::OnEntry()
{
NotifyHandler(kEvnSeekerStarted);
}
/*
* Method: OnExit()
* Purpose: called when the thread is terminating
* Comments: none
*/
void CSeeker::OnExit()
{
NotifyHandler(kEvnSeekerFinished,iFound);
}
/*
* Method: OnRunning()
* Purpose: called when the thread is running (body)
* Comments: none
*/
tUint32 CSeeker::OnRunning()
{
tPvCameraInfo Info;
tPvErr lErr;
if((lErr = PvCameraInfoByAddr(iAddr,&Info,NULL)))
iFound = false;
else
iFound = true;
return lErr;
}
| [
"[email protected]"
]
| [
[
[
1,
98
]
]
]
|
ad7d0b436a23614a736d4941b8e6767720a262bd | 7b4c786d4258ce4421b1e7bcca9011d4eeb50083 | /_20090206_代码统计专用文件夹/C++Primer中文版(第4版)/第一章 快速入门/20081217_测试_注释对不可嵌套.cpp | 690478ae637861c2cc746e98228e7594996e635f | []
| no_license | lzq123218/guoyishi-works | dbfa42a3e2d3bd4a984a5681e4335814657551ef | 4e78c8f2e902589c3f06387374024225f52e5a92 | refs/heads/master | 2021-12-04T11:11:32.639076 | 2011-05-30T14:12:43 | 2011-05-30T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 97 | cpp | #include <iostream>
/*
//meiyou
/* */meiyou
int v1,v2;
*/
int main()
{
return 0;
} | [
"baicaibang@70501136-4834-11de-8855-c187e5f49513"
]
| [
[
[
1,
11
]
]
]
|
75eca29c75d56d218f18537ce2f6e09ea4a43890 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/internal/XObjectComparator.cpp | 1cb62a0000cab967acaf0134d5059b869abc8f06 | [
"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 | 36,910 | cpp | /*
* Copyright 2003,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: XObjectComparator.cpp,v $
* Revision 1.8 2004/09/23 00:37:24 cargilld
* Remove unused variable and data member.
*
* Revision 1.7 2004/09/08 13:56:14 peiyongz
* Apache License Version 2.0
*
* Revision 1.6 2004/01/29 11:46:30 cargilld
* Code cleanup changes to get rid of various compiler diagnostic messages.
*
* Revision 1.5 2003/12/17 00:18:34 cargilld
* Update to memory management so that the static memory manager (one used to call Initialize) is only for static data.
*
* Revision 1.4 2003/12/16 18:42:27 knoaman
* fMayMatch is no longer a data member of IC_Field
*
* Revision 1.3 2003/11/12 20:29:05 peiyongz
* removal of fIDRefList
*
* Revision 1.2 2003/10/31 22:15:42 peiyongz
* dumpContent
*
* Revision 1.1 2003/10/29 16:14:15 peiyongz
* XObjectComparator/XTemplateComparator
*
* $Id: XObjectComparator.cpp,v 1.8 2004/09/23 00:37:24 cargilld Exp $
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/XObjectComparator.hpp>
#include <xercesc/internal/XTemplateComparator.hpp>
#include <stdio.h>
XERCES_CPP_NAMESPACE_BEGIN
/**********************************************************
*
* XMLGrammarPool
*
* Grammar
*
* SchemaGrammar
* DTDGrammar
*
***********************************************************/
void XObjectComparator::dumpContent(XMLGrammarPoolImpl* const gramPool)
{
RefHashTableOf<Grammar>* gramReg = gramPool->fGrammarRegistry;
RefHashTableOfEnumerator<Grammar> eNum(gramReg, false, gramPool->getMemoryManager());
int itemNumber = 0;
while (eNum.hasMoreElements())
{
eNum.nextElement();
itemNumber++;
}
printf("itemNumber = <%d>\n", itemNumber);
//Any thing in the lValue shall be found in the rValue
eNum.Reset();
while (eNum.hasMoreElements())
{
XMLCh* key = (XMLCh*) eNum.nextElementKey();
char* keyChar = XMLString::transcode(key);
printf("key=<%s>\n", keyChar);
XMLString::release(&keyChar);
Grammar* data = (Grammar*) gramReg->get(key);
printf("grammarType = <%d>\n", data->getGrammarType());
}
}
bool XObjectComparator::isEquivalent(XMLGrammarPoolImpl* const lValue
, XMLGrammarPoolImpl* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
#ifndef _DEBUG
return (
XTemplateComparator::isEquivalent(lValue->fGrammarRegistry
, rValue->fGrammarRegistry) &&
isEquivalent(lValue->fStringPool, rValue->fStringPool)
);
#else
bool v1 = XTemplateComparator::isEquivalent(lValue->fGrammarRegistry
, rValue->fGrammarRegistry);
bool v2 = isEquivalent(lValue->fStringPool, rValue->fStringPool);
return v1&&v2;
#endif
}
bool XObjectComparator::isEquivalent(Grammar* const lValue
, Grammar* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (lValue->getGrammarType() != rValue->getGrammarType())
return false;
if (lValue->getGrammarType() == Grammar::SchemaGrammarType)
{
return isEquivalent((SchemaGrammar*)lValue, (SchemaGrammar*)rValue);
}
else
{
return isEquivalent((DTDGrammar*)lValue, (DTDGrammar*)rValue);
}
}
bool XObjectComparator::isBaseEquivalent(Grammar* const
, Grammar* const)
{
return true;
}
bool XObjectComparator::isEquivalent(SchemaGrammar* const lValue
, SchemaGrammar* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent(lValue, rValue))
return false;
#ifndef _DEBUG
return (
(lValue->fValidated == rValue->fValidated) &&
XMLString::equals(lValue->fTargetNamespace, rValue->fTargetNamespace) &&
isEquivalent(lValue->fGramDesc, rValue->fGramDesc) &&
isEquivalent(&(lValue->fDatatypeRegistry),
&(rValue->fDatatypeRegistry)) &&
XTemplateComparator::isEquivalent(lValue->fElemDeclPool
, rValue->fElemDeclPool) &&
XTemplateComparator::isEquivalent(lValue->fElemNonDeclPool
, rValue->fElemNonDeclPool) &&
XTemplateComparator::isEquivalent(lValue->fGroupElemDeclPool
, rValue->fGroupElemDeclPool) &&
XTemplateComparator::isEquivalent(lValue->fNotationDeclPool
, rValue->fNotationDeclPool) &&
XTemplateComparator::isEquivalent(lValue->fAttributeDeclRegistry
, rValue->fAttributeDeclRegistry) &&
XTemplateComparator::isEquivalent(lValue->fComplexTypeRegistry
, rValue->fComplexTypeRegistry) &&
XTemplateComparator::isEquivalent(lValue->fGroupInfoRegistry
, rValue->fGroupInfoRegistry) &&
/***
XTemplateComparator::isEquivalent(lValue->fIDRefList
, rValue->fIDRefList) &&
***/
XTemplateComparator::isEquivalent(lValue->fValidSubstitutionGroups
, rValue->fValidSubstitutionGroups)
);
#else
bool v1 = lValue->fValidated == rValue->fValidated;
bool v2 = XMLString::equals(lValue->fTargetNamespace, rValue->fTargetNamespace);
bool v3 = isEquivalent(lValue->fGramDesc, rValue->fGramDesc);
bool v4 = isEquivalent(&(lValue->fDatatypeRegistry), &(rValue->fDatatypeRegistry));
bool v5 = XTemplateComparator::isEquivalent(lValue->fElemDeclPool
, rValue->fElemDeclPool);
bool v6 = XTemplateComparator::isEquivalent(lValue->fElemNonDeclPool
, rValue->fElemNonDeclPool);
bool v7 = XTemplateComparator::isEquivalent(lValue->fGroupElemDeclPool
, rValue->fGroupElemDeclPool) ;
bool v8 = XTemplateComparator::isEquivalent(lValue->fNotationDeclPool
, rValue->fNotationDeclPool);
bool v9 = XTemplateComparator::isEquivalent(lValue->fAttributeDeclRegistry
, rValue->fAttributeDeclRegistry);
bool v10 = XTemplateComparator::isEquivalent(lValue->fComplexTypeRegistry
, rValue->fComplexTypeRegistry);
bool v11 = XTemplateComparator::isEquivalent(lValue->fGroupInfoRegistry
, rValue->fGroupInfoRegistry);
/***
bool v12 = XTemplateComparator::isEquivalent(lValue->fIDRefList
, rValue->fIDRefList);
***/
bool v12 = true;
bool v13 = XTemplateComparator::isEquivalent(lValue->fValidSubstitutionGroups
, rValue->fValidSubstitutionGroups);
return v1&&v2&&v3&&v4&&v5&&v6&&v7&&v8&&v9&&v10&&v11&&v12&&v13;
#endif
}
/**********************************************************
*
* XMLGrammarDescription
*
* XMLSchemaDescription
* XMLDTDDescription
*
***********************************************************/
bool XObjectComparator::isEquivalent(XMLSchemaDescription* const lValue
, XMLSchemaDescription* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return true;
}
bool XObjectComparator::isEquivalent(XMLDTDDescription* const lValue
, XMLDTDDescription* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return true;
}
/**********************************************************
*
* XMLElementDecl
* SchemaElementDecl
* DTDElementDecl
*
***********************************************************/
bool XObjectComparator::isBaseEquivalent(XMLElementDecl* const lValue
, XMLElementDecl* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fCreateReason == rValue->fCreateReason) &&
(lValue->fId == rValue->fId) &&
(lValue->fExternalElement == rValue->fExternalElement) &&
isEquivalent(lValue->getElementName(), rValue->getElementName())
);
}
bool XObjectComparator::isEquivalent(SchemaElementDecl* const lValue
, SchemaElementDecl* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent((XMLElementDecl*)lValue, (XMLElementDecl*)rValue))
return false;
#ifndef _DEBUG
return (
(lValue->fModelType == rValue->fModelType) &&
(lValue->fEnclosingScope == rValue->fEnclosingScope) &&
(lValue->fFinalSet == rValue->fFinalSet) &&
(lValue->fBlockSet == rValue->fBlockSet) &&
(lValue->fMiscFlags == rValue->fMiscFlags) &&
(lValue->fValidity == rValue->fValidity) &&
(lValue->fValidation == rValue->fValidation) &&
(lValue->fSeenValidation == rValue->fSeenValidation) &&
(lValue->fSeenNoValidation == rValue->fSeenNoValidation) &&
(lValue->fHadContent == rValue->fHadContent) &&
XMLString::equals(lValue->fDefaultValue
, rValue->fDefaultValue) &&
isEquivalent(lValue->fDatatypeValidator
, rValue->fDatatypeValidator) &&
isEquivalent((DatatypeValidator*) lValue->fXsiSimpleTypeInfo
, (DatatypeValidator*) rValue->fXsiSimpleTypeInfo) &&
isEquivalent(lValue->fComplexTypeInfo
, rValue->fComplexTypeInfo) &&
isEquivalent(lValue->fXsiComplexTypeInfo
, rValue->fXsiComplexTypeInfo) &&
isEquivalent(lValue->fAttWildCard
, rValue->fAttWildCard) &&
isEquivalent(lValue->fSubstitutionGroupElem
, rValue->fSubstitutionGroupElem) &&
XTemplateComparator::isEquivalent(lValue->fAttDefs
, rValue->fAttDefs) &&
XTemplateComparator::isEquivalent(lValue->fIdentityConstraints
, rValue->fIdentityConstraints)
);
#else
bool v1 = lValue->fModelType == rValue->fModelType;
bool v2 = lValue->fEnclosingScope == rValue->fEnclosingScope;
bool v3 = lValue->fFinalSet == rValue->fFinalSet;
bool v4 = lValue->fBlockSet == rValue->fBlockSet;
bool v5 = lValue->fMiscFlags == rValue->fMiscFlags;
bool v6 = lValue->fValidity == rValue->fValidity;
bool v7 = lValue->fValidation == rValue->fValidation;
bool v8 = lValue->fSeenValidation == rValue->fSeenValidation;
bool v9 = lValue->fSeenNoValidation == rValue->fSeenNoValidation;
bool v10 = lValue->fHadContent == rValue->fHadContent;
bool v11 = XMLString::equals(lValue->fDefaultValue
, rValue->fDefaultValue);
bool v12 = isEquivalent(lValue->fDatatypeValidator
, rValue->fDatatypeValidator);
bool v13 = isEquivalent((DatatypeValidator*) lValue->fXsiSimpleTypeInfo
, (DatatypeValidator*) rValue->fXsiSimpleTypeInfo);
bool v14 = isEquivalent(lValue->fComplexTypeInfo
, rValue->fComplexTypeInfo);
bool v15 = isEquivalent(lValue->fXsiComplexTypeInfo
, rValue->fXsiComplexTypeInfo);
bool v16 = isEquivalent(lValue->fAttWildCard
, rValue->fAttWildCard);
bool v17 = isEquivalent(lValue->fSubstitutionGroupElem
, rValue->fSubstitutionGroupElem);
bool v18 = XTemplateComparator::isEquivalent(lValue->fAttDefs
, rValue->fAttDefs);
bool v19 = XTemplateComparator::isEquivalent(lValue->fIdentityConstraints
, rValue->fIdentityConstraints);
return v1&&v2&&v3&&v4&&v5&&v6&&v7&&v8&&v9&&v10&&v11&&v12&&v13&&v14&&v15&&v16&&v17&&v18&&v19;
#endif
}
bool XObjectComparator::isEquivalent(DTDElementDecl* const lValue
, DTDElementDecl* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent((XMLElementDecl*)lValue, (XMLElementDecl*)rValue))
return false;
//don't compare
//XMLContentModel* fContentModel;
//XMLCh* fFormattedModel;
return (
(lValue->fModelType == rValue->fModelType) &&
isEquivalent(lValue->fContentSpec
, rValue->fContentSpec) &&
isEquivalent(lValue->fAttList
, rValue->fAttList) &&
XTemplateComparator::isEquivalent(lValue->fAttDefs
, rValue->fAttDefs)
);
}
/**********************************************************
* XMLAttDef
* SchemaAttDef
* DTDAttDef
*
***********************************************************/
bool XObjectComparator::isBaseEquivalent(XMLAttDef* const lValue
, XMLAttDef* const rValue)
{
return (
(lValue->fDefaultType == rValue->fDefaultType) &&
(lValue->fType == rValue->fType) &&
(lValue->fCreateReason == rValue->fCreateReason) &&
(lValue->fProvided == rValue->fProvided) &&
(lValue->fExternalAttribute == rValue->fExternalAttribute) &&
(lValue->fId == rValue->fId) &&
XMLString::equals(lValue->fValue, rValue->fValue) &&
XMLString::equals(lValue->fEnumeration, rValue->fEnumeration)
);
}
bool XObjectComparator::isEquivalent(SchemaAttDef* const lValue
, SchemaAttDef* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent((XMLAttDef*)lValue, (XMLAttDef*)rValue))
return false;
return (
(lValue->fValidity == rValue->fValidity) &&
(lValue->fValidation == rValue->fValidation) &&
(lValue->fElemId == rValue->fElemId) &&
isEquivalent(lValue->fAttName, rValue->fAttName) &&
isEquivalent(lValue->fDatatypeValidator
, rValue->fDatatypeValidator) &&
isEquivalent(lValue->fAnyDatatypeValidator
, rValue->fAnyDatatypeValidator) &&
isEquivalent((DatatypeValidator*) lValue->fAnyDatatypeValidator
, (DatatypeValidator*) rValue->fAnyDatatypeValidator) &&
XTemplateComparator::isEquivalent(lValue->fNamespaceList
, rValue->fNamespaceList)
);
}
bool XObjectComparator::isEquivalent(DTDAttDef* const lValue
, DTDAttDef* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent((XMLAttDef*)lValue, (XMLAttDef*)rValue))
return false;
return (
(lValue->fElemId == rValue->fElemId) &&
XMLString::equals(lValue->fName, rValue->fName)
);
}
/**********************************************************
* XMLAttDefList
* SchemaAttDefList
* DTDAttDefList
*
***********************************************************/
bool XObjectComparator::isBaseEquivalent(XMLAttDefList* const lValue
, XMLAttDefList* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return true;
}
bool XObjectComparator::isEquivalent(SchemaAttDefList* const lValue
, SchemaAttDefList* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
//no base comparision needed
return XTemplateComparator::isEquivalent(lValue->fList, rValue->fList);
}
bool XObjectComparator::isEquivalent(DTDAttDefList* const lValue
, DTDAttDefList* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
//no base comparision needed
return XTemplateComparator::isEquivalent(lValue->fList, rValue->fList);
}
/**********************************************************
* XMLEntityDecl
* DTDEntityDecl
*
***********************************************************/
bool XObjectComparator::isBaseEquivalent(XMLEntityDecl* const lValue
, XMLEntityDecl* const rValue )
{
return (
(lValue->fId == rValue->fId) &&
(lValue->fValueLen == rValue->fValueLen) &&
XMLString::equals(lValue->fValue
, rValue->fValue) &&
XMLString::equals(lValue->fName
, rValue->fName) &&
XMLString::equals(lValue->fNotationName
, rValue->fNotationName) &&
XMLString::equals(lValue->fPublicId
, rValue->fPublicId) &&
XMLString::equals(lValue->fSystemId
, rValue->fSystemId) &&
XMLString::equals(lValue->fBaseURI
, rValue->fBaseURI)
);
}
bool XObjectComparator::isEquivalent(DTDEntityDecl* const lValue
, DTDEntityDecl* const rValue )
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent((XMLEntityDecl*)lValue, (XMLEntityDecl*)rValue))
return false;
return (
(lValue->fDeclaredInIntSubset == rValue->fDeclaredInIntSubset) &&
(lValue->fIsParameter == rValue->fIsParameter) &&
(lValue->fIsSpecialChar == rValue->fIsSpecialChar)
);
}
/**********************************************************
* XMLNotationDecl
*
* XMLEntityDecl
*
* ComplexTypeInfo
* XercesGroupInfo
* XercesAttGroupInfo
***********************************************************/
bool XObjectComparator::isEquivalent(XMLNotationDecl* const lValue
, XMLNotationDecl* const rValue )
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fId == rValue->fId) &&
XMLString::equals(lValue->fName , rValue->fName) &&
XMLString::equals(lValue->fPublicId, rValue->fPublicId) &&
XMLString::equals(lValue->fSystemId, rValue->fSystemId) &&
XMLString::equals(lValue->fBaseURI, rValue->fBaseURI)
);
}
bool XObjectComparator::isEquivalent(ComplexTypeInfo* const lValue
, ComplexTypeInfo* const rValue )
{
/***
don't compare
XMLContentModel* fContentModel;
XMLCh* fFormattedModel;
XSDLocator* fLocator;
*
* fContentSpecOrgURI: start of the array
* fContentSpecOrgURISize: size of the array
* fUniqueURI: the current last element in the array
***/
IS_EQUIVALENT(lValue, rValue)
#ifndef _DEBUG
return (
(lValue->fAnonymous == rValue->fAnonymous) &&
(lValue->fAbstract == rValue->fAbstract) &&
(lValue->fAdoptContentSpec == rValue->fAdoptContentSpec) &&
(lValue->fAttWithTypeId == rValue->fAttWithTypeId) &&
(lValue->fPreprocessed == rValue->fPreprocessed) &&
(lValue->fDerivedBy == rValue->fDerivedBy) &&
(lValue->fBlockSet == rValue->fBlockSet) &&
(lValue->fFinalSet == rValue->fFinalSet) &&
(lValue->fScopeDefined == rValue->fScopeDefined) &&
(lValue->fElementId == rValue->fElementId) &&
(lValue->fContentType == rValue->fContentType) &&
XMLString::equals(lValue->fTypeName, rValue->fTypeName) &&
XMLString::equals(lValue->fTypeLocalName, rValue->fTypeLocalName) &&
XMLString::equals(lValue->fTypeUri, rValue->fTypeUri) &&
isEquivalent(lValue->fBaseDatatypeValidator
, rValue->fBaseDatatypeValidator) &&
isEquivalent(lValue->fDatatypeValidator
, rValue->fDatatypeValidator) &&
isEquivalent(lValue->fBaseComplexTypeInfo
, rValue->fBaseComplexTypeInfo) &&
isEquivalent(lValue->fContentSpec
, rValue->fContentSpec) &&
isEquivalent(lValue->fAttWildCard
, rValue->fAttWildCard) &&
isEquivalent(lValue->fAttList
, rValue->fAttList) &&
XTemplateComparator::isEquivalent(lValue->fElements
, rValue->fElements) &&
XTemplateComparator::isEquivalent(lValue->fAttDefs
, rValue->fAttDefs)
);
#else
bool v1 = lValue->fAnonymous == rValue->fAnonymous;
bool v2 = lValue->fAbstract == rValue->fAbstract;
bool v3 = lValue->fAdoptContentSpec == rValue->fAdoptContentSpec;
bool v4 = lValue->fAttWithTypeId == rValue->fAttWithTypeId;
bool v5 = lValue->fPreprocessed == rValue->fPreprocessed;
bool v6 = lValue->fDerivedBy == rValue->fDerivedBy;
bool v7 = lValue->fBlockSet == rValue->fBlockSet;
bool v8 = lValue->fFinalSet == rValue->fFinalSet;
bool v9 = lValue->fScopeDefined == rValue->fScopeDefined;
bool v10 = lValue->fElementId == rValue->fElementId;
bool v11 = lValue->fContentType == rValue->fContentType;
bool v12 = XMLString::equals(lValue->fTypeName
, rValue->fTypeName);
bool v13 = XMLString::equals(lValue->fTypeLocalName
, rValue->fTypeLocalName);
bool v14 = XMLString::equals(lValue->fTypeUri
, rValue->fTypeUri);
bool v15 = isEquivalent(lValue->fBaseDatatypeValidator
, rValue->fBaseDatatypeValidator);
bool v16 = isEquivalent(lValue->fDatatypeValidator
, rValue->fDatatypeValidator);
bool v17 = isEquivalent(lValue->fBaseComplexTypeInfo
, rValue->fBaseComplexTypeInfo);
bool v18 = isEquivalent(lValue->fContentSpec
, rValue->fContentSpec);
bool v19 = isEquivalent(lValue->fAttWildCard
, rValue->fAttWildCard);
bool v20 = isEquivalent(lValue->fAttList
, rValue->fAttList);
bool v21 = XTemplateComparator::isEquivalent(lValue->fElements
, rValue->fElements);
bool v22 = XTemplateComparator::isEquivalent(lValue->fAttDefs
, rValue->fAttDefs);
return v1&&v2&&v3&&v4&&v5&&v6&&v7&&v8&&v9&&v10&&v11&&v12&&v13&&v14&&v15&&v16&&v17&&v18&&v19&&v20&&v21&&v22;
#endif
}
bool XObjectComparator::isEquivalent(XercesGroupInfo* const lValue
, XercesGroupInfo* const rValue )
{
IS_EQUIVALENT(lValue, rValue)
// don't compare
// XSDLocator* fLocator;
return (
(lValue->fCheckElementConsistency == rValue->fCheckElementConsistency) &&
(lValue->fScope == rValue->fScope) &&
isEquivalent(lValue->fContentSpec
, rValue->fContentSpec) &&
isEquivalent(lValue->fBaseGroup
, rValue->fBaseGroup) &&
XTemplateComparator::isEquivalent(lValue->fElements
, rValue->fElements)
);
}
bool XObjectComparator::isEquivalent(XercesAttGroupInfo* const lValue
, XercesAttGroupInfo* const rValue )
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fTypeWithId == rValue->fTypeWithId) &&
isEquivalent(lValue->fCompleteWildCard
, rValue->fCompleteWildCard) &&
XTemplateComparator::isEquivalent(lValue->fAttributes
, rValue->fAttributes) &&
XTemplateComparator::isEquivalent(lValue->fAnyAttributes
, rValue->fAnyAttributes)
);
}
/**********************************************************
*
* DatatypeValidator
*
*
* DatatypeValidatorFactory
*
***********************************************************/
bool XObjectComparator::isEquivalent(DatatypeValidator* const lValue
, DatatypeValidator* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (lValue->getType() != rValue->getType())
{
return false;
}
//todo
//to call individual isEquivalent according to the actual type
//
return true;
}
bool XObjectComparator::isBaseEquivalent(DatatypeValidator* const lValue
, DatatypeValidator* const rValue)
{
//todo
return true;
}
bool XObjectComparator::isEquivalent(DatatypeValidatorFactory* const lValue
, DatatypeValidatorFactory* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return XTemplateComparator::isEquivalent(lValue->fUserDefinedRegistry
, rValue->fUserDefinedRegistry);
}
/**********************************************************
*
* ContentSpecNode
* QName
* KVStringPair
* XMLRefInfo
* StringPool
*
***********************************************************/
bool XObjectComparator::isEquivalent(ContentSpecNode* const lValue
, ContentSpecNode* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fType == rValue->fType) &&
(lValue->fAdoptFirst == rValue->fAdoptFirst) &&
(lValue->fAdoptSecond == rValue->fAdoptSecond) &&
(lValue->fMinOccurs == rValue->fMinOccurs) &&
(lValue->fMaxOccurs == rValue->fMaxOccurs) &&
isEquivalent(lValue->fElement, rValue->fElement) &&
isEquivalent(lValue->fFirst, rValue->fFirst) &&
isEquivalent(lValue->fSecond, rValue->fSecond)
);
}
bool XObjectComparator::isEquivalent(QName* const lValue
, QName* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (XMLString::equals(lValue->fPrefix, rValue->fPrefix) &&
XMLString::equals(lValue->fLocalPart, rValue->fLocalPart) &&
(lValue->fURIId == rValue->fURIId)
);
}
bool XObjectComparator::isEquivalent(KVStringPair* const lValue
, KVStringPair* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (XMLString::equals(lValue->fKey, rValue->fKey) &&
XMLString::equals(lValue->fValue, rValue->fValue)
);
}
bool XObjectComparator::isEquivalent(XMLRefInfo* const lValue
, XMLRefInfo* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fDeclared == rValue->fDeclared) &&
(lValue->fUsed == rValue->fUsed) &&
XMLString::equals(lValue->fRefName, rValue->fRefName)
);
}
bool XObjectComparator::isEquivalent(XMLStringPool* const lValue
, XMLStringPool* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (lValue->getStringCount() != rValue->getStringCount())
return false;
for (unsigned int i = 1; i < lValue->getStringCount(); i++)
{
if (!XMLString::equals(lValue->getValueForId(i), rValue->getValueForId(i)))
return false;
}
return true;
}
/**********************************************************
*
* XercesNodeTest
* XercesStep
* XercesLocationPath
* XercesXPath
*
***********************************************************/
bool XObjectComparator::isEquivalent(XercesNodeTest* const lValue
, XercesNodeTest* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fType == rValue->fType) &&
isEquivalent(lValue->fName, rValue->fName)
);
}
bool XObjectComparator::isEquivalent(XercesStep* const lValue
, XercesStep* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fAxisType == rValue->fAxisType) &&
isEquivalent(lValue->fNodeTest, rValue->fNodeTest)
);
}
bool XObjectComparator::isEquivalent(XercesLocationPath* const lValue
, XercesLocationPath* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
XTemplateComparator::isEquivalent(lValue->fSteps, rValue->fSteps)
);
}
bool XObjectComparator::isEquivalent(XercesXPath* const lValue
, XercesXPath* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
(lValue->fEmptyNamespaceId == rValue->fEmptyNamespaceId) &&
XMLString::equals(lValue->fExpression
, rValue->fExpression) &&
XTemplateComparator::isEquivalent(lValue->fLocationPaths
, rValue->fLocationPaths)
);
}
/**********************************************************
*
* IC_Field
* IC_Select
*
* IdentityConstraint
* IC_Key
* IC_KeyRef
* IC_Unique
*
*
***********************************************************/
bool XObjectComparator::isEquivalent(IC_Field* const lValue
, IC_Field* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
isEquivalent(lValue->fXPath
, rValue->fXPath) &&
isEquivalent(lValue->fIdentityConstraint
, rValue->fIdentityConstraint)
);
}
bool XObjectComparator::isEquivalent(IC_Selector* const lValue
, IC_Selector* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
return (
isEquivalent(lValue->fXPath
, rValue->fXPath) &&
isEquivalent(lValue->fIdentityConstraint
, rValue->fIdentityConstraint)
);
}
bool XObjectComparator::isEquivalent(IdentityConstraint* const lValue
, IdentityConstraint* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (lValue->getType() != rValue->getType())
{
//throw exception here
return false;
}
switch(lValue->getType())
{
case IdentityConstraint::UNIQUE:
return isEquivalent((IC_Unique*)lValue, (IC_Unique*)rValue);
case IdentityConstraint::KEY:
return isEquivalent((IC_Key*)lValue, (IC_Key*)rValue);
case IdentityConstraint::KEYREF:
return isEquivalent((IC_KeyRef*)lValue, (IC_KeyRef*)rValue);
default:
//throw exception here
return false;
}
}
bool XObjectComparator::isBaseEquivalent(IdentityConstraint* const lValue
, IdentityConstraint* const rValue)
{
return (
XMLString::equals(lValue->fIdentityConstraintName
, rValue->fIdentityConstraintName) &&
XMLString::equals(lValue->fElemName
, rValue->fElemName) &&
isEquivalent(lValue->fSelector, rValue->fSelector) &&
XTemplateComparator::isEquivalent(lValue->fFields
, rValue->fFields)
);
}
bool XObjectComparator::isEquivalent(IC_Key* const lValue
, IC_Key* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent(lValue, rValue))
return false;
// no data
return true;
}
bool XObjectComparator::isEquivalent(IC_KeyRef* const lValue
, IC_KeyRef* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent(lValue, rValue))
return false;
return isEquivalent(lValue->fKey, rValue->fKey);
}
bool XObjectComparator::isEquivalent(IC_Unique* const lValue
, IC_Unique* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
if (!isBaseEquivalent(lValue, rValue))
return false;
// no data
return true;
}
/**********************************************************
* XMLNumber
* XMLDouble
* XMLFloat
* XMLBigDecimal
* XMLDateTime
*
***********************************************************/
bool XObjectComparator::isEquivalent(XMLNumber* const lValue
, XMLNumber* const rValue)
{
IS_EQUIVALENT(lValue, rValue)
//to do, to introduce numberType later
return true;
}
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
969
]
]
]
|
32df17821f0d1b1714f218e09289650f4ddbdf5e | e06c28b396351593f75722bcd5b57ca7a6004868 | /ext/OutBuffer.h | 6d69a83fed75141e2b53cb36687c9e1ae09c2fc2 | []
| no_license | taf2/ruby-lzma | 5c78c403bde88d49527ee41a28c6045dfd94e971 | edd53fed204c6a05956d69396974665ce1246189 | refs/heads/master | 2020-12-25T03:20:24.879180 | 2010-02-23T02:53:15 | 2010-02-23T02:53:15 | 531,285 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,282 | h | // OutBuffer.h
#ifndef __OUTBUFFER_H
#define __OUTBUFFER_H
#include "IStream.h"
#include "MyCom.h"
#ifndef _NO_EXCEPTIONS
struct COutBufferException
{
HRESULT ErrorCode;
COutBufferException(HRESULT errorCode): ErrorCode(errorCode) {}
};
#endif
class COutBuffer
{
protected:
Byte *_buffer;
UInt32 _pos;
UInt32 _limitPos;
UInt32 _streamPos;
UInt32 _bufferSize;
CMyComPtr<ISequentialOutStream> _stream;
UInt64 _processedSize;
Byte *_buffer2;
bool _overDict;
HRESULT FlushPart();
void FlushWithCheck();
public:
#ifdef _NO_EXCEPTIONS
HRESULT ErrorCode;
#endif
COutBuffer(): _buffer(0), _pos(0), _stream(0), _buffer2(0) {}
~COutBuffer() { Free(); }
bool Create(UInt32 bufferSize);
void Free();
void SetMemStream(Byte *buffer) { _buffer2 = buffer; }
void SetStream(ISequentialOutStream *stream);
void Init();
HRESULT Flush();
void ReleaseStream() { _stream.Release(); }
void WriteByte(Byte b)
{
_buffer[_pos++] = b;
if(_pos == _limitPos)
FlushWithCheck();
}
void WriteBytes(const void *data, size_t size)
{
for (size_t i = 0; i < size; i++)
WriteByte(((const Byte *)data)[i]);
}
UInt64 GetProcessedSize() const;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
d14b06299464f18004519b0831e1af0f4dc5b5c9 | 6dac9369d44799e368d866638433fbd17873dcf7 | /a.i.wars/src/trunk/SimpleTank/botdll.cpp | 985ccae323afc281c9453a7952988ff430fb33d2 | []
| no_license | christhomas/fusionengine | 286b33f2c6a7df785398ffbe7eea1c367e512b8d | 95422685027bb19986ba64c612049faa5899690e | refs/heads/master | 2020-04-05T22:52:07.491706 | 2006-10-24T11:21:28 | 2006-10-24T11:21:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | cpp | // TemplateBot.cpp : Defines the entry point for the DLL application.
//
#include "BotDLL.h"
#include <windows.h>
BOOL APIENTRY DllMain( HANDLE hModule,DWORD ul_reason_for_call,LPVOID lpReserved)
{
return TRUE;
}
TEMPLATEBOT_API ClientBot * CreateBot(char *name,GameServer *server,int key)
{
return new SimpleTank(name,server,key);
} | [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
15
]
]
]
|
447ed4ba98cba5688938954ecdfc69e2319316b3 | fac8de123987842827a68da1b580f1361926ab67 | /src/transporter/game/gameScene.h | 3ad54b71db63294283b5bc43cd4961ce1be6703c | []
| 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 | 363 | h | #ifndef GAMESCENE_H
#define GAMESCENE_H
#include "transporter.h"
class GameScene
{
protected : Game* game;
Surface* surface;
CarEntity* car;
public : GameScene();
~GameScene();
virtual bit init(Game* game);
void cleanUp();
GameVisualScene visualWorld;
PhysicsScene physicsWorld;
void createEntities();
};
#endif | [
"uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4"
]
| [
[
[
1,
20
]
]
]
|
5c540fffba0a450bdb79f6f165ccabfbb4c07260 | de98f880e307627d5ce93dcad1397bd4813751dd | /3libs/ut/include/OXTabView.h | a9b6321a8e2197530b9879c533079e8ce4e0e79e | []
| no_license | weimingtom/sls | 7d44391bc0c6ae66f83ddcb6381db9ae97ee0dd8 | d0d1de9c05ecf8bb6e4eda8a260c7a2f711615dd | refs/heads/master | 2021-01-10T22:20:55.638757 | 2011-03-19T06:23:49 | 2011-03-19T06:23:49 | 44,464,621 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 47,182 | h | // ==========================================================================
// Class Specification :
// COXTabViewContainer
// ==========================================================================
// Version: 9.3
// This software along with its related components, documentation and files ("The Libraries")
// is © 1994-2007 The Code Project (1612916 Ontario Limited) and use of The Libraries is
// governed by a software license agreement ("Agreement"). Copies of the Agreement are
// available at The Code Project (www.codeproject.com), as part of the package you downloaded
// to obtain this file, or directly from our office. For a copy of the license governing
// this software, you may contact us at [email protected], or by calling 416-849-8900.
// //////////////////////////////////////////////////////////////////////////
/*
For most applications it's not enough to use only one window to provide its all output.
There are different solutions for this problem like splitters or docking windows.
But they usually have common inconvenience: all windows are shown at the same time.
They take a precious screen space while could be rarely used.
COXShortcutBar control can be used in order to show a number of child windows while
keeping active (fully displayed) only one at a time. But COXShortcutBar was primarily
designed to show icons and have a set of notifications that make sense only while
using such controls as treeview or listview.
Very good example of how the problem could be resolved can be found in Developer Studio
IDE. For instance "Output" window (with "Build", "Debug", "Find in Files..." panes) or
"Result List" window (with "Search", "Lookup", "See Also" and "History" panes). We call
them TabViews.
TabViews can be a good alternative for splitter window when you need to have more than
one view per document. Also TabViews can be used within docking window and used as a
container for associated windows that usually implemented as dialog bars.
So we designed new class that implements TabViews: COXTabViewContainer.
COXTabViewContainer is easy to use. If you previously worked with splitter windows,
the implementation of TabViews will be familiar to you.
Here is the list of steps that should be taken in order to deploy TabViews in
your application:
First Case: COXTabViewContainer will be used as a container for document view(s).
1) Embed a COXTabViewContainer member variable in the parent frame (main frame
window for SDI application, MDIChild window for MDI application).
2) Override the parent frame's CFrameWnd::OnCreateClient member function.
3) From within the overridden OnCreateClient, call the Create member function
of COXTabViewContainer. In this function you have to specify the parent
window and optionally you can specify the initial rectangle, window styles
and window ID.
4) After COXTabViewContainer window was successfully created you can populate
it with window objects using AddPage or InsertPage function. If you are
inserting view object you have to specify runtime class and context
information in order not to break document/view architecture. If you are
adding window object that is not a document view then you have to create
it before adding to COXTabViewContainer window. In AddPage or InsertPage
functions you can specify text that will be used as page title in tab button.
Example:
BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
// TODO: Add your specialized code here and/or call the base class
UNREFERENCED_PARAMETER(lpcs);
if(!m_TabViewContainer.Create(this))
return FALSE;
if(!m_TabViewContainer.AddPage(pContext->m_pNewViewClass,
pContext,_T("Primary View")))
return FALSE;
if(!m_TabViewContainer.AddPage(RUNTIME_CLASS(CMyView2),
pContext,_T("View2")))
return FALSE;
m_TabViewContainer.SetActivePageIndex(0);
return TRUE;
}
Second Case: COXTabViewContainer will be used as a container for windows within
control bar.
1) Create your own CControlBar-derived class (you can use our
COXSizeControlBar as parent class if you need sizable docking windows).
Let's call CMyControlBar.
2) Embed a COXTabViewContainer member variable in this class.
3) Override CMyControlBar::OnCreate member function.
4) From within the overridden OnCreate, call the Create member function
of COXTabViewContainer. In this function you have to specify the parent
window and optionally you can specify the initial rectangle, window styles
and window ID.
5) After COXTabViewContainer window was successfully created you can populate
it with window objects using AddPage or InsertPage function. You have to
create window object before adding it to COXTabViewContainer. In AddPage or
InsertPage functions you can specify text that will be used as page title
in tab button.
6) Override CMyControlBar::OnSize member function and resize in it
COXTabViewContainer object as appropriate
Example:
int CMyControlBar::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (COXSizeControlBar::OnCreate(lpCreateStruct) == -1)
return -1;
if(!m_TabViewContainer.Create(this,rect))
return -1;
// edit control
if(!edit.Create(WS_CHILD|ES_MULTILINE|ES_AUTOHSCROLL|
ES_AUTOVSCROLL|WS_HSCROLL|WS_VSCROLL,CRect(0,0,0,0),
&m_TabViewContainer,1))
return -1;
m_TabViewContainer.AddPage(&edit,_T("Edit"));
// list box
if(!listBox.Create(WS_CHILD|WS_HSCROLL|WS_VSCROLL,
CRect(0,0,0,0),&m_TabViewContainer,2))
return -1;
m_TabViewContainer.AddPage(&listBox,_T("ListBox"));
// list control
if(!listCtrl.Create(WS_CHILD|LVS_REPORT,
CRect(0,0,0,0),&m_TabViewContainer,3))
return -1;
m_TabViewContainer.AddPage(&listCtrl,_T("List"));
// tree control
if(!treeCtrl.Create(WS_CHILD|TVS_HASLINES|TVS_LINESATROOT|TVS_HASBUTTONS,
CRect(0,0,0,0),&m_TabViewContainer,4))
return -1;
m_TabViewContainer.AddPage(&treeCtrl,_T("Tree"));
m_TabViewContainer.SetActivePageIndex(0);
return 0;
}
The most challenging problem was to support scrolling functionality for windows
that would be used as COXTabViewContainer pages. Unfortunately, different windows
object that support scrolling (CEdit, CTreeCtrl, CListBox, CListCtrl, CRichEditCtrl,
CEditView, CTreeView, CListView, CScrollView to name just the standrad ones)
implement it in a different way and anyway the handling of scrolling happens
internally in these objects so in order to control it we should have provided
derivations for all of above mentioned classes. Luckily we managed to resolve this
problem in different way so it doesn't require any efforts from programmer's side.
Actually, the only thing you have to do is to declare the class of window object
that is going to be used as COXTabViewContainer page in a specific way.
If you declare you class as follows:
class CMyView : public CEditView
now you have to do that in the following way:
class CMyView : public COXTabViewPage<CEditView>
or if you don't derive your own class and just use an object of existing one, e.g.:
CEdit m_edit;
instead you have to define it as:
COXTabViewPage<CEdit> m_edit;
COXTabViewPage is internal template based Ultimate Toolbox class that was designed
specifically to provide smooth integration of scrolling functionality for any
window within COXTabViewContainer object. All the details of implementation is hidden
for different type of windows is hidden. There is no any public functions that you
should specifically use.
But there is one limitation. The base class that is used for derivation has to have
default constructor. Some classes doesn't have it (e.g. CFormView). You can resolve
this problem through using intermediate class that will be derived from the one
that doesn't have default constructor and implement it. Then you just derive your
window object class that will be used as COXTabViewContainer page from this
intermediate class. Out of standard only CFormView doesn't have default constructor.
Below you will find the steps that should be taken in order to derive classes from
CFormView class.
1) Use Class Wizard to build CFormView derived class on the base of dialog template
as you usually do (let's call it CMyFormView)
2) CMyFormView will have default constructor which uses CFormView constructor with
dialog ID specified.
3) define another class that will be used as view in your application:
class CMyFormTabView : public COXTabViewPage<CMyFormView>
{
protected: // create from serialization only
DECLARE_DYNCREATE(CMyFormView)
};
The steps that should be taken in order to implement COXTabViewContainer in CControlBar
derived window can be applied in general case too. We just decided to show it using
CControlBar derived window because we feel like it's going to be used as parent window
for COXTabViewContainer in most cases.
Above we described the process of creating and populating of COXTabViewContainer object.
In most cases that would be all the code you need. For those who need to change
dynamically the contents of COXTabViewContainer object we provide a set of the
following functions.
In order to remove any page at run time you have to use DeletePage function.
To access scroll bar objects that we use internally in order to provide scrolling
functionality for COXTabViewContainer pages you have to call GetHorzScrollBar and
GetVertScrollBar functions.
To set/retrieve page title that is displayed in corresponding tab button use
GetPageTitle and SetPageTitle functions.
To set/retrive active page index call GetActivePageIndex and SetActivepageIndex
functions.
Refer to the class reference for list and description of all public functions.
Also take look at the following samples that can be found in .\samples\gui
subdirectory of your ultimate Toolbox directory:
TabViews - text editor with three panes: text editor, hex viewer,
list view with statistics on number of unique symbols
found in text.
Dynamic TabViews - MDI application that shows how to add/remove pages
dynamically
#include "OXTabView.h"
*/
#ifndef _TABVIEW_H
#define _TABVIEW_H
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "OXDllExt.h"
#ifndef __AFXCMN_H__
#include <afxcmn.h>
#define __AFXCMN_H__
#endif
#ifndef __AFXEXT_H__
#include <afxext.h>
#define __AFXEXT_H__
#endif
#ifndef __AFXTEMPL_H__
#include <afxtempl.h>
#define __AFXTEMPL_H__
#endif
#ifndef __AFXPRIV_H__
#include <afxpriv.h>
#define __AFXPRIV_H__
#endif
#ifndef __OXMFCIMPL_H__
#if _MFC_VER < 0x0700
#include <..\src\afximpl.h>
#else
#include <..\src\mfc\afximpl.h>
#endif
#define __OXMFCIMPL_H__
#endif
#ifndef __AFXCVIEW_H__
#include <afxcview.h> // MFC Common controls
#define __AFXCVIEW_H__
#endif
#ifndef __AFXRICH_H__
#include <afxrich.h>
#define __AFXRICH_H__
#endif
#include "UTB64Bit.h"
typedef struct _tagPAGEINFO
{
CWnd* pWnd;
CString sTitle;
BOOL bHasScrollHorz;
BOOL bHasScrollVert;
SCROLLINFO scrlInfoHorz;
SCROLLINFO scrlInfoVert;
// constructor
_tagPAGEINFO()
{
pWnd=NULL;
sTitle=_T("");
bHasScrollHorz=FALSE;
bHasScrollVert=FALSE;
}
// copy constructor
_tagPAGEINFO(const _tagPAGEINFO& pi)
{
ASSERT(pi.pWnd!=NULL);
pWnd=pi.pWnd;
sTitle=pi.sTitle;
bHasScrollHorz=pi.bHasScrollHorz;
bHasScrollVert=pi.bHasScrollVert;
scrlInfoHorz=pi.scrlInfoHorz;
scrlInfoVert=pi.scrlInfoVert;
}
// assignment operator
_tagPAGEINFO& operator=(const _tagPAGEINFO& pi)
{
if(this==&pi)
{
return *this;
}
ASSERT(pi.pWnd!=NULL);
pWnd=pi.pWnd;
sTitle=pi.sTitle;
bHasScrollHorz=pi.bHasScrollHorz;
bHasScrollVert=pi.bHasScrollVert;
scrlInfoHorz=pi.scrlInfoHorz;
scrlInfoVert=pi.scrlInfoVert;
return *this;
}
void GetScrollInfo(CWnd* pWnd, BOOL bHorzScrlBar)
{
ASSERT_VALID(pWnd);
if(bHorzScrlBar)
{
scrlInfoHorz.cbSize=sizeof(SCROLLINFO);
pWnd->GetScrollInfo(SB_HORZ,&scrlInfoHorz);
if(bHasScrollVert)
{
scrlInfoHorz.nMax-=::GetSystemMetrics(SM_CXVSCROLL);
// scrlInfoHorz.nPage-=::GetSystemMetrics(SM_CXVSCROLL);
if(scrlInfoHorz.nPos+(int)scrlInfoHorz.nPage>scrlInfoHorz.nMax)
{
scrlInfoHorz.nPos=scrlInfoHorz.nMax-scrlInfoHorz.nPage;
}
if(scrlInfoHorz.nTrackPos+(int)scrlInfoHorz.nPage>scrlInfoHorz.nMax)
{
scrlInfoHorz.nTrackPos=scrlInfoHorz.nMax-scrlInfoHorz.nPage;
}
}
if(scrlInfoHorz.nMax==0 || scrlInfoHorz.nPage==0)
{
bHasScrollHorz=FALSE;
}
}
else
{
scrlInfoVert.cbSize=sizeof(SCROLLINFO);
pWnd->GetScrollInfo(SB_VERT,&scrlInfoVert);
if(bHasScrollHorz)
{
scrlInfoVert.nMax-=1;
// scrlInfoVert.nPage-=1;
if(scrlInfoVert.nPos+(int)scrlInfoVert.nPage>scrlInfoVert.nMax)
{
scrlInfoVert.nPos=scrlInfoVert.nMax-scrlInfoVert.nPage;
}
if(scrlInfoVert.nTrackPos+(int)scrlInfoVert.nPage>scrlInfoVert.nMax)
{
scrlInfoVert.nTrackPos=scrlInfoVert.nMax-scrlInfoVert.nPage;
}
}
if(scrlInfoVert.nMax==0 || scrlInfoVert.nPage==0)
{
bHasScrollVert=FALSE;
}
}
}
} PAGEINFO;
////////////////////////////////////////////////////////////////////////
#define ID_TABVIEWCONTAINER_SIGN 0x3a7b4567
#define ID_SPLITTERWIDTH 6
#define ID_TABBTNOVERLAPSIZE 5
#define ID_TABBTNGAPSIZE 3
#define ID_MINSCROLLBARWIDTH 60
#define ID_INITABBTNAREAWIDTH 200
#define ID_SCROLLTABBTNAREASTEP 15
#define IDT_SCROLLPAGE_TIMER 122
#define ID_SCROLLPAGE_DELAY 200
#define IDT_CHECKSCROLLINFO_TIMER 123
#define ID_CHECKSCROLLINFO_PERIOD 1000
//////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// COXTabViewContainer window
class OX_CLASS_DECL COXTabViewContainer : public CWnd
{
DECLARE_DYNCREATE(COXTabViewContainer)
// Construction
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Constructs the object
COXTabViewContainer();
// Attributes
public:
typedef enum _tagHITTEST
{
SCROLLBARHORZ=-1,
SCROLLBARVERT=-2,
SCRLSTARTBTN=-3,
SCRLBACKWARDBTN=-4,
SCRLFORWARDBTN=-5,
SCRLENDBTN=-6,
SPLITTER=-7,
PAGE=-8,
TABBTNAREA=-9,
SIZEBAR=-10,
NONE=-11
} HITTEST;
protected:
// rectangle for TabView Container
//
// scroll buttons rectangles
CRect m_rectScrollToStartBtn;
CRect m_rectScrollBackwardBtn;
CRect m_rectScrollForwardBtn;
CRect m_rectScrollToEndBtn;
// tab button area origin
int m_nTabBtnAreaOrigin;
// the rectangle of the area that is covered by tab buttons
CRect m_rectTabBtnArea;
// tab buttons rectangles (coordinates relative to the top/left
// of m_rectTabBtnArea + m_nTabBtnAreaOrigin)
CArray<CRect,CRect&> m_arrTabBtnRects;
// last saved width of tab buttons area
int m_nLastTabBtnAreaWidth;
// scroll bars rectangles
CRect m_rectScrollBarHorz;
CRect m_rectScrollBarVert;
// rect for splitter
CRect m_rectSplitter;
// rect for size bar
CRect m_rectSizeBar;
// rect for page
CRect m_rectPage;
//
/////////////////////////////////////////
/////////////////////////////////////////
// array of pages
CArray<PAGEINFO,PAGEINFO> m_arrPages;
// index of currently active page
int m_nActivePageIndex;
/////////////////////////////////////////
// scroll style of the container (internal)
DWORD m_dwScrollStyle;
// internal array of unique IDs
CArray<DWORD,DWORD> m_arrUniqueIDs;
// scroll bars controls
CScrollBar m_scrlBarHorz;
CScrollBar m_scrlBarVert;
// the ID of last scroll button that was pressed
HITTEST m_nPressedScrlBtn;
// flag that specifies if last pressed scroll button is still pressed
BOOL m_bIsScrlBtnPressed;
// timer for tab buttons scrolling operations
INT_PTR m_nScrollPageTimer;
// flag that specifies that splitter has been pressed
BOOL m_bIsSplitterPressed;
// fonts to draw text in tab buttons
CFont m_fontTabBtnText;
CFont m_fontActiveTabBtnText;
// Operations
public:
// --- In : lpszClassName - ignored
// lpszWindowName - ignored
// dwStyle - The TabView container's style.
// rect - window rectangle
// pParentWnd - Pointer to the window that is the
// TabView container's parent.
// nID - The TabView container's ID.
// pContext - ignored
// --- Out :
// --- Returns: TRUE if TabView container was successfully created,
// or FALSE otherwise
// --- Effect : Creates the TabView container. Implemented in order to
// support dynamic creation of the object.
virtual BOOL Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName,
DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID,
CCreateContext* pContext=NULL);
// --- In : pParentWnd - Pointer to the window that is the
// TabView container's parent.
// rect - window rectangle
// dwStyle - The TabView container's style.
// nID - The TabView container's ID.
// --- Out :
// --- Returns: TRUE if TabView container was successfully created,
// or FALSE otherwise
// --- Effect : Creates the TabView container
virtual BOOL Create(CWnd* pParentWnd, CRect rect=CRect(0,0,0,0),
DWORD dwStyle=WS_CHILD|WS_VISIBLE, UINT nID=AFX_IDW_PANE_FIRST);
// --- In : pClass - pointer to runtime class information of
// the new window to be added as new page
// pContext - pointer to context info (refer to the
// description of CCreateContext class)
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns: TRUE if new page was successfully added, or FALSE otherwise
// --- Effect : Adds new page to TabView container. Use this version of
// function if you have to add CView derived class which is
// part of document/view architecture of your application
inline BOOL AddPage(
CRuntimeClass* pClass, CCreateContext* pContext, LPCTSTR lpszTitle=NULL)
{
return InsertPage(GetPageCount(),pClass,pContext,lpszTitle);
}
// --- In : pWnd - pointer to created window to be added
// as new page
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns: TRUE if new page was successfully added, or FALSE otherwise
// --- Effect : Adds new page to TabView container. Use this version of
// function if you have to add any generic window into the
// TabView container.
inline BOOL AddPage(CWnd* pWnd, LPCTSTR lpszTitle=NULL)
{
return InsertPage(GetPageCount(),pWnd,lpszTitle);
}
// --- In : nIndex - zero-based index of the new page
// pClass - pointer to runtime class information of
// the new window to be added as new page
// pContext - pointer to context info (refer to the
// description of CCreateContext class)
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns: TRUE if new page was successfully inserted, or FALSE otherwise
// --- Effect : Inserts new page to TabView container. Use this version of
// function if you have to insert CView derived class which is
// part of document/view architecture of your application
virtual BOOL InsertPage(int nIndex, CRuntimeClass* pClass,
CCreateContext* pContext, LPCTSTR lpszTitle=NULL);
// --- In : nIndex - zero-based index of the new page
// pWnd - pointer to created window to be inserted
// as new page
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns: TRUE if new page was successfully inserted, or FALSE otherwise
// --- Effect : Inserts new page to TabView container. Use this version of
// function if you have to add any generic window into the
// TabView container.
virtual BOOL InsertPage(int nIndex, CWnd* pWnd, LPCTSTR lpszTitle=NULL);
// --- In : pWnd - pointer to the page to be deleted
// bDestroy - flag that specifies if window has to be
// destroyed
// --- Out :
// --- Returns: TRUE if the specified page was successfully deleted,
// or FALSE otherwise
// --- Effect : Deletes existing page from TabView container.
BOOL DeletePage(CWnd* pWnd, BOOL bDestroy=TRUE);
// --- In : nIndex - zero-based index of the page to be deleted
// bDestroy - flag that specifies if window has to be
// destroyed
// --- Out :
// --- Returns: TRUE if the specified page was successfully deleted,
// or FALSE otherwise
// --- Effect : Deletes existing page from TabView container.
virtual BOOL DeletePage(int nIndex, BOOL bDestroy=TRUE);
// --- In : nIndex - zero-based index of the page to be retrieved
// --- Out :
// --- Returns: pointer to the corresponding page, or NULL if out of range
// index was specified
// --- Effect : Retrieves pointer to the page with specified index
inline CWnd* GetPage(int nIndex) const
{
ASSERT(nIndex>=0 && nIndex<GetPageCount());
if(nIndex>=0 && nIndex<GetPageCount())
{
return m_arrPages[nIndex].pWnd;
}
return NULL;
}
// --- In : pWnd - pointer to the page which title
// is to be retrieved
// --- Out :
// --- Returns: title of the corresponding page
// --- Effect : Retrieves title of the specified page
inline CString GetPageTitle(CWnd* pWnd) const
{
ASSERT(pWnd!=NULL);
if(pWnd==NULL)
{
return _T("");
}
int nIndex=-1;
if(!FindPage(pWnd,nIndex) || nIndex==-1)
{
return _T("");
}
return GetPageTitle(nIndex);
}
// --- In : nIndex - zero-based index of the page which title
// is to be retrieved
// --- Out :
// --- Returns: title of the corresponding page
// --- Effect : Retrieves title of the page with specified index
inline CString GetPageTitle(int nIndex) const
{
ASSERT(nIndex>=0 && nIndex<GetPageCount());
if(nIndex>=0 && nIndex<GetPageCount())
{
return m_arrPages[nIndex].sTitle;
}
return _T("");
}
// --- In : pWnd - pointer to the page which title
// is to be set
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns:
// --- Effect : Sets the title of the specified page
inline BOOL SetPageTitle(CWnd* pWnd, LPCTSTR lpszTitle)
{
ASSERT(pWnd!=NULL);
if(pWnd==NULL)
{
return FALSE;
}
int nIndex=-1;
if(!FindPage(pWnd,nIndex) || nIndex==-1)
{
return FALSE;
}
return SetPageTitle(nIndex,lpszTitle);
}
// --- In : nIndex - zero-based index of the page which title
// is to be set
// lpszTitle - text that will be used as page title in
// tab button
// --- Out :
// --- Returns:
// --- Effect : Sets title of the page with specified index
BOOL SetPageTitle(int nIndex, LPCTSTR lpszTitle);
// --- In :
// --- Out :
// --- Returns: number of pages in the Tab View container
// --- Effect : Retrieves the number of pages in the Tab View container
inline int GetPageCount() const { return PtrToInt(m_arrPages.GetSize()); }
// --- In : pTestWnd - pointer to the window to be tested
// as Tab View container's page
// hTestWnd - handle of the window to be tested
// as Tab View container's page
// --- Out : nIndex - reference to the variable where zero-based
// index of the found page will be saved
// --- Returns: TRUE if specified window is Tab View container's page,
// or FALSE otherwise
// --- Effect : Retrieves the flag that specifies whether the specified
// window is Tab View container's page and if it is TRUE then
// save the index of found page into nIndex
inline BOOL FindPage(CWnd* pTestWnd, int& nIndex) const
{
ASSERT(pTestWnd!=NULL);
if(pTestWnd!=NULL)
{
return FindPage(pTestWnd->m_hWnd,nIndex);
}
return FALSE;
}
inline BOOL FindPage(HWND hTestWnd, int& nIndex) const
{
BOOL bResult=FALSE;
for(nIndex=0; nIndex<GetPageCount(); nIndex++)
{
if(m_arrPages[nIndex].pWnd->m_hWnd==hTestWnd)
{
bResult=TRUE;
break;
}
}
return bResult;
}
// --- In : pTestWnd - pointer to the window to be tested
// as Tab View container's page
// hTestWnd - handle of the window to be tested
// as Tab View container's page
// --- Out :
// --- Returns: TRUE if specified window is Tab View container's page,
// or FALSE otherwise
// --- Effect : Retrieves the flag that specifies whether the specified
// window is Tab View container's page
inline BOOL IsPage(HWND hTestWnd) const
{
int nIndex=-1;
return FindPage(hTestWnd,nIndex);
}
inline BOOL IsPage(CWnd* pTestWnd) const
{
int nIndex=-1;
return FindPage(pTestWnd,nIndex);
}
// --- In : pTestWnd - pointer to the window to be tested as
// currently active Tab View container's page
// hTestWnd - handle of the window to be tested as
// currently active Tab View container's page
// --- Out :
// --- Returns: TRUE if specified window is currently active Tab View
// container's page, or FALSE otherwise
// --- Effect : Retrieves the flag that specifies whether the specified
// window is currently active Tab View container's page
inline BOOL IsActivePage(HWND hTestWnd) const
{
int nIndex=-1;
if(FindPage(hTestWnd,nIndex) && GetActivePageIndex()==nIndex)
{
return TRUE;
}
return FALSE;
}
inline BOOL IsActivePage(CWnd* pTestWnd) const
{
int nIndex=-1;
if(FindPage(pTestWnd,nIndex) && GetActivePageIndex()==nIndex)
{
return TRUE;
}
return FALSE;
}
// --- In :
// --- Out :
// --- Returns: index of currently active Tab View container's page
// --- Effect : Retrieves the index of currently active Tab View
// container's page
inline int GetActivePageIndex() const { return m_nActivePageIndex; }
// --- In :
// --- Out :
// --- Returns: pointer to currently active Tab View container's page
// --- Effect : Retrieves the pointer to currently active Tab View
// container's page
inline CWnd* GetActivePage() const
{
if(m_nActivePageIndex>=0 && m_nActivePageIndex<GetPageCount())
{
return m_arrPages[m_nActivePageIndex].pWnd;
}
return NULL;
}
// --- In : pWnd - pointer to the page to be set as active
// --- Out :
// --- Returns: TRUE is specified page was successfully set as active
// --- Effect : Sets the specified page as active one
inline BOOL SetActivePage(CWnd* pWnd)
{
ASSERT(pWnd!=NULL);
if(pWnd!=NULL)
{
int nIndex=-1;
if(FindPage(pWnd,nIndex))
{
return SetActivePageIndex(nIndex);
}
}
return FALSE;
}
// --- In : nIndex - index of the page to be set as active
// --- Out :
// --- Returns: TRUE is page with specified index was successfully set
// as active
// --- Effect : Sets the page with specified index as active one
virtual BOOL SetActivePageIndex(int nIndex);
// --- In :
// --- Out :
// --- Returns: pointer to the horizontal scroll bar control
// --- Effect : Retrieves pointer to the horizontal scroll bar control
inline CScrollBar* GetHorzScrollBar()
{
if(::IsWindow(m_scrlBarHorz.GetSafeHwnd()))
{
return &m_scrlBarHorz;
}
else
{
return NULL;
}
}
// --- In :
// --- Out :
// --- Returns: pointer to the vertical scroll bar control
// --- Effect : Retrieves pointer to the vertical scroll bar control
inline CScrollBar* GetVertScrollBar()
{
if(::IsWindow(m_scrlBarVert.GetSafeHwnd()))
{
return &m_scrlBarVert;
}
else
{
return NULL;
}
}
// --- In : lpszProfileName - name of hive in registry where
// all information about COXTabViewContainer
// will be saved.
// --- Out :
// --- Returns: TRUE if succeeds, or FALSE otherwise.
// --- Effect : Saves COXTabViewContainer state into registry
virtual BOOL SaveState(LPCTSTR lpszProfileName) ;
// --- In : lpszProfileName - name of hive in registry where
// all information about COXTabViewContainer
// was saved.
// --- Out :
// --- Returns: TRUE if succeeds, or FALSE otherwise.
// --- Effect : Loads COXTabViewContainer state from registry
virtual BOOL LoadState(LPCTSTR lpszProfileName);
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
//}}AFX_VIRTUAL
protected:
// sets the scroll style of the Tab View container.
// dwScrollStyle can be zero or any combination of WS_VSCROLL
// and WS_HSCROLL styles
virtual void SetScrollStyle(DWORD dwScrollStyle, BOOL bForceToRebuild=FALSE);
// retrieves the scroll style of the Tab View container.
// It can be zero or any combination of WS_VSCROLL and WS_HSCROLL styles
inline DWORD GetScrollStyle() const { return m_dwScrollStyle; }
// initialize internal PAGEINFO structure with scroll info for currently
// active page
void IniScrollInfo();
// calculates position of all Tab View container elements
virtual void CalcLayout();
// calculates position of all tab buttons
virtual void CalcTabBtnRects();
// resize scroll bar controls
void UpdateScrollSizes();
// retrieves unique ID for newly added page
virtual DWORD GetUniqueId();
// empties all internal position info of all Tab View container elements
void EmptyRects();
// redraw the specified scroll button.
void RedrawScrollButton(HITTEST hitTest);
// redraw tab buttons area
inline void RedrawTabBtnArea()
{
ASSERT(::IsWindow(GetSafeHwnd()));
RedrawWindow(m_rectTabBtnArea);
}
// redraw splitter
inline void RedrawSplitter()
{
ASSERT(::IsWindow(GetSafeHwnd()));
RedrawWindow(m_rectSplitter);
}
// redraw all Tab View container elements
inline void RedrawContainer()
{
CRect rect=m_rectScrollToStartBtn;
rect.right=m_rectSplitter.right;
RedrawWindow(rect);
RedrawWindow(m_rectSizeBar);
}
// the following virtual routines are responsible for drawing
// corresponding Tab View container elements
virtual void DrawScrollButtons(CDC* pDC);
virtual void DrawTabBtnArea(CDC* pDC);
virtual void DrawSplitter(CDC* pDC);
virtual void DrawSizeBar(CDC* pDC);
/////////////////////////////////////////////////////////////
// draws specified scroll button
virtual void DrawButton(CDC* pDC, CRect rect, HITTEST nButtonType) const;
// draws tab button for the page with specified index
virtual void DrawTabButton(CDC* pDC, int nIndex) const;
// starts handling "move splitter" or "scroll tab buttons" operation
void StartTracking(const CPoint& point);
// stops "move splitter" or "scroll tab buttons" operation
void StopTracking(const CPoint& point);
// the following test functions return the flag that specifies
// if corresponding scroll tab button operation can be accomplished
//
inline BOOL CanScrollToStart() const
{
ASSERT(m_nTabBtnAreaOrigin<=0);
return (m_nTabBtnAreaOrigin<0 &&
m_rectTabBtnArea.right>m_rectTabBtnArea.left);
}
inline BOOL CanScrollBackward() const { return CanScrollToStart(); }
inline BOOL CanScrollForward() const { return CanScrollToEnd(); }
inline BOOL CanScrollToEnd() const
{
ASSERT(m_nTabBtnAreaOrigin<=0);
if(GetPageCount()>0 &&
m_rectTabBtnArea.right>m_rectTabBtnArea.left)
{
ASSERT(GetPageCount()==m_arrTabBtnRects.GetSize());
CRect rect=m_arrTabBtnRects[GetPageCount()-1];
rect+=m_rectTabBtnArea.TopLeft();
return (rect.right+m_nTabBtnAreaOrigin>m_rectTabBtnArea.right);
}
return FALSE;
}
void EnsureTabBtnVisible(int nIndex, BOOL bPartialOk=FALSE);
/////////////////////////////////////////////////////////////////////
// Implementation
public:
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Destructs the object
virtual ~COXTabViewContainer();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Updates scroll info for currently active page
void UpdateScrollInfo();
// --- In :
// --- Out :
// --- Returns:
// --- Effect : Updates scroll state for currently active page
void UpdateScrollState();
// --- In : point - point in Tab View container client coordinates
// to be tested
// --- Out :
// --- Returns: if equals or more than zero then the return value specifies
// the corresponding index of tab button, otherwise it can be
// one of the following value:
//
// SCROLLBARHORZ - horizontal scroll bar control
// SCROLLBARVERT - vertical scroll bar control
// SCRLSTARTBTN - scroll button "scroll to start"
// SCRLBACKWARDBTN - scroll button "scroll backward"
// SCRLFORWARDBTN - scroll button "scroll forward"
// SCRLENDBTN - scroll button "scroll to end"
// SPLITTER - splitter
// PAGE - currently active page
// TABBTNAREA - tab buttons area
// SIZEBAR - sizebar
// NONE - out of Tab View container
//
// --- Effect : Retrieves the element of Tab View container over which
// the specified point is located
int HitTest(const CPoint& point) const;
// --- In : nScrlBtn - scroll button identifier. it can be one
// of the following:
//
// SCRLSTARTBTN - scroll button "scroll to start"
// SCRLBACKWARDBTN - scroll button "scroll backward"
// SCRLFORWARDBTN - scroll button "scroll forward"
// SCRLENDBTN - scroll button "scroll to end"
//
// --- Out :
// --- Returns:
// --- Effect : Scroll tab btn area in the specified direction
void ScrollPage(HITTEST nScrlBtn);
protected:
// special command routing to frame
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
// Generated message map functions
protected:
// overwrite standard handlers to overcome some problems with MFC
// standard painting routine
//{{AFX_MSG(COXTabViewContainer)
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnPaint();
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg BOOL OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnCancelMode();
afx_msg void OnDestroy();
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnSettingChange(UINT uFlags, LPCTSTR lpszSection);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
///////////////////////////////////////////////////////////////////////////
// --- In : pWnd - pointer to valid window
// bOnlyActive - if it is TRUE then the function will return
// non-NULL value only if specified window
// is current active page of parent TabView
// container
// --- Out :
// --- Returns: pointer to parent TabView container, or NULL if parent of
// the specified window is not TabView container
// --- Effect : Retrieves parent TabView container foor specified window
OX_API_DECL COXTabViewContainer* PASCAL
GetParentTabViewContainer(CWnd* pWnd, BOOL bOnlyActive=TRUE);
///////////////////////////////////////////////////////////////////////////
template<class PARENTWND>
class COXTabViewPage : public PARENTWND
{
public:
// Contruction
COXTabViewPage();
COXTabViewPage(UINT nIDTemplate); // Use this constructor for form views
// Scrolling Functions
virtual CScrollBar* GetScrollBarCtrl(int nBar) const;
// return sibling scrollbar control (or NULL if none)
// --- In : pMsg - Points to a MSG structure that contains the
// message to process
// --- Out :
// --- Returns: Nonzero if the message was translated and should not be
// dispatched; 0 if the message was not translated and should be
// dispatched.
// --- Effect : Used by class CWinApp to translate window messages before
// they are dispatched to the TranslateMessage() and
// DispatchMessage() Windows functions
virtual BOOL PreTranslateMessage(MSG* pMsg);
protected:
// timer for checking scroll info of currently active page
INT_PTR m_nCheckScrollInfoTimer;
BOOL m_bCurrentlyScrolling;
BOOL m_bHasInternalScrollBars;
BOOL m_bNeedsInternalRedrawing;
int m_nLastHorzPos;
int m_nLastVertPos;
protected:
// --- In : msg - message ID
// wp - WPARAM
// lp - LPARAM
// --- Out :
// --- Returns: result of message handling. Different for different messages.
// --- Effect : Handle all messages that go to the window
virtual LRESULT WindowProc(UINT msg, WPARAM wp, LPARAM lp);
// call this function to force the control to check its scroll state
virtual void CheckScrollInfo();
};
template<class PARENTWND>
COXTabViewPage<PARENTWND>::COXTabViewPage()
{
m_nCheckScrollInfoTimer=-1;
m_bCurrentlyScrolling=FALSE;
m_bHasInternalScrollBars=PARENTWND::IsKindOf(RUNTIME_CLASS(CEdit)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CEditView)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CListBox)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CTreeCtrl)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CTreeView)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CListCtrl)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CListView)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CRichEditCtrl)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CRichEditView));
m_bNeedsInternalRedrawing=PARENTWND::IsKindOf(RUNTIME_CLASS(CEdit)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CEditView)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CListBox));
m_nLastHorzPos=0;
m_nLastVertPos=0;
}
template<class PARENTWND>
COXTabViewPage<PARENTWND>::COXTabViewPage(UINT nIDTemplate) :
PARENTWND(nIDTemplate)
{
ASSERT(PARENTWND::IsKindOf(RUNTIME_CLASS(CFormView)));
m_nCheckScrollInfoTimer=-1;
m_bCurrentlyScrolling=FALSE;
m_bHasInternalScrollBars=FALSE;
m_nLastHorzPos=0;
m_nLastVertPos=0;
}
template<class PARENTWND>
CScrollBar* COXTabViewPage<PARENTWND>::GetScrollBarCtrl(int nBar) const
{
COXTabViewContainer* pContainer=GetParentTabViewContainer((CWnd*)this);
if(pContainer!=NULL)
{
ASSERT(nBar==SB_HORZ || nBar==SB_VERT);
CScrollBar* pScrlBar=NULL;
if(nBar==SB_HORZ)
{
if((GetStyle()&WS_HSCROLL)!=WS_HSCROLL)
{
pScrlBar=pContainer->GetHorzScrollBar();
}
}
else if(nBar==SB_VERT)
{
if((GetStyle()&WS_VSCROLL)!=WS_VSCROLL)
{
pScrlBar=pContainer->GetVertScrollBar();
}
}
if(pScrlBar!=NULL)
{
return pScrlBar;
}
}
return PARENTWND::GetScrollBarCtrl(nBar);
}
template<class PARENTWND>
LRESULT COXTabViewPage<PARENTWND>::WindowProc(UINT msg, WPARAM wp, LPARAM lp)
{
#if defined (_WINDLL)
#if defined (_AFXDLL)
AFX_MANAGE_STATE(AfxGetAppModuleState());
#else
AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif
#endif
ASSERT_VALID(this);
static BOOL g_bIgnoreResize=FALSE;
switch(msg)
{
case WM_CREATE:
{
LRESULT lResult=PARENTWND::WindowProc(msg,wp,lp);
if(lResult==-1)
return -1;
if(m_bHasInternalScrollBars)
{
m_nCheckScrollInfoTimer=SetTimer(IDT_CHECKSCROLLINFO_TIMER,
ID_CHECKSCROLLINFO_PERIOD,NULL);
if(m_nCheckScrollInfoTimer==-1)
{
return -1;
}
}
return 0;
}
case WM_DESTROY:
{
if(m_nCheckScrollInfoTimer!=-1)
{
KillTimer(m_nCheckScrollInfoTimer);
m_nCheckScrollInfoTimer=-1;
}
break;
}
case WM_TIMER:
{
if((int)wp==m_nCheckScrollInfoTimer)
{
if(m_bCurrentlyScrolling || ::GetCapture()==GetSafeHwnd())
{
return 0;
}
COXTabViewContainer* pContainer=GetParentTabViewContainer(this);
if(pContainer!=NULL)
{
ASSERT(m_bHasInternalScrollBars);
if(m_bNeedsInternalRedrawing)
{
pContainer->UpdateScrollState();
pContainer->UpdateScrollInfo();
}
else
{
g_bIgnoreResize=TRUE;
pContainer->UpdateScrollState();
pContainer->UpdateScrollInfo();
g_bIgnoreResize=FALSE;
}
}
return 0;
}
break;
}
case WM_HSCROLL:
case WM_VSCROLL:
{
if(LOWORD(wp)==SB_ENDSCROLL)
{
m_bCurrentlyScrolling=FALSE;
m_nLastHorzPos=GetScrollPos(SB_HORZ);
m_nLastVertPos=GetScrollPos(SB_VERT);
}
else
{
m_bCurrentlyScrolling=TRUE;
}
COXTabViewContainer* pContainer=GetParentTabViewContainer(this);
if(pContainer!=NULL && m_bHasInternalScrollBars)
{
// set current scroll info to the window
SCROLLINFO scrollInfo={ sizeof(SCROLLINFO) };
GetScrollInfo((msg==WM_HSCROLL ? SB_HORZ : SB_VERT),&scrollInfo);
BOOL bHandled=FALSE;
if(PARENTWND::IsKindOf(RUNTIME_CLASS(CListCtrl)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CListView)))
{
bHandled=TRUE;
switch(LOWORD(wp))
{
case SB_THUMBTRACK:
{
CListCtrl* pListCtrl=(CListCtrl*)this;
CRect rectItem;
pListCtrl->GetItemRect(0,rectItem,LVIR_BOUNDS);
int nPos=HIWORD(wp);
if(msg==WM_HSCROLL && nPos!=m_nLastHorzPos)
{
SendMessage(LVM_SCROLL,(nPos-m_nLastHorzPos),0);
m_nLastHorzPos=GetScrollPos(SB_HORZ);
}
else if(msg==WM_VSCROLL && nPos!=m_nLastVertPos)
{
SendMessage(LVM_SCROLL,0,
(nPos-m_nLastVertPos)*rectItem.Height());
m_nLastVertPos=GetScrollPos(SB_VERT);
}
}
break;
default:
{
bHandled=FALSE;
}
break;
}
}
if(!bHandled)
{
if(m_bNeedsInternalRedrawing)
{
PARENTWND::WindowProc(msg,wp,lp);
pContainer->UpdateScrollInfo();
}
else
{
PARENTWND::WindowProc(msg,wp,lp);
g_bIgnoreResize=TRUE;
pContainer->UpdateScrollInfo();
g_bIgnoreResize=FALSE;
}
}
}
else
{
if(pContainer!=NULL && PARENTWND::IsKindOf(RUNTIME_CLASS(CScrollView)))
{
((CScrollView*)this)->OnScroll((msg==WM_HSCROLL ?
MAKEWORD(LOWORD(wp),-1) : MAKEWORD(-1,LOWORD(wp))),HIWORD(wp));
}
else
{
PARENTWND::WindowProc(msg,wp,lp);
}
}
return 0;
}
case WM_SIZE:
{
COXTabViewContainer* pContainer=GetParentTabViewContainer(this);
if(pContainer!=NULL)
{
if(g_bIgnoreResize)
{
return 0;
}
if((GetStyle()&WS_VISIBLE)!=WS_VISIBLE)
{
PARENTWND::WindowProc(msg,wp,lp);
}
else if(PARENTWND::IsKindOf(RUNTIME_CLASS(CRichEditView)) ||
PARENTWND::IsKindOf(RUNTIME_CLASS(CRichEditCtrl)))
{
if(!m_bCurrentlyScrolling)
{
g_bIgnoreResize=TRUE;
pContainer->UpdateScrollState();
pContainer->UpdateScrollInfo();
ModifyStyle(WS_VISIBLE,NULL);
PARENTWND::WindowProc(msg,wp,lp);
ShowScrollBar(SB_HORZ,FALSE);
ShowScrollBar(SB_VERT,FALSE);
ModifyStyle(NULL,WS_VISIBLE);
Invalidate();
g_bIgnoreResize=FALSE;
}
}
else if(m_bNeedsInternalRedrawing)
{
int nTopIndex=CB_ERR;
if(PARENTWND::IsKindOf(RUNTIME_CLASS(CListBox)))
nTopIndex=((CListBox*)this)->GetTopIndex();
pContainer->UpdateScrollState();
pContainer->UpdateScrollInfo();
PARENTWND::WindowProc(msg,wp,lp);
if(PARENTWND::IsKindOf(RUNTIME_CLASS(CListBox)))
{
if(((CListBox*)this)->GetTopIndex()!=nTopIndex)
RedrawWindow();
}
}
else if(!m_bHasInternalScrollBars)
{
ModifyStyle(WS_VISIBLE,NULL);
pContainer->GetHorzScrollBar()->
ModifyStyle(WS_VISIBLE,NULL);
pContainer->GetVertScrollBar()->
ModifyStyle(WS_VISIBLE,NULL);
PARENTWND::WindowProc(msg,wp,lp);
ShowScrollBar(SB_HORZ,FALSE);
ShowScrollBar(SB_VERT,FALSE);
pContainer->GetHorzScrollBar()->
ModifyStyle(NULL,WS_VISIBLE);
pContainer->GetVertScrollBar()->
ModifyStyle(NULL,WS_VISIBLE);
ModifyStyle(NULL,WS_VISIBLE);
}
else
{
CSize sizeScrollPos(-1,-1);
if(PARENTWND::IsKindOf(RUNTIME_CLASS(CTreeCtrl)))
{
sizeScrollPos.cx=pContainer->GetHorzScrollBar()->
GetScrollPos();
sizeScrollPos.cy=pContainer->GetVertScrollBar()->
GetScrollPos();
}
g_bIgnoreResize=TRUE;
pContainer->UpdateScrollState();
pContainer->UpdateScrollInfo();
ModifyStyle(WS_VISIBLE,NULL);
PARENTWND::WindowProc(msg,wp,lp);
ShowScrollBar(SB_HORZ,FALSE);
g_bIgnoreResize=FALSE;
ShowScrollBar(SB_VERT,FALSE);
ModifyStyle(NULL,WS_VISIBLE);
if(PARENTWND::IsKindOf(RUNTIME_CLASS(CTreeCtrl)))
{
if(sizeScrollPos.cx!=pContainer->GetHorzScrollBar()->
GetScrollPos() ||
sizeScrollPos.cy!=pContainer->GetVertScrollBar()->
GetScrollPos())
{
RedrawWindow();
}
}
}
return 0;
}
break;
}
default:
{
if(m_bHasInternalScrollBars)
{
if(msg==WM_SYSCOMMAND || msg==WM_SHOWWINDOW ||
(msg>=WM_KEYFIRST && msg<=WM_KEYLAST) ||
(msg>=WM_SYSKEYFIRST && msg<=WM_SYSKEYLAST) ||
(msg>=WM_MOUSEFIRST && msg<=WM_MOUSELAST && msg!=WM_MOUSEMOVE))
{
CheckScrollInfo();
}
}
break;
}
}
// I don't handle it: pass along
return PARENTWND::WindowProc(msg,wp,lp);
}
template<class PARENTWND>
BOOL COXTabViewPage<PARENTWND>::PreTranslateMessage(MSG* pMsg)
{
if(m_bHasInternalScrollBars && pMsg->hwnd!=GetSafeHwnd() &&
(pMsg->message==WM_SYSCOMMAND || pMsg->message==WM_SHOWWINDOW ||
(pMsg->message>=WM_KEYFIRST && pMsg->message<=WM_KEYLAST) ||
(pMsg->message>=WM_SYSKEYFIRST && pMsg->message<=WM_SYSKEYLAST) ||
(pMsg->message>=WM_MOUSEFIRST && pMsg->message<=WM_MOUSELAST &&
pMsg->message!=WM_MOUSEMOVE)))
{
CheckScrollInfo();
}
return PARENTWND::PreTranslateMessage(pMsg);
}
template<class PARENTWND>
void COXTabViewPage<PARENTWND>::CheckScrollInfo()
{
ASSERT(::IsWindow(GetSafeHwnd()));
PostMessage(WM_TIMER,m_nCheckScrollInfoTimer);
}
#endif // _TABVIEW_H
///////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
]
| [
[
[
1,
1553
]
]
]
|
8b2c3d49049db4500e58dd2d26af740706bf039e | 4ac19e8642b3005d702a1112a722811c8b3cc7c6 | /src/a_scarti.cpp | 6731f314e5451ed84d61ab55529455df4bce1e20 | [
"BSD-3-Clause"
]
| permissive | amreisa/freeCGI | 5ab00029e86fad79a2580262c04afa3ae442e127 | 84c047c4790eaabbc9d2284242a44c204fe674ea | refs/heads/master | 2022-04-27T19:51:11.690512 | 2011-02-28T22:33:34 | 2011-02-28T22:33:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,285 | cpp |
#ifdef WIN32
#pragma message( "Compiling " __FILE__ )
#endif
#include "freeCGI.h"
#ifdef _DEBUG_DUMP_
void ASCartItem::dump(void)
{
//a_Only works if the _DEBUG_DUMP_ flag is set and MIME directive was sent (ie. Content-Type: text/html\n\n)
cout << endl << "---START: ASCartItem::dump()---";
APairItem::dump();
cout << "---END: ASCartItem::dump()---" << endl;
}
#endif
ASCartItem::ASCartItem(ASCartItem *psciSource)
{
if (psciSource)
_bCopy(*psciSource); //a_Copy the form item
else
{
m_iQuantity = 0x00;
}
}
ASCartItem::~ASCartItem()
{
}
void ASCartItem::_bCopy(const ASCartItem &sciSource)
{
APairItem::_bCopy(sciSource); //a_Parent copy
m_iQuantity = sciSource.sciGetQuantity();
}
void ASCartItem::doOut(AStreamOutput *pasOut) const
{
APairItem::doOut(pasOut);
}
ASCartItem &ASCartItem::operator +=(int iAddQ)
{
//a_Supports both positive and negative additions
//a_Doesn't assume iQuantity must be above zero (they don't have to be)
if (m_iQuantity + iAddQ > INT_MAX)
{
m_iQuantity = INT_MAX;
}
else
{
if (m_iQuantity + iAddQ < INT_MIN)
m_iQuantity = INT_MIN;
else
m_iQuantity += iAddQ;
}
return *this;
}
| [
"[email protected]"
]
| [
[
[
1,
62
]
]
]
|
2832aee6fdeb5a825b34ce685092807137e7e875 | 188058ec6dbe8b1a74bf584ecfa7843be560d2e5 | /FLVGServer/MainFrm.h | 2aa573dc34aae17e4238f50edbc162b9e02029e9 | []
| no_license | mason105/red5cpp | 636e82c660942e2b39c4bfebc63175c8539f7df0 | fcf1152cb0a31560af397f24a46b8402e854536e | refs/heads/master | 2021-01-10T07:21:31.412996 | 2007-08-23T06:29:17 | 2007-08-23T06:29:17 | 36,223,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,908 | h | // MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_MAINFRM_H__F76F66F5_B040_44F2_92D9_5D3BC35D2C33__INCLUDED_)
#define AFX_MAINFRM_H__F76F66F5_B040_44F2_92D9_5D3BC35D2C33__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "ControlPropertiesTreeCtrl.h"
#include "XDLSplitterWnd.h"
#include "VODFilesFormView.h"
#include "RelayFormView.h"
#include "PerfomanceView.h"
#include "PublishPointFormView.h"
#include "ConnectionFormView.h"
#include "SettingFormView.h"
#include "LogFormView.h"
#include "Dog.h"
#include "GHttpServer.h"
class CControlFrameWnd;
class CMainFrame : public CXTMainFrm
{
protected: // create from serialization only
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// Attributes
public:
CXTPDockingPaneManager m_paneManager;
CXTPDockingPaneManager* GetDockingPaneManager() {
return &m_paneManager;
}
void OnUDPDataHandleCallBack(sockaddr* from,
char * pData,
unsigned long DataLength);
// Operations
public:
static void DefaultXDLSSetting(XDLS_Setting *pSetting);
BOOL InitializeCaptionBar();
int Helper_GetCurrentofConnections();
virtual void GetWindowTitle (CString& rString);
void ExpandPaneTree(BOOL bExpand);
FLVServer* XFLVServer_Ptr(){
return _FLVServer;
}
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMainFrame)
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
//}}AFX_VIRTUAL
// Implementation
public:
CString m_strBindIP;
CString m_strOutWindowText;
BOOL IsInited;
void Run(){OnRun();}
void Stop(){OnStop();}
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
public: // control bar embedded members
CString strStartTime;
CToolBar m_wndToolBar;
CControlPropertiesTreeCtrl m_wndControlPropertiesTreeCtrl;
CImageList m_ilTreeIcons;
CXTCaption m_wndCaption;
CFont m_fontCaption;
CXDLSplitterWnd m_wndSplitterCaption;
CControlFrameWnd* m_pControlFrameWnd;
CPerfomanceView* m_pPerfomanceView;
CPublishPointFormView* m_pPublishPointFormView;
CVODFilesFormView* m_pVODFilesFormView;
CRelayFormView* m_pRelayFormView;
CConnectionFormView* m_pConnectionFormView;
CSettingFormView* m_pSettingFormView;
CLogFormView* m_pLogFormView;
CWnd* m_pActiveView;
XDLS_Setting m_XDLS_Setting;
FLVServer* _FLVServer;
GHttpServer _HttpServer;
public:
void OnDelFile();
void WatchVODPath();
void OnStop_inner();
void OnFtpNewFile(LPVOID params);
// Generated message map functions
protected:
//{{AFX_MSG(CMainFrame)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnGetMinMaxInfo (MINMAXINFO FAR* lpMMI);
afx_msg void OnDestroy();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnRun();
afx_msg void OnUpdateRun(CCmdUI* pCmdUI);
afx_msg void OnStop();
afx_msg void OnUpdateStop(CCmdUI* pCmdUI);
afx_msg void OnTimer(UINT nIDEvent);
afx_msg void OnClose();
afx_msg void OnNcPaint();
afx_msg BOOL OnCopyData(CWnd* pWnd, COPYDATASTRUCT* pCopyDataStruct);
//}}AFX_MSG
afx_msg LRESULT OnDockingPaneNotify (WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnControlPropertiesTreeSelected (WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnGetOut (WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MAINFRM_H__F76F66F5_B040_44F2_92D9_5D3BC35D2C33__INCLUDED_)
| [
"soaris@46205fef-a337-0410-8429-7db05d171fc8"
]
| [
[
[
1,
132
]
]
]
|
7612d5214e6a3e3f616422d2b3464642d0be5eee | cfa1c9f0d1e0bef25f48586d19395b5658752f5b | /Proj_2/LightSoundSystem.cpp | efd6e3462fff031237c22402c706871f0383af92 | []
| no_license | gemini14/AirBall | de9c9a9368bb58d7f7c8fe243a900b11d0596227 | 5d41d3f2c5282f50e7074010f7c1d3b5a804be77 | refs/heads/master | 2021-03-12T21:42:26.819173 | 2011-05-11T08:10:51 | 2011-05-11T08:10:51 | 1,732,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,834 | cpp | #include "LightSoundSystem.h"
#include <iostream>
namespace Tuatara
{
void LightSoundSystem::DisplayError( const FMOD_RESULT& result )
{
#if defined(_DEBUG) | defined(DEBUG)
std::cout << "FMOD error: " << FMOD_ErrorString( result ) << "\n";
#endif
}
void LightSoundSystem::ErrorCheck( const FMOD_RESULT& result )
{
if( result != FMOD_OK )
{
DisplayError( result );
}
}
LightSoundSystem::LightSoundSystem( const char *soundFilename )
: system( nullptr), sound( nullptr ), soundChannel( nullptr )
{
ErrorCheck( FMOD::System_Create( &system ) );
FMOD_RESULT result = system->init( 1, FMOD_INIT_NORMAL, nullptr );
if( result == FMOD_OK )
{
ErrorCheck( system->createStream( soundFilename, FMOD_LOOP_NORMAL | FMOD_CREATESTREAM, nullptr, &sound ) );
}
}
LightSoundSystem::~LightSoundSystem()
{
if( sound != nullptr )
{
system->release();
}
if( system != nullptr )
{
system->release();
}
}
void LightSoundSystem::AdjustVolume( const float& volume )
{
if( soundChannel != nullptr && volume <= 1.0f && volume >= 0.0f )
{
soundChannel->setVolume( volume );
}
}
void LightSoundSystem::PausePlayback()
{
if( soundChannel != nullptr )
{
soundChannel->setPaused( true );
}
}
void LightSoundSystem::ResumePlayback()
{
if( soundChannel != nullptr )
{
soundChannel->setPaused( false );
}
}
void LightSoundSystem::StartPlayback( bool startPaused )
{
ErrorCheck( system->playSound( FMOD_CHANNEL_FREE, sound, startPaused, &soundChannel ) );
}
void LightSoundSystem::StopPlayback()
{
if( soundChannel != nullptr )
{
soundChannel->stop();
}
}
void LightSoundSystem::Update()
{
if( system != nullptr )
{
system->update();
}
}
} | [
"devnull@localhost"
]
| [
[
[
1,
92
]
]
]
|
5571b89ae5b141acd450fb74b757634a4e760b07 | ad80c85f09a98b1bfc47191c0e99f3d4559b10d4 | /code/src/audio/ndsound_error.cc | 20ab73e596967aac3e5aa8a296d7895093e2df08 | []
| 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 | 2,144 | cc | #define N_IMPLEMENTS nDSoundServer2
//-------------------------------------------------------------------
// ndsound_error.cc
// (C) 2000 RadonLabs GmbH -- A.Weissflog
//-------------------------------------------------------------------
#include "audio/ndsoundserver2.h"
//-------------------------------------------------------------------
/**
@brief Resolve DirectSound error code into string.
15-May-00 floh created
*/
//-------------------------------------------------------------------
const char *ndsound_Error(HRESULT hr)
{
char *s;
switch (hr) {
case DS_NO_VIRTUALIZATION: s="DS_NO_VIRTUALIZATION"; break;
case DSERR_ALLOCATED: s="DSERR_ALLOCATED"; break;
case DSERR_CONTROLUNAVAIL: s="DSERR_CONTROLUNAVAIL"; break;
case DSERR_INVALIDPARAM: s="DSERR_INVALIDPARAM"; break;
case DSERR_INVALIDCALL: s="DSERR_INVALIDCALL"; break;
case DSERR_GENERIC: s="DSERR_GENERIC"; break;
case DSERR_PRIOLEVELNEEDED: s="DSERR_PRIOLEVELNEEDED"; break;
case DSERR_OUTOFMEMORY: s="DSERR_OUTOFMEMORY"; break;
case DSERR_BADFORMAT: s="DSERR_BADFORMAT"; break;
case DSERR_UNSUPPORTED: s="DSERR_UNSUPPORTED"; break;
case DSERR_NODRIVER: s="DSERR_NODRIVER"; break;
case DSERR_ALREADYINITIALIZED: s="DSERR_ALREADYINITIALIZED"; break;
case DSERR_NOAGGREGATION: s="DSERR_NOAGGREGATION"; break;
case DSERR_BUFFERLOST: s="DSERR_BUFFERLOST"; break;
case DSERR_OTHERAPPHASPRIO: s="DSERR_OTHERAPPHASPRIO"; break;
case DSERR_UNINITIALIZED: s="DSERR_UNINITIALIZED"; break;
case DSERR_NOINTERFACE: s="DSERR_NOINTERFACE"; break;
case DSERR_ACCESSDENIED: s="DSERR_ACCESSDENIED"; break;
default: s="<UNKNOWN ERROR>"; break;
};
return s;
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"plushe@411252de-2431-11de-b186-ef1da62b6547"
]
| [
[
[
1,
44
]
]
]
|
9220bfe28f42ca4a89c0cb37d309f401435f5d96 | b22c254d7670522ec2caa61c998f8741b1da9388 | /GameServer/PlayerInfoHandler.cpp | 82ae4568b0c2e0e26400b6e00ec16ee1a8fc89ac | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,579 | cpp | /*
------------------------[ Lbanet Source ]-------------------------
Copyright (C) 2009
Author: Vivien Delage [Rincevent_123]
Email : [email protected]
-------------------------------[ GNU License ]-------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-----------------------------------------------------------------------------
*/
#include "PlayerInfoHandler.h"
#include "LogHandler.h"
#include "DatabaseHandlerBase.h"
/************************************************************************/
/* constructor
/************************************************************************/
PlayerInfoHandler::PlayerInfoHandler(long PlayerDbId, DatabaseHandlerBase *DbH, ServerDataHandler* DataH)
: _PlayerDbId(PlayerDbId), _DbH(DbH), _DataH(DataH)
{
_nextMap = _DataH->GetWorldInfo().StartInfo.FirstMap;
}
/************************************************************************/
/* destructor
/************************************************************************/
PlayerInfoHandler::~PlayerInfoHandler()
{
}
/************************************************************************/
/* save info to database
/************************************************************************/
void PlayerInfoHandler::SaveToDatabase()
{
}
/************************************************************************/
/* load info from database
/************************************************************************/
void PlayerInfoHandler::LoadFromDatabase()
{
}
/************************************************************************/
/* return the map the player should be connected to
/************************************************************************/
std::string PlayerInfoHandler::GetNextMap()
{
return _nextMap;
} | [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
76
]
]
]
|
b5d858449695c335c4a7ce0c76884e77572a347c | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testsyssim/src/tsyssimblocks.cpp | b32bf8caf6b981842e473fb0710ca412d603aab4 | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,854 | cpp | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
/*
* ==============================================================================
* Name : tsyssimblocks.cpp
* Part of : testsyssim
*
* Description : ?Description
* Version: 0.5
*
*/
#include "tsyssim.h"
// MACROS
#define MASK_RWUSR 0066
// -----------------------------------------------------------------------------
// CTestSyssim::getgrpid : To get group ID
// description : This is a test function for simulated "getgid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getgrpid( )
{
getgid();
_LIT(Kerr , "getgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setgrpid : To set group ID
// description : This is a test function for simulated "setgid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setgrpid( )
{
setgid((gid_t)0);
_LIT(Kerr , "setgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::geteffgrpid : To get effective group ID
// description : This is a test function for simulated "getegid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::geteffgrpid( )
{
getegid();
_LIT(Kerr , "geteffgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::seteffgrpid : To set effective group ID
// description : This is a test function for simulated "setegid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::seteffgrpid( )
{
setegid((gid_t)0);
_LIT(Kerr , "seteffgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setregrpid : To set real and effective group ID
// description : This is a test function for simulated "setregid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setregrpid( )
{
setregid((gid_t)0, (gid_t)0);
_LIT(Kerr , "setregrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getusrid : To get user ID
// description : This is a test function for simulated "getuid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getusrid( )
{
getuid();
_LIT(Kerr , "getusrid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setusrid : To set user ID
// description : This is a test function for simulated "setuid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setusrid( )
{
setuid((uid_t)0);
_LIT(Kerr , "setusrid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::geteffusrid : To get effective user ID
// description : This is a test function for simulated "geteuid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::geteffusrid( )
{
geteuid();
_LIT(Kerr , "geteffusrid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::seteffusrid : To set effective user ID
// description : This is a test function for simulated "seteuid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::seteffusrid( )
{
seteuid((uid_t)0);
_LIT(Kerr , "seteffusrid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setreusrid : To set real and effective user ID
// description : This is a test function for simulated "setreuid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setreusrid( )
{
setreuid((uid_t)0, (uid_t)0);
_LIT(Kerr , "setreusrid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getpgrpid : To get process group ID
// description : This is a test function for simulated "getpgid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getpgrpid( )
{
getpgid((pid_t)0);
_LIT(Kerr , "getpgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setpgrpid : To set process group ID
// description : This is a test function for simulated "setpgid" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setpgrpid( )
{
setpgid((pid_t)0, (pid_t)0);
_LIT(Kerr , "setpgrpid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getprocgrp : This is equivalent to getpgid(0)
// description : This is a test function for simulated "getpgrp" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getprocgrp( )
{
getpgrp();
_LIT(Kerr , "getprocgrp is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setprocgrp : This is equivalent to setpgid(0,0)
// description : This is a test function for simulated "setpgrp" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setprocgrp( )
{
setpgrp((pid_t)0, (pid_t)0);
_LIT(Kerr , "setprocgrp is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getgrps : To get supplementary group list.
// description : This is a test function for simulated "getgroups" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getgrps( )
{
int size = 0;
gid_t list[2];
getgroups(size, list);
_LIT(Kerr , "getgrps is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::setsessid : To create new session or process group.
// description : This is a test function for simulated "setsid" call. Concept of
// process group or session are not supported by the platform unlike
// unix like systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::setsessid( )
{
setsid();
_LIT(Kerr , "setsessid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getpprocid : To get parent process ID.
// description : This is a test function for simulated "getppid" call. Ability to
// obtain parent process ID are not supported by the platform unlike
// unix like systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getpprocid( )
{
getppid();
_LIT(Kerr , "getpprocid is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::filemask : To set file's mode creation mask.
// description : This is a test function for simulated "umask" call. Ability to
// obtain parent process ID are not supported by the platform unlike
// unix like systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::filemask( )
{
umask((mode_t)MASK_RWUSR);
_LIT(Kerr , "filemask is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::chowner : To change the file's owner and group.
// description : This is a test function for simulated "chown" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::chowner( )
{
char *file = "C:\\MyFile.txt";
chown(file, 0, 0);
_LIT(Kerr , "chowner is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::lchowner : To change a symbolic link file's owner and group.
// description : This is a test function for simulated "lchown" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::lchowner( )
{
char *file = "C:\\MyFile.txt";
lchown(file, 0, 0);
_LIT(Kerr , "chowner is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::initgrps : Initialize supplementry group list.
// description : This is a test function for simulated "initgroups" call. Concept of
// user and groups are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::initgrps( )
{
char list[2];
initgroups(list, 0);
_LIT(Kerr , "initgrps is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::schedyield : yield control to a similar or higher priority thread.
// description : This is a test function for simulated "sched_yield" call. Concept of
// thread/process yield are not supported by the platform unlike unix like
// systems.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::schedyield( )
{
sched_yield();
_LIT(Kerr , "schedyield is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getproioritymax: yield control to a similar or higher priority thread.
// description : This is a test function for simulated "sched_get_priority_max" call.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getproioritymax( )
{
sched_get_priority_max(1);
_LIT(Kerr , "getproioritymax is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// -----------------------------------------------------------------------------
// CTestSyssim::getproioritymin: yield control to a similar or higher priority thread.
// description : This is a test function for simulated "sched_get_priority_min" call.
// Returns: KErrNone: Always
// -----------------------------------------------------------------------------
//
TInt CTestSyssim::getproioritymin( )
{
sched_get_priority_min(1);
_LIT(Kerr , "getproioritymin is simulated and not supported by plf");
WARN_PRINTF1(Kerr);
return KErrNone;
}
// End of File
| [
"none@none"
]
| [
[
[
1,
422
]
]
]
|
e249c87cc84ac8df5c21d3bb2bd4db30cecb6cb2 | c0bd82eb640d8594f2d2b76262566288676b8395 | /src/game/ItemInterface.cpp | 0668c8f27b9e899bf4d50ce1b3063b127cfd4dc3 | [
"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 | 82,894 | cpp | // Copyright (C) 2004 WoW Daemon
//
// 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.
//
// Item interface
//
#include "StdAfx.h"
#include "Item.h"
#include "Container.h"
#include "ItemPrototype.h"
#include "Player.h"
//
//-------------------------------------------------------------------//
ItemInterface::ItemInterface( Player *pPlayer )
{
m_pOwner = pPlayer;
memset(m_pItems, 0, sizeof(Item*)*MAX_INVENTORY_SLOT);
memset(m_pBuyBack, 0, sizeof(Item*)*MAX_BUYBACK_SLOT);
}
//-------------------------------------------------------------------//
ItemInterface::~ItemInterface()
{
for(int i = 0; i < MAX_INVENTORY_SLOT; i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->IsContainer())
{
delete ((Container*)(m_pItems[i]));
}
else
{
delete m_pItems[i];
}
}
}
}
//-------------------------------------------------------------------// 100%
uint32 ItemInterface::m_CreateForPlayer(ByteBuffer *data)
{
ASSERT(m_pOwner != NULL);
uint32 count = 0;
for(int i = 0; i < MAX_INVENTORY_SLOT; i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->IsContainer())
{
count += ((Container*)(m_pItems[i]))->BuildCreateUpdateBlockForPlayer(data, m_pOwner);
if(m_pItems[i]->GetProto())
{
for(int e=0; e < m_pItems[i]->GetProto()->ContainerSlots; e++)
{
Item *pItem = ((Container*)(m_pItems[i]))->GetItem(e);
if(pItem)
{
if(pItem->IsContainer())
{
count += ((Container*)(pItem))->BuildCreateUpdateBlockForPlayer( data, m_pOwner );
}
else
{
count += pItem->BuildCreateUpdateBlockForPlayer( data, m_pOwner );
}
}
}
}
}
else
{
count += m_pItems[i]->BuildCreateUpdateBlockForPlayer(data, m_pOwner);
}
}
}
return count;
}
//-------------------------------------------------------------------// 100%
void ItemInterface::m_DestroyForPlayer()
{
ASSERT(m_pOwner != NULL);
for(int i = 0; i < MAX_INVENTORY_SLOT; i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->IsContainer())
{
if(m_pItems[i]->GetProto())
{
for(int e=0; e < m_pItems[i]->GetProto()->ContainerSlots; e++)
{
Item *pItem = ((Container*)(m_pItems[i]))->GetItem(e);
if(pItem)
{
if(pItem->IsContainer())
{
((Container*)(pItem))->DestroyForPlayer( m_pOwner );
}
else
{
pItem->DestroyForPlayer( m_pOwner );
}
}
}
}
((Container*)(m_pItems[i]))->DestroyForPlayer( m_pOwner );
}
else
{
m_pItems[i]->DestroyForPlayer( m_pOwner );
}
}
}
}
//-------------------------------------------------------------------//
//Description: Creates and adds a item that can be manipulated after
//-------------------------------------------------------------------//
Item *ItemInterface::SafeAddItem(uint32 ItemId, int8 ContainerSlot, int8 slot)
{
Item *pItem;
ItemPrototype *pProto = objmgr.GetItemPrototype(ItemId);
if(!pProto) { return NULL; }
if(pProto->InventoryType == INVTYPE_BAG)
{
pItem = (Item*)new Container();
static_cast<Container*>(pItem)->Create(objmgr.GenerateLowGuid(HIGHGUID_CONTAINER), ItemId, m_pOwner);
if(m_AddItem(pItem, ContainerSlot, slot))
{
return pItem;
}
else
{
delete pItem;
return NULL;
}
}
else
{
pItem = new Item();
pItem->Create(objmgr.GenerateLowGuid(HIGHGUID_ITEM), ItemId, m_pOwner);
if(m_AddItem(pItem, ContainerSlot, slot))
{
return pItem;
}
else
{
delete pItem;
return NULL;
}
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: Creates and adds a item that can be manipulated after
//-------------------------------------------------------------------//
bool ItemInterface::SafeAddItem(Item *pItem, int8 ContainerSlot, int8 slot)
{
return m_AddItem(pItem, ContainerSlot, slot);
}
//-------------------------------------------------------------------//
//Description: adds items to player inventory, this includes all types of slots.
//-------------------------------------------------------------------//
bool ItemInterface::m_AddItem(Item *item, int8 ContainerSlot, int8 slot)
{
ASSERT(slot < MAX_INVENTORY_SLOT);
ASSERT(ContainerSlot < MAX_INVENTORY_SLOT);
ASSERT(item != NULL);
if(item->GetProto())
{
//case 1, item is from backpack container
if(ContainerSlot == INVENTORY_SLOT_NOT_SET)
{
//ASSERT(m_pItems[slot] == NULL);
if(GetInventoryItem(slot) != NULL)
{
//sLog.outError("bugged inventory: %u %u", m_pOwner->GetName(), item->GetGUID());
SlotResult result = this->FindFreeInventorySlot(item->GetProto());
// send message to player
sChatHandler.BlueSystemMessageToPlr(m_pOwner, "A duplicated item, `%s` was found in your inventory. We've attempted to add it to a free slot in your inventory, if there is none this will fail. It will be attempted again the next time you log on.",
item->GetProto()->Name1.c_str());
if(result.Result == true)
{
// Found a new slot for that item.
slot = result.Slot;
ContainerSlot = result.ContainerSlot;
}
else
{
// don't leak memory!
if(item->IsContainer())
delete ((Container*)item);
else
delete item;
return false;
}
}
if(!GetInventoryItem(slot)) //slot is free, add item.
{
item->SetOwner( m_pOwner );
item->SetUInt64Value(ITEM_FIELD_CONTAINED, m_pOwner->GetGUID());
m_pItems[slot] = item;
if (item->GetProto()->Bonding == ITEM_BIND_ON_PICKUP)
item->SoulBind();
if( m_pOwner->IsInWorld() && !item->IsInWorld())
{
item->AddToWorld();
ByteBuffer buf(2500);
uint32 count = item->BuildCreateUpdateBlockForPlayer( &buf, m_pOwner );
m_pOwner->PushUpdateData(&buf, count);
}
m_pOwner->SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2), item->GetGUID());
}
else
{
return false;
}
}
else //case 2: item is from a bag container
{
if(GetInventoryItem(ContainerSlot) && GetInventoryItem(ContainerSlot)->IsContainer())//container exists
{
bool result = static_cast<Container*>(m_pItems[ContainerSlot])->AddItem(slot, item);
if(!result)
{
return false;
}
}
else
{
return false;
}
}
}
else
{
return false;
}
if ( slot < EQUIPMENT_SLOT_END && ContainerSlot == INVENTORY_SLOT_NOT_SET )
{
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
m_pOwner->SetUInt32Value(VisibleBase, item->GetUInt32Value(OBJECT_FIELD_ENTRY));
m_pOwner->SetUInt32Value(VisibleBase + 1, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT));
m_pOwner->SetUInt32Value(VisibleBase + 2, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 3));
m_pOwner->SetUInt32Value(VisibleBase + 3, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 6));
m_pOwner->SetUInt32Value(VisibleBase + 4, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 9));
m_pOwner->SetUInt32Value(VisibleBase + 5, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 12));
m_pOwner->SetUInt32Value(VisibleBase + 6, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 15));
m_pOwner->SetUInt32Value(VisibleBase + 7, item->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 18));
m_pOwner->SetUInt32Value(VisibleBase + 8, item->GetUInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID));
}
if( m_pOwner->IsInWorld() && slot < INVENTORY_SLOT_BAG_END && ContainerSlot == INVENTORY_SLOT_NOT_SET)
{
m_pOwner->ApplyItemMods( item,slot, true );
}
if(slot == EQUIPMENT_SLOT_OFFHAND && item->GetProto()->Class == ITEM_CLASS_WEAPON)
m_pOwner->SetDuelWield(true);
return true;
}
//-------------------------------------------------------------------//
//Description: Checks if the slot is a Bag slot
//-------------------------------------------------------------------//
bool ItemInterface::IsBagSlot(int8 slot)
{
if((slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END) || (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END))
{
return true;
}
return false;
}
//-------------------------------------------------------------------//
//Description: removes the item safely and returns it back for usage
//-------------------------------------------------------------------//
Item *ItemInterface::SafeRemoveAndRetreiveItemFromSlot(int8 ContainerSlot, int8 slot, bool destroy)
{
ASSERT(slot < MAX_INVENTORY_SLOT);
ASSERT(ContainerSlot < MAX_INVENTORY_SLOT);
Item *pItem = NULL;
if(ContainerSlot == INVENTORY_SLOT_NOT_SET)
{
pItem = GetInventoryItem(ContainerSlot,slot);
if (pItem == NULL) { return NULL; }
m_pItems[slot] = NULL;
m_pOwner->SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2), 0 );
if ( slot < EQUIPMENT_SLOT_END )
{
m_pOwner->ApplyItemMods( pItem, slot, false );
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
for (int i = VisibleBase; i < VisibleBase + 12; ++i)
{
m_pOwner->SetUInt32Value(i, 0);
m_pOwner->SetBaseUInt32Value(i, 0);
}
}
if(slot == EQUIPMENT_SLOT_OFFHAND)
m_pOwner->SetDuelWield(false);
if(destroy)
{
if (pItem->IsInWorld())
{
pItem->RemoveFromWorld();
}
pItem->DeleteFromDB();
}
}
else
{
Item *pContainer = GetInventoryItem(ContainerSlot);
if(pContainer && pContainer->IsContainer())
{
pItem = static_cast<Container*>(pContainer)->SafeRemoveAndRetreiveItemFromSlot(slot, destroy);
if (pItem == NULL) { return NULL; }
}
}
return pItem;
}
//-------------------------------------------------------------------//
//Description: removes the item safely by guid and returns it back for usage, supports full inventory
//-------------------------------------------------------------------//
Item *ItemInterface::SafeRemoveAndRetreiveItemByGuid(uint64 guid, bool destroy)
{
int8 i = 0;
for(i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
}
for(i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
}
for(i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
}
for(i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
else
{
if(item && item->IsContainer() && item->GetProto())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2 && item2->GetGUID() == guid)
{
return ((Container*)item)->SafeRemoveAndRetreiveItemFromSlot(j, destroy);
}
}
}
}
}
for(i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
}
for(i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeRemoveAndRetreiveItemFromSlot(INVENTORY_SLOT_NOT_SET, i, destroy);
}
else
{
if(item && item->IsContainer() && item->GetProto())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2 && item2->GetGUID() == guid)
{
return ((Container*)item)->SafeRemoveAndRetreiveItemFromSlot(j, destroy);
}
}
}
}
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: completely removes item from player
//Result: true if item removal was succefull
//-------------------------------------------------------------------//
bool ItemInterface::SafeFullRemoveItemFromSlot(int8 ContainerSlot, int8 slot)
{
ASSERT(slot < MAX_INVENTORY_SLOT);
ASSERT(ContainerSlot < MAX_INVENTORY_SLOT);
if(ContainerSlot == INVENTORY_SLOT_NOT_SET)
{
Item *pItem = GetInventoryItem(slot);
if (pItem == NULL) { return false; }
m_pItems[slot] = NULL;
m_pOwner->SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2), 0 );
if ( slot < EQUIPMENT_SLOT_END )
{
m_pOwner->ApplyItemMods(pItem, slot, false );
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * 16);
for (int i = VisibleBase; i < VisibleBase + 12; ++i)
{
m_pOwner->SetUInt32Value(i, 0);
m_pOwner->SetBaseUInt32Value(i, 0);
}
}
if(slot == EQUIPMENT_SLOT_OFFHAND)
m_pOwner->SetDuelWield(false);
if (pItem->IsInWorld())
{
pItem->RemoveFromWorld();
}
pItem->DeleteFromDB();
delete pItem;
}
else
{
Item *pContainer = GetInventoryItem(ContainerSlot);
if(pContainer && pContainer->IsContainer())
{
static_cast<Container*>(pContainer)->SafeFullRemoveItemFromSlot(slot);
}
}
return true;
}
//-------------------------------------------------------------------//
//Description: removes the item safely by guid, supports full inventory
//-------------------------------------------------------------------//
bool ItemInterface::SafeFullRemoveItemByGuid(uint64 guid)
{
int8 i = 0;
for(i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
}
for(i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
}
for(i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
}
for(i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
else
{
if(item && item->IsContainer() && item->GetProto())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2 && item2->GetGUID() == guid)
{
return ((Container*)item)->SafeFullRemoveItemFromSlot(j);
}
}
}
}
}
for(i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
}
for(i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item && item->GetGUID() == guid)
{
return this->SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
}
else
{
if(item && item->IsContainer() && item->GetProto())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2 && item2->GetGUID() == guid)
{
return ((Container*)item)->SafeFullRemoveItemFromSlot(j);
}
}
}
}
}
return false;
}
//-------------------------------------------------------------------//
//Description: Gets a item from Inventory
//-------------------------------------------------------------------//
Item *ItemInterface::GetInventoryItem(int8 slot)
{
if(slot == INVENTORY_SLOT_NOT_SET || slot > MAX_INVENTORY_SLOT)
{
return NULL;
}
return m_pItems[slot];
}
//-------------------------------------------------------------------//
//Description: Gets a Item from inventory or container
//-------------------------------------------------------------------//
Item *ItemInterface::GetInventoryItem(int8 ContainerSlot, int8 slot)
{
if(ContainerSlot == INVENTORY_SLOT_NOT_SET)
{
if(slot == INVENTORY_SLOT_NOT_SET || slot > MAX_INVENTORY_SLOT)
{
return NULL;
}
return m_pItems[slot];
}
else
{
if(IsBagSlot(ContainerSlot))
{
if(m_pItems[ContainerSlot])
{
return static_cast<Container*>(m_pItems[ContainerSlot])->GetItem(slot);
}
}
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: checks for stacks that didnt reached max capacity
//-------------------------------------------------------------------//
Item* ItemInterface::FindItemLessMax(uint32 itemid, uint32 cnt, bool IncBank)
{
int8 i = 0;
for(i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if((item->GetProto()->ItemId == itemid) && (item->GetProto()->MaxCount >= (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) + cnt)))
{
return item;
}
}
}
for(i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2)
{
if((item2->GetProto()->ItemId == itemid) && (item2->GetProto()->MaxCount >= (item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT) + cnt)))
{
return item2;
}
}
}
}
}
}
if(IncBank)
{
for(i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if((item->GetProto()->ItemId == itemid) && (item->GetProto()->MaxCount >= (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) + cnt)))
{
return item;
}
}
}
for(i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2)
{
if((item2->GetProto()->ItemId == itemid) && (item2->GetProto()->MaxCount >= (item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT) + cnt)))
{
return item2;
}
}
}
}
}
}
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: finds item ammount on inventory, banks not included
//-------------------------------------------------------------------//
uint32 ItemInterface::GetItemCount(uint32 itemid, bool IncBank)
{
uint32 cnt = 0;
int8 i = 0;
for(i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if(item->GetProto()->ItemId == itemid)
{
cnt += item->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
}
}
}
for(i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2)
{
if (item2->GetProto()->ItemId == itemid)
{
cnt += item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
}
}
}
}
}
}
for(i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if(item->GetProto()->ItemId == itemid)
{
cnt += item->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
}
}
}
if(IncBank)
{
for(i = BANK_SLOT_ITEM_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if(item->GetProto()->ItemId == itemid)
{
cnt += item->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
}
}
}
for(i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer())
{
for (int8 j =0; j < item->GetProto()->ContainerSlots; j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2)
{
if(item2->GetProto()->ItemId == itemid)
{
cnt += item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
}
}
}
}
}
}
}
return cnt;
}
//-------------------------------------------------------------------//
//Description: Removes a ammount of items from inventory
//-------------------------------------------------------------------//
bool ItemInterface::RemoveItemAmt(uint32 id, uint32 amt)
{
if (GetItemCount(id) < amt)
{
return false;
}
int8 i;
for(i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if(item->GetProto()->ItemId == id)
{
if (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) > amt)
{
item->SetCount(item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) - amt);
return true;
}
else if (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT)== amt)
{
bool result = SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
if(result)
{
return true;
}
else
{
return false;
}
}
else
{
amt -= item->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
bool result = SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
if(result)
{
return true;
}
else
{
return false;
}
}
}
}
}
for(i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
for (int8 j =0; j < item->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)item)->GetItem(j);
if (item2)
{
if (item2->GetProto()->ItemId == id)
{
if (item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT) > amt)
{
item2->SetCount(item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT) - amt);
return true;
}
else if (item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT)== amt)
{
bool result = SafeFullRemoveItemFromSlot(i, j);
if(result)
{
return true;
}
else
{
return false;
}
}
else
{
amt -= item2->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
bool result = SafeFullRemoveItemFromSlot(i, j);
if(result)
{
return true;
}
else
{
return false;
}
}
}
}
}
}
}
for(i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
Item *item = GetInventoryItem(i);
if (item)
{
if(item->GetProto()->ItemId == id)
{
if (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) > amt)
{
item->SetCount(item->GetUInt32Value(ITEM_FIELD_STACK_COUNT) - amt);
return true;
}
else if (item->GetUInt32Value(ITEM_FIELD_STACK_COUNT)== amt)
{
bool result = SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
if(result)
{
return true;
}
else
{
return false;
}
}
else
{
amt -= item->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
bool result = SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, i);
if(result)
{
return true;
}
else
{
return false;
}
}
}
}
}
return false;
}
//-------------------------------------------------------------------//
//Description: Gets slot number by itemid, banks not included
//-------------------------------------------------------------------//
int8 ItemInterface::GetInventorySlotById(uint32 ID)
{
for(int8 i=0;i<INVENTORY_SLOT_ITEM_END;i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->GetProto()->ItemId == ID)
{
return i;
}
}
}
for(int8 i=INVENTORY_KEYRING_START; i<INVENTORY_KEYRING_END; i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->GetProto()->ItemId == ID)
{
return i;
}
}
}
return ITEM_NO_SLOT_AVAILABLE;
}
//-------------------------------------------------------------------//
//Description: Gets slot number by item guid, banks not included
//-------------------------------------------------------------------//
int8 ItemInterface::GetInventorySlotByGuid(uint64 guid)
{
for(int8 i=EQUIPMENT_SLOT_START ;i<INVENTORY_SLOT_ITEM_END;i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->GetGUID() == guid)
{
return i;
}
}
}
for(int8 i=INVENTORY_KEYRING_START; i<INVENTORY_KEYRING_END; i++)
{
if(m_pItems[i])
{
if(m_pItems[i]->GetGUID() == guid)
{
return i;
}
}
}
return ITEM_NO_SLOT_AVAILABLE; //was changed from 0 cuz 0 is the slot for head
}
//-------------------------------------------------------------------//
//Description: Adds a Item to a free slot
//-------------------------------------------------------------------//
bool ItemInterface::AddItemToFreeSlot(Item *item)
{
if(!item) { return false; }
int8 i = 0;
//detect special bag item
if(item->GetProto()->BagFamily)
{
if(item->GetProto()->BagFamily == ITEM_TYPE_KEYRING)
{
for(int8 i=INVENTORY_KEYRING_START; i<INVENTORY_KEYRING_END; i++)
{
if(m_pItems[i] == NULL)
{
bool result = SafeAddItem(item, INVENTORY_SLOT_NOT_SET, i);
if(result) { return true; }
}
}
}
else
{
for(i=INVENTORY_SLOT_BAG_START;i<INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i])
{
if (m_pItems[i]->GetProto()->BagFamily == item->GetProto()->BagFamily)
{
if(m_pItems[i]->IsContainer())
{
bool result = static_cast<Container*>(m_pItems[i])->AddItemToFreeSlot(item);
if (result) { return true; }
}
}
}
}
}
}
//INVENTORY
for(i=INVENTORY_SLOT_ITEM_START;i<INVENTORY_SLOT_ITEM_END;i++)
{
if(m_pItems[i] == NULL)
{
return SafeAddItem(item, INVENTORY_SLOT_NOT_SET, i);
}
}
//INVENTORY BAGS
for(i=INVENTORY_SLOT_BAG_START;i<INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] != NULL && m_pItems[i]->GetProto()->BagFamily == 0) //special bags ignored
{
for (int8 j =0; j < m_pItems[i]->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)m_pItems[i])->GetItem(j);
if (item2 == NULL)
{
return SafeAddItem(item, i, j);
}
}
}
}
return false;
}
//-------------------------------------------------------------------//
//Description: Calculates inventory free slots, bag inventory slots not included
//-------------------------------------------------------------------//
uint32 ItemInterface::CalculateFreeSlots(ItemPrototype *proto)
{
uint32 count = 0;
int8 i;
if(proto)
{
if(proto->BagFamily)
{
if(proto->BagFamily == ITEM_TYPE_KEYRING)
{
for(int8 i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
if(m_pItems[i] == NULL)
{
count++;
}
}
}
else
{
for(int8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] && m_pItems[i]->IsContainer())
{
if (m_pItems[i]->GetProto()->BagFamily == proto->BagFamily)
{
int8 slot = ((Container*)m_pItems[i])->FindFreeSlot();
if(slot != ITEM_NO_SLOT_AVAILABLE)
{
count++;
}
}
}
}
}
}
}
for(i=INVENTORY_SLOT_ITEM_START;i<INVENTORY_SLOT_ITEM_END;i++)
{
if(m_pItems[i] == NULL)
{
count++;
}
}
for(i=INVENTORY_SLOT_BAG_START;i<INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] != NULL )
{
if(m_pItems[i]->IsContainer() && !m_pItems[i]->GetProto()->BagFamily)
{
for (int8 j =0; j < m_pItems[i]->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)m_pItems[i])->GetItem(j);
if (item2 == NULL)
{
count++;
}
}
}
}
}
return count;
}
//-------------------------------------------------------------------//
//Description: finds a free slot on the backpack
//-------------------------------------------------------------------//
int8 ItemInterface::FindFreeBackPackSlot()
{
//search for backpack slots
for(int8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if(!item)
{
return i;
}
}
return ITEM_NO_SLOT_AVAILABLE; //no slots available
}
//-------------------------------------------------------------------//
//Description: converts bank bags slot ids into player bank byte slots(0-5)
//-------------------------------------------------------------------//
int8 ItemInterface::GetInternalBankSlotFromPlayer(int8 islot)
{
switch(islot)
{
case BANK_SLOT_BAG_1:
{
return 1;
}
case BANK_SLOT_BAG_2:
{
return 2;
}
case BANK_SLOT_BAG_3:
{
return 3;
}
case BANK_SLOT_BAG_4:
{
return 4;
}
case BANK_SLOT_BAG_5:
{
return 5;
}
case BANK_SLOT_BAG_6:
{
return 6;
}
case BANK_SLOT_BAG_7:
{
return 7;
}
default:
return 8;
}
}
//-------------------------------------------------------------------//
//Description: checks if the item can be equiped on a specific slot
//-------------------------------------------------------------------//
int8 ItemInterface::CanEquipItemInSlot(int8 DstInvSlot, int8 slot, ItemPrototype *proto, bool ignore_combat)
{
uint32 type=proto->InventoryType;
if((slot < INVENTORY_SLOT_BAG_END && DstInvSlot == INVENTORY_SLOT_NOT_SET) || (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END && DstInvSlot == INVENTORY_SLOT_NOT_SET))
{
if (!ignore_combat && m_pOwner->isInCombat())
return INV_ERR_CANT_DO_IN_COMBAT;
// Check to see if we have the correct race
if(!(proto->AllowableRace& (1<<m_pOwner->getRace())))
return INV_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
// Check to see if we have the correct class
if(!(proto->AllowableClass & (1<<(m_pOwner->getClass()-1))))
return INV_ERR_YOU_CAN_NEVER_USE_THAT_ITEM2;
// Check to see if we have the reqs for that reputation(disabled atm)
if(proto->RequiredFaction)
return INV_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
// Check to see if we have the correct level.
if(proto->RequiredLevel>m_pOwner->GetUInt32Value(UNIT_FIELD_LEVEL))
return INV_ERR_YOU_MUST_REACH_LEVEL_N;
if(proto->Class == 4)
{
if(!(m_pOwner->GetArmorProficiency()&(((uint32)(1))<<proto->SubClass)))
return INV_ERR_NO_REQUIRED_PROFICIENCY;
}
else if(proto->Class == 2)
{
if(!(m_pOwner->GetWeaponProficiency()&(((uint32)(1))<<proto->SubClass)))
return INV_ERR_NO_REQUIRED_PROFICIENCY;
}
/*
uint32 SubClassSkill = GetSkillByProto(proto);
// removed those loops, use the skill lookup functions
if(SubClassSkill)
{
if(!HasSkillLine(SubClassSkill))
return INV_ERR_NO_REQUIRED_PROFICIENCY;
}*/
if(proto->RequiredSkill)
if (proto->RequiredSkillRank > m_pOwner->GetSkillAmt(proto->RequiredSkill))
return INV_ERR_SKILL_ISNT_HIGH_ENOUGH;
// You are dead !
if(m_pOwner->getDeathState() == DEAD)
return INV_ERR_YOU_ARE_DEAD;
}
switch(slot)
{
case EQUIPMENT_SLOT_HEAD:
{
if(type == INVTYPE_HEAD)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_NECK:
{
if(type == INVTYPE_NECK)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_SHOULDERS:
{
if(type == INVTYPE_SHOULDERS)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_BODY:
{
if(type == INVTYPE_BODY)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_CHEST:
{
if(type == INVTYPE_CHEST || type == INVTYPE_ROBE)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_WAIST:
{
if(type == INVTYPE_WAIST)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_LEGS:
{
if(type == INVTYPE_LEGS)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_FEET:
{
if(type == INVTYPE_FEET)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_WRISTS:
{
if(type == INVTYPE_WRISTS)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_HANDS:
{
if(type == INVTYPE_HANDS)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_FINGER1:
case EQUIPMENT_SLOT_FINGER2:
{
if(type == INVTYPE_FINGER)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_TRINKET1:
case EQUIPMENT_SLOT_TRINKET2:
{
if(type == INVTYPE_TRINKET)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_BACK:
{
if(type == INVTYPE_CLOAK)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_MAINHAND:
{
if(type == INVTYPE_WEAPON || type == INVTYPE_WEAPONMAINHAND ||
(type == INVTYPE_2HWEAPON && !GetInventoryItem(EQUIPMENT_SLOT_OFFHAND)))
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_OFFHAND:
{
if(type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND)
{
Item* mainweapon = GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
if(mainweapon) //item exists
{
if(mainweapon->GetProto())
{
if(mainweapon->GetProto()->InventoryType != INVTYPE_2HWEAPON)
{
if(m_pOwner->HasSkillLine(SKILL_DUAL_WIELD))
return 0;
else
return INV_ERR_CANT_DUAL_WIELD;
}
else
return INV_ERR_CANT_EQUIP_WITH_TWOHANDED;
}
}
else
{
if(m_pOwner->HasSkillLine(SKILL_DUAL_WIELD))
return 0;
else
return INV_ERR_CANT_DUAL_WIELD;
}
}
else if(type == INVTYPE_SHIELD || type == INVTYPE_HOLDABLE)
{
Item* mainweapon = GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
if(mainweapon) //item exists
{
if(mainweapon->GetProto())
{
if(mainweapon->GetProto()->InventoryType != INVTYPE_2HWEAPON)
{
return 0;
}
else
return INV_ERR_CANT_EQUIP_WITH_TWOHANDED;
}
}
else
{
return 0;
}
}
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;
}
case EQUIPMENT_SLOT_RANGED:
{
if(type == INVTYPE_RANGED || type == INVTYPE_THROWN || type == INVTYPE_RANGEDRIGHT || type == INVTYPE_RELIC)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT;//6;
}
case EQUIPMENT_SLOT_TABARD:
{
if(type == INVTYPE_TABARD)
return 0;
else
return INV_ERR_ITEM_DOESNT_GO_TO_SLOT; // 6;
}
case BANK_SLOT_BAG_1:
case BANK_SLOT_BAG_2:
case BANK_SLOT_BAG_3:
case BANK_SLOT_BAG_4:
case BANK_SLOT_BAG_5:
case BANK_SLOT_BAG_6:
case BANK_SLOT_BAG_7:
{
uint32 bytes,slots;
int8 islot;
if(!GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot))
{
//check if player got that slot.
bytes = m_pOwner->GetUInt32Value(PLAYER_BYTES_2);
slots =(uint8) (bytes >> 16);
islot = GetInternalBankSlotFromPlayer(slot);
if(slots < islot)
{
return INV_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
}
//in case bank slot exists, check if player can put the item there
if(type == INVTYPE_BAG)
{
return 0;
}
else
{
return INV_ERR_NOT_A_BAG;
}
}
else
{
if(GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot)->GetProto()->BagFamily)
{
if((IsBagSlot(slot) && DstInvSlot == INVENTORY_SLOT_NOT_SET))
{
if(proto->InventoryType == INVTYPE_BAG )
{
return 0;
}
}
if(proto->BagFamily == GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot)->GetProto()->BagFamily)
{
return 0;
}
else
{
return INV_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
}
else
{
return 0;
}
}
}
case INVENTORY_SLOT_BAG_1:
case INVENTORY_SLOT_BAG_2:
case INVENTORY_SLOT_BAG_3:
case INVENTORY_SLOT_BAG_4:
{
if(GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot))
{
if(GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot)->GetProto()->BagFamily)
{
if((IsBagSlot(slot) && DstInvSlot == INVENTORY_SLOT_NOT_SET))
{
if(proto->InventoryType == INVTYPE_BAG )
{
return 0;
}
}
if(proto->BagFamily == GetInventoryItem(INVENTORY_SLOT_NOT_SET,slot)->GetProto()->BagFamily)
{
return 0;
}
else
{
return INV_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
}
else
{
return 0;
}
}
else
{
if(type == INVTYPE_BAG)
{
return 0;
}
else
{
return INV_ERR_NOT_A_BAG;
}
}
}
case INVENTORY_SLOT_ITEM_1:
case INVENTORY_SLOT_ITEM_2:
case INVENTORY_SLOT_ITEM_3:
case INVENTORY_SLOT_ITEM_4:
case INVENTORY_SLOT_ITEM_5:
case INVENTORY_SLOT_ITEM_6:
case INVENTORY_SLOT_ITEM_7:
case INVENTORY_SLOT_ITEM_8:
case INVENTORY_SLOT_ITEM_9:
case INVENTORY_SLOT_ITEM_10:
case INVENTORY_SLOT_ITEM_11:
case INVENTORY_SLOT_ITEM_12:
case INVENTORY_SLOT_ITEM_13:
case INVENTORY_SLOT_ITEM_14:
case INVENTORY_SLOT_ITEM_15:
case INVENTORY_SLOT_ITEM_16:
{
return 0;
}
case INVENTORY_KEYRING_1:
case INVENTORY_KEYRING_2:
case INVENTORY_KEYRING_3:
case INVENTORY_KEYRING_4:
case INVENTORY_KEYRING_5:
case INVENTORY_KEYRING_6:
case INVENTORY_KEYRING_7:
case INVENTORY_KEYRING_8:
case INVENTORY_KEYRING_9:
case INVENTORY_KEYRING_10:
case INVENTORY_KEYRING_11:
case INVENTORY_KEYRING_12:
case INVENTORY_KEYRING_13:
case INVENTORY_KEYRING_14:
case INVENTORY_KEYRING_15:
case INVENTORY_KEYRING_16:
case INVENTORY_KEYRING_17:
case INVENTORY_KEYRING_18:
case INVENTORY_KEYRING_19:
case INVENTORY_KEYRING_20:
case INVENTORY_KEYRING_21:
case INVENTORY_KEYRING_22:
case INVENTORY_KEYRING_23:
case INVENTORY_KEYRING_24:
case INVENTORY_KEYRING_25:
case INVENTORY_KEYRING_26:
case INVENTORY_KEYRING_27:
case INVENTORY_KEYRING_28:
case INVENTORY_KEYRING_29:
case INVENTORY_KEYRING_30:
case INVENTORY_KEYRING_31:
case INVENTORY_KEYRING_32:
{
if(proto->BagFamily == ITEM_TYPE_KEYRING )
{
return 0;
}
else
{
return INV_ERR_ITEM_DOESNT_GO_INTO_BAG;
}
}
default:
return 0;
}
}
//-------------------------------------------------------------------//
//Description: Checks if player can receive the item
//-------------------------------------------------------------------//
int8 ItemInterface::CanReceiveItem(ItemPrototype * item, uint32 amount)
{
if(!item)
{
return NULL;
}
if(item->Unique)
{
uint32 count = GetItemCount(item->ItemId, true);
if(count == item->Unique || ((count + amount) > item->Unique))
{
return INV_ERR_CANT_CARRY_MORE_OF_THIS;
}
}
return NULL;
}
void ItemInterface::BuyItem(ItemPrototype *item, uint32 amount)
{
m_pOwner->ModUInt32Value(PLAYER_FIELD_COINAGE, -(GetBuyPriceForItem(item, amount, amount)));
ItemExtendedCostEntry *ex = ItemExtendedCostStore::getSingleton().LookupEntry(item->ItemExtendedCost);
for(int i = 0;i<5;i++)
{
if(ex->item[i])
{
m_pOwner->GetItemInterface()->RemoveItemAmt(ex->item[i],ex->count[i]);
}
}
m_pOwner->ModUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, -(ex->honor));
m_pOwner->ModUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, -(ex->arena));
}
int8 ItemInterface::CanAffordItem(ItemPrototype *item,uint32 amount)
{
if(item->ItemExtendedCost)
{
ItemExtendedCostEntry *ex = ItemExtendedCostStore::getSingleton().LookupEntry(item->ItemExtendedCost);
for(int i = 0;i<5;i++)
{
if(ex->item[i])
{
if(m_pOwner->GetItemInterface()->GetItemCount(ex->item[i]) < ex->count[i], false)
return INV_ERR_NOT_ENOUGH_MONEY;
}
}
if(m_pOwner->GetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY) < ex->honor)
return INV_ERR_NOT_ENOUGH_MONEY;
if(m_pOwner->GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY ) < ex->arena)
return INV_ERR_NOT_ENOUGH_MONEY;
}
if(item->BuyPrice)
{
int32 price = GetBuyPriceForItem(item, amount, amount);
if(m_pOwner->GetUInt32Value(PLAYER_FIELD_COINAGE) < price)
{
return INV_ERR_NOT_ENOUGH_MONEY;
}
}
if(item->RequiredFaction)
{
return INV_ERR_ITEM_REPUTATION_NOT_ENOUGH;
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: Gets the Item slot by item type
//-------------------------------------------------------------------//
int8 ItemInterface::GetItemSlotByType(uint32 type)
{
switch(type)
{
case INVTYPE_NON_EQUIP:
return ITEM_NO_SLOT_AVAILABLE;
case INVTYPE_HEAD:
{
return EQUIPMENT_SLOT_HEAD;
}
case INVTYPE_NECK:
{
return EQUIPMENT_SLOT_NECK;
}
case INVTYPE_SHOULDERS:
{
return EQUIPMENT_SLOT_SHOULDERS;
}
case INVTYPE_BODY:
{
return EQUIPMENT_SLOT_BODY;
}
case INVTYPE_CHEST:
{
return EQUIPMENT_SLOT_CHEST;
}
case INVTYPE_ROBE: // ???
{
return EQUIPMENT_SLOT_CHEST;
}
case INVTYPE_WAIST:
{
return EQUIPMENT_SLOT_WAIST;
}
case INVTYPE_LEGS:
{
return EQUIPMENT_SLOT_LEGS;
}
case INVTYPE_FEET:
{
return EQUIPMENT_SLOT_FEET;
}
case INVTYPE_WRISTS:
{
return EQUIPMENT_SLOT_WRISTS;
}
case INVTYPE_HANDS:
{
return EQUIPMENT_SLOT_HANDS;
}
case INVTYPE_FINGER:
{
if (!GetInventoryItem(EQUIPMENT_SLOT_FINGER1))
return EQUIPMENT_SLOT_FINGER1;
else if (!GetInventoryItem(EQUIPMENT_SLOT_FINGER2))
return EQUIPMENT_SLOT_FINGER2;
else
return EQUIPMENT_SLOT_FINGER1; //auto equips always in finger 1
}
case INVTYPE_TRINKET:
{
if (!GetInventoryItem(EQUIPMENT_SLOT_TRINKET1))
return EQUIPMENT_SLOT_TRINKET1;
else if (!GetInventoryItem(EQUIPMENT_SLOT_TRINKET2))
return EQUIPMENT_SLOT_TRINKET2;
else
return EQUIPMENT_SLOT_TRINKET1; //auto equips always on trinket 1
}
case INVTYPE_CLOAK:
{
return EQUIPMENT_SLOT_BACK;
}
case INVTYPE_WEAPON:
{
if (!GetInventoryItem(EQUIPMENT_SLOT_MAINHAND) )
return EQUIPMENT_SLOT_MAINHAND;
else if(!GetInventoryItem(EQUIPMENT_SLOT_OFFHAND))
return EQUIPMENT_SLOT_OFFHAND;
else
return EQUIPMENT_SLOT_MAINHAND;
}
case INVTYPE_SHIELD:
{
return EQUIPMENT_SLOT_OFFHAND;
}
case INVTYPE_RANGED:
{
return EQUIPMENT_SLOT_RANGED;
}
case INVTYPE_2HWEAPON:
{
return EQUIPMENT_SLOT_MAINHAND;
}
case INVTYPE_TABARD:
{
return EQUIPMENT_SLOT_TABARD;
}
case INVTYPE_WEAPONMAINHAND:
{
return EQUIPMENT_SLOT_MAINHAND;
}
case INVTYPE_WEAPONOFFHAND:
{
return EQUIPMENT_SLOT_OFFHAND;
}
case INVTYPE_HOLDABLE:
{
return EQUIPMENT_SLOT_OFFHAND;
}
case INVTYPE_THROWN:
return EQUIPMENT_SLOT_RANGED; // ?
case INVTYPE_RANGEDRIGHT:
return EQUIPMENT_SLOT_RANGED; // ?
case INVTYPE_RELIC:
return EQUIPMENT_SLOT_RANGED;
case INVTYPE_BAG:
{
for (int8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
if (!GetInventoryItem(i))
return i;
}
return ITEM_NO_SLOT_AVAILABLE; //bags are not suposed to be auto-equiped when slots are not free
}
default:
return ITEM_NO_SLOT_AVAILABLE;
}
}
//-------------------------------------------------------------------//
//Description: Gets a Item by guid
//-------------------------------------------------------------------//
Item* ItemInterface::GetItemByGUID(uint64 Guid)
{
int8 i ;
//EQUIPMENT
for(i=EQUIPMENT_SLOT_START;i<EQUIPMENT_SLOT_END;i++)
{
if(m_pItems[i] != 0)
{
if( m_pItems[i]->GetGUID() == Guid)
{
return m_pItems[i];
}
}
}
//INVENTORY BAGS
for(i=INVENTORY_SLOT_BAG_START;i<INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] != NULL)
{
if(m_pItems[i]->GetGUID()==Guid) { return m_pItems[i]; }
for (int8 j =0; j < m_pItems[i]->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)m_pItems[i])->GetItem(j);
if (item2)
{
if (item2->GetGUID() == Guid)
{
return item2;
}
}
}
}
}
//INVENTORY
for(i=INVENTORY_SLOT_ITEM_START;i<INVENTORY_SLOT_ITEM_END;i++)
{
if(m_pItems[i] != 0)
{
if(m_pItems[i]->GetGUID() == Guid)
{
return m_pItems[i];
}
}
}
//Keyring
for(i=INVENTORY_KEYRING_START;i<INVENTORY_KEYRING_END;i++)
{
if(m_pItems[i] != 0)
{
if(m_pItems[i]->GetGUID() == Guid)
{
return m_pItems[i];
}
}
}
return NULL;
}
//-------------------------------------------------------------------//
//Description: Inventory Error report
//-------------------------------------------------------------------//
void ItemInterface::BuildInventoryChangeError(Item *SrcItem, Item *DstItem, uint8 Error)
{
WorldPacket data;
data.Initialize( SMSG_INVENTORY_CHANGE_FAILURE );
data << Error;
if(Error == 1)
{
if(SrcItem)
{
data << SrcItem->GetProto()->RequiredLevel;
}
}
data << (SrcItem ? SrcItem->GetGUID() : uint64(0));
data << (DstItem ? DstItem->GetGUID() : uint64(0));
data << uint8(0);
m_pOwner->GetSession()->SendPacket( &data );
}
void ItemInterface::EmptyBuyBack()
{
for (uint32 j = 0;j < 12;j++)
{
if (m_pBuyBack[j] != NULL)
{
m_pBuyBack[j]->DestroyForPlayer(m_pOwner);
m_pBuyBack[j]->DeleteFromDB();
if(m_pBuyBack[j]->IsContainer())
{
delete static_cast<Container*>(m_pBuyBack[j]);
}
else
{
delete m_pBuyBack[j];
}
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*j),0);
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j,0);
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j,0);
m_pBuyBack[j] = NULL;
}
else
break;
}
}
void ItemInterface::AddBuyBackItem(Item *it,uint32 price)
{
int i;
if ((m_pBuyBack[11] != NULL) && (m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + 22) != 0))
{
if(m_pBuyBack[0] != NULL)
{
m_pBuyBack[0]->DestroyForPlayer(m_pOwner);
m_pBuyBack[0]->DeleteFromDB();
if(m_pBuyBack[0]->IsContainer())
{
delete static_cast<Container*>(m_pBuyBack[0]);
}
else
{
delete m_pBuyBack[0];
}
m_pBuyBack[0] = NULL;
}
for (int j = 0;j < 11;j++)
{
//SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*j),buyback[j+1]->GetGUID());
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*j),m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + ((j+1)*2) ) );
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j,m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j+1));
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j,m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j+1));
m_pBuyBack[j] = m_pBuyBack[j+1];
}
m_pBuyBack[11] = it;
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*(11)),m_pBuyBack[11]->GetGUID());
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + 11,price);
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + 11,time(NULL));
return;
}
for(i=0; i < 24;i+=2)
{
if((m_pOwner->GetUInt32Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + i) == 0) || (m_pBuyBack[i/2] == NULL))
{
Log::getSingleton().outDetail("setting buybackslot %u\n",i/2);
m_pBuyBack[i/2] = it;
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + i,m_pBuyBack[i/2]->GetGUID());
//SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + i,it->GetGUID());
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + (i/2),price);
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + (i/2),time(NULL));
return;
}
}
}
void ItemInterface::RemoveBuyBackItem(uint32 index)
{
int32 j = 0;
for (j = index;j < 11;j++)
{
if (m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (j*2)) != 0)
{
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*j), m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + ((j+1)*2)));
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j, m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j+1));
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j, m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j+1));
if ((m_pBuyBack[j+1] != NULL) && (m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + ((j+1)*2)) != 0))
{
m_pBuyBack[j] = m_pBuyBack[j+1];
}
else
{
if(m_pBuyBack[j])
{
m_pBuyBack[j] = NULL;
}
Log::getSingleton().outDetail("nulling %u\n",(j));
}
}
else
return;
}
j = 11;
m_pOwner->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (2*j), m_pOwner->GetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + ((j+1)*2)));
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j, m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + j+1));
m_pOwner->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j, m_pOwner->GetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + j+1));
if(m_pBuyBack[11])
{
m_pBuyBack[11] = NULL;
}
}
//-------------------------------------------------------------------//
//Description: swap inventory slots
//-------------------------------------------------------------------//
void ItemInterface::SwapItemSlots(int8 srcslot, int8 dstslot)
{
ASSERT(srcslot < MAX_INVENTORY_SLOT && srcslot >= NULL);
ASSERT(dstslot < MAX_INVENTORY_SLOT && dstslot >= NULL);
Item *SrcItem = GetInventoryItem(srcslot);
Item *DstItem = GetInventoryItem(dstslot);
if(SrcItem && DstItem && SrcItem->GetEntry()==DstItem->GetEntry()&& SrcItem->GetProto()->MaxCount>1)
{
uint32 total=SrcItem->GetUInt32Value(ITEM_FIELD_STACK_COUNT)+DstItem->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
if(total<=DstItem->GetProto()->MaxCount)
{
DstItem->ModUInt32Value(ITEM_FIELD_STACK_COUNT, SrcItem->GetUInt32Value(ITEM_FIELD_STACK_COUNT));
SafeFullRemoveItemFromSlot(INVENTORY_SLOT_NOT_SET, srcslot);
return;
}
else
{
if(DstItem->GetUInt32Value(ITEM_FIELD_STACK_COUNT) == DstItem->GetProto()->MaxCount)
{
}
else
{
int32 delta=DstItem->GetProto()->MaxCount-DstItem->GetUInt32Value(ITEM_FIELD_STACK_COUNT);
DstItem->SetUInt32Value(ITEM_FIELD_STACK_COUNT,DstItem->GetProto()->MaxCount);
SrcItem->ModUInt32Value(ITEM_FIELD_STACK_COUNT,-delta);
return;
}
}
}
m_pItems[srcslot] = DstItem;
m_pItems[dstslot] = SrcItem;
if(m_pItems[dstslot])
{
m_pOwner->SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (dstslot*2)), m_pItems[dstslot]->GetGUID() );
}
else
{
m_pOwner->SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (dstslot*2)), 0 );
}
if( m_pItems[srcslot])
{
m_pOwner->SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD + srcslot*2, m_pItems[srcslot]->GetGUID() );
}
else
{
m_pOwner->SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (srcslot*2)), 0 );
}
bool noreapply=( srcslot < EQUIPMENT_SLOT_END && dstslot < EQUIPMENT_SLOT_END);//just move inside inv, no equip/unequip
if(srcslot < EQUIPMENT_SLOT_END) // source item is inside inventory
{
// remove mods from original item
if(!noreapply)
{
if(m_pItems[dstslot]) // Remove mods from the old item in this slot.
m_pOwner->ApplyItemMods(m_pItems[dstslot], srcslot, false);
if(m_pItems[srcslot]) // Apply mods from the new item into this slot
m_pOwner->ApplyItemMods(m_pItems[srcslot], dstslot, true);
}
if(m_pItems[srcslot]) // dstitem goes into here.
{
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (srcslot * 16);
m_pOwner->SetUInt32Value(VisibleBase, m_pItems[srcslot]->GetUInt32Value(OBJECT_FIELD_ENTRY));
m_pOwner->SetUInt32Value(VisibleBase + 1, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT));
m_pOwner->SetUInt32Value(VisibleBase + 2, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 3));
m_pOwner->SetUInt32Value(VisibleBase + 3, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 6));
m_pOwner->SetUInt32Value(VisibleBase + 4, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 9));
m_pOwner->SetUInt32Value(VisibleBase + 5, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 12));
m_pOwner->SetUInt32Value(VisibleBase + 6, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 15));
m_pOwner->SetUInt32Value(VisibleBase + 7, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 18));
m_pOwner->SetUInt32Value(VisibleBase + 8, m_pItems[srcslot]->GetUInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID));
// handle bind on equip
if(m_pItems[srcslot]->GetProto()->Bonding == ITEM_BIND_ON_EQUIP)
m_pItems[srcslot]->SoulBind();
}
else
{
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (srcslot * 16);
m_pOwner->SetUInt32Value(VisibleBase, 0);
m_pOwner->SetUInt32Value(VisibleBase + 1, 0);
m_pOwner->SetUInt32Value(VisibleBase + 2, 0);
m_pOwner->SetUInt32Value(VisibleBase + 3, 0);
m_pOwner->SetUInt32Value(VisibleBase + 4, 0);
m_pOwner->SetUInt32Value(VisibleBase + 5, 0);
m_pOwner->SetUInt32Value(VisibleBase + 6, 0);
m_pOwner->SetUInt32Value(VisibleBase + 7, 0);
m_pOwner->SetUInt32Value(VisibleBase + 8, 0);
}
}
if(dstslot < EQUIPMENT_SLOT_END) // source item is inside inventory
{
// remove mods from original item
if(!noreapply)
{
if(m_pItems[srcslot]) // Remove mods from the old item in this slot.
m_pOwner->ApplyItemMods(m_pItems[srcslot], dstslot, false);
if(m_pItems[dstslot]) // Apply mods from the new item into this slot
m_pOwner->ApplyItemMods(m_pItems[dstslot], srcslot, true);
}
if(m_pItems[dstslot]) // srcitem goes into here.
{
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (dstslot * 16);
m_pOwner->SetUInt32Value(VisibleBase, m_pItems[dstslot]->GetUInt32Value(OBJECT_FIELD_ENTRY));
m_pOwner->SetUInt32Value(VisibleBase + 1, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT));
m_pOwner->SetUInt32Value(VisibleBase + 2, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 3));
m_pOwner->SetUInt32Value(VisibleBase + 3, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 6));
m_pOwner->SetUInt32Value(VisibleBase + 4, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 9));
m_pOwner->SetUInt32Value(VisibleBase + 5, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 12));
m_pOwner->SetUInt32Value(VisibleBase + 6, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 15));
m_pOwner->SetUInt32Value(VisibleBase + 7, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_ENCHANTMENT + 18));
m_pOwner->SetUInt32Value(VisibleBase + 8, m_pItems[dstslot]->GetUInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID));
// handle bind on equip
if(m_pItems[dstslot]->GetProto()->Bonding == ITEM_BIND_ON_EQUIP)
m_pItems[dstslot]->SoulBind();
} else {
int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (dstslot * 16);
m_pOwner->SetUInt32Value(VisibleBase, 0);
m_pOwner->SetUInt32Value(VisibleBase + 1, 0);
m_pOwner->SetUInt32Value(VisibleBase + 2, 0);
m_pOwner->SetUInt32Value(VisibleBase + 3, 0);
m_pOwner->SetUInt32Value(VisibleBase + 4, 0);
m_pOwner->SetUInt32Value(VisibleBase + 5, 0);
m_pOwner->SetUInt32Value(VisibleBase + 6, 0);
m_pOwner->SetUInt32Value(VisibleBase + 7, 0);
m_pOwner->SetUInt32Value(VisibleBase + 8, 0);
}
}
if(dstslot == EQUIPMENT_SLOT_OFFHAND || srcslot == EQUIPMENT_SLOT_OFFHAND)
{
if(m_pItems[EQUIPMENT_SLOT_OFFHAND] != 0 && m_pItems[EQUIPMENT_SLOT_OFFHAND]->GetProto()->Class == ITEM_CLASS_WEAPON)
m_pOwner->SetDuelWield(true);
else
m_pOwner->SetDuelWield(false);
}
}
//-------------------------------------------------------------------//
//Description: Item Loading
//-------------------------------------------------------------------//
void ItemInterface::mLoadItemsFromDatabase()
{
int8 containerslot, slot;
Item* item;
ItemPrototype *proto;
std::stringstream invq;
invq << "SELECT * FROM playeritems WHERE ownerguid=" << m_pOwner->GetGUIDLow() << " ORDER BY containerslot ASC";
QueryResult *result = sDatabase.Query( invq.str().c_str() );
if(result)
{
do
{
Field *fields = result->Fetch();
containerslot = fields[10].GetInt8();
slot = fields[11].GetInt8();
proto = objmgr.GetItemPrototype(fields[2].GetUInt32());
if(proto)
{
if(proto->InventoryType == INVTYPE_BAG)
{
item=new Container();
((Container*)item)->LoadFromDB(fields);
}
else
{
item = new Item();
item->LoadFromDB(fields, m_pOwner, false);
}
SafeAddItem(item, containerslot, slot);
}
}
while( result->NextRow() );
}
delete result;
}
//-------------------------------------------------------------------//
//Description: Item saving
//-------------------------------------------------------------------//
void ItemInterface::mSaveItemsToDatabase(bool first)
{
int8 x;
for(x = EQUIPMENT_SLOT_START; x < INVENTORY_KEYRING_END; ++x)
{
if(GetInventoryItem(x) != NULL)
{
if(!( (m_pOwner->GetItemInterface()->GetInventoryItem(x)->GetProto()->Flags)&2 )) // skip conjured item on save
{
if(IsBagSlot(x) && GetInventoryItem(x)->IsContainer())
{
((Container*)GetInventoryItem(x))->SaveBagToDB(x, first);
}
else
{
GetInventoryItem(x)->SaveToDB(INVENTORY_SLOT_NOT_SET, x, first);
}
}
}
}
}
bool ItemInterface::AddItemToFreeBankSlot(Item *item)
{
//special items first
for(int8 i=BANK_SLOT_BAG_START;i<BANK_SLOT_BAG_END;i++)
{
if(m_pItems[i])
{
if (m_pItems[i]->GetProto()->BagFamily == item->GetProto()->BagFamily)
{
if(m_pItems[i]->IsContainer())
{
bool result = static_cast<Container*>(m_pItems[i])->AddItemToFreeSlot(item);
if(result) { return true; }
}
}
}
}
for(int8 i= BANK_SLOT_ITEM_START;i< BANK_SLOT_ITEM_END;i++)
{
if(m_pItems[i] == NULL)
{
return SafeAddItem(item, INVENTORY_SLOT_NOT_SET, i);
}
}
for(int8 i=BANK_SLOT_BAG_START;i<BANK_SLOT_BAG_END;i++)
{
if(m_pItems[i] != NULL && m_pItems[i]->GetProto()->BagFamily == 0) //special bags ignored
{
for (int8 j =0; j < m_pItems[i]->GetProto()->ContainerSlots;j++)
{
Item *item2 = ((Container*)m_pItems[i])->GetItem(j);
if (item2 == NULL)
{
return SafeAddItem(item, i, j);
}
}
}
}
return false;
}
int8 ItemInterface::FindSpecialBag(Item *item)
{
for(int8 i=INVENTORY_SLOT_BAG_START;i<INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] != NULL)
{
if (m_pItems[i]->GetProto()->BagFamily == item->GetProto()->BagFamily)
{
return i;
}
}
}
return ITEM_NO_SLOT_AVAILABLE;
}
int8 ItemInterface::FindFreeKeyringSlot()
{
for(int8 i=INVENTORY_KEYRING_START;i<INVENTORY_KEYRING_END;i++)
{
if(m_pItems[i] == NULL)
{
return i;
}
}
return ITEM_NO_SLOT_AVAILABLE;
}
SlotResult ItemInterface::FindFreeInventorySlot(ItemPrototype *proto)
{
//special item
//special slots will be ignored of item is not set
if(proto)
{
if(proto->BagFamily)
{
if(proto->BagFamily == ITEM_TYPE_KEYRING)
{
for(int8 i = INVENTORY_KEYRING_START; i < INVENTORY_KEYRING_END; i++)
{
if(m_pItems[i] == NULL)
{
result.ContainerSlot = ITEM_NO_SLOT_AVAILABLE;
result.Slot = i;
result.Result = true;
return result;
}
}
}
else
{
for(int8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
{
if(m_pItems[i] && m_pItems[i]->IsContainer())
{
if (m_pItems[i]->GetProto()->BagFamily == proto->BagFamily)
{
int8 slot = ((Container*)m_pItems[i])->FindFreeSlot();
if(slot != ITEM_NO_SLOT_AVAILABLE)
{
result.ContainerSlot = i;
result.Slot = slot;
result.Result = true;
return result;
}
}
}
}
}
}
}
//backpack
for(int8 i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if(!item)
{
result.ContainerSlot = ITEM_NO_SLOT_AVAILABLE;
result.Slot = i;
result.Result = true;
return result;
}
}
//bags
for(int8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer() && !item->GetProto()->BagFamily)
{
int8 slot = ((Container*)m_pItems[i])->FindFreeSlot();
if(slot != ITEM_NO_SLOT_AVAILABLE)
{
result.ContainerSlot = i;
result.Slot = slot;
result.Result = true;
return result;
}
}
}
}
result.ContainerSlot = ITEM_NO_SLOT_AVAILABLE;
result.Slot = ITEM_NO_SLOT_AVAILABLE;
result.Result = false;
return result;
}
SlotResult ItemInterface::FindFreeBankSlot(ItemPrototype *proto)
{
//special item
//special slots will be ignored of item is not set
if(proto)
{
if(proto->BagFamily)
{
for(int8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END;i++)
{
if(m_pItems[i] && m_pItems[i]->IsContainer())
{
if (m_pItems[i]->GetProto()->BagFamily == proto->BagFamily)
{
int8 slot = ((Container*)m_pItems[i])->FindFreeSlot();
if(slot != ITEM_NO_SLOT_AVAILABLE)
{
result.ContainerSlot = i;
result.Slot = slot;
result.Result = true;
return result;
}
}
}
}
}
}
//backpack
for(int8 i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
{
Item *item = GetInventoryItem(i);
if(!item)
{
result.ContainerSlot = ITEM_NO_SLOT_AVAILABLE;
result.Slot = i;
result.Result = true;
return result;
}
}
//bags
for(int8 i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
{
Item *item = GetInventoryItem(i);
if(item)
{
if(item->IsContainer() && !item->GetProto()->BagFamily)
{
int8 slot = ((Container*)m_pItems[i])->FindFreeSlot();
if(slot != ITEM_NO_SLOT_AVAILABLE)
{
result.ContainerSlot = i;
result.Slot = slot;
result.Result = true;
return result;
}
}
}
}
result.ContainerSlot = ITEM_NO_SLOT_AVAILABLE;
result.Slot = ITEM_NO_SLOT_AVAILABLE;
result.Result = false;
return result;
}
void ItemInterface::ReduceItemDurability()
{
uint32 f = sRand.randInt(100);
if(f <= 10) //10% chance to loose 1 dur from a random valid item.
{
int32 slot = sRand.randInt(EQUIPMENT_SLOT_END);
Item *pItem = GetInventoryItem(INVENTORY_SLOT_NOT_SET, slot);
if(pItem)
{
if(pItem->GetUInt32Value(ITEM_FIELD_DURABILITY) && pItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY))
{
pItem->SetUInt32Value(ITEM_FIELD_DURABILITY, (pItem->GetUInt32Value(ITEM_FIELD_DURABILITY)-1));
//check final durabiity
if(!pItem->GetUInt32Value(ITEM_FIELD_DURABILITY)) //no dur left
{
this->GetOwner()->ApplyItemMods(pItem,slot,false);
}
}
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
2486
]
]
]
|
450a6d167db3d2154150a6e14a6189d90e1cf2ca | 4333d643613acfc1c84d8de951b53c451df995b3 | /moduled/dbfs/dbfs.cpp | 11cc55021c6f106da6a1339417d2012d90ae9613 | []
| no_license | BackupTheBerlios/forg-svn | c8f1c78135d4ff1a287fe92fe3c970a01fbaa685 | 95c4d86f47b31b00901fef71e232877fb95bf6a1 | refs/heads/master | 2016-09-06T08:18:48.279319 | 2006-05-11T11:57:36 | 2006-05-11T11:57:36 | 40,664,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | cpp | // dbfs.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
struct
{
void* hello;
} dll_interface ;
void hello();
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch( ul_reason_for_call )
{
case DLL_PROCESS_ATTACH:
printf( "DLL loaded sucesfully!\n" );
dll_interface.hello = &hello;
break;
case DLL_PROCESS_DETACH:
printf( "DLL Is Being Unloaded!\n" );
getchar();
break;
}
return TRUE;
}
void hello()
{
printf( "Hello, World! From DLL ;)\n" );
getchar();
}
/*void* get_interface()
{
return &dll_interface;
}*/
| [
"jartur@31294a5a-bf12-0410-abdd-c0a4511ea72c"
]
| [
[
[
1,
44
]
]
]
|
5e048c725025176e7088305e7bc7b2046e870597 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/python/test/callbacks.cpp | b25136b2b02a3a7095537df2f35c98ed6566b870 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,856 | cpp | // Copyright David Abrahams 2002.
// 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)
#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
#include <boost/python/class.hpp>
#include <boost/ref.hpp>
#include <boost/python/ptr.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/reference_existing_object.hpp>
#include <boost/python/call.hpp>
#include <boost/python/object.hpp>
#include <boost/assert.hpp>
using namespace boost::python;
BOOST_STATIC_ASSERT(converter::is_object_manager<handle<> >::value);
int apply_int_int(PyObject* f, int x)
{
return call<int>(f, x);
}
void apply_void_int(PyObject* f, int x)
{
call<void>(f, x);
}
struct X
{
explicit X(int x) : x(x), magic(7654321) { ++counter; }
X(X const& rhs) : x(rhs.x), magic(7654321) { ++counter; }
~X() { BOOST_ASSERT(magic == 7654321); magic = 6666666; x = 9999; --counter; }
void set(int x) { BOOST_ASSERT(magic == 7654321); this->x = x; }
int value() const { BOOST_ASSERT(magic == 7654321); return x; }
static int count() { return counter; }
private:
void operator=(X const&);
private:
int x;
long magic;
static int counter;
};
X apply_X_X(PyObject* f, X x)
{
return call<X>(f, x);
}
void apply_void_X_ref(PyObject* f, X& x)
{
call<void>(f, boost::ref(x));
}
X& apply_X_ref_handle(PyObject* f, handle<> obj)
{
return call<X&>(f, obj);
}
X* apply_X_ptr_handle_cref(PyObject* f, handle<> const& obj)
{
return call<X*>(f, obj);
}
void apply_void_X_cref(PyObject* f, X const& x)
{
call<void>(f, boost::cref(x));
}
void apply_void_X_ptr(PyObject* f, X* x)
{
call<void>(f, ptr(x));
}
void apply_void_X_deep_ptr(PyObject* f, X* x)
{
call<void>(f, x);
}
char const* apply_cstring_cstring(PyObject* f, char const* s)
{
return call<char const*>(f, s);
}
char const* apply_cstring_pyobject(PyObject* f, PyObject* s)
{
return call<char const*>(f, borrowed(s));
}
char apply_char_char(PyObject* f, char c)
{
return call<char>(f, c);
}
char const* apply_to_string_literal(PyObject* f)
{
return call<char const*>(f, "hello, world");
}
handle<> apply_to_own_type(handle<> x)
{
// Tests that we can return handle<> from a callback and that we
// can pass arbitrary handle<T>.
return call<handle<> >(x.get(), type_handle(borrowed(x->ob_type)));
}
object apply_object_object(PyObject* f, object x)
{
return call<object>(f, x);
}
int X::counter;
BOOST_PYTHON_MODULE(callbacks_ext)
{
def("apply_object_object", apply_object_object);
def("apply_to_own_type", apply_to_own_type);
def("apply_int_int", apply_int_int);
def("apply_void_int", apply_void_int);
def("apply_X_X", apply_X_X);
def("apply_void_X_ref", apply_void_X_ref);
def("apply_void_X_cref", apply_void_X_cref);
def("apply_void_X_ptr", apply_void_X_ptr);
def("apply_void_X_deep_ptr", apply_void_X_deep_ptr);
def("apply_X_ptr_handle_cref", apply_X_ptr_handle_cref
, return_value_policy<reference_existing_object>());
def("apply_X_ref_handle", apply_X_ref_handle
, return_value_policy<reference_existing_object>());
def("apply_cstring_cstring", apply_cstring_cstring);
def("apply_cstring_pyobject", apply_cstring_pyobject);
def("apply_char_char", apply_char_char);
def("apply_to_string_literal", apply_to_string_literal);
class_<X>("X", init<int>())
.def(init<X const&>())
.def("value", &X::value)
.def("set", &X::set)
;
def("x_count", &X::count);
}
#include "module_tail.cpp"
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
149
]
]
]
|
fb737d0e084d5357e1ce1346ee786821816d1f71 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEToolsCommon/SECollada/SEColladaSceneEffectL.cpp | 6187fb36d22c2adcc191bd1600cb82676c7fb956 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,402 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEToolsCommonPCH.h"
#include "SEColladaScene.h"
using namespace Swing;
//----------------------------------------------------------------------------
SEColladaEffect* SEColladaScene::GetEffect(const char* acName)
{
if( !acName )
{
return 0;
}
for( int i = 0; i < (int)m_Effects.size(); i++ )
{
if( strcmp(m_Effects[i]->GetName().c_str(), acName) == 0 )
{
return m_Effects[i];
}
}
return 0;
}
//----------------------------------------------------------------------------
bool SEColladaScene::LoadEffectLibrary(domLibrary_effectsRef spLib)
{
ToolSystem::DebugOutput("SEColladaScene::Loading SEEffect Library" );
int iEffectCount = (int)spLib->getEffect_array().getCount();
for( int i = 0; i < iEffectCount; i++ )
{
LoadEffect(spLib->getEffect_array()[i]);
}
return true;
}
//----------------------------------------------------------------------------
SEColladaEffect* SEColladaScene::LoadEffect(domEffectRef spDomEffect)
{
if( !spDomEffect )
{
return 0;
}
xsID strEffectID = spDomEffect->getId();
if( !strEffectID )
{
return 0;
}
SEColladaEffect* pEffect = GetEffect((const char*)strEffectID);
if( pEffect )
{
// This effect is already in our effect catalog.
return pEffect;
}
ToolSystem::DebugOutput("Add new effect %s", strEffectID);
domEffect* pDomEffect = (domEffect*)spDomEffect;
if( pDomEffect )
{
// CAUTION 1: effect element could have images.
// Get all images in this effect.
int iEffectImageCount = (int)pDomEffect->getImage_array().getCount();
for( int i = 0; i < iEffectImageCount; i++ )
{
LoadImage(pDomEffect->getImage_array()[i]);
}
// Create our effect base on COLLADA effect.
pEffect = SE_NEW SEColladaEffect;
pEffect->SetName(strEffectID);
// How many profiles are there?
int iProfileCount =
(int)pDomEffect->getFx_profile_abstract_array().getCount();
// Just scan the profiles to find the profile_COMMON for now.
for( int i = 0; i < iProfileCount; i++ )
{
domFx_profile_abstract* pDomProfile =
pDomEffect->getFx_profile_abstract_array()[i];
char* acTypeName = (char*)pDomProfile->getTypeName();
if( strcmp("profile_COMMON", acTypeName) == 0 )
{
// Found the common profile, get the technique from it as well.
domProfile_COMMON* pDomProfileCommon =
(domProfile_COMMON*)pDomProfile;
// CAUTION 2: profile element could have images.
// Get all images in profile_COMMON.
int iProfileImageCount =
(int)pDomProfileCommon->getImage_array().getCount();
for( int j = 0; j < iProfileImageCount; j++ )
{
LoadImage(pDomProfileCommon->getImage_array()[j]);
}
domProfile_COMMON::domTechnique* pDomTechnique =
pDomProfileCommon->getTechnique();
if( !pDomTechnique )
{
break;
}
// CAUTION 3: technique element could have images.
// Get all images in profile_COMMON's technique.
int iTechniqueImageCount =
(int)pDomTechnique->getImage_array().getCount();
for( int j = 0; j < iTechniqueImageCount; j++ )
{
LoadImage(pDomTechnique->getImage_array()[j]);
}
// This support is really basic, since the shader models don't
// descend from a common type.
// We have to handle each one individually. There can only be
// one lighting model in the technique.
// All of them assume the texture is in the diffuse component
// for now.
SEColladaShaderElements tempShaderElements;
domProfile_COMMON::domTechnique::domConstant* pDomConstant =
pDomTechnique->getConstant();
if( pDomConstant )
{
ParseConstant(pEffect, &tempShaderElements, pDomConstant);
}
domProfile_COMMON::domTechnique::domLambert* pDomLambert =
pDomTechnique->getLambert();
if( pDomLambert )
{
ParseLambert(pEffect, &tempShaderElements, pDomLambert);
}
domProfile_COMMON::domTechnique::domPhong* pDomPhong =
pDomTechnique->getPhong();
if( pDomPhong )
{
ParsePhong(pEffect, &tempShaderElements, pDomPhong);
}
domProfile_COMMON::domTechnique::domBlinn* pDomBlinn =
pDomTechnique->getBlinn();
if( pDomBlinn )
{
ParseBlinn(pEffect, &tempShaderElements, pDomBlinn);
}
// Hash the newparam elements of the profile for later use.
domCommon_newparam_type_Array& rDomNewparamArray =
pDomProfileCommon->getNewparam_array();
std::map<std::string, domCommon_newparam_type*> tempNewParams;
int iNewParamCount = (int)rDomNewparamArray.getCount();
for( int j = 0; j < iNewParamCount; j++ )
{
xsNCName strNewParamSID = rDomNewparamArray[j]->getSid();
tempNewParams[strNewParamSID] = rDomNewparamArray[j];
}
// TODO:
// Take only the texture from diffuse for now.
SETexture* pTexture = GetTextureFromShaderElement(
tempNewParams, tempShaderElements.Diffuse);
if( pTexture )
{
pEffect->Textures.push_back(pTexture);
}
// Handle an effect with no texture.
m_Effects.push_back(pEffect);
return pEffect;
}
else
{
ToolSystem::DebugOutput("%s is not supported yet",
acTypeName);
}
}
}
return 0;
}
//----------------------------------------------------------------------------
float SEColladaScene::GetFloat(domCommon_float_or_param_type* pParam)
{
if( pParam->getFloat() )
{
return (float)pParam->getFloat()->getValue();
}
return 0.0f;
}
//----------------------------------------------------------------------------
SEColorRGB SEColladaScene::GetColor(
domCommon_color_or_texture_type_complexType* pParam)
{
if( pParam->getColor() )
{
domFx_color_common& rDomColor = pParam->getColor()->getValue();
return SEColorRGB((float)rDomColor[0], (float)rDomColor[1],
(float)rDomColor[2]);
}
return SEColorRGB::SE_RGB_BLACK;
}
//----------------------------------------------------------------------------
SETexture* SEColladaScene::GetTextureFromShaderElement(
std::map<std::string, domCommon_newparam_type*>& rNewParams,
domCommon_color_or_texture_type* pShaderElement)
{
if( !pShaderElement )
{
return 0;
}
domCommon_color_or_texture_type::domTexture* pDomTextureElement =
pShaderElement->getTexture();
if( !pDomTextureElement )
{
return 0;
}
// If we can not find the newparam of sampler from our hash map,
// then we try to solve it by using DAE runtime helper functions.
std::string strSamplerSID = pDomTextureElement->getTexture();
domCommon_newparam_type* pDomNewParam = rNewParams[strSamplerSID];
if( !pDomNewParam )
{
xsIDREF tempIDRef(strSamplerSID.c_str());
tempIDRef.setContainer(pShaderElement);
tempIDRef.resolveElement();
domImage* pDomImage = (domImage*)tempIDRef.getElement();
SEImage* pImage = LoadImage(pDomImage);
SE_ASSERT( pImage );
SETexture* pTexture = SE_NEW SETexture(pImage);
return pTexture;
}
std::string strSurfaceSID =
pDomNewParam->getSampler2D()->getSource()->getValue();
pDomNewParam = rNewParams[strSurfaceSID];
domFx_surface_init_common* pDomSurfaceInit =
pDomNewParam->getSurface()->getFx_surface_init_common();
if( !pDomSurfaceInit )
{
return 0;
}
xsIDREF& rIDRef = pDomSurfaceInit->getInit_from_array()[0]->getValue();
rIDRef.resolveElement();
domImage* pDomImage = (domImage*)rIDRef.getElement();
SEImage* pImage = LoadImage(pDomImage);
SE_ASSERT( pImage );
SETexture* pTexture = SE_NEW SETexture(pImage);
return pTexture;
}
//----------------------------------------------------------------------------
void SEColladaScene::ParseConstant(SEColladaEffect* pEffect,
SEColladaShaderElements* pShaderElements,
domProfile_COMMON::domTechnique::domConstant* pDomConstant)
{
pShaderElements->Emission = pDomConstant->getEmission();
if( pShaderElements->Emission )
{
pEffect->Material->Emissive = GetColor(pShaderElements->Emission);
}
pShaderElements->Reflective = pDomConstant->getReflective();
if( pShaderElements->Reflective )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflective =
// GetColor(pShaderElements->Reflective);
}
pShaderElements->Reflectivity = pDomConstant->getReflectivity();
if( pShaderElements->Reflectivity )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflectivity =
// GetFloat(pShaderElements->Reflectivity);
}
pShaderElements->Transparent = pDomConstant->getTransparent();
if( pShaderElements->Transparent )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Transparent = GetColor(pShaderElements->Transparent);
}
pShaderElements->Transarency = pDomConstant->getTransparency();
if( pShaderElements->Transarency )
{
pEffect->Material->Alpha = GetFloat(pShaderElements->Transarency);
}
pShaderElements->IndexOfRefaction = pDomConstant->getIndex_of_refraction();
if( pShaderElements->IndexOfRefaction )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->RefractiveIndex =
// GetFloat(pShaderElements->IndexOfRefaction);
}
}
//----------------------------------------------------------------------------
void SEColladaScene::ParseLambert(SEColladaEffect* pEffect,
SEColladaShaderElements* pShaderElements,
domProfile_COMMON::domTechnique::domLambert* pDomLambert)
{
pShaderElements->Emission = pDomLambert->getEmission();
if( pShaderElements->Emission )
{
pEffect->Material->Emissive = GetColor(pShaderElements->Emission);
}
pShaderElements->Ambient = pDomLambert->getAmbient();
if( pShaderElements->Ambient )
{
pEffect->Material->Ambient = GetColor(pShaderElements->Ambient);
}
pShaderElements->Diffuse = pDomLambert->getDiffuse();
if( pShaderElements->Diffuse )
{
pEffect->Material->Diffuse = GetColor(pShaderElements->Diffuse);
}
pShaderElements->Reflective = pDomLambert->getReflective();
if( pShaderElements->Reflective )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflective =
// GetColor(pShaderElements->Reflective);
}
pShaderElements->Reflectivity = pDomLambert->getReflectivity();
if( pShaderElements->Reflectivity )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflectivity =
// GetFloat(pShaderElements->Reflectivity);
}
pShaderElements->Transparent = pDomLambert->getTransparent();
if( pShaderElements->Transparent )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Transparent = GetColor(pShaderElements->Transparent);
}
pShaderElements->Transarency = pDomLambert->getTransparency();
if( pShaderElements->Transarency )
{
pEffect->Material->Alpha = GetFloat(pShaderElements->Transarency);
}
pShaderElements->IndexOfRefaction = pDomLambert->getIndex_of_refraction();
if( pShaderElements->IndexOfRefaction )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->RefractiveIndex =
// GetFloat(pShaderElements->IndexOfRefaction);
}
}
//----------------------------------------------------------------------------
void SEColladaScene::ParsePhong(SEColladaEffect* pEffect,
SEColladaShaderElements* pShaderElements,
domProfile_COMMON::domTechnique::domPhong* pDomPhong)
{
pShaderElements->Emission = pDomPhong->getEmission();
if( pShaderElements->Emission )
{
pEffect->Material->Emissive = GetColor(pShaderElements->Emission);
}
pShaderElements->Ambient = pDomPhong->getAmbient();
if( pShaderElements->Ambient )
{
pEffect->Material->Ambient = GetColor(pShaderElements->Ambient);
}
pShaderElements->Diffuse = pDomPhong->getDiffuse();
if( pShaderElements->Diffuse )
{
pEffect->Material->Diffuse = GetColor(pShaderElements->Diffuse);
}
pShaderElements->Specular = pDomPhong->getSpecular();
if( pShaderElements->Specular )
{
pEffect->Material->Specular = GetColor(pShaderElements->Specular);
}
pShaderElements->Shininess = pDomPhong->getShininess();
if( pShaderElements->Shininess )
{
pEffect->Material->Shininess = GetFloat(pShaderElements->Shininess);
}
pShaderElements->Reflective = pDomPhong->getReflective();
if( pShaderElements->Reflective )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflective =
// GetColor(pShaderElements->Reflective);
}
pShaderElements->Reflectivity = pDomPhong->getReflectivity();
if( pShaderElements->Reflectivity )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflectivity =
// GetFloat(pShaderElements->Reflectivity);
}
pShaderElements->Transparent = pDomPhong->getTransparent();
if( pShaderElements->Transparent )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Transparent = GetColor(pShaderElements->Transparent);
}
pShaderElements->Transarency = pDomPhong->getTransparency();
if( pShaderElements->Transarency )
{
pEffect->Material->Alpha = GetFloat(pShaderElements->Transarency);
}
pShaderElements->IndexOfRefaction = pDomPhong->getIndex_of_refraction();
if( pShaderElements->IndexOfRefaction )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->RefractiveIndex =
// GetFloat(pShaderElements->IndexOfRefaction);
}
}
//----------------------------------------------------------------------------
void SEColladaScene::ParseBlinn(SEColladaEffect* pEffect,
SEColladaShaderElements* pShaderElements,
domProfile_COMMON::domTechnique::domBlinn* pDomblinn)
{
pShaderElements->Emission = pDomblinn->getEmission();
if( pShaderElements->Emission )
{
pEffect->Material->Emissive = GetColor(pShaderElements->Emission);
}
pShaderElements->Ambient = pDomblinn->getAmbient();
if( pShaderElements->Ambient )
{
pEffect->Material->Ambient = GetColor(pShaderElements->Ambient);
}
pShaderElements->Diffuse = pDomblinn->getDiffuse();
if( pShaderElements->Diffuse )
{
pEffect->Material->Diffuse = GetColor(pShaderElements->Diffuse);
}
pShaderElements->Specular = pDomblinn->getSpecular();
if( pShaderElements->Specular )
{
pEffect->Material->Specular = GetColor(pShaderElements->Specular);
}
pShaderElements->Shininess = pDomblinn->getShininess();
if( pShaderElements->Shininess )
{
pEffect->Material->Shininess = GetFloat(pShaderElements->Shininess);
}
pShaderElements->Reflective = pDomblinn->getReflective();
if( pShaderElements->Reflective )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflective =
// GetColor(pShaderElements->Reflective);
}
pShaderElements->Reflectivity = pDomblinn->getReflectivity();
if( pShaderElements->Reflectivity )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->Reflectivity =
// GetFloat(pShaderElements->Reflectivity);
}
pShaderElements->Transparent = pDomblinn->getTransparent();
if( pShaderElements->Transparent )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Transparent = GetColor(pShaderElements->Transparent);
}
pShaderElements->Transarency = pDomblinn->getTransparency();
if( pShaderElements->Transarency )
{
pEffect->Material->Alpha = GetFloat(pShaderElements->Transarency);
}
pShaderElements->IndexOfRefaction = pDomblinn->getIndex_of_refraction();
if( pShaderElements->IndexOfRefaction )
{
// TODO:
// We don't have this parameter for now.
// pEffect->Material->RefractiveIndex =
// GetFloat(pShaderElements->IndexOfRefaction);
}
}
//---------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
553
]
]
]
|
ecb40f4f172d2e4866766edecfc141687197c7ef | 898bce7e226fcd51aa6cacfa73ffbbecf9a8425b | /src/core/NppPluginMsgSender.h | 1609a02c8e8b86941abf4fdb8dfe66be7b3c4fe9 | []
| no_license | azhai/IndentByFold | a1b966255f34e97eb7940e165c67800a403c5a0a | 45e193ab4f8c413c0090633893eaad815181bfc2 | refs/heads/master | 2021-01-01T03:53:56.723994 | 2011-09-18T19:21:49 | 2011-09-18T19:21:49 | 58,097,931 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | h | #ifndef _npp_plugin_msg_sender_h_
#define _npp_plugin_msg_sender_h_
//---------------------------------------------------------------------------
#include "base.h"
#include "npp_stuff/PluginInterface.h"
#include <string>
class CNppPluginMsgSender
{
protected:
HWND m_hNppWnd;
std::basic_string<TCHAR> m_srcModuleName;
public:
CNppPluginMsgSender( HWND hNppWnd, const TCHAR* srcModuleName ) :
m_hNppWnd( hNppWnd ), m_srcModuleName( srcModuleName ) {
}
void setSrcModuleName( const TCHAR* srcModuleName ) {
m_srcModuleName = srcModuleName;
}
BOOL SendMsg( const TCHAR *destModuleName, long internalMsg, void* info ) {
CommunicationInfo ci = { internalMsg,
m_srcModuleName.c_str(),
info
};
return ( BOOL ) ::SendMessage( m_hNppWnd,
NPPM_MSGTOPLUGIN,
( WPARAM ) destModuleName,
( LPARAM ) &ci
);
}
};
//---------------------------------------------------------------------------
#endif
| [
"[email protected]"
]
| [
[
[
1,
38
]
]
]
|
54e34b782d65487cda78d2ae61dc1522b64b8573 | 282057a05d0cbf9a0fe87457229f966a2ecd3550 | /EIBStdLib/src/xml/xpath_expression.cpp | d753719a4527704cb9cfecb739526193213d1c2b | []
| 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 | 5,425 | cpp | /*
www.sourceforge.net/projects/tinyxpath
Copyright (c) 2002-2004 Yves Berquin ([email protected])
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "xml/xpath_expression.h"
#include "xml/lex_util.h"
namespace TinyXPath
{
/// Get the expression_result as an int
int expression_result::i_get_int ()
{
switch (e_type)
{
case e_int :
return i_content;
case e_bool :
return o_content ? 1 : 0;
case e_double :
return (int) (d_content);
default :
return atoi (S_get_string () . c_str ());
}
}
/// Get the expression_result as a double
double expression_result::d_get_double ()
{
switch (e_type)
{
case e_double :
return d_content;
case e_int :
return (double) i_content;
case e_bool :
return o_content ? 1.0 : 0.0;
default :
return atof (S_get_string () . c_str ());
}
}
/// Get the expression_result as a string
TIXML_STRING expression_result::S_get_string ()
{
TIXML_STRING S_res;
node_set * nsp_ptr;
S_res = "";
switch (e_type)
{
case e_string :
S_res = S_content;
break;
case e_int :
v_assign_int_to_string (S_res, i_get_int ());
break;
case e_double :
v_assign_double_to_string (S_res, d_get_double ());
break;
case e_node_set :
// See XPath 1.0 spec, 4.2 :
// An argument is converted to type string as if by calling the string function
// ...
// A node-set is converted to a string by returning the string-value of the node
// in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
nsp_ptr = nsp_get_node_set ();
if (nsp_ptr -> u_get_nb_node_in_set ())
{
nsp_ptr -> v_document_sort (XNp_root);
if (nsp_ptr -> o_is_attrib (0))
S_res = nsp_ptr -> XAp_get_attribute_in_set (0) -> Value ();
else
S_res = nsp_ptr -> XNp_get_node_in_set (0) -> Value ();
}
break;
case e_bool :
if (o_get_bool ())
S_res = "true";
else
S_res = "false";
break;
case e_invalid:
break;
}
return S_res;
}
/**
Get the expression_result as a bool\n
The boolean function converts its argument to a boolean as follows:
- a number is true if and only if it is neither positive or negative zero nor NaN
- a node-set is true if and only if it is non-empty
- a string is true if and only if its length is non-zero
- an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type
*/
bool expression_result::o_get_bool ()
{
node_set * nsp_ptr;
switch (e_type)
{
case e_int :
return i_content != 0;
case e_double :
return (d_get_double () == 0.0);
case e_string :
return S_content . length () > 0;
break;
case e_node_set :
// See XPath 1.0 spec, 3.2 :
// An argument is converted to type string as if by calling the string function
// ...
// A node-set is converted to a string by returning the string-value of the node
// in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
nsp_ptr = nsp_get_node_set ();
return nsp_ptr -> u_get_nb_node_in_set () != 0;
case e_bool :
return o_content;
case e_invalid:
break;
}
return false;
}
#ifdef TINYXPATH_DEBUG
/// Debug function to print an expression_result to stdout
void expression_result::v_dump ()
{
switch (e_type)
{
case e_bool :
printf (" bool : %s\n", o_content ? "true" : "false");
break;
case e_string :
printf (" string : %s\n", S_content . c_str ());
break;
case e_int :
printf (" int : %d", i_content);
if (S_comment . length ())
printf (" (%s)", S_comment . c_str ());
printf ("\n");
break;
case e_double :
printf (" double : %f\n", d_content);
break;
case e_node_set :
printf (" node set\n");
ns_set . v_dump ();
break;
case e_invalid :
printf (" (invalid)\n");
break;
}
}
#endif
}
| [
"[email protected]"
]
| [
[
[
1,
178
]
]
]
|
4bf59137351e79ea7662b32db2de1ba1e894a580 | 113b284df51a798c943e36aaa21273e7379391a9 | /RecycleBinGadget/RecycleBinDLL/recyclebin.h | 6b5772e1810e0437f4e65fa0235c366df30759cd | []
| no_license | ccMatrix/desktopgadgets | bf171b75b446faf16443202c06e98c0a4b5eef7c | f5fa36e042ce274910f62e5d3510072ae07acf5e | refs/heads/master | 2020-12-25T19:26:10.514144 | 2010-03-01T23:24:15 | 2010-03-01T23:24:15 | 32,254,664 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 991 | h | // recyclebin.h : Deklaration von Crecyclebin
#pragma once
#include "resource.h" // Hauptsymbole
#include "RecycleBinDLL.h"
// Crecyclebin
class ATL_NO_VTABLE Crecyclebin :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<Crecyclebin, &CLSID_recyclebin>,
public IDispatchImpl<Irecyclebin, &IID_Irecyclebin, &LIBID_RecycleBinDLLLib, /*wMajor =*/ 0xFFFF, /*wMinor =*/ 0xFFFF>
{
public:
Crecyclebin()
{
}
DECLARE_REGISTRY_RESOURCEID(IDR_RECYCLEBIN)
BEGIN_COM_MAP(Crecyclebin)
COM_INTERFACE_ENTRY(Irecyclebin)
COM_INTERFACE_ENTRY(IDispatch)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease()
{
}
public:
STDMETHOD(binStatus)(USHORT* status);
STDMETHOD(openRecycleBin)(void);
STDMETHOD(emptyBin)(void);
STDMETHOD(moveToBin)(BSTR* filename);
void logError(char* str);
};
OBJECT_ENTRY_AUTO(__uuidof(recyclebin), Crecyclebin)
| [
"codename.matrix@e00a1d1f-563d-0410-a555-bbce3309907e"
]
| [
[
[
1,
50
]
]
]
|
8f65ada32436e3524cf996e32ee2b4ca9f77b802 | fad6f9883d4ad2686c196dc532a9ecb9199500ee | /NXP-LPC/CommTest/CommTest/PacketDetailDlg.cpp | b06212a00f946d3775002e8e6062ed4f489c90ae | []
| no_license | aquarius20th/nxp-lpc | fe83d6a140d361a1737d950ff728c6ea9a16a1dd | 4abfb804daf0ac9c59bd90d879256e7a3c1b2f30 | refs/heads/master | 2021-01-10T13:54:40.237682 | 2009-12-22T14:54:59 | 2009-12-22T14:54:59 | 48,420,260 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,731 | cpp | // PacketDetailDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "CommTest.h"
#include "PacketDetailDlg.h"
#include "Packet.h"
typedef enum PACKET_COL
{
PACKET_COLUMN_IDX, //名称
PACKET_COLUMN_HEX, //
PACKET_COLUMN_DEC ,
PACKET_COLUMN_ASC
};
// CPacketDetailDlg 对话框
IMPLEMENT_DYNAMIC(CPacketDetailDlg, CBCGPDialog)
CPacketDetailDlg::CPacketDetailDlg(CPacket *pPacket,CWnd* pParent /*=NULL*/)
: CBCGPDialog(CPacketDetailDlg::IDD, pParent)
,m_pPacket(pPacket)
, m_nId(0)
{
ASSERT(pPacket);
ASSERT( m_pPacket);
}
CPacketDetailDlg::~CPacketDetailDlg()
{
}
void CPacketDetailDlg::DoDataExchange(CDataExchange* pDX)
{
CBCGPDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_STATIC_PACKET_ID, m_nId);
}
BEGIN_MESSAGE_MAP(CPacketDetailDlg, CBCGPDialog)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CPacketDetailDlg 消息处理程序
const int GRID_TOP = 24;
BOOL CPacketDetailDlg::OnInitDialog()
{
CBCGPDialog::OnInitDialog();
EnableVisualManagerStyle( );
// TODO: 在此添加额外的初始化
m_nId = m_pPacket->m_nId;
CRect rectGrid;
GetClientRect (&rectGrid);
rectGrid.top += GRID_TOP;
m_wndGridTree.Create (WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER, rectGrid, this, (UINT)-1);
m_wndGridTree.EnableColumnAutoSize (TRUE);
m_wndGridTree.SetSingleSel (FALSE);
m_wndGridTree.EnableGroupByBox (FALSE);
m_wndGridTree.SetReadOnly ();
m_wndGridTree.SetWholeRowSel ();
m_wndGridTree.EnableHeader (TRUE, 0);
CBitmap bmp;
bmp.LoadBitmap (IDB_BITMAP_LIST);
m_Images.Create (16, 16, ILC_COLOR32 | ILC_MASK, 0, 0);
m_Images.Add (&bmp, RGB (255, 0, 255));
m_wndGridTree.SetImageList (&m_Images);
CBCGPGridColors colors;
colors.m_LeftOffsetColors.m_clrBackground = globalData.clrWindow;
m_wndGridTree.SetColorTheme (colors);
m_wndGridTree.InsertColumn (PACKET_COLUMN_IDX, _T(" "), 120);
m_wndGridTree.InsertColumn (PACKET_COLUMN_HEX, _T("十六进制"), 130);
m_wndGridTree.InsertColumn (PACKET_COLUMN_DEC, _T("十进制"), 130);
m_wndGridTree.InsertColumn (PACKET_COLUMN_ASC, _T("ASC"), 130);
UpdateTree();
CWnd *pWnd = GetDlgItem(IDC_STATIC_PACKET_TIME);
ASSERT(pWnd);
if(pWnd)
{
CString szTxt;
szTxt.Format( _T("%d-%02d-%02d %02d:%02d:%02d.%03d"),m_pPacket->m_stBuild.wYear,
m_pPacket->m_stBuild.wMonth,m_pPacket->m_stBuild.wDay,m_pPacket->m_stBuild.wHour,
m_pPacket->m_stBuild.wMinute,m_pPacket->m_stBuild.wSecond,m_pPacket->m_stBuild.wMilliseconds);
pWnd->SetWindowText(szTxt);
}
UpdateData(FALSE);
return TRUE; // return TRUE unless you set the focus to a control
// 异常: OCX 属性页应返回 FALSE
}
void CPacketDetailDlg::OnSize(UINT nType, int cx, int cy)
{
CBCGPDialog::OnSize(nType, cx, cy);
// TODO: 在此处添加消息处理程序代码
if (m_wndGridTree.GetSafeHwnd())
{
CRect rc;
GetClientRect(rc);
rc.top += GRID_TOP;
rc.InflateRect(1,1);
m_wndGridTree.MoveWindow(rc);
}
}
CBCGPGridRow* CPacketDetailDlg::CreateNewRow ()
{
CBCGPGridRow* pRow = m_wndGridTree. CreateRow (m_wndGridTree.GetColumnCount ());
for (int i = 0; i < m_wndGridTree.GetColumnCount ();i++)
{
pRow->GetItem (i)->AllowEdit (FALSE);
}
return pRow;
}
void CPacketDetailDlg:: UpdateTree( )
{
if (m_wndGridTree.GetSafeHwnd() == NULL)
return;
ASSERT(m_pPacket);
if(m_pPacket == NULL)
return;
CBCGPGridRow* pRootRow = CreateNewRow ( );
ASSERT_VALID (pRootRow);
pRootRow->AllowSubItems ();
unsigned char *pData = NULL;
unsigned int nLen = 0;
pData = m_pPacket->GetPacket(nLen);
if (pData && nLen && nLen <= MAX_PACKET_LEN)
{
CString szTxt;
szTxt.Format(_T("长度:%d"),nLen);
pRootRow->GetItem (PACKET_COLUMN_IDX)->SetValue ( _variant_t (szTxt) ,FALSE);
pRootRow->GetItem (PACKET_COLUMN_IDX)->SetImage (32,FALSE);
m_wndGridTree.AddRow (pRootRow, FALSE);
unsigned int i = 0;
for (i = 0 ;i <nLen; i++)
{
//版本信息
CBCGPGridRow* pDataRow = CreateNewRow ( );
ASSERT_VALID(pDataRow);
pDataRow->GetItem (PACKET_COLUMN_IDX)->SetImage (35,FALSE);
szTxt.Format(_T("%d"),i+1);
pDataRow->GetItem (PACKET_COLUMN_IDX)->SetValue ( _variant_t (szTxt),FALSE);
szTxt.Format(_T("%02X"),pData[i]);
pDataRow->GetItem (PACKET_COLUMN_HEX)->SetValue ( _variant_t (szTxt),FALSE);
szTxt.Format(_T("%02d"),pData[i]);
pDataRow->GetItem (PACKET_COLUMN_DEC)->SetValue ( _variant_t (szTxt),FALSE);
szTxt.Format(_T("%C"),pData[i]);
pDataRow->GetItem (PACKET_COLUMN_ASC)->SetValue ( _variant_t (szTxt),FALSE);
pRootRow->AddSubItem (pDataRow, FALSE);
}
m_wndGridTree.AdjustLayout();
}
}
| [
"lijin.unix@13de9a6c-71d3-11de-b374-81e7cb8b6ca2"
]
| [
[
[
1,
183
]
]
]
|
dc4a560afa9a0bc7e991067c231b2b8b207b4d57 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-world/Player.cpp | b8c0d6d75c53ff0be8d59fe540993404bd77be9c | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 322,027 | cpp | /*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
UpdateMask Player::m_visibleUpdateMask;
#define COLLISION_MOUNT_CHECK_INTERVAL 1000
Player::Player( uint32 guid ) : m_mailBox(guid)
{
int i,j;
m_objectTypeId = TYPEID_PLAYER;
m_valuesCount = PLAYER_END;
m_uint32Values = _fields;
memset(m_uint32Values, 0,(PLAYER_END)*sizeof(uint32));
m_updateMask.SetCount(PLAYER_END);
SetUInt32Value( OBJECT_FIELD_TYPE,TYPE_PLAYER|TYPE_UNIT|TYPE_OBJECT);
SetUInt32Value( OBJECT_FIELD_GUID,guid);
m_wowGuid.Init(GetGUID());
m_finishingmovesdodge = false;
iActivePet = 0;
// resurrector = 0;
SpellCrtiticalStrikeRatingBonus = 0;
SpellHasteRatingBonus = 1.0f;
m_lifetapbonus = 0;
info = NULL; // Playercreate info
SoulStone = 0;
SoulStoneReceiver = 0;
misdirectionTarget = 0;
bReincarnation = false;
removeReagentCost = false;
m_furorChance = 0;
Seal = 0;
judgespell = 0;
m_session = 0;
TrackingSpell = 0;
m_status = 0;
offhand_dmg_mod = 0.5;
m_walkSpeed = 2.5f;
m_runSpeed = PLAYER_NORMAL_RUN_SPEED;
m_isMoving = false;
strafing = false;
jumping = false;
moving = false;
m_ShapeShifted = 0;
m_curTarget = 0;
m_curSelection = 0;
m_lootGuid = 0;
m_Summon = NULL;
m_PetNumberMax = 0;
m_lastShotTime = 0;
m_H_regenTimer = 0;
m_P_regenTimer = 0;
m_onTaxi = false;
m_taxi_pos_x = 0;
m_taxi_pos_y = 0;
m_taxi_pos_z = 0;
m_taxi_ride_time = 0;
// Attack related variables
m_blockfromspellPCT = 0;
m_critfromspell = 0;
m_spellcritfromspell = 0;
m_hitfromspell = 0;
m_healthfromspell = 0;
m_manafromspell = 0;
m_healthfromitems = 0;
m_manafromitems = 0;
m_talentresettimes = 0;
m_nextSave = getMSTime() + sWorld.getIntRate(INTRATE_SAVE);
m_currentSpell = NULL;
m_resurrectHealth = m_resurrectMana = 0;
m_GroupInviter = 0;
Lfgcomment = "";
for(i=0;i<3;i++)
{
LfgType[i]=0;
LfgDungeonId[i]=0;
}
for(i=0;i<28;i++){
MechanicDurationPctMod[i]=0;
}
m_Autojoin = false;
m_AutoAddMem = false;
LfmDungeonId=0;
LfmType=0;
m_invitersGuid = 0;
m_currentMovement = MOVE_UNROOT;
m_isGmInvisible = false;
//DK
m_invitersGuid = 0;
//Trade
ResetTradeVariables();
mTradeTarget = 0;
//Duel
DuelingWith = NULL;
m_duelCountdownTimer = 0;
m_duelStatus = 0;
m_duelState = DUEL_STATE_FINISHED; // finished
//WayPoint
waypointunit = NULL;
//PVP
//PvPTimeoutEnabled = false;
//Tutorials
for (i = 0 ; i < 8 ; i++ )
m_Tutorials[ i ] = 0x00;
m_lootGuid = 0;
m_banned = false;
//Bind possition
m_bind_pos_x = 0;
m_bind_pos_y = 0;
m_bind_pos_z = 0;
m_bind_mapid = 0;
m_bind_zoneid = 0;
// Rest
m_timeLogoff = 0;
m_isResting = 0;
m_restState = 0;
m_restAmount = 0;
m_afk_reason = "";
m_playedtime[0] = 0;
m_playedtime[1] = 0;
m_playedtime[2] = (uint32)UNIXTIME;
m_AllowAreaTriggerPort = true;
// Battleground
m_bgEntryPointMap = 0;
m_bgEntryPointX = 0;
m_bgEntryPointY = 0;
m_bgEntryPointZ = 0;
m_bgEntryPointO = 0;
m_bgQueueType = 0;
m_bgQueueInstanceId = 0;
m_bgIsQueued = false;
m_bg = 0;
m_bgHasFlag = false;
m_bgEntryPointInstance = 0;
// gm stuff
//m_invincible = false;
bGMTagOn = false;
CooldownCheat = false;
CastTimeCheat = false;
PowerCheat = false;
GodModeCheat = false;
FlyCheat = false;
//FIX for professions
weapon_proficiency = 0x4000;//2^14
//FIX for shit like shirt etc
armor_proficiency = 1;
m_bUnlimitedBreath = false;
m_UnderwaterState = 0;
m_UnderwaterTime = 60000;
m_UnderwaterMaxTime = 60000;
m_UnderwaterLastDmg = getMSTime();
m_SwimmingTime = 0;
m_BreathDamageTimer = 0;
//transport shit
m_TransporterGUID = 0;
m_TransporterX = 0.0f;
m_TransporterY = 0.0f;
m_TransporterZ = 0.0f;
m_TransporterO = 0.0f;
m_TransporterTime = 0.0f;
m_lockTransportVariables= false;
// Autoshot variables
m_AutoShotTarget = 0;
m_onAutoShot = false;
m_AutoShotDuration = 0;
m_AutoShotAttackTimer = 0;
m_AutoShotSpell = NULL;
m_AttackMsgTimer = 0;
timed_quest_slot = 0;
m_GM_SelectedGO = 0;
for(i = 0;i < 7; i++)
{
FlatResistanceModifierPos[i] = 0;
FlatResistanceModifierNeg[i] = 0;
BaseResistanceModPctPos[i] = 0;
BaseResistanceModPctNeg[i] = 0;
ResistanceModPctPos[i] = 0;
ResistanceModPctNeg[i] = 0;
SpellDelayResist[i] = 0;
m_casted_amount[i] = 0;
}
for(i = 0; i < 6; i++)
for(j = 0; j < 7; j++)
{
SpellHealDoneByAttribute[i][j] = 0;
}
for(i = 0; i < 5; i++)
{
FlatStatModPos[i] = 0;
FlatStatModNeg[i] = 0;
StatModPctPos[i] = 0;
StatModPctNeg[i] = 0;
TotalStatModPctPos[i] = 0;
TotalStatModPctNeg[i] = 0;
}
for(i = 0; i < 12; i++)
{
IncreaseDamageByType[i] = 0;
IncreaseDamageByTypePCT[i] = 0;
IncreaseCricticalByTypePCT[i] = 0;
}
PctIgnoreRegenModifier = 0.0f;
m_retainedrage = 0;
DetectedRange = 0;
m_targetIcon = 0;
bShouldHaveLootableOnCorpse = false;
m_MountSpellId = 0;
bHasBindDialogOpen = false;
m_CurrentCharm = 0;
m_CurrentTransporter = NULL;
m_SummonedObject = NULL;
m_currentLoot = (uint64)NULL;
pctReputationMod = 0;
roll = 0;
mUpdateCount = 0;
mCreationCount = 0;
bCreationBuffer.reserve(40000);
bUpdateBuffer.reserve(30000);//ought to be > than enough ;)
mOutOfRangeIds.reserve(1000);
mOutOfRangeIdCount = 0;
bProcessPending = false;
for(i = 0; i < 25; ++i)
m_questlog[i] = NULL;
m_ItemInterface = new ItemInterface(this);
CurrentGossipMenu = NULL;
SDetector = new SpeedCheatDetector;
cannibalize = false;
m_AreaID = 0;
m_actionsDirty = false;
cannibalizeCount = 0;
rageFromDamageDealt = 0;
rageFromDamageTaken = 0;
m_honorToday = 0;
m_honorYesterday = 0;
m_honorPoints = 0;
m_killsToday = 0;
m_killsYesterday = 0;
m_killsLifetime = 0;
m_honorless = false;
m_lastSeenWeather = 0;
m_attacking = false;
myCorpse = 0;
bCorpseCreateable = true;
blinked = false;
m_explorationTimer = getMSTime();
linkTarget = 0;
AuraStackCheat = false;
TriggerpassCheat = false;
m_pvpTimer = 0;
m_globalCooldown = 0;
m_lastHonorResetTime = 0;
memset(&mActions, 0, PLAYER_ACTION_BUTTON_SIZE);
tutorialsDirty = true;
m_TeleportState = 1;
m_beingPushed = false;
for(i = 0; i < NUM_CHARTER_TYPES; ++i)
m_charters[i]=NULL;
for(i = 0; i < NUM_ARENA_TEAM_TYPES; ++i)
m_arenaTeams[i]=NULL;
flying_aura = 0;
resend_speed = false;
rename_pending = false;
iInstanceType = 0;
memset(reputationByListId, 0, sizeof(FactionReputation*) * 128);
m_comboTarget = 0;
m_comboPoints = 0;
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER, 0.0f);
SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER, 0.0f);
UpdateLastSpeeds();
m_resist_critical[0]=m_resist_critical[1]=0;
for(i = 0; i < 3; i++ )
{
m_resist_hit[i] = 0.0f;
m_attack_speed[i] = 1.0f;
}
ok_to_remove = false;
m_modphyscritdmgPCT = 0;
m_RootedCritChanceBonus = 0;
m_ModInterrMRegenPCT = 0;
m_ModInterrMRegen =0;
m_RegenManaOnSpellResist=0;
m_rap_mod_pct = 0;
m_modblockabsorbvalue = 0;
m_modblockvaluefromspells = 0;
m_summoner = m_summonInstanceId = m_summonMapId = 0;
m_spellcomboPoints = 0;
m_pendingBattleground = 0;
m_deathVision = false;
m_resurrecter = 0;
m_retainComboPoints = false;
last_heal_spell = NULL;
m_playerInfo = NULL;
m_sentTeleportPosition.ChangeCoords(999999.0f,999999.0f,999999.0f);
m_speedChangeCounter=1;
memset(&m_bgScore,0,sizeof(BGScore));
m_arenaPoints = 0;
memset(&m_spellIndexTypeTargets, 0, sizeof(uint64)*NUM_SPELL_TYPE_INDEX);
m_base_runSpeed = m_runSpeed;
m_base_walkSpeed = m_walkSpeed;
m_arenateaminviteguid=0;
m_arenaPoints=0;
m_honorRolloverTime=0;
hearth_of_wild_pct = 0;
raidgrouponlysent=false;
loot.gold=0;
m_waterwalk=false;
m_setwaterwalk=false;
m_areaSpiritHealer_guid=0;
m_CurrentTaxiPath=NULL;
m_setflycheat = false;
m_fallDisabledUntil = 0;
m_lfgMatch = NULL;
m_lfgInviterGuid = 0;
m_mountCheckTimer = 0;
m_taxiMapChangeNode = 0;
this->OnLogin();
#ifdef ENABLE_COMPRESSED_MOVEMENT
m_movementBuffer.reserve(5000);
#endif
m_requiresNoAmmo = false;
m_safeFall = 0;
m_noFallDamage = false;
z_axisposition = 0.0f;
m_KickDelay = 0;
m_passOnLoot = false;
m_changingMaps = true;
m_outStealthDamageBonusPct = m_outStealthDamageBonusPeriod = m_outStealthDamageBonusTimer = 0;
m_vampiricEmbrace = m_vampiricTouch = 0;
LastSeal = 0;
m_flyhackCheckTimer = 0;
#ifdef TRACK_IMMUNITY_BUG
m_immunityTime = 0;
#endif
m_skills.clear();
m_wratings.clear();
m_taxiPaths.clear();
m_QuestGOInProgress.clear();
m_removequests.clear();
m_finishedQuests.clear();
m_finishedDailies.clear();
quest_spells.clear();
quest_mobs.clear();
m_onStrikeSpells.clear();
m_onStrikeSpellDmg.clear();
mSpellOverrideMap.clear();
mSpells.clear();
mDeletedSpells.clear();
mShapeShiftSpells.clear();
m_Pets.clear();
m_itemsets.clear();
m_reputation.clear();
m_channels.clear();
m_visibleObjects.clear();
m_forcedReactions.clear();
m_friends.clear();
m_ignores.clear();
m_hasFriendList.clear();
loginauras.clear();
OnMeleeAuras.clear();
damagedone.clear();
tocritchance.clear();
m_visibleFarsightObjects.clear();
SummonSpells.clear();
PetSpells.clear();
delayedPackets.clear();
gmTargets.clear();
visiblityChangableSet.clear();
_splineMap.clear();
for (i=0; i<NUM_COOLDOWN_TYPES; i++) {
m_cooldownMap[i].clear();
}
}
void Player::OnLogin()
{
}
Player::~Player ( )
{
if(!ok_to_remove)
{
printf("Player deleted from non-logoutplayer!\n");
OutputCrashLogLine("Player deleted from non-logoutplayer!");
#ifdef WIN32
CStackWalker sw;
sw.ShowCallstack();
#endif
objmgr.RemovePlayer(this);
}
if(m_session)
{
m_session->SetPlayer(0);
if(!ok_to_remove)
m_session->Disconnect();
}
Player * pTarget;
if(mTradeTarget != 0)
{
pTarget = GetTradeTarget();
if(pTarget)
pTarget->mTradeTarget = 0;
}
pTarget = objmgr.GetPlayer(GetInviter());
if(pTarget)
pTarget->SetInviter(0);
if( m_Summon )
m_Summon->Remove( true, true, false );
mTradeTarget = 0;
if(DuelingWith != 0)
DuelingWith->DuelingWith = 0;
DuelingWith = 0;
CleanupGossipMenu();
ASSERT(!IsInWorld());
// delete m_talenttree
CleanupChannels();
for(int i = 0; i < 25; ++i)
{
if(m_questlog[i] != NULL)
{
delete m_questlog[i];
m_questlog[i] = NULL;
}
}
for(SplineMap::iterator itr = _splineMap.begin(); itr != _splineMap.end(); ++itr)
delete itr->second;
_splineMap.clear();
if(m_ItemInterface) {
delete m_ItemInterface;
m_ItemInterface = NULL;
}
for(ReputationMap::iterator itr = m_reputation.begin(); itr != m_reputation.end(); ++itr)
delete itr->second;
m_reputation.clear();
m_objectTypeId = TYPEID_UNUSED;
if(m_playerInfo)
m_playerInfo->m_loggedInPlayer=NULL;
delete SDetector;
SDetector = NULL;
while( delayedPackets.size() )
{
WorldPacket * pck = delayedPackets.next();
delete pck;
}
delayedPackets.clear();
}
ARCEMU_INLINE uint32 GetSpellForLanguage(uint32 SkillID)
{
switch(SkillID)
{
case SKILL_LANG_COMMON:
return 668;
break;
case SKILL_LANG_ORCISH:
return 669;
break;
case SKILL_LANG_TAURAHE:
return 670;
break;
case SKILL_LANG_DARNASSIAN:
return 671;
break;
case SKILL_LANG_DWARVEN:
return 672;
break;
case SKILL_LANG_THALASSIAN:
return 813;
break;
case SKILL_LANG_DRACONIC:
return 814;
break;
case SKILL_LANG_DEMON_TONGUE:
return 815;
break;
case SKILL_LANG_TITAN:
return 816;
break;
case SKILL_LANG_OLD_TONGUE:
return 817;
break;
case SKILL_LANG_GNOMISH:
return 7430;
break;
case SKILL_LANG_TROLL:
return 7341;
break;
case SKILL_LANG_GUTTERSPEAK:
return 17737;
break;
case SKILL_LANG_DRAENEI:
return 29932;
break;
}
return 0;
}
///====================================================================
/// Create
/// params: p_newChar
/// desc: data from client to create a new character
///====================================================================
bool Player::Create(WorldPacket& data )
{
uint8 race,class_,gender,skin,face,hairStyle,hairColor,facialHair,outfitId;
// unpack data into member variables
data >> m_name;
// correct capitalization
CapitalizeString(m_name);
data >> race >> class_ >> gender >> skin >> face;
data >> hairStyle >> hairColor >> facialHair >> outfitId;
info = objmgr.GetPlayerCreateInfo(race, class_);
if(!info)
{
// info not found... disconnect
//sCheatLog.writefromsession(m_session, "tried to create invalid player with race %u and class %u", race, class_);
m_session->Disconnect();
return false;
}
// check that the account CAN create TBC characters, if we're making some
if(race >= RACE_BLOODELF && !m_session->HasFlag(ACCOUNT_FLAG_XPACK_01))
{
//sCheatLog.writefromsession(m_session, "tried to create player with race %u and class %u but no expansion flags", race, class_);
m_session->Disconnect();
return false;
}
m_mapId = info->mapId;
m_zoneId = info->zoneId;
m_position.ChangeCoords(info->positionX, info->positionY, info->positionZ);
m_bind_pos_x = info->positionX;
m_bind_pos_y = info->positionY;
m_bind_pos_z = info->positionZ;
m_bind_mapid = info->mapId;
m_bind_zoneid = info->zoneId;
m_isResting = 0;
m_restAmount = 0;
m_restState = 0;
memset(m_taximask, 0, sizeof(uint32)*8);
// set race dbc
myRace = dbcCharRace.LookupEntry(race);
myClass = dbcCharClass.LookupEntry(class_);
if(!myRace || !myClass)
{
// information not found
sCheatLog.writefromsession(m_session, "tried to create invalid player with race %u and class %u, dbc info not found", race, class_);
m_session->Disconnect();
return false;
}
if(myRace->team_id == 7)
m_team = 0;
else
m_team = 1;
uint8 powertype = static_cast<uint8>(myClass->power_type);
// Automatically add the race's taxi hub to the character's taximask at creation time ( 1 << (taxi_node_id-1) )
memset(m_taximask,0,sizeof(m_taximask));
switch(race)
{
case RACE_TAUREN: m_taximask[0]= 2097152; break;
case RACE_HUMAN: m_taximask[0]= 2; break;
case RACE_DWARF: m_taximask[0]= 32; break;
case RACE_GNOME: m_taximask[0]= 32; break;
case RACE_ORC: m_taximask[0]= 4194304; break;
case RACE_TROLL: m_taximask[0]= 4194304; break;
case RACE_UNDEAD: m_taximask[0]= 1024; break;
case RACE_NIGHTELF: m_taximask[0]= 100663296; break;
case RACE_BLOODELF: m_taximask[2]= 131072; break;
case RACE_DRAENEI: m_taximask[2]= 536870912; break;
}
// Set Starting stats for char
//SetFloatValue(OBJECT_FIELD_SCALE_X, ((race==RACE_TAUREN)?1.3f:1.0f));
SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
SetUInt32Value(UNIT_FIELD_HEALTH, info->health);
SetUInt32Value(UNIT_FIELD_POWER1, info->mana );
//SetUInt32Value(UNIT_FIELD_POWER2, 0 ); // this gets devided by 10
SetUInt32Value(UNIT_FIELD_POWER3, info->focus );
SetUInt32Value(UNIT_FIELD_POWER4, info->energy );
SetUInt32Value(UNIT_FIELD_MAXHEALTH, info->health);
SetUInt32Value(UNIT_FIELD_MAXPOWER1, info->mana );
SetUInt32Value(UNIT_FIELD_MAXPOWER2, info->rage );
SetUInt32Value(UNIT_FIELD_MAXPOWER3, info->focus );
SetUInt32Value(UNIT_FIELD_MAXPOWER4, info->energy );
//THIS IS NEEDED
SetUInt32Value(UNIT_FIELD_BASE_HEALTH, info->health);
SetUInt32Value(UNIT_FIELD_BASE_MANA, info->mana );
SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, info->factiontemplate );
SetUInt32Value(UNIT_FIELD_LEVEL, sWorld.start_level);
//ApplyLevelInfo(Info, sWorld.start_level);
/* if(sWorld.start_level >= 10 && sWorld.start_level <= PLAYER_LEVEL_CAP)
{int startingTalents;
startingTalents = sWorld.start_level - 9;
SetUInt32Value(PLAYER_CHARACTER_POINTS1,startingTalents);}*/
SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
//UNIT_FIELD_BYTES_1 (standstate) | (unk1) | (unk2) | (attackstate)
SetUInt32Value(UNIT_FIELD_BYTES_2, (0x28 << 8) );
if(class_ == WARRIOR)
SetShapeShift(FORM_BATTLESTANCE);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
SetUInt32Value(UNIT_FIELD_STAT0, info->strength );
SetUInt32Value(UNIT_FIELD_STAT1, info->ability );
SetUInt32Value(UNIT_FIELD_STAT2, info->stamina );
SetUInt32Value(UNIT_FIELD_STAT3, info->intellect );
SetUInt32Value(UNIT_FIELD_STAT4, info->spirit );
SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.388999998569489f );
SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
if(race != 10)
{
SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId + gender );
SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId + gender );
} else {
SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId - gender );
SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId - gender );
}
EventModelChange();
//SetFloatValue(UNIT_FIELD_MINDAMAGE, info->mindmg );
//SetFloatValue(UNIT_FIELD_MAXDAMAGE, info->maxdmg );
SetUInt32Value(UNIT_FIELD_ATTACK_POWER, info->attackpower );
SetUInt32Value(PLAYER_BYTES, ((skin) | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
//PLAYER_BYTES_2 GM ON/OFF BANKBAGSLOTS RESTEDSTATE
// SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0xEE << 8) | (0x01 << 16) | (0x02 << 24)));
SetUInt32Value(PLAYER_BYTES_2, (facialHair /*| (0xEE << 8)*/ | (0x02 << 24)));//no bank slot by default!
//PLAYER_BYTES_3 DRUNKENSTATE PVPRANK
SetUInt32Value(PLAYER_BYTES_3, ((gender) | (0x00 << 8) | (0x00 << 16) | (GetPVPRank() << 24)));
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, 400);
SetUInt32Value(PLAYER_FIELD_BYTES, 0x08 );
SetUInt32Value(PLAYER_CHARACTER_POINTS2,2);
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.m_levelCap);
for(uint32 x=0;x<7;x++)
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+x, 1.00);
SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, 0xEEEEEEEE);
m_StableSlotCount = 0;
Item *item;
for(std::set<uint32>::iterator sp = info->spell_list.begin();sp!=info->spell_list.end();sp++)
{
mSpells.insert((*sp));
}
m_FirstLogin = true;
skilllineentry * se;
for(std::list<CreateInfo_SkillStruct>::iterator ss = info->skills.begin(); ss!=info->skills.end(); ss++)
{
se = dbcSkillLine.LookupEntry(ss->skillid);
if(se->type != SKILL_TYPE_LANGUAGE)
_AddSkillLine(se->id, ss->currentval, ss->maxval);
}
_UpdateMaxSkillCounts();
//Chances depend on stats must be in this order!
//UpdateStats();
//UpdateChances();
_InitialReputation();
// Add actionbars
for(std::list<CreateInfo_ActionBarStruct>::iterator itr = info->actionbars.begin();itr!=info->actionbars.end();++itr)
{
setAction(itr->button, itr->action, itr->type, itr->misc);
}
for(std::list<CreateInfo_ItemStruct>::iterator is = info->items.begin(); is!=info->items.end(); is++)
{
if ( (*is).protoid != 0)
{
item=objmgr.CreateItem((*is).protoid,this);
if(item)
{
item->SetUInt32Value(ITEM_FIELD_STACK_COUNT,(*is).amount);
if((*is).slot<INVENTORY_SLOT_BAG_END)
{
if( !GetItemInterface()->SafeAddItem(item, INVENTORY_SLOT_NOT_SET, (*is).slot) )
item->DeleteMe();
}
else
{
if( !GetItemInterface()->AddItemToFreeSlot(item) )
item->DeleteMe();
}
}
}
}
sHookInterface.OnCharacterCreate(this);
load_health = m_uint32Values[UNIT_FIELD_HEALTH];
load_mana = m_uint32Values[UNIT_FIELD_POWER1];
return true;
}
void Player::Update( uint32 p_time )
{
if(!IsInWorld())
return;
Unit::Update( p_time );
uint32 mstime = getMSTime();
if(m_attacking)
{
// Check attack timer.
if(mstime >= m_attackTimer)
_EventAttack(false);
if( m_dualWield && mstime >= m_attackTimer_1 )
_EventAttack( true );
}
if( m_onAutoShot)
{
if( m_AutoShotAttackTimer > p_time )
{
//sLog.outDebug( "HUNTER AUTOSHOT 0) %i, %i", m_AutoShotAttackTimer, p_time );
m_AutoShotAttackTimer -= p_time;
}
else
{
//sLog.outDebug( "HUNTER AUTOSHOT 1) %i", p_time );
EventRepeatSpell();
}
}
else if(m_AutoShotAttackTimer > 0)
{
if(m_AutoShotAttackTimer > p_time)
m_AutoShotAttackTimer -= p_time;
else
m_AutoShotAttackTimer = 0;
}
// Breathing
if( m_UnderwaterState & UNDERWATERSTATE_UNDERWATER )
{
// keep subtracting timer
if( m_UnderwaterTime )
{
// not taking dmg yet
if(p_time >= m_UnderwaterTime)
m_UnderwaterTime = 0;
else
m_UnderwaterTime -= p_time;
}
if( !m_UnderwaterTime )
{
// check last damage dealt timestamp, and if enough time has elapsed deal damage
if( mstime >= m_UnderwaterLastDmg )
{
uint32 damage = m_uint32Values[UNIT_FIELD_MAXHEALTH] / 10;
WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, 21);
data << GetGUID() << uint8(DAMAGE_DROWNING) << damage << uint64(0);
SendMessageToSet(&data, true);
DealDamage(this, damage, 0, 0, 0);
m_UnderwaterLastDmg = mstime + 1000;
}
}
}
else
{
// check if we're not on a full breath timer
if(m_UnderwaterTime < m_UnderwaterMaxTime)
{
// regenning
m_UnderwaterTime += (p_time * 10);
if(m_UnderwaterTime >= m_UnderwaterMaxTime)
{
m_UnderwaterTime = m_UnderwaterMaxTime;
StopMirrorTimer(1);
}
}
}
// Lava Damage
if(m_UnderwaterState & UNDERWATERSTATE_LAVA)
{
// check last damage dealt timestamp, and if enough time has elapsed deal damage
if(mstime >= m_UnderwaterLastDmg)
{
uint32 damage = m_uint32Values[UNIT_FIELD_MAXHEALTH] / 5;
WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, 21);
data << GetGUID() << uint8(DAMAGE_LAVA) << damage << uint64(0);
SendMessageToSet(&data, true);
DealDamage(this, damage, 0, 0, 0);
m_UnderwaterLastDmg = mstime + 1000;
}
}
// Autosave
if(mstime >= m_nextSave)
SaveToDB(false);
if(m_CurrentTransporter && !m_lockTransportVariables)
{
// Update our position, using trnasporter X/Y
float c_tposx = m_CurrentTransporter->GetPositionX() + m_TransporterX;
float c_tposy = m_CurrentTransporter->GetPositionY() + m_TransporterY;
float c_tposz = m_CurrentTransporter->GetPositionZ() + m_TransporterZ;
SetPosition(c_tposx, c_tposy, c_tposz, GetOrientation(), false);
}
// Exploration
if(mstime >= m_explorationTimer)
{
_EventExploration();
m_explorationTimer = mstime + 3000;
}
if(m_pvpTimer)
{
if(p_time >= m_pvpTimer)
{
RemovePvPFlag();
m_pvpTimer = 0;
}
else
m_pvpTimer -= p_time;
}
if (sWorld.Collision) {
if(m_MountSpellId != 0)
{
if( mstime >= m_mountCheckTimer )
{
if( CollideInterface.IsIndoor( m_mapId, m_position ) )
{
RemoveAura( m_MountSpellId );
m_MountSpellId = 0;
}
else
{
m_mountCheckTimer = mstime + COLLISION_MOUNT_CHECK_INTERVAL;
}
}
}
if( mstime >= m_flyhackCheckTimer )
{
_FlyhackCheck();
m_flyhackCheckTimer = mstime + 10000;
}
}
#ifdef TRACK_IMMUNITY_BUG
bool immune = false;
for(uint32 i = 0; i < 7; i++)
if (SchoolImmunityList[i]) immune = true;
if (immune) {
if (m_immunityTime == 0) {
m_immunityTime = mstime;
}
if ((mstime - m_immunityTime) > 15000) {
sLog.outString("plr guid=%d has been immune for > 15sec: %u %u %u %u %u %u %u, resetting states", GetLowGUID(),
SchoolImmunityList[0], SchoolImmunityList[1], SchoolImmunityList[2], SchoolImmunityList[3],
SchoolImmunityList[4], SchoolImmunityList[5], SchoolImmunityList[6]);
for(uint32 i = 0; i < 7; i++)
if (SchoolImmunityList[i]) SchoolImmunityList[i] = 0;
}
} else {
m_immunityTime = 0;
}
#endif
}
void Player::EventDismount(uint32 money, float x, float y, float z)
{
ModUnsigned32Value( PLAYER_FIELD_COINAGE , -(int32)money );
SetPosition(x, y, z, true);
if(!m_taxiPaths.size())
SetTaxiState(false);
SetTaxiPath(NULL);
UnSetTaxiPos();
m_taxi_ride_time = 0;
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID , 0);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER);
SetPlayerSpeed(RUN, m_runSpeed);
sEventMgr.RemoveEvents(this, EVENT_PLAYER_TAXI_INTERPOLATE);
// Save to database on dismount
SaveToDB(false);
// If we have multiple "trips" to do, "jump" on the next one :p
if(m_taxiPaths.size())
{
TaxiPath * p = *m_taxiPaths.begin();
m_taxiPaths.erase(m_taxiPaths.begin());
TaxiStart(p, taxi_model_id, 0);
}
}
void Player::_EventAttack( bool offhand )
{
if (m_currentSpell)
{
if(m_currentSpell->GetProto()->ChannelInterruptFlags != 0) // this is a channeled spell - ignore the attack event
return;
m_currentSpell->cancel();
setAttackTimer(500, offhand);
return;
}
if( IsFeared() || IsStunned() )
return;
Unit *pVictim = NULL;
if(m_curSelection)
pVictim = GetMapMgr()->GetUnit(m_curSelection);
//Can't find victim, stop attacking
if (!pVictim)
{
sLog.outDetail("Player::Update: No valid current selection to attack, stopping attack\n");
setHRegenTimer(5000); //prevent clicking off creature for a quick heal
EventAttackStop();
return;
}
if (!canReachWithAttack(pVictim))
{
if(m_AttackMsgTimer != 1)
{
m_session->OutPacket(SMSG_ATTACKSWING_NOTINRANGE);
m_AttackMsgTimer = 1;
}
setAttackTimer(300, offhand);
}
else if(!isInFront(pVictim))
{
// We still have to do this one.
if(m_AttackMsgTimer != 2)
{
m_session->OutPacket(SMSG_ATTACKSWING_BADFACING);
m_AttackMsgTimer = 2;
}
setAttackTimer(300, offhand);
}
else
{
m_AttackMsgTimer = 0;
// Set to weapon time.
setAttackTimer(0, offhand);
//pvp timeout reset
if(pVictim->IsPlayer())
{
if (static_cast< Player* >(pVictim)->cannibalize)
{
sEventMgr.RemoveEvents(pVictim, EVENT_CANNIBALIZE);
pVictim->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0);
static_cast< Player* >(pVictim)->cannibalize = false;
}
}
if(this->IsStealth())
{
RemoveAura( m_stealth );
SetStealth(0);
}
if (!GetOnMeleeSpell() || offhand)
{
Strike( pVictim, ( offhand ? OFFHAND : MELEE ), NULL, 0, 0, 0, false, false );
}
else
{
SpellEntry *spellInfo = dbcSpell.LookupEntry(GetOnMeleeSpell());
SetOnMeleeSpell(0);
Spell *spell = SpellPool.PooledNew();
spell->Init(this,spellInfo,true,NULL);
SpellCastTargets targets;
targets.m_unitTarget = GetSelection();
spell->prepare(&targets);
}
}
}
void Player::_EventCharmAttack()
{
if(!m_CurrentCharm)
return;
Unit *pVictim = NULL;
if(!IsInWorld())
{
m_CurrentCharm=0;
sEventMgr.RemoveEvents(this,EVENT_PLAYER_CHARM_ATTACK);
return;
}
if(m_curSelection == 0)
{
sEventMgr.RemoveEvents(this, EVENT_PLAYER_CHARM_ATTACK);
return;
}
pVictim= GetMapMgr()->GetUnit(m_curSelection);
//Can't find victim, stop attacking
if (!pVictim)
{
sLog.outError( "WORLD: "I64FMT" doesn't exist.",m_curSelection);
sLog.outDetail("Player::Update: No valid current selection to attack, stopping attack\n");
this->setHRegenTimer(5000); //prevent clicking off creature for a quick heal
clearStateFlag(UF_ATTACKING);
EventAttackStop();
}
else
{
Unit *currentCharm = GetMapMgr()->GetUnit( m_CurrentCharm );
if( !currentCharm )
return;
if (!currentCharm->canReachWithAttack(pVictim))
{
if(m_AttackMsgTimer == 0)
{
//m_session->OutPacket(SMSG_ATTACKSWING_NOTINRANGE);
m_AttackMsgTimer = 2000; // 2 sec till next msg.
}
// Shorten, so there isnt a delay when the client IS in the right position.
sEventMgr.ModifyEventTimeLeft(this, EVENT_PLAYER_CHARM_ATTACK, 100);
}
else if(!currentCharm->isInFront(pVictim))
{
if(m_AttackMsgTimer == 0)
{
m_session->OutPacket(SMSG_ATTACKSWING_BADFACING);
m_AttackMsgTimer = 2000; // 2 sec till next msg.
}
// Shorten, so there isnt a delay when the client IS in the right position.
sEventMgr.ModifyEventTimeLeft(this, EVENT_PLAYER_CHARM_ATTACK, 100);
}
else
{
//if(pVictim->GetTypeId() == TYPEID_UNIT)
// pVictim->GetAIInterface()->StopMovement(5000);
//pvp timeout reset
/*if(pVictim->IsPlayer())
{
if( static_cast< Player* >( pVictim )->DuelingWith == NULL)//Dueling doesn't trigger PVP
static_cast< Player* >( pVictim )->PvPTimeoutUpdate(false); //update targets timer
if(DuelingWith == NULL)//Dueling doesn't trigger PVP
PvPTimeoutUpdate(false); //update casters timer
}*/
if (!currentCharm->GetOnMeleeSpell())
{
currentCharm->Strike( pVictim, MELEE, NULL, 0, 0, 0, false, false );
}
else
{
SpellEntry *spellInfo = dbcSpell.LookupEntry(currentCharm->GetOnMeleeSpell());
currentCharm->SetOnMeleeSpell(0);
Spell *spell = SpellPool.PooledNew();
spell->Init(currentCharm,spellInfo,true,NULL);
SpellCastTargets targets;
targets.m_unitTarget = GetSelection();
spell->prepare(&targets);
//delete spell; // deleted automatically, no need to do this.
}
}
}
}
void Player::EventAttackStart()
{
m_attacking = true;
if(m_MountSpellId)
RemoveAura(m_MountSpellId);
}
void Player::EventAttackStop()
{
if( m_CurrentCharm != 0 )
sEventMgr.RemoveEvents(this, EVENT_PLAYER_CHARM_ATTACK);
m_attacking = false;
}
void Player::_EventExploration()
{
if (isDead())
return;
if (!IsInWorld())
return;
if(m_position.x > _maxX || m_position.x < _minX || m_position.y > _maxY || m_position.y < _minY)
return;
if(GetMapMgr()->GetCellByCoords(GetPositionX(),GetPositionY()) == NULL)
return;
uint16 AreaId = GetMapMgr()->GetAreaID(GetPositionX(),GetPositionY());
if(!AreaId || AreaId == 0xFFFF)
return;
// AreaId fix for undercity and ironforge. This will now enable rest for these 2 cities.
// since they're both on the same map, only 1 map id check
if (GetMapId() == 0)
{
// get position
float ss_x = m_position.x;
float ss_y = m_position.y;
float ss_z = m_position.z;
// Check for Undercity, Tirisfal Glades, and Ruins of Lordaeron, if neither, skip
if (AreaId == 153 || AreaId == 85 || m_AreaID == 1497)
{
// ruins check
if (ss_z < 74)
{
// box with coord 1536,174 -> 1858,353; and z < 62.5 for reachable areas
if (ss_y > 174 && ss_y < 353 && ss_x > 1536 && ss_x < 1858)
{
AreaId = 1497;
}
}
// inner city check
if (ss_z < 38)
{
// box with coord 1238, 11 -> 1823, 640; and z < 38 for undeground
if (ss_y > 11 && ss_y < 640 && ss_x > 1238 && ss_x < 1823)
{
AreaId = 1497;
}
}
// todo bat tunnel, only goes part way, but should be fine for now
}
// Check for Ironforge, and Gates of IronForge.. if neither skip
if (AreaId == 809 || m_AreaID == 1537) {
// height check
if (ss_z > 480)
{
// box with coord -5097.3, -828 -> -4570, -1349.3; and z > 480.
if (ss_y > -1349.3 && ss_y < -828 && ss_x > -5097.3 && ss_x < -4570)
{
AreaId = 1537;
}
}
}
}
AreaTable * at = dbcArea.LookupEntry(AreaId);
if(at == 0)
return;
/*char areaname[200];
if(at)
{
strcpy(areaname, sAreaStore.LookupString((uint32)at->name));
}
else
{
strcpy(areaname, "UNKNOWN");
}
sChatHandler.BlueSystemMessageToPlr(this,areaname);*/
int offset = at->explorationFlag / 32;
offset += PLAYER_EXPLORED_ZONES_1;
uint32 val = (uint32)(1 << (at->explorationFlag % 32));
uint32 currFields = GetUInt32Value(offset);
if(AreaId != m_AreaID)
{
m_AreaID = AreaId;
UpdatePvPArea();
if(GetGroup())
GetGroup()->UpdateOutOfRangePlayer(this, 128, true, NULL);
}
// Zone update, this really should update to a parent zone if one exists.
// Will show correct location on your character screen, as well zoneid in DB will have correct value
// for any web sites that access that data.
if(at->ZoneId == 0 && m_zoneId != AreaId)
{
ZoneUpdate(AreaId);
}
else if (at->ZoneId != 0 && m_zoneId != at->ZoneId)
{
ZoneUpdate(at->ZoneId);
}
if(at->ZoneId != 0 && m_zoneId != at->ZoneId)
ZoneUpdate(at->ZoneId);
bool rest_on = false;
// Check for a restable area
if(at->AreaFlags & AREA_CITY_AREA || at->AreaFlags & AREA_CITY)
{
// check faction
if((at->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || (at->category == AREAC_HORDE_TERRITORY && GetTeam() == 1) )
{
rest_on = true;
}
else if(at->category != AREAC_ALLIANCE_TERRITORY && at->category != AREAC_HORDE_TERRITORY)
{
rest_on = true;
}
}
else
{
//second AT check for subzones.
if(at->ZoneId)
{
AreaTable * at2 = dbcArea.LookupEntry(at->ZoneId);
if(at2 && at2->AreaFlags & AREA_CITY_AREA || at2 && at2->AreaFlags & AREA_CITY)
{
if((at2->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || (at2->category == AREAC_HORDE_TERRITORY && GetTeam() == 1) )
{
rest_on = true;
}
else if(at2->category != AREAC_ALLIANCE_TERRITORY && at2->category != AREAC_HORDE_TERRITORY)
{
rest_on = true;
}
}
}
}
if (rest_on)
{
if(!m_isResting) ApplyPlayerRestState(true);
}
else
{
if(m_isResting)
{
if (sWorld.Collision) {
const LocationVector & loc = GetPosition();
if(!CollideInterface.IsIndoor(GetMapId(), loc.x, loc.y, loc.z + 2.0f))
ApplyPlayerRestState(false);
} else {
ApplyPlayerRestState(false);
}
}
}
if( !(currFields & val) && !GetTaxiState() && !m_TransporterGUID)//Unexplored Area // bur: we dont want to explore new areas when on taxi
{
SetUInt32Value(offset, (uint32)(currFields | val));
uint32 explore_xp = at->level * 10;
explore_xp *= float2int32(sWorld.getRate(RATE_EXPLOREXP));
WorldPacket data(SMSG_EXPLORATION_EXPERIENCE, 8);
data << at->AreaId << explore_xp;
m_session->SendPacket(&data);
if(getLevel() < GetUInt32Value(PLAYER_FIELD_MAX_LEVEL) && explore_xp)
GiveXP(explore_xp, 0, false);
}
}
void Player::EventDeath()
{
if (m_state & UF_ATTACKING)
EventAttackStop();
if (m_onTaxi)
sEventMgr.RemoveEvents(this, EVENT_PLAYER_TAXI_DISMOUNT);
if(!IS_INSTANCE(GetMapId()) && !sEventMgr.HasEvent(this,EVENT_PLAYER_FORECED_RESURECT)) //Should never be true
sEventMgr.AddEvent(this,&Player::RepopRequestedPlayer,EVENT_PLAYER_FORECED_RESURECT,PLAYER_FORCED_RESURECT_INTERVAL,1,0); //in case he forgets to release spirit (afk or something)
RemoveNegativeAuras();
}
void Player::BuildEnumData( WorldPacket * p_data )
{
*p_data << GetGUID();
*p_data << m_name;
//uint32 bytes = GetUInt32Value(UNIT_FIELD_BYTES_0);
//#ifdef USING_BIG_ENDIAN
//SetUInt32Value(UNIT_FIELD_BYTES_0, swap32(UNIT_FIELD_BYTES_0));
//#endif
*p_data << GetByte(UNIT_FIELD_BYTES_0,0);//uint8(bytes & 0xff); // race
*p_data << GetByte(UNIT_FIELD_BYTES_0,1);//uint8((bytes >> 8) & 0xff); // class
*p_data << GetByte(UNIT_FIELD_BYTES_0,2);//uint8((bytes >> 16) & 0xff); // gender
//#ifdef USING_BIG_ENDIAN
//SetUInt32Value(UNIT_FIELD_BYTES_0, swap32(UNIT_FIELD_BYTES_0));
//#endif
*p_data << GetUInt32Value(PLAYER_BYTES);
/*
bytes = GetUInt32Value(PLAYER_BYTES);
*p_data << uint8(bytes & 0xff); //skin
*p_data << uint8((bytes >> 8) & 0xff); //face
*p_data << uint8((bytes >> 16) & 0xff); //hairstyle
*p_data << uint8((bytes >> 24) & 0xff); //haircolor
*/
///bytes = GetUInt32Value(PLAYER_BYTES_2);
#ifdef USING_BIG_ENDIAN
*p_data << GetByte(PLAYER_BYTES_2,3);//uint8(bytes & 0xff); //facialhair
#else
*p_data << GetByte(PLAYER_BYTES_2,0);//uint8(bytes & 0xff); //facialhair
#endif
*p_data << uint8(getLevel()); //level
*p_data << m_zoneId;
*p_data << m_mapId;
*p_data << m_position;
*p_data << GetUInt32Value(PLAYER_GUILDID);// guild
if(rename_pending) *p_data << uint32(0x00A04342); // wtf blizz? :P
else if(m_banned) *p_data << (uint32)7; // Banned (cannot login)
else if(isDead()) *p_data << (uint32)8704; // Dead (displaying as Ghost)
else *p_data << (uint32)1; // Alive
*p_data << (uint8)m_restState; // rest state
// pet stuff
CreatureInfo *info = NULL;
if(getClass()==WARLOCK || getClass()==HUNTER)
{
QueryResult *result = CharacterDatabase.Query("SELECT entry FROM playerpets WHERE ownerguid=%u AND active=1", GetUInt32Value(OBJECT_FIELD_GUID));
if(result)
{
info = CreatureNameStorage.LookupEntry(result->Fetch()[0].GetUInt32());
delete result;
}
}
if(info) //PET INFO uint32 displayid, uint32 level, uint32 familyid
*p_data << uint32(info->Male_DisplayID) << uint32(getLevel()) << uint32(info->Family);
else
*p_data << uint32(0) << uint32(0) << uint32(0);
for (uint32 i = 0; i < EQUIPMENT_SLOT_END ; i++)//max equipment slot is 18....this is strange
{
if (GetItemInterface()->GetInventoryItem(i) != NULL)
{
*p_data << (uint32)GetItemInterface()->GetInventoryItem(i)->GetProto()->DisplayInfoID;
*p_data << (uint8)GetItemInterface()->GetInventoryItem(i)->GetProto()->InventoryType;
}
else
{
*p_data << (uint32)0;
*p_data << (uint8)0;
}
}
//blizz send 20 slots for some reason(or no reason :P)
*p_data << (uint32)0;
*p_data << (uint8)0;
}
/// This function sends the message displaying the purple XP gain for the char
/// It assumes you will send out an UpdateObject packet at a later time.
void Player::GiveXP(uint32 xp, const uint64 &guid, bool allowbonus)
{
if ( xp < 1 )
return;
if(getLevel() >= GetUInt32Value(PLAYER_FIELD_MAX_LEVEL))
return;
uint32 restxp = xp;
//add reststate bonus (except for quests)
if(m_restState == RESTSTATE_RESTED && allowbonus)
{
restxp = SubtractRestXP(xp);
xp += restxp;
}
UpdateRestState();
SendLogXPGain(guid,xp,restxp,guid == 0 ? true : false);
/*
uint32 curXP = GetUInt32Value(PLAYER_XP);
uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
uint32 newXP = curXP + xp;
uint32 level = GetUInt32Value(UNIT_FIELD_LEVEL);
bool levelup = false;
if(m_Summon != NULL && m_Summon->GetUInt32Value(UNIT_CREATED_BY_SPELL) == 0)
m_Summon->GiveXP(xp);
uint32 TotalHealthGain = 0, TotalManaGain = 0;
uint32 cl=getClass();
// Check for level-up
while (newXP >= nextLvlXP)
{
levelup = true;
// Level-Up!
newXP -= nextLvlXP; // reset XP to 0, but add extra from this xp add
level ++; // increment the level
if( level > 9)
{
//Give Talent Point
uint32 curTalentPoints = GetUInt32Value(PLAYER_CHARACTER_POINTS1);
SetUInt32Value(PLAYER_CHARACTER_POINTS1,curTalentPoints+1);
}
}
*/
int32 newxp = m_uint32Values[PLAYER_XP] + xp;
int32 nextlevelxp = lvlinfo->XPToNextLevel;
uint32 level = m_uint32Values[UNIT_FIELD_LEVEL];
LevelInfo * li;
bool levelup = false;
while(newxp >= nextlevelxp && newxp > 0)
{
++level;
li = objmgr.GetLevelInfo(getRace(), getClass(), level);
if (li == NULL) return;
newxp -= nextlevelxp;
nextlevelxp = li->XPToNextLevel;
levelup = true;
if(level > 9)
ModUnsigned32Value(PLAYER_CHARACTER_POINTS1, 1);
if(level >= GetUInt32Value(PLAYER_FIELD_MAX_LEVEL))
break;
}
if(level > GetUInt32Value(PLAYER_FIELD_MAX_LEVEL))
level = GetUInt32Value(PLAYER_FIELD_MAX_LEVEL);
if(levelup)
{
m_playedtime[0] = 0; //Reset the "Current level played time"
SetUInt32Value(UNIT_FIELD_LEVEL, level);
LevelInfo * oldlevel = lvlinfo;
lvlinfo = objmgr.GetLevelInfo(getRace(), getClass(), level);
if (lvlinfo == NULL) return;
CalculateBaseStats();
// Generate Level Info Packet and Send to client
SendLevelupInfo(
level,
lvlinfo->HP - oldlevel->HP,
lvlinfo->Mana - oldlevel->Mana,
lvlinfo->Stat[0] - oldlevel->Stat[0],
lvlinfo->Stat[1] - oldlevel->Stat[1],
lvlinfo->Stat[2] - oldlevel->Stat[2],
lvlinfo->Stat[3] - oldlevel->Stat[3],
lvlinfo->Stat[4] - oldlevel->Stat[4]);
_UpdateMaxSkillCounts();
UpdateStats();
//UpdateChances();
// Set next level conditions
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, lvlinfo->XPToNextLevel);
// ScriptMgr hook for OnPostLevelUp
sHookInterface.OnPostLevelUp(this);
// Set stats
for(uint32 i = 0; i < 5; ++i)
{
BaseStats[i] = lvlinfo->Stat[i];
CalcStat(i);
}
// Small chance you die and levelup at the same time, and you enter a weird state.
if(isDead())
ResurrectPlayer();
//set full hp and mana
SetUInt32Value(UNIT_FIELD_HEALTH,GetUInt32Value(UNIT_FIELD_MAXHEALTH));
SetUInt32Value(UNIT_FIELD_POWER1,GetUInt32Value(UNIT_FIELD_MAXPOWER1));
// if warlock has summonned pet, increase its level too
if(info->class_ == WARLOCK) {
if((m_Summon != NULL) && (m_Summon->IsInWorld()) && (m_Summon->isAlive())) {
m_Summon->ModUnsigned32Value(UNIT_FIELD_LEVEL, 1);
m_Summon->ApplyStatsForLevel();
}
}
}
// Set the update bit
SetUInt32Value(PLAYER_XP, newxp);
HandleProc(PROC_ON_GAIN_EXPIERIENCE, this, NULL);
m_procCounter = 0;
}
void Player::smsg_InitialSpells()
{
PlayerCooldownMap::iterator itr, itr2;
uint16 spellCount = (uint16)mSpells.size();
size_t itemCount = m_cooldownMap[0].size() + m_cooldownMap[1].size();
uint32 mstime = getMSTime();
size_t pos;
WorldPacket data(SMSG_INITIAL_SPELLS, 5 + (spellCount * 4) + (itemCount * 4) );
data << uint8(0);
data << uint16(spellCount); // spell count
SpellSet::iterator sitr;
for (sitr = mSpells.begin(); sitr != mSpells.end(); ++sitr)
{
// todo: check out when we should send 0x0 and when we should send 0xeeee
// this is not slot,values is always eeee or 0,seems to be cooldown
data << uint16(*sitr); // spell id
data << uint16(0x0000);
}
pos = data.wpos();
data << uint16( 0 ); // placeholder
itemCount = 0;
for( itr = m_cooldownMap[COOLDOWN_TYPE_SPELL].begin(); itr != m_cooldownMap[COOLDOWN_TYPE_SPELL].end(); )
{
itr2 = itr++;
// don't keep around expired cooldowns
if( itr2->second.ExpireTime < mstime || (itr2->second.ExpireTime - mstime) < 10000 )
{
m_cooldownMap[COOLDOWN_TYPE_SPELL].erase( itr2 );
continue;
}
data << uint16( itr2->first ); // spell id
data << uint16( itr2->second.ItemId ); // item id
data << uint16( 0 ); // spell category
data << uint32( itr2->second.ExpireTime - mstime ); // cooldown remaining in ms (for spell)
data << uint32( 0 ); // cooldown remaining in ms (for category)
++itemCount;
#ifdef _DEBUG
Log.Debug("InitialSpells", "sending spell cooldown for spell %u to %u ms", itr2->first, itr2->second.ExpireTime - mstime);
#endif
}
for( itr = m_cooldownMap[COOLDOWN_TYPE_CATEGORY].begin(); itr != m_cooldownMap[COOLDOWN_TYPE_CATEGORY].end(); )
{
itr2 = itr++;
// don't keep around expired cooldowns
if( itr2->second.ExpireTime < mstime || (itr2->second.ExpireTime - mstime) < 10000 )
{
m_cooldownMap[COOLDOWN_TYPE_CATEGORY].erase( itr2 );
continue;
}
data << uint16( itr2->second.SpellId ); // spell id
data << uint16( itr2->second.ItemId ); // item id
data << uint16( itr2->first ); // spell category
data << uint32( 0 ); // cooldown remaining in ms (for spell)
data << uint32( itr2->second.ExpireTime - mstime ); // cooldown remaining in ms (for category)
++itemCount;
#ifdef _DEBUG
Log.Debug("InitialSpells", "sending category cooldown for cat %u to %u ms", itr2->first, itr2->second.ExpireTime - mstime);
#endif
}
#ifdef USING_BIG_ENDIAN
*(uint16*)&data.contents()[pos] = swap16((uint16)itemCount);
#else
*(uint16*)&data.contents()[pos] = (uint16)itemCount;
#endif
GetSession()->SendPacket(&data);
uint32 v = 0;
GetSession()->OutPacket(0x041d, 4, &v);
//Log::getSingleton( ).outDetail( "CHARACTER: Sent Initial Spells" );
}
void Player::_SavePet(QueryBuffer * buf)
{
// Remove any existing info
if(buf == NULL)
CharacterDatabase.Execute("DELETE FROM playerpets WHERE ownerguid=%u", GetUInt32Value(OBJECT_FIELD_GUID));
else
buf->AddQuery("DELETE FROM playerpets WHERE ownerguid=%u", GetUInt32Value(OBJECT_FIELD_GUID));
if( m_Summon && m_Summon->IsInWorld() && m_Summon->GetPetOwner() == this ) // update PlayerPets array with current pet's info
{
PlayerPet*pPet = GetPlayerPet(m_Summon->m_PetNumber);
if(!pPet || pPet->active == false)
m_Summon->UpdatePetInfo(true);
else m_Summon->UpdatePetInfo(false);
if(!m_Summon->Summon) // is a pet
{
// save pet spellz
PetSpellMap::iterator itr = m_Summon->mSpells.begin();
uint32 pn = m_Summon->m_PetNumber;
if(buf == NULL)
CharacterDatabase.Execute("DELETE FROM playerpetspells WHERE petnumber=%u", pn);
else
buf->AddQuery("DELETE FROM playerpetspells WHERE petnumber=%u", pn);
for(; itr != m_Summon->mSpells.end(); ++itr)
{
if(buf == NULL)
CharacterDatabase.Execute("INSERT INTO playerpetspells VALUES(%u, %u, %u, %u)", GetLowGUID(), pn, itr->first->Id, itr->second);
else
buf->AddQuery("INSERT INTO playerpetspells VALUES(%u, %u, %u, %u)", GetLowGUID(), pn, itr->first->Id, itr->second);
}
}
}
std::stringstream ss;
for(std::map<uint32, PlayerPet*>::iterator itr = m_Pets.begin(); itr != m_Pets.end(); itr++)
{
ss.rdbuf()->str("");
ss << "REPLACE INTO playerpets VALUES('"
<< GetLowGUID() << "','"
<< itr->second->number << "','"
<< CharacterDatabase.EscapeString(itr->second->name) << "','"
<< itr->second->entry << "','"
<< itr->second->fields << "','"
<< itr->second->xp << "','"
<< (itr->second->active ? 1 : 0) + itr->second->stablestate * 10 << "','"
<< itr->second->level << "','"
<< itr->second->loyaltyxp << "','"
<< itr->second->actionbar << "','"
<< itr->second->happinessupdate << "','"
<< itr->second->summon << "','"
<< itr->second->loyaltypts << "','"
<< itr->second->loyaltyupdate << "','"
<< (long)itr->second->reset_time << "','"
<< itr->second->reset_cost << "','"
<< itr->second->spellid << "')";
if(buf == NULL)
CharacterDatabase.ExecuteNA(ss.str().c_str());
else
buf->AddQueryStr(ss.str());
}
}
void Player::_SavePetSpells(QueryBuffer * buf)
{
// Remove any existing
if(buf == NULL)
CharacterDatabase.Execute("DELETE FROM playersummonspells WHERE ownerguid=%u", GetLowGUID());
else
buf->AddQuery("DELETE FROM playersummonspells WHERE ownerguid=%u", GetLowGUID());
// Save summon spells
map<uint32, set<uint32> >::iterator itr = SummonSpells.begin();
for(; itr != SummonSpells.end(); ++itr)
{
set<uint32>::iterator it = itr->second.begin();
for(; it != itr->second.end(); ++it)
{
if(buf == NULL)
CharacterDatabase.Execute("INSERT INTO playersummonspells VALUES(%u, %u, %u)", GetLowGUID(), itr->first, (*it));
else
buf->AddQuery("INSERT INTO playersummonspells VALUES(%u, %u, %u)", GetLowGUID(), itr->first, (*it));
}
}
}
void Player::AddSummonSpell(uint32 Entry, uint32 SpellID)
{
SpellEntry * sp = dbcSpell.LookupEntry(SpellID);
map<uint32, set<uint32> >::iterator itr = SummonSpells.find(Entry);
if(itr == SummonSpells.end())
SummonSpells[Entry].insert(SpellID);
else
{
set<uint32>::iterator it3;
for(set<uint32>::iterator it2 = itr->second.begin(); it2 != itr->second.end();)
{
it3 = it2++;
if(dbcSpell.LookupEntry(*it3)->NameHash == sp->NameHash)
itr->second.erase(it3);
}
itr->second.insert(SpellID);
}
}
void Player::RemoveSummonSpell(uint32 Entry, uint32 SpellID)
{
map<uint32, set<uint32> >::iterator itr = SummonSpells.find(Entry);
if(itr != SummonSpells.end())
{
itr->second.erase(SpellID);
if(itr->second.size() == 0)
SummonSpells.erase(itr);
}
}
set<uint32>* Player::GetSummonSpells(uint32 Entry)
{
map<uint32, set<uint32> >::iterator itr = SummonSpells.find(Entry);
if(itr != SummonSpells.end())
{
return &(itr->second);
}
return 0;
}
void Player::_LoadPet(QueryResult * result)
{
m_PetNumberMax=0;
if(!result)
return;
do
{
Field *fields = result->Fetch();
fields = result->Fetch();
PlayerPet *pet = new PlayerPet;
pet->number = fields[1].GetUInt32();
pet->name = fields[2].GetString();
pet->entry = fields[3].GetUInt32();
pet->fields = fields[4].GetString();
pet->xp = fields[5].GetUInt32();
pet->active = fields[6].GetInt8()%10 > 0 ? true : false;
pet->stablestate = fields[6].GetInt8() / 10;
pet->level = fields[7].GetUInt32();
pet->loyaltyxp = fields[8].GetUInt32();
pet->actionbar = fields[9].GetString();
pet->happinessupdate = fields[10].GetUInt32();
pet->summon = (fields[11].GetUInt32()>0 ? true : false);
pet->loyaltypts = fields[12].GetUInt32();
pet->loyaltyupdate = fields[13].GetUInt32();
pet->reset_time = fields[14].GetUInt32();
pet->reset_cost = fields[15].GetUInt32();
pet->spellid = fields[16].GetUInt32();
m_Pets[pet->number] = pet;
if(pet->active)
{
if(iActivePet) // how the hell can this happen
{
//printf("pet warning - >1 active pet.. weird..");
}
else
iActivePet = pet->number;
}
if(pet->number > m_PetNumberMax)
m_PetNumberMax = pet->number;
}while(result->NextRow());
}
void Player::SpawnPet(uint32 pet_number)
{
std::map<uint32, PlayerPet*>::iterator itr = m_Pets.find(pet_number);
if(itr == m_Pets.end())
{
sLog.outError("PET SYSTEM: "I64FMT" Tried to load invalid pet %d", GetGUID(), pet_number);
return;
}
if (itr->second->spellid == 0)
{
Pet *pPet = objmgr.CreatePet();
pPet->SetInstanceID(GetInstanceID());
pPet->LoadFromDB(this, itr->second);
}
else
{
SpellEntry *pSpell = dbcSpell.LookupEntry(itr->second->spellid);
CreatureInfo *ci = CreatureNameStorage.LookupEntry(pSpell->EffectMiscValue[0]);
if(ci)
{
//if demonic sacrifice auras are still active, remove them
RemoveAura(18789);
RemoveAura(18790);
RemoveAura(18791);
RemoveAura(18792);
RemoveAura(35701);
Pet *summon = objmgr.CreatePet();
summon->SetInstanceID(GetInstanceID());
summon->CreateAsSummon(pSpell->EffectMiscValue[0], ci, NULL, this, pSpell, 1, 0);
}
}
}
void Player::SpawnActivePet()
{
if( m_Summon != NULL )
return;
std::map< uint32, PlayerPet* >::iterator itr = m_Pets.begin();
for( ; itr != m_Pets.end(); itr++ )
if( itr->second->stablestate == STABLE_STATE_ACTIVE && itr->second->active )
{
SpawnPet( itr->first );
return;
}
}
void Player::_LoadPetSpells(QueryResult * result)
{
std::stringstream query;
std::map<uint32, std::list<uint32>* >::iterator itr;
uint32 entry = 0;
uint32 spell = 0;
if(result)
{
do
{
Field *fields = result->Fetch();
entry = fields[1].GetUInt32();
spell = fields[2].GetUInt32();
AddSummonSpell(entry, spell);
}
while( result->NextRow() );
}
}
void Player::addSpell(uint32 spell_id)
{
SpellSet::iterator iter = mSpells.find(spell_id);
if(iter != mSpells.end())
return;
mSpells.insert(spell_id);
if(IsInWorld())
{
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(spell_id);
m_session->OutPacket(SMSG_LEARNED_SPELL, 4, &swapped);
#else
m_session->OutPacket(SMSG_LEARNED_SPELL, 4, &spell_id);
#endif
}
// Check if we're a deleted spell
iter = mDeletedSpells.find(spell_id);
if(iter != mDeletedSpells.end())
mDeletedSpells.erase(iter);
// Check if we're logging in.
if(!IsInWorld())
return;
// Add the skill line for this spell if we don't already have it.
skilllinespell * sk = objmgr.GetSpellSkill(spell_id);
if(sk && !_HasSkillLine(sk->skilline))
{
skilllineentry * skill = dbcSkillLine.LookupEntry(sk->skilline);
SpellEntry * spell = dbcSpell.LookupEntry(spell_id);
uint32 max = 1;
switch(skill->type)
{
case SKILL_TYPE_PROFESSION:
max=75*((spell->RankNumber)+1);
ModUnsigned32Value( PLAYER_CHARACTER_POINTS2, -1 ); // we are learning a proffesion, so substract a point.
break;
case SKILL_TYPE_SECONDARY:
max=75*((spell->RankNumber)+1);
break;
case SKILL_TYPE_WEAPON:
max=5*getLevel();
break;
case SKILL_TYPE_CLASS:
case SKILL_TYPE_ARMOR:
if(skill->id == SKILL_LOCKPICKING || skill->id == SKILL_POISONS)
max=5*getLevel();
break;
};
_AddSkillLine(sk->skilline, 1, max);
_UpdateMaxSkillCounts();
}
}
//===================================================================================================================
// Set Create Player Bits -- Sets bits required for creating a player in the updateMask.
// Note: Doesn't set Quest or Inventory bits
// updateMask - the updatemask to hold the set bits
//===================================================================================================================
void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
{
if(target == this)
{
Object::_SetCreateBits(updateMask, target);
}
else
{
for(uint32 index = 0; index < m_valuesCount; index++)
{
if(m_uint32Values[index] != 0 && Player::m_visibleUpdateMask.GetBit(index))
updateMask->SetBit(index);
}
}
}
void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
{
if(target == this)
{
Object::_SetUpdateBits(updateMask, target);
}
else
{
Object::_SetUpdateBits(updateMask, target);
*updateMask &= Player::m_visibleUpdateMask;
}
}
void Player::InitVisibleUpdateBits()
{
Player::m_visibleUpdateMask.SetCount(PLAYER_END);
Player::m_visibleUpdateMask.SetBit(OBJECT_FIELD_GUID);
Player::m_visibleUpdateMask.SetBit(OBJECT_FIELD_TYPE);
Player::m_visibleUpdateMask.SetBit(OBJECT_FIELD_SCALE_X);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_SUMMON);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_SUMMON+1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_TARGET);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_TARGET+1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_HEALTH);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_POWER1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_POWER2);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_POWER3);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_POWER4);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_POWER5);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXHEALTH);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXPOWER1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXPOWER2);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXPOWER3);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXPOWER4);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MAXPOWER5);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_LEVEL);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BYTES_0);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_FLAGS);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_FLAGS_2);
for(uint32 i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; i ++)
Player::m_visibleUpdateMask.SetBit(i);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BASEATTACKTIME);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BASEATTACKTIME+1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_COMBATREACH);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_DISPLAYID);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BYTES_1);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_PETNUMBER);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_CHANNEL_OBJECT);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_CHANNEL_OBJECT+1);
Player::m_visibleUpdateMask.SetBit(UNIT_CHANNEL_SPELL);
Player::m_visibleUpdateMask.SetBit(UNIT_DYNAMIC_FLAGS);
Player::m_visibleUpdateMask.SetBit(UNIT_NPC_EMOTESTATE);
Player::m_visibleUpdateMask.SetBit(PLAYER_FLAGS);
Player::m_visibleUpdateMask.SetBit(PLAYER_BYTES);
Player::m_visibleUpdateMask.SetBit(PLAYER_BYTES_2);
Player::m_visibleUpdateMask.SetBit(PLAYER_BYTES_3);
Player::m_visibleUpdateMask.SetBit(PLAYER_GUILD_TIMESTAMP);
Player::m_visibleUpdateMask.SetBit(PLAYER_DUEL_TEAM);
Player::m_visibleUpdateMask.SetBit(PLAYER_DUEL_ARBITER);
Player::m_visibleUpdateMask.SetBit(PLAYER_DUEL_ARBITER+1);
Player::m_visibleUpdateMask.SetBit(PLAYER_GUILDID);
Player::m_visibleUpdateMask.SetBit(PLAYER_GUILDRANK);
Player::m_visibleUpdateMask.SetBit(PLAYER_CHOSEN_TITLE);
Player::m_visibleUpdateMask.SetBit(UNIT_FIELD_BYTES_2);
for(uint16 i = 0; i < EQUIPMENT_SLOT_END; i++)
{
Player::m_visibleUpdateMask.SetBit((uint16)(PLAYER_VISIBLE_ITEM_1_0 + (i*16))); // visual items for other players
Player::m_visibleUpdateMask.SetBit((uint16)(PLAYER_VISIBLE_ITEM_1_0+1 + (i*16))); // visual items for other players
}
/* fuck i hate const - burlex */
/*if(target && target->GetGroup() == const_cast<Player*>(this)->GetGroup() && const_cast<Player*>(this)->GetSubGroup() == target->GetSubGroup())
{
// quest fields are the same for party members
for(uint32 i = PLAYER_QUEST_LOG_1_01; i < PLAYER_QUEST_LOG_25_2; ++i)
Player::m_visibleUpdateMask.SetBit(i);
}*/
}
void Player::DestroyForPlayer( Player *target ) const
{
Unit::DestroyForPlayer( target );
}
#define IS_ARENA(x) ( (x) >= BATTLEGROUND_ARENA_2V2 && (x) <= BATTLEGROUND_ARENA_5V5 )
void Player::SaveToDB(bool bNewCharacter /* =false */)
{
bool in_arena = false;
QueryBuffer * buf = NULL;
if(!bNewCharacter)
buf = new QueryBuffer;
if( m_bg != NULL && IS_ARENA( m_bg->GetType() ) )
in_arena = true;
if(m_uint32Values[PLAYER_CHARACTER_POINTS2]>2)
m_uint32Values[PLAYER_CHARACTER_POINTS2]=2;
//Calc played times
uint32 playedt = (uint32)UNIXTIME - m_playedtime[2];
m_playedtime[0] += playedt;
m_playedtime[1] += playedt;
m_playedtime[2] += playedt;
std::stringstream ss;
ss << "REPLACE INTO characters VALUES ("
<< GetLowGUID() << ", "
<< GetSession()->GetAccountId() << ","
// stat saving
<< "'" << m_name << "', "
<< uint32(getRace()) << ","
<< uint32(getClass()) << ","
<< uint32(getGender()) << ",";
if(m_uint32Values[UNIT_FIELD_FACTIONTEMPLATE] != info->factiontemplate)
ss << m_uint32Values[UNIT_FIELD_FACTIONTEMPLATE] << ",";
else
ss << "0,";
ss << uint32(getLevel()) << ","
<< m_uint32Values[PLAYER_XP] << ","
// dump exploration data
<< "'";
for(uint32 i = 0; i < 64; ++i)
ss << m_uint32Values[PLAYER_EXPLORED_ZONES_1 + i] << ",";
ss << "','";
// dump skill data
/*for(uint32 i=PLAYER_SKILL_INFO_1_1;i<PLAYER_CHARACTER_POINTS1;i+=3)
{
if(m_uint32Values[i])
{
ss << m_uint32Values[i] << ","
<< m_uint32Values[i+1]<< ",";
}
}*/
/*for(uint32 i = PLAYER_SKILL_INFO_1_1; i < PLAYER_CHARACTER_POINTS1; ++i)
ss << m_uint32Values[i] << " ";
*/
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->first && itr->second.Skill->type != SKILL_TYPE_LANGUAGE)
{
ss << itr->first << ";"
<< itr->second.CurrentValue << ";"
<< itr->second.MaximumValue << ";";
}
}
uint32 player_flags = m_uint32Values[PLAYER_FLAGS];
{
// Remove un-needed and problematic player flags from being saved :p
if(player_flags & PLAYER_FLAG_PARTY_LEADER)
player_flags &= ~PLAYER_FLAG_PARTY_LEADER;
if(player_flags & PLAYER_FLAG_AFK)
player_flags &= ~PLAYER_FLAG_AFK;
if(player_flags & PLAYER_FLAG_DND)
player_flags &= ~PLAYER_FLAG_DND;
if(player_flags & PLAYER_FLAG_GM)
player_flags &= ~PLAYER_FLAG_GM;
if(player_flags & PLAYER_FLAG_PVP_TOGGLE)
player_flags &= ~PLAYER_FLAG_PVP_TOGGLE;
if(player_flags & PLAYER_FLAG_FREE_FOR_ALL_PVP)
player_flags &= ~PLAYER_FLAG_FREE_FOR_ALL_PVP;
}
ss << "', "
<< m_uint32Values[PLAYER_FIELD_WATCHED_FACTION_INDEX] << ","
<< m_uint32Values[PLAYER_CHOSEN_TITLE]<< ","
<< GetUInt64Value(PLAYER_FIELD_KNOWN_TITLES) << ","
<< m_uint32Values[PLAYER_FIELD_COINAGE] << ","
<< m_uint32Values[PLAYER_AMMO_ID] << ","
<< m_uint32Values[PLAYER_CHARACTER_POINTS2] << ",";
if (m_uint32Values[PLAYER_CHARACTER_POINTS1] > 61 && ! GetSession()->HasGMPermissions())
SetUInt32Value(PLAYER_CHARACTER_POINTS1, 61);
ss << m_uint32Values[PLAYER_CHARACTER_POINTS1] << ","
<< load_health << ","
<< load_mana << ","
<< uint32(GetPVPRank()) << ","
<< m_uint32Values[PLAYER_BYTES] << ","
<< m_uint32Values[PLAYER_BYTES_2] << ","
<< player_flags << ","
<< m_uint32Values[PLAYER_FIELD_BYTES] << ",";
if( in_arena )
{
// if its an arena, save the entry coords instead
ss << m_bgEntryPointX << ", ";
ss << m_bgEntryPointY << ", ";
ss << m_bgEntryPointZ << ", ";
ss << m_bgEntryPointO << ", ";
ss << m_bgEntryPointMap << ", ";
}
else
{
// save the normal position
ss << m_position.x << ", "
<< m_position.y << ", "
<< m_position.z << ", "
<< m_position.o << ", "
<< m_mapId << ", ";
}
ss << m_zoneId << ", '";
for(uint32 i = 0; i < 8; i++ )
ss << m_taximask[i] << " ";
ss << "', "
<< m_banned << ", '"
<< CharacterDatabase.EscapeString(m_banreason) << "', "
<< (uint32)UNIXTIME << ",";
//online state
if(GetSession()->_loggingOut || bNewCharacter)
{
ss << "0,";
}else
{
ss << "1,";
}
ss
<< m_bind_pos_x << ", "
<< m_bind_pos_y << ", "
<< m_bind_pos_z << ", "
<< m_bind_mapid << ", "
<< m_bind_zoneid << ", "
<< uint32(m_isResting) << ", "
<< uint32(m_restState) << ", "
<< uint32(m_restAmount) << ", '"
<< uint32(m_playedtime[0]) << " "
<< uint32(m_playedtime[1]) << " "
<< uint32(playedt) << " ', "
<< uint32(m_deathState) << ", "
<< m_talentresettimes << ", "
<< m_FirstLogin << ", "
<< rename_pending
<< "," << m_arenaPoints << ","
<< (uint32)m_StableSlotCount << ",";
// instances
if( in_arena )
{
ss << m_bgEntryPointInstance << ", ";
}
else
{
ss << m_instanceId << ", ";
}
ss << m_bgEntryPointMap << ", "
<< m_bgEntryPointX << ", "
<< m_bgEntryPointY << ", "
<< m_bgEntryPointZ << ", "
<< m_bgEntryPointO << ", "
<< m_bgEntryPointInstance << ", ";
// taxi
if(m_onTaxi&&m_CurrentTaxiPath) {
ss << m_CurrentTaxiPath->GetID() << ", ";
ss << lastNode << ", ";
ss << GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID);
} else {
ss << "0, 0, 0";
}
ss << "," << (m_CurrentTransporter ? m_CurrentTransporter->GetEntry() : (uint32)0);
ss << ",'" << m_TransporterX << "','" << m_TransporterY << "','" << m_TransporterZ << "'";
ss << ",'";
// Dump spell data to stringstream
SpellSet::iterator spellItr = mSpells.begin();
for(; spellItr != mSpells.end(); ++spellItr)
{
ss << uint32(*spellItr) << ",";
}
ss << "','";
// Dump deleted spell data to stringstream
spellItr = mDeletedSpells.begin();
for(; spellItr != mDeletedSpells.end(); ++spellItr)
{
ss << uint32(*spellItr) << ",";
}
ss << "','";
// Dump reputation data
ReputationMap::iterator iter = m_reputation.begin();
for(; iter != m_reputation.end(); ++iter)
{
ss << int32(iter->first) << "," << int32(iter->second->flag) << "," << int32(iter->second->baseStanding) << "," << int32(iter->second->standing) << ",";
}
ss << "','";
// Add player action bars
for(uint32 i = 0; i < 120; ++i)
{
ss << uint32(mActions[i].Action) << ","
<< uint32(mActions[i].Misc) << ","
<< uint32(mActions[i].Type) << ",";
}
ss << "','";
if(!bNewCharacter)
SaveAuras(ss);
// ss << LoadAuras;
ss << "','";
// Add player finished quests
set<uint32>::iterator fq = m_finishedQuests.begin();
for(; fq != m_finishedQuests.end(); ++fq)
{
ss << (*fq) << ",";
}
ss << "', '";
DailyMutex.Acquire();
set<uint32>::iterator fdq = m_finishedDailies.begin();
for(; fdq != m_finishedDailies.end(); fdq++)
{
ss << (*fdq) << ",";
}
DailyMutex.Release();
ss << "', ";
ss << m_honorRolloverTime << ", ";
ss << m_killsToday << ", " << m_killsYesterday << ", " << m_killsLifetime << ", ";
ss << m_honorToday << ", " << m_honorYesterday << ", ";
ss << m_honorPoints << ", ";
ss << iInstanceType << ")";
if(bNewCharacter)
CharacterDatabase.WaitExecuteNA(ss.str().c_str());
else
buf->AddQueryStr(ss.str());
//Save Other related player stuff
// Inventory
GetItemInterface()->mSaveItemsToDatabase(bNewCharacter, buf);
// save quest progress
_SaveQuestLogEntry(buf);
// Tutorials
_SaveTutorials(buf);
// GM Ticket
//TODO: Is this really necessary? Tickets will allways be saved on creation, update and so on...
GM_Ticket* ticket = objmgr.GetGMTicketByPlayer(GetGUID());
if(ticket != NULL)
objmgr.SaveGMTicket(ticket, buf);
// Cooldown Items
_SavePlayerCooldowns( buf );
// Pets
if(getClass() == HUNTER || getClass() == WARLOCK)
{
_SavePet(buf);
_SavePetSpells(buf);
}
m_nextSave = getMSTime() + sWorld.getIntRate(INTRATE_SAVE);
if(buf)
CharacterDatabase.AddQueryBuffer(buf);
}
void Player::_SaveQuestLogEntry(QueryBuffer * buf)
{
for(std::set<uint32>::iterator itr = m_removequests.begin(); itr != m_removequests.end(); ++itr)
{
if(buf == NULL)
CharacterDatabase.Execute("DELETE FROM questlog WHERE player_guid=%u AND quest_id=%u", GetLowGUID(), (*itr));
else
buf->AddQuery("DELETE FROM questlog WHERE player_guid=%u AND quest_id=%u", GetLowGUID(), (*itr));
}
m_removequests.clear();
for(int i = 0; i < 25; ++i)
{
if(m_questlog[i] != NULL)
m_questlog[i]->SaveToDB(buf);
}
}
bool Player::canCast(SpellEntry *m_spellInfo)
{
if (m_spellInfo->EquippedItemClass != 0)
{
if(this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND))
{
if((int32)this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND)->GetProto()->Class == m_spellInfo->EquippedItemClass)
{
if (m_spellInfo->EquippedItemSubClass != 0)
{
if (m_spellInfo->EquippedItemSubClass != 173555 && m_spellInfo->EquippedItemSubClass != 96 && m_spellInfo->EquippedItemSubClass != 262156)
{
if (pow(2.0,(this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND)->GetProto()->SubClass) != m_spellInfo->EquippedItemSubClass))
return false;
}
}
}
}
else if(m_spellInfo->EquippedItemSubClass == 173555)
return false;
if (this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED))
{
if((int32)this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED)->GetProto()->Class == m_spellInfo->EquippedItemClass)
{
if (m_spellInfo->EquippedItemSubClass != 0)
{
if (m_spellInfo->EquippedItemSubClass != 173555 && m_spellInfo->EquippedItemSubClass != 96 && m_spellInfo->EquippedItemSubClass != 262156)
{
if (pow(2.0,(this->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED)->GetProto()->SubClass) != m_spellInfo->EquippedItemSubClass)) return false;
}
}
}
}
else if
(m_spellInfo->EquippedItemSubClass == 262156)
return false;
}
return true;
}
void Player::RemovePendingPlayer()
{
if(m_session)
{
uint8 respons = 0x42; // CHAR_LOGIN_NO_CHARACTER
m_session->OutPacket(SMSG_CHARACTER_LOGIN_FAILED, 1, &respons);
m_session->m_loggingInPlayer = NULL;
}
ok_to_remove = true;
delete this;
}
bool Player::LoadFromDB(uint32 guid)
{
AsyncQuery * q = new AsyncQuery( new SQLClassCallbackP0<Player>(this, &Player::LoadFromDBProc) );
q->AddQuery("SELECT * FROM characters WHERE guid=%u AND forced_rename_pending = 0",guid);
q->AddQuery("SELECT * FROM tutorials WHERE playerId=%u",guid);
q->AddQuery("SELECT cooldown_type, cooldown_misc, cooldown_expire_time, cooldown_spellid, cooldown_itemid FROM playercooldowns WHERE player_guid=%u", guid);
q->AddQuery("SELECT * FROM questlog WHERE player_guid=%u",guid);
q->AddQuery("SELECT * FROM playeritems WHERE ownerguid=%u ORDER BY containerslot ASC", guid);
q->AddQuery("SELECT * FROM playerpets WHERE ownerguid=%u ORDER BY petnumber", guid);
q->AddQuery("SELECT * FROM playersummonspells where ownerguid=%u ORDER BY entryid", guid);
q->AddQuery("SELECT * FROM mailbox WHERE player_guid = %u", guid);
// social
q->AddQuery("SELECT friend_guid, note FROM social_friends WHERE character_guid = %u", guid);
q->AddQuery("SELECT character_guid FROM social_friends WHERE friend_guid = %u", guid);
q->AddQuery("SELECT ignore_guid FROM social_ignores WHERE character_guid = %u", guid);
// queue it!
m_uint32Values[OBJECT_FIELD_GUID] = guid;
CharacterDatabase.QueueAsyncQuery(q);
return true;
}
void Player::LoadFromDBProc(QueryResultVector & results)
{
uint32 field_index = 2;
#define get_next_field fields[field_index++]
if(GetSession() == NULL || results.size() < 8) // should have 8 queryresults for aplayer load.
{
RemovePendingPlayer();
return;
}
QueryResult *result = results[0].result;
if(!result)
{
Log.Error ("Player::LoadFromDB",
"Player login query failed! guid = %u",
GetLowGUID ());
RemovePendingPlayer();
return;
}
if (result->GetFieldCount () != 80)
{
Log.Error ("Player::LoadFromDB",
"Expected 80 fields from the database, "
"but received %u!",
(unsigned int) result->GetFieldCount ());
RemovePendingPlayer();
return;
}
Field *fields = result->Fetch();
if(fields[1].GetUInt32() != m_session->GetAccountId())
{
sCheatLog.writefromsession(m_session, "player tried to load character not belonging to them (guid %u, on account %u)",
fields[0].GetUInt32(), fields[1].GetUInt32());
RemovePendingPlayer();
return;
}
uint32 banned = fields[32].GetUInt32();
if(banned && (banned < 100 || banned > (uint32)UNIXTIME))
{
RemovePendingPlayer();
return;
}
// Load name
m_name = get_next_field.GetString();
// Load race/class from fields
setRace(get_next_field.GetUInt8());
setClass(get_next_field.GetUInt8());
setGender(get_next_field.GetUInt8());
uint32 cfaction = get_next_field.GetUInt32();
// set race dbc
myRace = dbcCharRace.LookupEntryForced(getRace());
myClass = dbcCharClass.LookupEntryForced(getClass());
if(!myClass || !myRace)
{
// bad character
printf("guid %u failed to login, no race or class dbc found. (race %u class %u)\n", (unsigned int)GetLowGUID(), (unsigned int)getRace(), (unsigned int)getClass());
RemovePendingPlayer();
return;
}
if(myRace->team_id == 7)
{
m_bgTeam = m_team = 0;
}
else
{
m_bgTeam = m_team = 1;
}
SetNoseLevel();
// set power type
SetPowerType(myClass->power_type);
// obtain player create info
info = objmgr.GetPlayerCreateInfo(getRace(), getClass());
if(!info)
{
sLog.outError("%s: player guid %u has no playerCreateInfo!\n", (unsigned int)GetLowGUID());
RemovePendingPlayer();
return;
}
// set level
m_uint32Values[UNIT_FIELD_LEVEL] = get_next_field.GetUInt32();
/*if(m_uint32Values[UNIT_FIELD_LEVEL] > PLAYER_LEVEL_CAP)
m_uint32Values[UNIT_FIELD_LEVEL] = PLAYER_LEVEL_CAP;*/
// obtain level/stats information
lvlinfo = objmgr.GetLevelInfo(getRace(), getClass(), getLevel());
if(!lvlinfo)
{
printf("guid %u level %u class %u race %u levelinfo not found!\n", (unsigned int)GetLowGUID(), (unsigned int)getLevel(), (unsigned int)getClass(), (unsigned int)getRace());
RemovePendingPlayer();
return;
}
CalculateBaseStats();
// set xp
m_uint32Values[PLAYER_XP] = get_next_field.GetUInt32();
// Process exploration data.
uint32 Counter = 0;
char * end;
char * start = (char*)get_next_field.GetString();//buff;
while(Counter <64)
{
end = strchr(start,',');
if(!end)break;
*end=0;
SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + Counter, atol(start));
start = end +1;
Counter++;
}
// Process skill data.
Counter = 0;
start = (char*)get_next_field.GetString();//buff;
// new format
const ItemProf * prof;
if(!strchr(start, ' ') && !strchr(start,';'))
{
/* no skills - reset to defaults */
for(std::list<CreateInfo_SkillStruct>::iterator ss = info->skills.begin(); ss!=info->skills.end(); ss++)
{
if(ss->skillid && ss->currentval && ss->maxval && !::GetSpellForLanguage(ss->skillid))
_AddSkillLine(ss->skillid, ss->currentval, ss->maxval);
}
}
else
{
char * f = strdup(start);
start = f;
if(!strchr(start,';'))
{
/* old skill format.. :< */
uint32 v1,v2,v3;
PlayerSkill sk;
for(;;)
{
end = strchr(start, ' ');
if(!end)
break;
*end = 0;
v1 = atol(start);
start = end + 1;
end = strchr(start, ' ');
if(!end)
break;
*end = 0;
v2 = atol(start);
start = end + 1;
end = strchr(start, ' ');
if(!end)
break;
v3 = atol(start);
start = end + 1;
if(v1 & 0xffff)
{
sk.Reset(v1 & 0xffff);
sk.CurrentValue = v2 & 0xffff;
sk.MaximumValue = (v2 >> 16) & 0xffff;
if( !sk.CurrentValue )
sk.CurrentValue = 1;
m_skills.insert( make_pair(sk.Skill->id, sk) );
}
}
}
else
{
uint32 v1,v2,v3;
PlayerSkill sk;
for(;;)
{
end = strchr(start, ';');
if(!end)
break;
*end = 0;
v1 = atol(start);
start = end + 1;
end = strchr(start, ';');
if(!end)
break;
*end = 0;
v2 = atol(start);
start = end + 1;
end = strchr(start, ';');
if(!end)
break;
v3 = atol(start);
start = end + 1;
/* add the skill */
if(v1)
{
sk.Reset(v1);
sk.CurrentValue = v2;
sk.MaximumValue = v3;
if( !sk.CurrentValue )
sk.CurrentValue = 1;
m_skills.insert(make_pair(v1, sk));
}
}
}
free(f);
}
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->first == SKILL_RIDING)
{
itr->second.CurrentValue = itr->second.MaximumValue;
}
prof = GetProficiencyBySkill(itr->first);
if(prof)
{
if(prof->itemclass==4)
armor_proficiency|=prof->subclass;
else
weapon_proficiency|=prof->subclass;
}
}
// set the rest of the stuff
m_uint32Values[ PLAYER_FIELD_WATCHED_FACTION_INDEX ] = get_next_field.GetUInt32();
m_uint32Values[ PLAYER_CHOSEN_TITLE ] = get_next_field.GetUInt32();
SetUInt64Value( PLAYER_FIELD_KNOWN_TITLES, get_next_field.GetUInt64() );
m_uint32Values[ PLAYER_FIELD_COINAGE ] = get_next_field.GetUInt32();
m_uint32Values[ PLAYER_AMMO_ID ] = get_next_field.GetUInt32();
m_uint32Values[ PLAYER_CHARACTER_POINTS2 ] = get_next_field.GetUInt32();
m_uint32Values[ PLAYER_CHARACTER_POINTS1 ] = get_next_field.GetUInt32();
load_health = get_next_field.GetUInt32();
load_mana = get_next_field.GetUInt32();
SetUInt32Value( UNIT_FIELD_HEALTH, load_health );
uint8 pvprank = get_next_field.GetUInt8();
SetUInt32Value( PLAYER_BYTES, get_next_field.GetUInt32() );
SetUInt32Value( PLAYER_BYTES_2, get_next_field.GetUInt32() );
SetUInt32Value( PLAYER_BYTES_3, getGender() | ( pvprank << 24 ) );
SetUInt32Value( PLAYER_FLAGS, get_next_field.GetUInt32() );
SetUInt32Value( PLAYER_FIELD_BYTES, get_next_field.GetUInt32() );
//m_uint32Values[0x22]=(m_uint32Values[0x22]>0x46)?0x46:m_uint32Values[0x22];
m_position.x = get_next_field.GetFloat();
m_position.y = get_next_field.GetFloat();
m_position.z = get_next_field.GetFloat();
m_position.o = get_next_field.GetFloat();
m_mapId = get_next_field.GetUInt32();
m_zoneId = get_next_field.GetUInt32();
// Calculate the base stats now they're all loaded
for(uint32 i = 0; i < 5; ++i)
CalcStat(i);
// for(uint32 x = PLAYER_SPELL_CRIT_PERCENTAGE1; x < PLAYER_SPELL_CRIT_PERCENTAGE06 + 1; ++x)
/// SetFloatValue(x, 0.0f);
for(uint32 x = PLAYER_FIELD_MOD_DAMAGE_DONE_PCT; x < PLAYER_FIELD_MOD_HEALING_DONE_POS; ++x)
SetFloatValue(x, 1.0f);
// Normal processing...
// UpdateMaxSkills();
UpdateStats();
//UpdateChances();
// Initialize 'normal' fields
//SetFloatValue(OBJECT_FIELD_SCALE_X, ((getRace()==RACE_TAUREN)?1.3f:1.0f));
SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f);
//SetUInt32Value(UNIT_FIELD_POWER2, 0);
SetUInt32Value(UNIT_FIELD_POWER3, info->focus);
SetUInt32Value(UNIT_FIELD_POWER4, info->energy );
SetUInt32Value(UNIT_FIELD_MAXPOWER2, info->rage );
SetUInt32Value(UNIT_FIELD_MAXPOWER3, info->focus );
SetUInt32Value(UNIT_FIELD_MAXPOWER4, info->energy );
if(getClass() == WARRIOR)
SetShapeShift(FORM_BATTLESTANCE);
SetUInt32Value(UNIT_FIELD_BYTES_2, (0x28 << 8) );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED);
SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, 0.388999998569489f );
SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
if(getRace() != 10)
{
SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId + getGender() );
SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId + getGender() );
} else {
SetUInt32Value(UNIT_FIELD_DISPLAYID, info->displayId - getGender() );
SetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID, info->displayId - getGender() );
}
EventModelChange();
SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.m_levelCap);
SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, info->factiontemplate);
if(cfaction)
{
SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, info->factiontemplate);
// re-calculate team
switch(cfaction)
{
case 1: // human
case 3: // dwarf
case 4: // ne
case 8: // gnome
case 927: // dreinei
m_team = m_bgTeam = 0;
break;
default:
m_team = m_bgTeam = 1;
break;
}
}
LoadTaxiMask( get_next_field.GetString() );
m_banned = get_next_field.GetUInt32(); //Character ban
m_banreason = get_next_field.GetString();
m_timeLogoff = get_next_field.GetUInt32();
field_index++;
m_bind_pos_x = get_next_field.GetFloat();
m_bind_pos_y = get_next_field.GetFloat();
m_bind_pos_z = get_next_field.GetFloat();
m_bind_mapid = get_next_field.GetUInt32();
m_bind_zoneid = get_next_field.GetUInt32();
m_isResting = get_next_field.GetUInt8();
m_restState = get_next_field.GetUInt8();
m_restAmount = get_next_field.GetUInt32();
std::string tmpStr = get_next_field.GetString();
m_playedtime[0] = (uint32)atoi((const char*)strtok((char*)tmpStr.c_str()," "));
m_playedtime[1] = (uint32)atoi((const char*)strtok(NULL," "));
m_deathState = (DeathState)get_next_field.GetUInt32();
m_talentresettimes = get_next_field.GetUInt32();
m_FirstLogin = get_next_field.GetBool();
rename_pending = get_next_field.GetBool();
m_arenaPoints = get_next_field.GetUInt32();
if (m_arenaPoints > 5000) m_arenaPoints = 5000;
for(uint32 z = 0; z < NUM_CHARTER_TYPES; ++z)
m_charters[z] = objmgr.GetCharterByGuid(GetGUID(), (CharterTypes)z);
for(uint32 z = 0; z < NUM_ARENA_TEAM_TYPES; ++z)
{
m_arenaTeams[z] = objmgr.GetArenaTeamByGuid(GetLowGUID(), z);
if(m_arenaTeams[z] != NULL)
{
SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (z*6), m_arenaTeams[z]->m_id);
if(m_arenaTeams[z]->m_leader == GetLowGUID())
SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (z*6) + 1, 0);
else
SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (z*6) + 1, 1);
}
}
m_StableSlotCount = get_next_field.GetUInt32();
m_instanceId = get_next_field.GetUInt32();
m_bgEntryPointMap = get_next_field.GetUInt32();
m_bgEntryPointX = get_next_field.GetFloat();
m_bgEntryPointY = get_next_field.GetFloat();
m_bgEntryPointZ = get_next_field.GetFloat();
m_bgEntryPointO = get_next_field.GetFloat();
m_bgEntryPointInstance = get_next_field.GetUInt32();
uint32 taxipath = get_next_field.GetUInt32();
TaxiPath *path = NULL;
if(taxipath)
{
path = sTaxiMgr.GetTaxiPath(taxipath);
lastNode = get_next_field.GetUInt32();
if(path)
{
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, get_next_field.GetUInt32());
SetTaxiPath(path);
m_onTaxi = true;
}
else
field_index++;
}
else
{
field_index++;
field_index++;
}
m_TransporterGUID = get_next_field.GetUInt32();
if(m_TransporterGUID)
{
Transporter * t = objmgr.GetTransporter(GUID_LOPART(m_TransporterGUID));
m_TransporterGUID = t ? t->GetGUID() : 0;
}
m_TransporterX = get_next_field.GetFloat();
m_TransporterY = get_next_field.GetFloat();
m_TransporterZ = get_next_field.GetFloat();
// Load Spells from CSV data.
start = (char*)get_next_field.GetString();//buff;
SpellEntry * spProto;
while(true)
{
end = strchr(start,',');
if(!end)break;
*end=0;
//mSpells.insert(atol(start));
spProto = dbcSpell.LookupEntryForced(atol(start));
//#define _language_fix_ 1
#ifndef _language_fix_
if(spProto)
mSpells.insert(spProto->Id);
#else
if (spProto)
{
skilllinespell * _spell = objmgr.GetSpellSkill(spProto->Id);
if (_spell)
{
skilllineentry * _skill = dbcSkillLine.LookupEntry(_spell->skilline);
if (_skill && _skill->type != SKILL_TYPE_LANGUAGE)
{
mSpells.insert(spProto->Id);
}
}
else
{
mSpells.insert(spProto->Id);
}
}
#endif
//#undef _language_fix_
start = end +1;
}
start = (char*)get_next_field.GetString();//buff;
while(true)
{
end = strchr(start,',');
if(!end)break;
*end=0;
spProto = dbcSpell.LookupEntryForced(atol(start));
if(spProto)
mDeletedSpells.insert(spProto->Id);
start = end +1;
}
// Load Reputatation CSV Data
start =(char*) get_next_field.GetString();
FactionDBC * factdbc ;
FactionReputation * rep;
uint32 id;
int32 basestanding;
int32 standing;
uint32 fflag;
while(true)
{
end = strchr(start,',');
if(!end)break;
*end=0;
id = atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
fflag = atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
basestanding = atoi(start);//atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
standing = atoi(start);// atol(start);
start = end +1;
// listid stuff
factdbc = dbcFaction.LookupEntryForced(id);
if ( factdbc == NULL || factdbc->RepListId < 0 ) continue;
ReputationMap::iterator rtr = m_reputation.find(id);
if(rtr != m_reputation.end())
delete rtr->second;
rep = new FactionReputation;
rep->baseStanding = basestanding;
rep->standing = standing;
rep->flag = fflag;
m_reputation[id]=rep;
reputationByListId[factdbc->RepListId] = rep;
}
if(!m_reputation.size())
_InitialReputation();
// Load saved actionbars
start = (char*)get_next_field.GetString();
Counter =0;
while(Counter < 120)
{
end = strchr(start,',');
if(!end)break;
*end=0;
mActions[Counter].Action = (uint16)atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
mActions[Counter].Misc = (uint8)atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
mActions[Counter++].Type = (uint8)atol(start);
start = end +1;
}
//LoadAuras = get_next_field.GetString();
start = (char*)get_next_field.GetString();//buff;
do
{
end = strchr(start,',');
if(!end)break;
*end=0;
LoginAura la;
la.id = atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
la.dur = atol(start);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
la.positive = (start!=NULL);
start = end +1;
end = strchr(start,',');
if(!end)break;
*end=0;
la.charges = atol(start);
start = end +1;
loginauras.push_back(la);
} while(true);
// Load saved finished quests
start = (char*)get_next_field.GetString();
while(true)
{
end = strchr(start,',');
if(!end)break;
*end=0;
m_finishedQuests.insert(atol(start));
start = end +1;
}
start = (char*)get_next_field.GetString();
while(true)
{
end = strchr(start,',');
if(!end) break;
*end = 0;
m_finishedDailies.insert(atol(start));
start = end +1;
}
m_honorRolloverTime = get_next_field.GetUInt32();
m_killsToday = get_next_field.GetUInt32();
m_killsYesterday = get_next_field.GetUInt32();
m_killsLifetime = get_next_field.GetUInt32();
m_honorToday = get_next_field.GetUInt32();
m_honorYesterday = get_next_field.GetUInt32();
m_honorPoints = get_next_field.GetUInt32();
if (m_honorPoints > 75000) m_honorPoints = 75000;
RolloverHonor();
iInstanceType = get_next_field.GetUInt32();
HonorHandler::RecalculateHonorFields(this);
for(uint32 x=0;x<5;x++)
BaseStats[x]=GetUInt32Value(UNIT_FIELD_STAT0+x);
_setFaction();
//class fixes
switch(getClass())
{
case PALADIN:
armor_proficiency|=(1<<7);//LIBRAM
break;
case DRUID:
armor_proficiency|=(1<<8);//IDOL
break;
case SHAMAN:
armor_proficiency|=(1<<9);//TOTEM
break;
case WARLOCK:
case HUNTER:
_LoadPet(results[5].result);
_LoadPetSpells(results[6].result);
break;
}
if(m_session->CanUseCommand('c'))
_AddLanguages(true);
else
_AddLanguages(false);
OnlineTime = (uint32)UNIXTIME;
if(GetGuildId())
SetUInt32Value(PLAYER_GUILD_TIMESTAMP, (uint32)UNIXTIME);
#undef get_next_field
// load properties
_LoadTutorials(results[1].result);
_LoadPlayerCooldowns(results[2].result);
_LoadQuestLogEntry(results[3].result);
m_ItemInterface->mLoadItemsFromDatabase(results[4].result);
m_mailBox.Load(results[7].result);
// SOCIAL
if( results[8].result != NULL ) // this query is "who are our friends?"
{
result = results[8].result;
do
{
fields = result->Fetch();
if( strlen( fields[1].GetString() ) )
m_friends.insert( make_pair( fields[0].GetUInt32(), strdup(fields[1].GetString()) ) );
else
m_friends.insert( make_pair( fields[0].GetUInt32(), (char*)NULL) );
} while (result->NextRow());
}
if( results[9].result != NULL ) // this query is "who has us in their friends?"
{
result = results[9].result;
do
{
m_hasFriendList.insert( result->Fetch()[0].GetUInt32() );
} while (result->NextRow());
}
if( results[10].result != NULL ) // this query is "who are we ignoring"
{
result = results[10].result;
do
{
m_ignores.insert( result->Fetch()[0].GetUInt32() );
} while (result->NextRow());
}
// END SOCIAL
// Check skills that player shouldn't have
if (_HasSkillLine(SKILL_DUAL_WIELD) && !HasSpell(674)) {
_RemoveSkillLine(SKILL_DUAL_WIELD);
}
m_session->FullLogin(this);
m_session->m_loggingInPlayer=NULL;
if( !isAlive() )
myCorpse = objmgr.GetCorpseByOwner(GetLowGUID());
// check for multiple gems with unique-equipped flag
uint32 count;
uint32 uniques[64];
int nuniques=0;
for( uint32 x = EQUIPMENT_SLOT_START; x < EQUIPMENT_SLOT_END; ++x )
{
ItemInterface *itemi = GetItemInterface();
Item * it = itemi->GetInventoryItem(x);
if( it != NULL )
{
for( count=0; count<it->GetSocketsCount(); count++ )
{
EnchantmentInstance *ei = it->GetEnchantment(2+count);
if (ei && ei->Enchantment)
{
ItemPrototype * ip = ItemPrototypeStorage.LookupEntry(ei->Enchantment->GemEntry);
if (ip && ip->Flags & ITEM_FLAG_UNIQUE_EQUIP &&
itemi->IsEquipped(ip->ItemId))
{
int i;
for (i=0; i<nuniques; i++)
{
if (uniques[i] == ip->ItemId)
{
// found a duplicate unique-equipped gem, remove it
it->RemoveEnchantment(2+count);
break;
}
}
if (i == nuniques) // not found
uniques[nuniques++] = ip->ItemId;
}
}
}
}
}
}
void Player::SetPersistentInstanceId(Instance *pInstance)
{
if(pInstance == NULL)
return;
// Skip this handling for flagged GMs.
if(bGMTagOn)
return;
// Bind instance to "my" group.
if(m_playerInfo && m_playerInfo->m_Group && pInstance->m_creatorGroup == 0)
pInstance->m_creatorGroup = m_playerInfo && m_playerInfo->m_Group->GetID();
// Skip handling for non-persistent instances.
if(!IS_PERSISTENT_INSTANCE(pInstance))
return;
// Set instance for group if not done yet.
if(m_playerInfo && m_playerInfo->m_Group && (m_playerInfo->m_Group->m_instanceIds[pInstance->m_mapId][pInstance->m_difficulty] == 0 || !sInstanceMgr.InstanceExists(pInstance->m_mapId, m_playerInfo->m_Group->m_instanceIds[pInstance->m_mapId][pInstance->m_difficulty])))
{
m_playerInfo->m_Group->m_instanceIds[pInstance->m_mapId][pInstance->m_difficulty] = pInstance->m_instanceId;
m_playerInfo->m_Group->SaveToDB();
}
// Instance is not saved yet (no bosskill)
if(!pInstance->m_persistent)
{
SetPersistentInstanceId(pInstance->m_mapId, pInstance->m_difficulty, 0);
}
// Set instance id to player.
else
{
SetPersistentInstanceId(pInstance->m_mapId, pInstance->m_difficulty, pInstance->m_instanceId);
}
sLog.outDebug("Added player %u to saved instance %u on map %u.", (uint32)GetGUID(), pInstance->m_instanceId, pInstance->m_mapId);
}
void Player::SetPersistentInstanceId(uint32 mapId, uint32 difficulty, uint32 instanceId)
{
if(mapId >= NUM_MAPS || difficulty >= NUM_INSTANCE_MODES || m_playerInfo == NULL)
return;
m_playerInfo->savedInstanceIdsLock.Acquire();
PlayerInstanceMap::iterator itr = m_playerInfo->savedInstanceIds[difficulty].find(mapId);
if(itr == m_playerInfo->savedInstanceIds[difficulty].end())
{
if(instanceId != 0)
m_playerInfo->savedInstanceIds[difficulty].insert(PlayerInstanceMap::value_type(mapId, instanceId));
}
else
{
if(instanceId == 0)
m_playerInfo->savedInstanceIds[difficulty].erase(itr);
else
(*itr).second = instanceId;
}
m_playerInfo->savedInstanceIdsLock.Release();
CharacterDatabase.Execute("REPLACE INTO `instanceids` (`playerguid`, `mapid`, `mode`, `instanceid`) VALUES ( %u, %u, %u, %u )", m_playerInfo->guid, mapId, difficulty, instanceId);
}
void Player::RolloverHonor()
{
uint32 current_val = (g_localTime.tm_year << 16) | g_localTime.tm_yday;
if( current_val != m_honorRolloverTime )
{
m_honorRolloverTime = current_val;
m_honorYesterday = m_honorToday;
m_killsYesterday = m_killsToday;
m_honorToday = m_killsToday = 0;
}
}
void Player::_LoadQuestLogEntry(QueryResult * result)
{
QuestLogEntry *entry;
Quest *quest;
Field *fields;
uint32 questid;
uint32 baseindex;
// clear all fields
for(int i = 0; i < 25; ++i)
{
baseindex = PLAYER_QUEST_LOG_1_1 + (i * 4);
SetUInt32Value(baseindex + 0, 0);
SetUInt32Value(baseindex + 1, 0);
SetUInt32Value(baseindex + 2, 0);
SetUInt32Value(baseindex + 3, 0);
}
int slot = 0;
if(result)
{
do
{
fields = result->Fetch();
questid = fields[1].GetUInt32();
quest = QuestStorage.LookupEntry(questid);
slot = fields[2].GetUInt32();
ASSERT(slot != -1);
// remove on next save if bad quest
if(!quest)
{
m_removequests.insert(questid);
continue;
}
if(m_questlog[slot] != 0)
continue;
entry = new QuestLogEntry;
entry->Init(quest, this, slot);
entry->LoadFromDB(fields);
entry->UpdatePlayerFields();
} while(result->NextRow());
}
}
QuestLogEntry* Player::GetQuestLogForEntry(uint32 quest)
{
for(int i = 0; i < 25; ++i)
{
if(m_questlog[i] == ((QuestLogEntry*)0x00000001))
m_questlog[i] = NULL;
if(m_questlog[i] != NULL)
{
if(m_questlog[i]->GetQuest() && m_questlog[i]->GetQuest()->id == quest)
return m_questlog[i];
}
}
return NULL;
/*uint32 x = PLAYER_QUEST_LOG_1_1;
uint32 y = 0;
for(; x < PLAYER_VISIBLE_ITEM_1_CREATOR && y < 25; x += 3, y++)
{
if(m_uint32Values[x] == quest)
return m_questlog[y];
}
return NULL;*/
}
void Player::SetQuestLogSlot(QuestLogEntry *entry, uint32 slot)
{
m_questlog[slot] = entry;
}
void Player::AddToWorld()
{
FlyCheat = false;
m_setflycheat=false;
// check transporter
if(m_TransporterGUID && m_CurrentTransporter)
{
SetPosition(m_CurrentTransporter->GetPositionX() + m_TransporterX,
m_CurrentTransporter->GetPositionY() + m_TransporterY,
m_CurrentTransporter->GetPositionZ() + m_TransporterZ,
GetOrientation(), false);
}
// If we join an invalid instance and get booted out, this will prevent our stats from doubling :P
if(IsInWorld())
return;
m_beingPushed = true;
Object::AddToWorld();
// Add failed.
if(m_mapMgr == NULL)
{
// eject from instance
m_beingPushed = false;
EjectFromInstance();
return;
}
if(m_session)
m_session->SetInstance(m_mapMgr->GetInstanceID());
}
void Player::AddToWorld(MapMgr * pMapMgr)
{
FlyCheat = false;
m_setflycheat=false;
// check transporter
if(m_TransporterGUID && m_CurrentTransporter)
{
SetPosition(m_CurrentTransporter->GetPositionX() + m_TransporterX,
m_CurrentTransporter->GetPositionY() + m_TransporterY,
m_CurrentTransporter->GetPositionZ() + m_TransporterZ,
GetOrientation(), false);
}
// If we join an invalid instance and get booted out, this will prevent our stats from doubling :P
if(IsInWorld())
return;
m_beingPushed = true;
Object::AddToWorld(pMapMgr);
// Add failed.
if(m_mapMgr == NULL)
{
// eject from instance
m_beingPushed = false;
EjectFromInstance();
return;
}
if(m_session)
m_session->SetInstance(m_mapMgr->GetInstanceID());
}
void Player::OnPrePushToWorld()
{
SendInitialLogonPackets();
}
void Player::OnPushToWorld()
{
if(m_TeleportState == 2) // Worldport Ack
OnWorldPortAck();
SpeedCheatReset();
m_beingPushed = false;
AddItemsToWorld();
m_lockTransportVariables = false;
// delay the unlock movement packet
WorldPacket * data = new WorldPacket(SMSG_MOVE_UNLOCK_MOVEMENT, 4);
*data << uint32(0);
delayedPackets.add(data);
sWorld.mInWorldPlayerCount++;
// Update PVP Situation
LoginPvPSetup();
if ( m_playerInfo->lastOnline + 900 < UNIXTIME ) // did we logged out for more than 15 minutes?
m_ItemInterface->RemoveAllConjured();
Unit::OnPushToWorld();
if(m_FirstLogin)
{
sHookInterface.OnFirstEnterWorld(this);
LevelInfo * Info = objmgr.GetLevelInfo(getRace(), getClass(), sWorld.start_level);
ApplyLevelInfo(Info, sWorld.start_level);
m_FirstLogin = false;
}
sHookInterface.OnEnterWorld(this);
if(m_TeleportState == 1) // First world enter
CompleteLoading();
m_TeleportState = 0;
if(GetTaxiState())
{
if( m_taxiMapChangeNode != 0 )
{
lastNode = m_taxiMapChangeNode;
}
// Create HAS to be sent before this!
ProcessPendingUpdates();
TaxiStart(GetTaxiPath(),
GetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID),
lastNode);
m_taxiMapChangeNode = 0;
}
if(flying_aura && m_mapId != 530)
{
RemoveAura(flying_aura);
flying_aura = 0;
}
/* send weather */
sWeatherMgr.SendWeather(this);
SetUInt32Value( UNIT_FIELD_HEALTH, ( load_health > m_uint32Values[UNIT_FIELD_MAXHEALTH] ? m_uint32Values[UNIT_FIELD_MAXHEALTH] : load_health ));
SetUInt32Value( UNIT_FIELD_POWER1, ( load_mana > m_uint32Values[UNIT_FIELD_MAXPOWER1] ? m_uint32Values[UNIT_FIELD_MAXPOWER1] : load_mana ));
if( !GetSession()->HasGMPermissions() )
GetItemInterface()->CheckAreaItems();
#ifdef ENABLE_COMPRESSED_MOVEMENT
//sEventMgr.AddEvent(this, &Player::EventDumpCompressedMovement, EVENT_PLAYER_FLUSH_MOVEMENT, World::m_movementCompressInterval, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
MovementCompressor->AddPlayer(this);
#endif
if( m_mapMgr && m_mapMgr->m_battleground != NULL && m_bg != m_mapMgr->m_battleground )
{
m_bg = m_mapMgr->m_battleground;
m_bg->PortPlayer( this, true );
}
if( m_bg != NULL )
m_bg->OnPlayerPushed( this );
z_axisposition = 0.0f;
m_changingMaps = false;
}
void Player::RemoveFromWorld()
{
if(raidgrouponlysent)
event_RemoveEvents(EVENT_PLAYER_EJECT_FROM_INSTANCE);
load_health = m_uint32Values[UNIT_FIELD_HEALTH];
load_mana = m_uint32Values[UNIT_FIELD_POWER1];
if(m_bg)
{
m_bg->RemovePlayer(this, true);
m_bg = NULL;
}
RemoveFieldSummon();
// Cancel trade if it's active.
Player * pTarget;
if(mTradeTarget != 0)
{
pTarget = GetTradeTarget();
if(pTarget)
pTarget->ResetTradeVariables();
ResetTradeVariables();
}
//clear buyback
GetItemInterface()->EmptyBuyBack();
for(uint32 x=0;x<4;x++)
{
if(m_TotemSlots[x])
m_TotemSlots[x]->TotemExpire();
}
ClearSplinePackets();
if( m_Summon )
{
m_Summon->GetAIInterface()->SetPetOwner(0);
m_Summon->Remove( false, true, false );
}
if(m_SummonedObject)
{
if(m_SummonedObject->GetInstanceID() != GetInstanceID())
{
sEventMgr.AddEvent(m_SummonedObject, &Object::Delete, EVENT_GAMEOBJECT_EXPIRE, 100, 1,0);
}else
{
if(m_SummonedObject->GetTypeId() == TYPEID_PLAYER)
{
}
else
{
if(m_SummonedObject->IsInWorld())
{
m_SummonedObject->RemoveFromWorld(true);
}
delete m_SummonedObject;
}
}
m_SummonedObject = NULL;
}
if(IsInWorld())
{
RemoveItemsFromWorld();
Unit::RemoveFromWorld(false);
}
sWorld.mInWorldPlayerCount--;
#ifdef ENABLE_COMPRESSED_MOVEMENT
MovementCompressor->RemovePlayer(this);
m_movementBufferLock.Acquire();
m_movementBuffer.clear();
m_movementBufferLock.Release();
//sEventMgr.RemoveEvents(this, EVENT_PLAYER_FLUSH_MOVEMENT);
#endif
if(GetTaxiState())
event_RemoveEvents( EVENT_PLAYER_TAXI_INTERPOLATE );
m_changingMaps = true;
}
// TODO: perhaps item should just have a list of mods, that will simplify code
void Player::_ApplyItemMods(Item* item, int8 slot, bool apply, bool justdrokedown /* = false */, bool skip_stat_apply /* = false */)
{
if (slot >= INVENTORY_SLOT_BAG_END)
return;
ASSERT( item );
ItemPrototype* proto = item->GetProto();
//fast check to skip mod applying if the item doesnt meat the requirements.
if( !item->IsContainer() && item->GetUInt32Value( ITEM_FIELD_DURABILITY ) == 0 && item->GetUInt32Value( ITEM_FIELD_MAXDURABILITY ) && justdrokedown == false )
{
return;
}
//check for rnd prop
item->ApplyRandomProperties( true );
//Items Set check
uint32 setid = proto->ItemSet;
// These season pvp itemsets are interchangeable and each set group has the same
// bonuses if you have a full set made up of parts from any of the 3 similar sets
// you will get the highest sets bonus
// TODO: make a config for server so they can configure which season is active season
// * Gladiator's Battlegear
if( setid == 701 || setid == 736 || setid == 567 )
setid = 736;
// * Gladiator's Dreadgear
if( setid == 702 || setid == 734 || setid == 568 )
setid = 734;
// * Gladiator's Earthshaker
if( setid == 703 || setid == 732 || setid == 578 )
setid= 732;
// * Gladiator's Felshroud
if( setid == 704 || setid == 735 || setid == 615 )
setid = 735;
// * Gladiator's Investiture
if( setid == 705 || setid == 728 || setid == 687 )
setid = 728;
// * Gladiator's Pursuit
if( setid == 706 || setid == 723 || setid == 586 )
setid = 723;
// * Gladiator's Raiment
if( setid == 707 || setid == 729 || setid == 581 )
setid = 729;
// * Gladiator's Redemption
if( setid == 708 || setid == 725 || setid == 690 )
setid = 725;
// * Gladiator's Refuge
if( setid == 709 || setid == 720 || setid == 685 )
setid = 720;
// * Gladiator's Regalia
if( setid == 710 || setid == 724 || setid == 579 )
setid = 724;
// * Gladiator's Sanctuary
if( setid == 711 || setid == 721 || setid == 584 )
setid = 721;
// * Gladiator's Thunderfist
if( setid == 712 || setid == 733 || setid == 580 )
setid = 733;
// * Gladiator's Vestments
if( setid == 713 || setid == 730 || setid == 577 )
setid = 730;
// * Gladiator's Vindication
if( setid == 714 || setid == 726 || setid == 583 )
setid = 726;
// * Gladiator's Wartide
if( setid == 715 || setid == 731 || setid == 686 )
setid = 731;
// * Gladiator's Wildhide
if( setid == 716 || setid == 722 || setid == 585 )
setid = 722;
// Set
if( setid != 0 )
{
ItemSetEntry* set = dbcItemSet.LookupEntry( setid );
ASSERT( set );
ItemSet* Set = NULL;
std::list<ItemSet>::iterator i;
for( i = m_itemsets.begin(); i != m_itemsets.end(); i++ )
{
if( i->setid == setid )
{
Set = &(*i);
break;
}
}
if( apply )
{
if( Set == NULL )
{
Set = new ItemSet;
memset( Set, 0, sizeof( ItemSet ) );
Set->itemscount = 1;
Set->setid = setid;
}
else
Set->itemscount++;
if( !set->RequiredSkillID || ( _GetSkillLineCurrent( set->RequiredSkillID, true ) >= set->RequiredSkillAmt ) )
{
for( uint32 x=0;x<8;x++)
{
if( Set->itemscount==set->itemscount[x])
{//cast new spell
SpellEntry *info = dbcSpell.LookupEntry( set->SpellID[x] );
Spell * spell = SpellPool.PooledNew();
spell->Init( this, info, true, NULL );
SpellCastTargets targets;
targets.m_unitTarget = this->GetGUID();
spell->prepare( &targets );
}
}
}
if( i == m_itemsets.end() )
{
m_itemsets.push_back( *Set );
delete Set;
}
}
else
{
if( Set )
{
for( uint32 x = 0; x < 8; x++ )
if( Set->itemscount == set->itemscount[x] )
{
this->RemoveAura( set->SpellID[x], GetGUID() );
}
if(!(--Set->itemscount))
m_itemsets.erase(i);
}
}
}
// Armor
if( proto->Armor )
{
if( apply )BaseResistance[0 ]+= proto->Armor;
else BaseResistance[0] -= proto->Armor;
CalcResistance( 0 );
}
// Resistances
//TODO: FIXME: can there be negative resistances from items?
if( proto->FireRes )
{
if( apply )
FlatResistanceModifierPos[2] += proto->FireRes;
else
FlatResistanceModifierPos[2] -= proto->FireRes;
CalcResistance( 2 );
}
if( proto->NatureRes )
{
if( apply )
FlatResistanceModifierPos[3] += proto->NatureRes;
else
FlatResistanceModifierPos[3] -= proto->NatureRes;
CalcResistance( 3 );
}
if( proto->FrostRes )
{
if( apply )
FlatResistanceModifierPos[4] += proto->FrostRes;
else
FlatResistanceModifierPos[4] -= proto->FrostRes;
CalcResistance( 4 );
}
if( proto->ShadowRes )
{
if( apply )
FlatResistanceModifierPos[5] += proto->ShadowRes;
else
FlatResistanceModifierPos[5] -= proto->ShadowRes;
CalcResistance( 5 );
}
if( proto->ArcaneRes )
{
if( apply )
FlatResistanceModifierPos[6] += proto->ArcaneRes;
else
FlatResistanceModifierPos[6] -= proto->ArcaneRes;
CalcResistance( 6 );
}
// Stats
for( int i = 0; i < 10; i++ )
{
int32 val = proto->Stats[i].Value;
if( val == 0 )
continue;
ModifyBonuses( proto->Stats[i].Type, val, apply );
}
// Damage
if( proto->Damage[0].Min )
{
if( proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_RANGEDRIGHT || proto->InventoryType == INVTYPE_THROWN )
{
BaseRangedDamage[0] += apply ? proto->Damage[0].Min : -proto->Damage[0].Min;
BaseRangedDamage[1] += apply ? proto->Damage[0].Max : -proto->Damage[0].Max;
}
else
{
if( slot == EQUIPMENT_SLOT_OFFHAND )
{
BaseOffhandDamage[0] = apply ? proto->Damage[0].Min : 0;
BaseOffhandDamage[1] = apply ? proto->Damage[0].Max : 0;
}
else
{
BaseDamage[0] = apply ? proto->Damage[0].Min : 1;
BaseDamage[1] = apply ? proto->Damage[0].Max : 1;
}
}
}
// Misc
if( apply )
{
// Apply all enchantment bonuses
item->ApplyEnchantmentBonuses();
for( int k = 0; k < 5; k++ )
{
// stupid fucked dbs
if( item->GetProto()->Spells[k].Id == 0 )
continue;
if( item->GetProto()->Spells[k].Trigger == 1 )
{
SpellEntry* spells = dbcSpell.LookupEntry( item->GetProto()->Spells[k].Id );
if( spells->RequiredShapeShift )
{
AddShapeShiftSpell( spells->Id );
continue;
}
Spell *spell = SpellPool.PooledNew();
spell->Init( this, spells ,true, NULL );
SpellCastTargets targets;
targets.m_unitTarget = this->GetGUID();
spell->castedItemId = item->GetEntry();
spell->prepare( &targets );
}
else if( item->GetProto()->Spells[k].Trigger == 2 )
{
ProcTriggerSpell ts;
ts.origId = 0;
ts.spellId = item->GetProto()->Spells[k].Id;
ts.procChance = 5;
ts.caster = this->GetGUID();
ts.procFlags = PROC_ON_MELEE_ATTACK;
ts.deleted = false;
ts.groupRelation = 0;
ts.ProcType = 0;
ts.LastTrigger = 0;
ts.procCharges = 0;
m_procSpells.push_front( ts );
}
}
}
else
{
// Remove all enchantment bonuses
item->RemoveEnchantmentBonuses();
for( int k = 0; k < 5; k++ )
{
if( item->GetProto()->Spells[k].Trigger == 1 )
{
SpellEntry* spells = dbcSpell.LookupEntry( item->GetProto()->Spells[k].Id );
if( spells->RequiredShapeShift )
RemoveShapeShiftSpell( spells->Id );
else
RemoveAura( item->GetProto()->Spells[k].Id );
}
else if( item->GetProto()->Spells[k].Trigger == 2 )
{
std::list<struct ProcTriggerSpell>::iterator i;
// Debug: i changed this a bit the if was not indented to the for
// so it just set last one to deleted looks like unintended behaviour
// because you can just use end()-1 to remove last so i put the if
// into the for
for( i = m_procSpells.begin(); i != m_procSpells.end(); i++ )
{
if( (*i).spellId == item->GetProto()->Spells[k].Id && !(*i).deleted )
{
//m_procSpells.erase(i);
i->deleted = true;
break;
}
}
}
}
}
if( !apply ) // force remove auras added by using this item
{
for(uint32 k = MAX_POSITIVE_AURAS_EXTEDED_START; k < MAX_POSITIVE_AURAS_EXTEDED_END; ++k)
{
Aura* m_aura = this->m_auras[k];
if( m_aura != NULL && m_aura->m_castedItemId && m_aura->m_castedItemId == proto->ItemId )
m_aura->Remove();
}
}
if( !skip_stat_apply )
UpdateStats();
}
void Player::SetMovement(uint8 pType, uint32 flag)
{
WorldPacket data(13);
switch(pType)
{
case MOVE_ROOT:
{
data.SetOpcode(SMSG_FORCE_MOVE_ROOT);
data << GetNewGUID();
data << flag;
m_currentMovement = MOVE_ROOT;
}break;
case MOVE_UNROOT:
{
data.SetOpcode(SMSG_FORCE_MOVE_UNROOT);
data << GetNewGUID();
data << flag;
m_currentMovement = MOVE_UNROOT;
}break;
case MOVE_WATER_WALK:
{
m_setwaterwalk=true;
data.SetOpcode(SMSG_MOVE_WATER_WALK);
data << GetNewGUID();
data << flag;
}break;
case MOVE_LAND_WALK:
{
m_setwaterwalk=false;
data.SetOpcode(SMSG_MOVE_LAND_WALK);
data << GetNewGUID();
data << flag;
}break;
default:break;
}
if(data.size() > 0)
SendMessageToSet(&data, true);
}
void Player::SetPlayerSpeed(uint8 SpeedType, float value)
{
/*WorldPacket data(18);
data << GetNewGUID();
data << m_speedChangeCounter++;
if(SpeedType == RUN) // nfi what this is.. :/
data << uint8(1);
data << value;*/
WorldPacket data(50);
/*if(SpeedType==FLY)
{
data << GetNewGUID();
data << m_speedChangeCounter++;
if(SpeedType == RUN) // nfi what this is.. :/
data << uint8(1);
data << value;
}
else
{
data << GetNewGUID();
data << uint32(0);
data << uint8(0);
data << uint32(getMSTime());
data << GetPosition();
data << m_position.o;
data << uint32(0);
data << value;
}*/
if( SpeedType != SWIMBACK )
{
data << GetNewGUID();
data << m_speedChangeCounter++;
if( SpeedType == RUN )
data << uint8(1);
data << value;
}
else
{
data << GetNewGUID();
data << uint32(0);
data << uint8(0);
data << uint32(getMSTime());
data << GetPosition();
data << m_position.o;
data << uint32(0);
data << value;
}
switch(SpeedType)
{
case RUN:
{
if(value == m_lastRunSpeed)
return;
data.SetOpcode(SMSG_FORCE_RUN_SPEED_CHANGE);
m_runSpeed = value;
m_lastRunSpeed = value;
}break;
case RUNBACK:
{
if(value == m_lastRunBackSpeed)
return;
data.SetOpcode(SMSG_FORCE_RUN_BACK_SPEED_CHANGE);
m_backWalkSpeed = value;
m_lastRunBackSpeed = value;
}break;
case SWIM:
{
if(value == m_lastSwimSpeed)
return;
data.SetOpcode(SMSG_FORCE_SWIM_SPEED_CHANGE);
m_swimSpeed = value;
m_lastSwimSpeed = value;
}break;
case SWIMBACK:
{
if(value == m_lastBackSwimSpeed)
break;
data.SetOpcode(SMSG_FORCE_SWIM_BACK_SPEED_CHANGE);
m_backSwimSpeed = value;
m_lastBackSwimSpeed = value;
}break;
case FLY:
{
if(value == m_lastFlySpeed)
return;
data.SetOpcode(SMSG_FORCE_MOVE_SET_FLY_SPEED);
m_flySpeed = value;
m_lastFlySpeed = value;
}break;
default:return;
}
SendMessageToSet(&data , true);
}
void Player::SendDungeonDifficulty()
{
// Why CMSG_DUNGEON_DIFFICULTY ? CMSG == Client Message...
//TODO: Should rename it to MSG_DUNGEON_DIFFICULTY
WorldPacket data(CMSG_DUNGEON_DIFFICULTY, 12);
data << (uint32)iInstanceType;
data << (uint32)0x1;
data << (uint32)InGroup();
GetSession()->SendPacket(&data);
}
void Player::BuildPlayerRepop()
{
// cleanup first
uint32 AuraIds[] = {20584,9036,8326,0};
RemoveAuras(AuraIds); // cebernic: removeaura just remove once(bug?).
SetUInt32Value( UNIT_FIELD_HEALTH, 1 );
SpellCastTargets tgt;
tgt.m_unitTarget=this->GetGUID();
if(getRace()==RACE_NIGHTELF)
{
SpellEntry *inf=dbcSpell.LookupEntry(9036); // cebernic:20584 triggered.
Spell*sp=SpellPool.PooledNew();
sp->Init(this,inf,true,NULL);
sp->prepare(&tgt);
}
else
{
SpellEntry *inf=dbcSpell.LookupEntry(8326);
Spell*sp=SpellPool.PooledNew();
sp->Init(this,inf,true,NULL);
sp->prepare(&tgt);
}
StopMirrorTimer(0);
StopMirrorTimer(1);
StopMirrorTimer(2);
SetFlag(PLAYER_FLAGS, 0x10);
SetMovement(MOVE_UNROOT, 1);
SetMovement(MOVE_WATER_WALK, 1);
}
void Player::RepopRequestedPlayer()
{
sEventMgr.RemoveEvents(this, EVENT_PLAYER_CHECKFORCHEATS); // cebernic:-> Remove this first
sEventMgr.RemoveEvents( this, EVENT_PLAYER_FORECED_RESURECT ); //in case somebody resurrected us before this event happened
if( myCorpse != NULL ) {
// cebernic: wOOo dead+dead = undead ? :D just resurrect player
myCorpse->ResetDeathClock();
ResurrectPlayer();
return;
}
if( m_CurrentTransporter != NULL )
{
m_CurrentTransporter->RemovePlayer( this );
m_CurrentTransporter = NULL;
m_TransporterGUID = 0;
ResurrectPlayer();
RepopAtGraveyard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId() );
return;
}
MapInfo * pMapinfo = NULL;
// Set death state to corpse, that way players will lose visibility
setDeathState( CORPSE );
// Update visibility, that way people wont see running corpses :P
UpdateVisibility();
// If we're in battleground, remove the skinnable flag.. has bad effects heheh
RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE );
bool corpse = (m_bg != NULL) ? m_bg->CreateCorpse( this ) : true;
if( corpse )
CreateCorpse();
BuildPlayerRepop();
// cebernic: don't do this.
if ( !m_bg || ( m_bg && m_bg->HasStarted() ) )
{
pMapinfo = WorldMapInfoStorage.LookupEntry( GetMapId() );
if( pMapinfo != NULL )
{
if( pMapinfo->type == INSTANCE_NULL || pMapinfo->type == INSTANCE_PVP )
{
RepopAtGraveyard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId() );
}
else
{
RepopAtGraveyard( pMapinfo->repopx, pMapinfo->repopy, pMapinfo->repopz, pMapinfo->repopmapid );
}
}
else
{
//RepopAtGraveyard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId() );
//cebernic: Mapinfo NULL? let's search from bindposition.
RepopAtGraveyard( GetBindPositionX(),GetBindPositionY(),GetBindPositionZ(),GetBindMapId( ) );
}
}
if( corpse )
{
SpawnCorpseBody();
if ( myCorpse!=NULL ) myCorpse->ResetDeathClock();
/* Send Spirit Healer Location */
WorldPacket data( SMSG_SPIRIT_HEALER_POS, 16 );
data << m_mapId << m_position;
m_session->SendPacket( &data );
/* Corpse reclaim delay */
WorldPacket data2( SMSG_CORPSE_RECLAIM_DELAY, 4 );
data2 << (uint32)( CORPSE_RECLAIM_TIME_MS );
GetSession()->SendPacket( &data2 );
}
if (pMapinfo) {
switch( pMapinfo->mapid )
{
case 550: //The Eye
case 552: //The Arcatraz
case 553: //The Botanica
case 554: //The Mechanar
ResurrectPlayer();
break;
}
}
}
void Player::ResurrectPlayer()
{
sEventMgr.RemoveEvents(this,EVENT_PLAYER_FORECED_RESURECT); //in case somebody resurected us before this event happened
if( m_resurrectHealth )
SetUInt32Value( UNIT_FIELD_HEALTH, (uint32)min( m_resurrectHealth, m_uint32Values[UNIT_FIELD_MAXHEALTH] ) );
if( m_resurrectMana )
SetUInt32Value( UNIT_FIELD_POWER1, (uint32)min( m_resurrectMana, m_uint32Values[UNIT_FIELD_MAXPOWER1] ) );
m_resurrectHealth = m_resurrectMana = 0;
SpawnCorpseBones();
RemoveNegativeAuras();
uint32 AuraIds[] = {20584,9036,8326,0};
RemoveAuras(AuraIds); // cebernic: removeaura just remove once(bug?).
RemoveFlag(PLAYER_FLAGS, 0x10);
setDeathState(ALIVE);
UpdateVisibility();
if ( m_resurrecter && IsInWorld()
//don't pull players inside instances with this trick. Also fixes the part where you were able to double item bonuses
&& m_resurrectInstanceID == GetInstanceID()
)
{
SafeTeleport( m_resurrectMapId, m_resurrectInstanceID, m_resurrectPosition );
}
m_resurrecter = 0;
SetMovement(MOVE_LAND_WALK, 1);
// reinit
m_lastRunSpeed = 0;
m_lastRunBackSpeed = 0;
m_lastSwimSpeed = 0;
m_lastRunBackSpeed = 0;
m_lastFlySpeed = 0;
//Zack : shit on grill. So auras should be removed on player death instead of making this :P
//wee can afford this bullshit atm since auras are lost uppon death -> no immunities
for(uint32 i = 0; i < 7; i++)
SchoolImmunityList[i]=0;
}
void Player::KillPlayer()
{
setDeathState(JUST_DIED);
// Battleground stuff
if(m_bg)
m_bg->HookOnPlayerDeath(this);
EventDeath();
m_session->OutPacket(SMSG_CANCEL_COMBAT);
m_session->OutPacket(SMSG_CANCEL_AUTO_REPEAT);
SetMovement(MOVE_ROOT, 0);
StopMirrorTimer(0);
StopMirrorTimer(1);
StopMirrorTimer(2);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED); //player death animation, also can be used with DYNAMIC_FLAGS <- huh???
SetUInt32Value( UNIT_DYNAMIC_FLAGS, 0x00 );
if(this->getClass() == WARRIOR) //rage resets on death
SetUInt32Value(UNIT_FIELD_POWER2, 0);
sHookInterface.OnDeath(this);
}
void Player::CreateCorpse()
{
Corpse *pCorpse;
uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
objmgr.DelinkPlayerCorpses(this);
if(!this->bCorpseCreateable)
{
bCorpseCreateable = true; // for next time
return; // no corpse allowed!
}
pCorpse = objmgr.CreateCorpse();
pCorpse->SetInstanceID(GetInstanceID());
pCorpse->Create(this, GetMapId(), GetPositionX(),
GetPositionY(), GetPositionZ(), GetOrientation());
_uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
_pb = GetUInt32Value(PLAYER_BYTES);
_pb2 = GetUInt32Value(PLAYER_BYTES_2);
uint8 race = (uint8)(_uf);
uint8 skin = (uint8)(_pb);
uint8 face = (uint8)(_pb >> 8);
uint8 hairstyle = (uint8)(_pb >> 16);
uint8 haircolor = (uint8)(_pb >> 24);
uint8 facialhair = (uint8)(_pb2);
_cfb1 = ((0x00) | (race << 8) | (0x00 << 16) | (skin << 24));
_cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
pCorpse->SetZoneId( GetZoneId() );
pCorpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
pCorpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
pCorpse->SetUInt32Value( CORPSE_FIELD_FLAGS, 4 );
pCorpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetUInt32Value(UNIT_FIELD_DISPLAYID) );
if(m_bg)
{
// remove our lootable flags
RemoveFlag(UNIT_DYNAMIC_FLAGS, U_DYN_FLAG_LOOTABLE);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
loot.gold = 0;
pCorpse->generateLoot();
if(bShouldHaveLootableOnCorpse)
{
pCorpse->SetUInt32Value(CORPSE_FIELD_DYNAMIC_FLAGS, 1); // sets it so you can loot the plyr
}
else
{
// hope this works
pCorpse->SetUInt32Value(CORPSE_FIELD_FLAGS, 60);
}
// now that our corpse is created, don't do it again
bShouldHaveLootableOnCorpse = false;
}
else
{
pCorpse->loot.gold = 0;
}
uint32 iDisplayID = 0;
uint16 iIventoryType = 0;
uint32 _cfi = 0;
Item * pItem;
for (int8 i = 0; i < EQUIPMENT_SLOT_END; i++)
{
if(( pItem = GetItemInterface()->GetInventoryItem(i)) != 0)
{
iDisplayID = pItem->GetProto()->DisplayInfoID;
iIventoryType = (uint16)pItem->GetProto()->InventoryType;
_cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
pCorpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
}
}
//save corpse in db for future use
pCorpse->SaveToDB();
}
void Player::SpawnCorpseBody()
{
Corpse *pCorpse;
pCorpse = objmgr.GetCorpseByOwner(this->GetLowGUID());
if(pCorpse && !pCorpse->IsInWorld())
{
if(bShouldHaveLootableOnCorpse && pCorpse->GetUInt32Value(CORPSE_FIELD_DYNAMIC_FLAGS) != 1)
pCorpse->SetUInt32Value(CORPSE_FIELD_DYNAMIC_FLAGS, 1); // sets it so you can loot the plyr
if(m_mapMgr == 0)
pCorpse->AddToWorld();
else
pCorpse->PushToWorld(m_mapMgr);
}
myCorpse = pCorpse;
}
void Player::SpawnCorpseBones()
{
Corpse *pCorpse;
pCorpse = objmgr.GetCorpseByOwner(GetLowGUID());
myCorpse = 0;
if(pCorpse)
{
if (pCorpse->IsInWorld() && pCorpse->GetCorpseState() == CORPSE_STATE_BODY)
{
if(pCorpse->GetInstanceID() != GetInstanceID())
{
sEventMgr.AddEvent(pCorpse, &Corpse::SpawnBones, EVENT_CORPSE_SPAWN_BONES, 100, 1,0);
}
else
pCorpse->SpawnBones();
}
else
{
//Cheater!
}
}
}
void Player::DeathDurabilityLoss(double percent)
{
m_session->OutPacket(SMSG_DURABILITY_DAMAGE_DEATH);
uint32 pDurability;
uint32 pMaxDurability;
int32 pNewDurability;
Item * pItem;
for (int8 i = 0; i < EQUIPMENT_SLOT_END; i++)
{
if((pItem = GetItemInterface()->GetInventoryItem(i)) != 0)
{
pMaxDurability = pItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
pDurability = pItem->GetUInt32Value(ITEM_FIELD_DURABILITY);
if(pDurability)
{
pNewDurability = (uint32)(pMaxDurability*percent);
pNewDurability = (pDurability - pNewDurability);
if(pNewDurability < 0)
pNewDurability = 0;
if(pNewDurability <= 0)
{
ApplyItemMods(pItem, i, false, true);
}
pItem->SetUInt32Value(ITEM_FIELD_DURABILITY,(uint32)pNewDurability);
pItem->m_isDirty = true;
}
}
}
}
void Player::RepopAtGraveyard(float ox, float oy, float oz, uint32 mapid)
{
bool first = true;
//float closestX = 0, closestY = 0, closestZ = 0, closestO = 0;
StorageContainerIterator<GraveyardTeleport> * itr;
LocationVector src(ox, oy, oz);
LocationVector dest(0, 0, 0, 0);
LocationVector temp;
float closest_dist = 999999.0f;
float dist;
if(m_bg && m_bg->HookHandleRepop(this))
{
return;
}
else
{
uint32 areaid = sInstanceMgr.GetMap(mapid)->GetAreaID(ox,oy);
AreaTable * at = dbcArea.LookupEntry(areaid);
if(!at) return;
//uint32 mzone = ( at->ZoneId ? at->ZoneId : at->AreaId);
itr = GraveyardStorage.MakeIterator();
while(!itr->AtEnd())
{
GraveyardTeleport *pGrave = itr->Get();
if((pGrave->MapId == mapid && pGrave->FactionID == GetTeam() || pGrave->MapId == mapid && pGrave->FactionID == 3)
|| (pGrave->MapId == mapid && pGrave->FactionID == GetTeam() || pGrave->MapId == mapid && pGrave->FactionID == 3))
{
temp.ChangeCoords(pGrave->X, pGrave->Y, pGrave->Z);
dist = src.DistanceSq(temp);
if( first || dist < closest_dist )
{
first = false;
closest_dist = dist;
dest = temp;
}
}
if(!itr->Inc())
break;
}
itr->Destruct();
}
if(sHookInterface.OnRepop(this) && dest.x != 0 && dest.y != 0 && dest.z != 0)
{
SafeTeleport(mapid, 0, dest);
}
// //correct method as it works on official server, and does not require any damn sql
// //no factions! no zones! no sqls! 1word: blizz-like
// float closestX , closestY , closestZ ;
// uint32 entries=sWorldSafeLocsStore.GetNumRows();
// GraveyardEntry*g;
// uint32 mymapid=mapid
// float mx=ox,my=oy;
// float last_distance=9e10;
//
// for(uint32 x=0;x<entries;x++)
// {
// g=sWorldSafeLocsStore.LookupEntry(x);
// if(g->mapid!=mymapid)continue;
// float distance=(mx-g->x)*(mx-g->x)+(my-g->y)*(my-g->y);
// if(distance<last_distance)
// {
// closestX=g->x;
// closestY=g->y;
// closestZ=g->z;
// last_distance=distance;
// }
//
//
// }
// if(last_distance<1e10)
//#endif
}
void Player::JoinedChannel(Channel *c)
{
if( c != NULL )
m_channels.insert(c);
}
void Player::LeftChannel(Channel *c)
{
if( c != NULL )
m_channels.erase(c);
}
void Player::CleanupChannels()
{
set<Channel *>::iterator i;
Channel * c;
for(i = m_channels.begin(); i != m_channels.end();)
{
c = *i;
++i;
c->Part(this);
}
}
void Player::SendInitialActions()
{
#ifndef USING_BIG_ENDIAN
m_session->OutPacket(SMSG_ACTION_BUTTONS, PLAYER_ACTION_BUTTON_SIZE, &mActions);
#else
/* we can't do this the fast way on ppc, due to endianness */
WorldPacket data(SMSG_ACTION_BUTTONS, PLAYER_ACTION_BUTTON_SIZE);
for(uint32 i = 0; i < PLAYER_ACTION_BUTTON_SIZE; ++i)
{
data << mActions[i].Action << mActions[i].Type << mActions[i].Misc;
}
m_session->SendPacket(&data);
#endif
}
void Player::setAction(uint8 button, uint16 action, uint8 type, uint8 misc)
{
if( button >= 120 )
return; //packet hack to crash server
mActions[button].Action = action;
mActions[button].Type = type;
mActions[button].Misc = misc;
}
//Groupcheck
bool Player::IsGroupMember(Player *plyr)
{
if(m_playerInfo->m_Group != NULL)
return m_playerInfo->m_Group->HasMember(plyr->m_playerInfo);
return false;
}
int32 Player::GetOpenQuestSlot()
{
for (uint32 i = 0; i < 25; ++i)
if (m_questlog[i] == NULL)
return i;
return -1;
}
void Player::AddToFinishedQuests(uint32 quest_id)
{
//maybe that shouldn't be an assert, but i'll leave it for now
//ASSERT(m_finishedQuests.find(quest_id) == m_finishedQuests.end());
//Removed due to crash
//If it failed though, then he's probably cheating.
if (m_finishedQuests.find(quest_id) != m_finishedQuests.end())
return;
m_finishedQuests.insert(quest_id);
}
bool Player::HasFinishedQuest(uint32 quest_id)
{
return (m_finishedQuests.find(quest_id) != m_finishedQuests.end());
}
bool Player::GetQuestRewardStatus(uint32 quest_id)
{
return HasFinishedQuest(quest_id);
}
//From Mangos Project
void Player::_LoadTutorials(QueryResult * result)
{
if(result)
{
Field *fields = result->Fetch();
for (int iI=0; iI<8; iI++)
m_Tutorials[iI] = fields[iI + 1].GetUInt32();
}
tutorialsDirty = false;
}
void Player::_SaveTutorials(QueryBuffer * buf)
{
if(tutorialsDirty)
{
if(buf == NULL)
CharacterDatabase.Execute("REPLACE INTO tutorials VALUES('%u','%u','%u','%u','%u','%u','%u','%u','%u')", GetLowGUID(), m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
else
buf->AddQuery("REPLACE INTO tutorials VALUES('%u','%u','%u','%u','%u','%u','%u','%u','%u')", GetLowGUID(), m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
tutorialsDirty = false;
}
}
uint32 Player::GetTutorialInt(uint32 intId )
{
ASSERT( intId < 8 );
return m_Tutorials[intId];
}
void Player::SetTutorialInt(uint32 intId, uint32 value)
{
if(intId >= 8)
return;
ASSERT( (intId < 8) );
m_Tutorials[intId] = value;
tutorialsDirty = true;
}
//Player stats calculation for saving at lvl up, etc
/*void Player::CalcBaseStats()
{//static_cast< Player* >( this )->getClass() == HUNTER ||
//TODO take into account base stats at create
uint32 AP, RAP;
//Save AttAck power
if(getClass() == ROGUE || getClass() == HUNTER)
{
AP = GetBaseUInt32Value(UNIT_FIELD_STAT0) + GetBaseUInt32Value(UNIT_FIELD_STAT1);
RAP = (GetBaseUInt32Value(UNIT_FIELD_STAT1) * 2);
SetBaseUInt32Value(UNIT_FIELD_ATTACK_POWER, AP);
SetBaseUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, RAP);
}
else
{
AP = (GetBaseUInt32Value(UNIT_FIELD_STAT0) * 2);
RAP = (GetBaseUInt32Value(UNIT_FIELD_STAT1) * 2);
SetBaseUInt32Value(UNIT_FIELD_ATTACK_POWER, AP);
SetBaseUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, RAP);
}
}*/
void Player::UpdateHit(int32 hit)
{
/*std::list<Affect*>::iterator i;
Affect::ModList::const_iterator j;
Affect *aff;
uint32 in = hit;
for (i = GetAffectBegin(); i != GetAffectEnd(); i++)
{
aff = *i;
for (j = aff->GetModList().begin();j != aff->GetModList().end(); j++)
{
Modifier mod = (*j);
if ((mod.GetType() == SPELL_AURA_MOD_HIT_CHANCE))
{
SpellEntry *spellInfo = sSpellStore.LookupEntry(aff->GetSpellId());
if (this->canCast(spellInfo))
in += mod.GetAmount();
}
}
}
SetHitFromSpell(in);*/
}
float Player::GetDefenseChance(uint32 opLevel)
{
float chance;
chance = float( _GetSkillLineCurrent( SKILL_DEFENSE, true ) - ( opLevel * 5.0f ) );
chance += CalcRating( PLAYER_RATING_MODIFIER_DEFENCE );
chance = floorf( chance ) * 0.04f; // defense skill is treated as an integer on retail
return chance;
}
#define BASE_BLOCK_CHANCE 5.0f
#define BASE_PARRY_CHANCE 5.0f
// Gets dodge chances before defense skill is applied
float Player::GetDodgeChance()
{
uint32 pClass = (uint32)getClass();
float chance;
// base dodge chance
chance = baseDodge[pClass];
// dodge from agility
chance += float( GetUInt32Value( UNIT_FIELD_STAT1 ) / dodgeRatio[getLevel()-1][pClass] );
// dodge from dodge rating
chance += CalcRating( PLAYER_RATING_MODIFIER_DODGE );
// dodge from spells
chance += GetDodgeFromSpell();
return max( chance, 0.0f ); // make sure we dont have a negative chance
}
// Gets block chances before defense skill is applied
// Assumes the caller will check for shields
float Player::GetBlockChance()
{
float chance;
// base block chance
chance = BASE_BLOCK_CHANCE;
// block rating
chance += CalcRating( PLAYER_RATING_MODIFIER_BLOCK );
// block chance from spells
chance += GetBlockFromSpell();
return max( chance, 0.0f ); // make sure we dont have a negative chance
}
// Get parry chances before defense skill is applied
float Player::GetParryChance()
{
float chance;
// base parry chance
chance = BASE_PARRY_CHANCE;
// parry rating
chance += CalcRating( PLAYER_RATING_MODIFIER_PARRY );
// parry chance from spells
chance += GetParryFromSpell();
return max( chance, 0.0f ); // make sure we dont have a negative chance
}
void Player::UpdateChances()
{
uint32 pClass = (uint32)getClass();
uint32 pLevel = (getLevel() > PLAYER_LEVEL_CAP) ? PLAYER_LEVEL_CAP : getLevel();
float tmp = 0;
float defence_contribution = 0;
// avoidance from defense skill
defence_contribution = GetDefenseChance( pLevel );
// dodge
tmp = GetDodgeChance();
tmp += defence_contribution;
tmp = min( max( tmp, 0.0f ), 95.0f );
SetFloatValue( PLAYER_DODGE_PERCENTAGE, tmp );
// block
Item* it = this->GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_OFFHAND );
if( it != NULL && it->GetProto()->InventoryType == INVTYPE_SHIELD )
{
tmp = GetBlockChance();
tmp += defence_contribution;
tmp = min( max( tmp, 0.0f ), 95.0f );
}
else
tmp = 0.0f;
SetFloatValue( PLAYER_BLOCK_PERCENTAGE, tmp );
// parry (can only parry with something in main hand)
it = this->GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_MAINHAND );
if( it != NULL )
{
tmp = GetParryChance();
tmp += defence_contribution;
tmp = min( max( tmp, 0.0f ), 95.0f );
}
else
tmp = 0.0f;
SetFloatValue( PLAYER_PARRY_PERCENTAGE, tmp );
//critical
gtFloat* baseCrit = dbcMeleeCritBase.LookupEntry(pClass-1);
gtFloat* CritPerAgi = dbcMeleeCrit.LookupEntry(pLevel - 1 + (pClass-1)*100);
tmp = 100*(baseCrit->val + GetUInt32Value( UNIT_FIELD_STAT1 ) * CritPerAgi->val);
float melee_bonus = 0;
float ranged_bonus = 0;
if ( tocritchance.size() > 0 ) // crashfix by cebernic
{
map< uint32, WeaponModifier >::iterator itr = tocritchance.begin();
Item* tItemMelee = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_MAINHAND );
Item* tItemRanged = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_RANGED );
//-1 = any weapon
for(; itr != tocritchance.end(); ++itr )
{
if( itr->second.wclass == ( uint32 )-1 || ( tItemMelee != NULL && ( 1 << tItemMelee->GetProto()->SubClass & itr->second.subclass ) ) )
{
melee_bonus += itr->second.value;
}
if( itr->second.wclass == ( uint32 )-1 || ( tItemRanged != NULL && ( 1 << tItemRanged->GetProto()->SubClass & itr->second.subclass ) ) )
{
ranged_bonus += itr->second.value;
}
}
}
float cr = tmp + CalcRating( PLAYER_RATING_MODIFIER_MELEE_CRIT ) + melee_bonus;
SetFloatValue( PLAYER_CRIT_PERCENTAGE, min( cr, 95.0f ) );
float rcr = tmp + CalcRating( PLAYER_RATING_MODIFIER_RANGED_CRIT ) + ranged_bonus;
SetFloatValue( PLAYER_RANGED_CRIT_PERCENTAGE, min( rcr, 95.0f ) );
gtFloat* SpellCritBase = dbcSpellCritBase.LookupEntry(pClass-1);
gtFloat* SpellCritPerInt = dbcSpellCrit.LookupEntry(pLevel - 1 + (pClass-1)*100);
spellcritperc = 100*(SpellCritBase->val + GetUInt32Value( UNIT_FIELD_STAT3 ) * SpellCritPerInt->val) +
this->GetSpellCritFromSpell() +
this->CalcRating( PLAYER_RATING_MODIFIER_SPELL_CRIT );
UpdateChanceFields();
}
void Player::UpdateChanceFields()
{
// Update spell crit values in fields
for(uint32 i = 0; i < 7; ++i)
{
SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1 + i, SpellCritChanceSchool[i]+spellcritperc);
}
}
void Player::ModAttackSpeed( int32 mod, ModType type )
{
if( mod == 0 )
return;
if( mod > 0 )
m_attack_speed[ type ] *= 1.0f + ( ( float )mod / 100.0f );
else
m_attack_speed[ type ] /= 1.0f + ( ( float )( - mod ) / 100.0f );
if( type == MOD_SPELL )
SetFloatValue( UNIT_MOD_CAST_SPEED, 1.0f / ( m_attack_speed[ MOD_SPELL ] * SpellHasteRatingBonus ) );
}
void Player::UpdateAttackSpeed()
{
uint32 speed = 2000;
Item *weap ;
if( GetShapeShift() == FORM_CAT )
{
speed = 1000;
}
else if( GetShapeShift() == FORM_BEAR || GetShapeShift() == FORM_DIREBEAR )
{
speed = 2500;
}
else if( !disarmed )//regular
{
weap = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_MAINHAND) ;
if( weap != NULL )
speed = weap->GetProto()->Delay;
}
SetUInt32Value( UNIT_FIELD_BASEATTACKTIME,
( uint32 )( (float) speed / ( m_attack_speed[ MOD_MELEE ] * ( 1.0f + CalcRating( PLAYER_RATING_MODIFIER_MELEE_HASTE ) / 100.0f ) ) ) );
weap = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_OFFHAND );
if( weap != NULL && weap->GetProto()->Class == ITEM_CLASS_WEAPON )
{
speed = weap->GetProto()->Delay;
SetUInt32Value( UNIT_FIELD_BASEATTACKTIME_01,
( uint32 )( (float) speed / ( m_attack_speed[ MOD_MELEE ] * ( 1.0f + CalcRating( PLAYER_RATING_MODIFIER_MELEE_HASTE ) / 100.0f ) ) ) );
}
weap = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_RANGED );
if( weap != NULL )
{
speed = weap->GetProto()->Delay;
SetUInt32Value( UNIT_FIELD_RANGEDATTACKTIME,
( uint32 )( (float) speed / ( m_attack_speed[ MOD_RANGED ] * ( 1.0f + CalcRating( PLAYER_RATING_MODIFIER_RANGED_HASTE ) / 100.0f ) ) ) );
}
}
void Player::UpdateStats()
{
UpdateAttackSpeed();
// formulas from wowwiki
int32 AP = 0;
int32 RAP = 0;
int32 hpdelta = 128;
int32 manadelta = 128;
uint32 str = GetUInt32Value(UNIT_FIELD_STAT0);
uint32 agi = GetUInt32Value(UNIT_FIELD_STAT1);
uint32 lev = getLevel();
// Attack power
uint32 cl = getClass();
switch (cl)
{
case DRUID:
//(Strength x 2) - 20
AP = str * 2 - 20;
//Agility - 10
RAP = agi - 10;
if( GetShapeShift() == FORM_MOONKIN )
{
//(Strength x 2) + (Character Level x 1.5) - 20
AP += float2int32( static_cast<float>(lev) * 1.5f );
}
if( GetShapeShift() == FORM_CAT )
{
//(Strength x 2) + Agility + (Character Level x 2) - 20
AP += agi + (lev *2);
}
if( GetShapeShift() == FORM_BEAR || GetShapeShift() == FORM_DIREBEAR )
{
//(Strength x 2) + (Character Level x 3) - 20
AP += (lev *3);
}
break;
case ROGUE:
//Strength + Agility + (Character Level x 2) - 20
AP = str + agi + (lev *2) - 20;
//Character Level + Agility - 10
RAP = lev + agi - 10;
break;
case HUNTER:
//Strength + Agility + (Character Level x 2) - 20
AP = str + agi + (lev *2) - 20;
//(Character Level x 2) + Agility - 10
RAP = (lev *2) + agi - 10;
break;
case SHAMAN:
//(Strength x 2) + (Character Level x 2) - 20
AP = (str *2) + (lev *2) -20;
//Agility - 10
RAP = agi - 10;
break;
case PALADIN:
//(Strength x 2) + (Character Level x 3) - 20
AP = (str *2) + (lev *3) - 20;
//Agility - 10
RAP = agi - 10;
break;
case WARRIOR:
//(Strength x 2) + (Character Level x 3) - 20
AP = (str *2) + (lev *3) - 20;
//Character Level + Agility - 10
RAP = lev + agi - 10;
break;
default: //mage,priest,warlock
AP = agi - 10;
}
/* modifiers */
RAP += int32(float(float(m_rap_mod_pct) * float(float(m_uint32Values[UNIT_FIELD_STAT3]) / 100.0f)));
if( RAP < 0 )RAP = 0;
if( AP < 0 )AP = 0;
SetUInt32Value( UNIT_FIELD_ATTACK_POWER, AP );
SetUInt32Value( UNIT_FIELD_RANGED_ATTACK_POWER, RAP );
LevelInfo* lvlinfo = objmgr.GetLevelInfo( this->getRace(), this->getClass(), lev );
if( lvlinfo != NULL )
{
hpdelta = lvlinfo->Stat[2] * 10;
manadelta = lvlinfo->Stat[3] * 15;
}
lvlinfo = objmgr.GetLevelInfo( this->getRace(), this->getClass(), 1 );
if( lvlinfo != NULL )
{
hpdelta -= lvlinfo->Stat[2] * 10;
manadelta -= lvlinfo->Stat[3] * 15;
}
int32 hp = GetUInt32Value( UNIT_FIELD_BASE_HEALTH );
int32 stat_bonus = GetUInt32Value( UNIT_FIELD_POSSTAT2 ) - GetUInt32Value( UNIT_FIELD_NEGSTAT2 );
if ( stat_bonus < 0 )
stat_bonus = 0; //avoid of having negative health
int32 bonus = stat_bonus * 10 + m_healthfromspell + m_healthfromitems;
int32 res = hp + bonus + hpdelta;
int32 oldmaxhp = GetUInt32Value( UNIT_FIELD_MAXHEALTH );
if( res < hp ) res = hp;
SetUInt32Value( UNIT_FIELD_MAXHEALTH, res );
if( ( int32 )GetUInt32Value( UNIT_FIELD_HEALTH ) > res )
SetUInt32Value( UNIT_FIELD_HEALTH, res );
else if( ( cl == DRUID) && ( GetShapeShift() == FORM_BEAR || GetShapeShift() == FORM_DIREBEAR ) )
{
res = float2int32( ( float )GetUInt32Value( UNIT_FIELD_MAXHEALTH ) * ( float )GetUInt32Value( UNIT_FIELD_HEALTH ) / float( oldmaxhp ) );
SetUInt32Value( UNIT_FIELD_HEALTH, res );
}
if( cl != WARRIOR && cl != ROGUE )
{
// MP
int32 mana = GetUInt32Value( UNIT_FIELD_BASE_MANA );
stat_bonus = GetUInt32Value( UNIT_FIELD_POSSTAT3 ) - GetUInt32Value( UNIT_FIELD_NEGSTAT3 );
if ( stat_bonus < 0 )
stat_bonus = 0; //avoid of having negative mana
bonus = stat_bonus * 15 + m_manafromspell + m_manafromitems ;
res = mana + bonus + manadelta;
if( res < mana )res = mana;
SetUInt32Value(UNIT_FIELD_MAXPOWER1, res);
if((int32)GetUInt32Value(UNIT_FIELD_POWER1)>res)
SetUInt32Value(UNIT_FIELD_POWER1,res);
//Manaregen
const static float BaseRegen[70] = {0.034965f, 0.034191f, 0.033465f, 0.032526f, 0.031661f, 0.031076f, 0.030523f, 0.029994f, 0.029307f, 0.028661f, 0.027584f, 0.026215f, 0.025381f, 0.024300f, 0.023345f, 0.022748f, 0.021958f, 0.021386f, 0.020790f, 0.020121f, 0.019733f, 0.019155f, 0.018819f, 0.018316f, 0.017936f, 0.017576f, 0.017201f, 0.016919f, 0.016581f, 0.016233f, 0.015994f, 0.015707f, 0.015464f, 0.015204f, 0.014956f, 0.014744f, 0.014495f, 0.014302f, 0.014094f, 0.013895f, 0.013724f, 0.013522f, 0.013363f, 0.013175f, 0.012996f, 0.012853f, 0.012687f, 0.012539f, 0.012384f, 0.012233f, 0.012113f, 0.011973f, 0.011859f, 0.011714f, 0.011575f, 0.011473f, 0.011342f, 0.011245f, 0.011110f, 0.010999f, 0.010700f, 0.010522f, 0.010290f, 0.010119f, 0.009968f, 0.009808f, 0.009651f, 0.009553f, 0.009445f, 0.009327f};
uint32 Spirit = GetUInt32Value( UNIT_FIELD_STAT4 );
uint32 Intellect = GetUInt32Value( UNIT_FIELD_STAT3 );
uint32 level = getLevel();
if(level > 70) level = 70;
float amt = ( 0.001f + sqrt((float)Intellect) * Spirit * BaseRegen[level-1] )*PctPowerRegenModifier[POWER_TYPE_MANA];
SetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN,amt+m_ModInterrMRegen/5.0f);
SetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT,amt*m_ModInterrMRegenPCT/100.0f+m_ModInterrMRegen/5.0f);
}
// Spell haste rating
float haste = 1.0f + CalcRating( PLAYER_RATING_MODIFIER_SPELL_HASTE ) / 100.0f;
if( haste != SpellHasteRatingBonus )
{
float value = GetFloatValue( UNIT_MOD_CAST_SPEED ) * SpellHasteRatingBonus / haste; // remove previous mod and apply current
SetFloatValue( UNIT_MOD_CAST_SPEED, value );
SpellHasteRatingBonus = haste; // keep value for next run
}
// Shield Block
Item* shield = GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_OFFHAND);
if( shield != NULL && shield->GetProto()->InventoryType == INVTYPE_SHIELD )
{
float block_multiplier = ( 100.0f + float( m_modblockabsorbvalue ) ) / 100.0f;
if( block_multiplier < 1.0f )block_multiplier = 1.0f;
int32 blockable_damage = float2int32( (float( shield->GetProto()->Block ) + ( float(m_modblockvaluefromspells + GetUInt32Value( PLAYER_RATING_MODIFIER_BLOCK ) )) + ( ( float( str ) / 20.0f ) - 1.0f ) ) * block_multiplier);
SetUInt32Value( PLAYER_SHIELD_BLOCK, blockable_damage );
}
else
{
SetUInt32Value( PLAYER_SHIELD_BLOCK, 0 );
}
// Expertise
// Expertise is somewhat tricky. Expertise on items is expertise "rating" where as "expertise"
// on the character sheet is the rating modified by a factor. The bonus % this value gives is
// actually the "rating" modified by another factor.
// eg. 100 expertise rating from items
// 100 / 3.92 = 25 expertise
// 100 / 15.77 = 6.3% reduced dodge/parry chances
SetUInt32Value( PLAYER_EXPERTISE, float2int32( CalcRating( PLAYER_RATING_MODIFIER_EXPERTISE ) ) ); // value displayed in char sheet
//SetUInt32Value( PLAYER_RATING_MODIFIER_EXPERTISE2, GetUInt32Value( PLAYER_RATING_MODIFIER_EXPERTISE ) );
UpdateChances();
CalcDamage();
}
uint32 Player::SubtractRestXP(uint32 amount)
{
if(GetUInt32Value(UNIT_FIELD_LEVEL) >= GetUInt32Value(PLAYER_FIELD_MAX_LEVEL)) // Save CPU, don't waste time on this if you've reached max_level
amount = 0;
int32 restAmount = m_restAmount - (amount << 1); // remember , we are dealing with xp without restbonus, so multiply by 2
if( restAmount < 0)
m_restAmount = 0;
else
m_restAmount = restAmount;
Log.Debug("REST","Subtracted %d rest XP to a total of %d", amount, m_restAmount);
UpdateRestState(); // Update clients interface with new values.
return amount;
}
void Player::AddCalculatedRestXP(uint32 seconds)
{
// At level one, players will all start in the normal tier.
// When a player rests in a city or at an inn they will gain rest bonus at a very slow rate.
// Eight hours of rest will be needed for a player to gain one "bubble" of rest bonus.
// At any given time, players will be able to accumulate a maximum of 30 "bubbles" worth of rest bonus which
// translates into approximately 1.5 levels worth of rested play (before your character returns to normal rest state).
// Thanks to the comforts of a warm bed and a hearty meal, players who rest or log out at an Inn will
// accumulate rest credit four times faster than players logged off outside of an Inn or City.
// Players who log out anywhere else in the world will earn rest credit four times slower.
// http://www.worldofwarcraft.com/info/basics/resting.html
// Define xp for a full bar ( = 20 bubbles)
uint32 xp_to_lvl = uint32(lvlinfo->XPToNextLevel);
// get RestXP multiplier from config.
float bubblerate = sWorld.getRate(RATE_RESTXP);
// One bubble (5% of xp_to_level) for every 8 hours logged out.
// if multiplier RestXP (from ascent.config) is f.e 2, you only need 4hrs/bubble.
uint32 rested_xp = uint32(0.05f * xp_to_lvl * ( seconds / (3600 * ( 8 / bubblerate))));
// if we are at a resting area rest_XP goes 4 times faster (making it 1 bubble every 2 hrs)
if (m_isResting)
rested_xp <<= 2;
// Add result to accumulated rested XP
m_restAmount += uint32(rested_xp);
// and set limit to be max 1.5 * 20 bubbles * multiplier (1.5 * xp_to_level * multiplier)
if (m_restAmount > xp_to_lvl + (uint32)((float)( xp_to_lvl >> 1 ) * bubblerate ))
m_restAmount = xp_to_lvl + (uint32)((float)( xp_to_lvl >> 1 ) * bubblerate );
Log.Debug("REST","Add %d rest XP to a total of %d, RestState %d", rested_xp, m_restAmount,m_isResting);
// Update clients interface with new values.
UpdateRestState();
}
void Player::UpdateRestState()
{
if(m_restAmount && GetUInt32Value(UNIT_FIELD_LEVEL) < GetUInt32Value(PLAYER_FIELD_MAX_LEVEL))
m_restState = RESTSTATE_RESTED;
else
m_restState = RESTSTATE_NORMAL;
// Update RestState 100%/200%
SetUInt32Value(PLAYER_BYTES_2, ((GetUInt32Value(PLAYER_BYTES_2) & 0x00FFFFFF) | (m_restState << 24)));
//update needle (weird, works at 1/2 rate)
SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, m_restAmount >> 1);
}
void Player::ApplyPlayerRestState(bool apply)
{
if(apply)
{
m_restState = RESTSTATE_RESTED;
m_isResting = true;
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_RESTING); //put zzz icon
}
else
{
m_isResting = false;
RemoveFlag(PLAYER_FLAGS,PLAYER_FLAG_RESTING); //remove zzz icon
}
UpdateRestState();
}
#define CORPSE_VIEW_DISTANCE 1600 // 40*40
bool Player::CanSee(Object* obj) // * Invisibility & Stealth Detection - Partha *
{
if (obj == this)
return true;
uint32 object_type = obj->GetTypeId();
if(getDeathState() == CORPSE) // we are dead and we have released our spirit
{
if(object_type == TYPEID_PLAYER)
{
Player *pObj = static_cast< Player* >(obj);
if(myCorpse && myCorpse->GetDistanceSq(obj) <= CORPSE_VIEW_DISTANCE)
return !pObj->m_isGmInvisible; // we can see all players within range of our corpse except invisible GMs
if(m_deathVision) // if we have arena death-vision we can see all players except invisible GMs
return !pObj->m_isGmInvisible;
return (pObj->getDeathState() == CORPSE); // we can only see players that are spirits
}
if(myCorpse)
{
if(myCorpse == obj)
return true;
if(myCorpse->GetDistanceSq(obj) <= CORPSE_VIEW_DISTANCE)
return true; // we can see everything within range of our corpse
}
if(m_deathVision) // if we have arena death-vision we can see everything
return true;
if(object_type == TYPEID_UNIT)
{
Unit *uObj = static_cast<Unit *>(obj);
return uObj->IsSpiritHealer(); // we can't see any NPCs except spirit-healers
}
return false;
}
//------------------------------------------------------------------
switch(object_type) // we are alive or we haven't released our spirit yet
{
case TYPEID_PLAYER:
{
Player *pObj = static_cast< Player* >(obj);
if(pObj->m_invisible) // Invisibility - Detection of Players
{
if(pObj->getDeathState() == CORPSE)
return bGMTagOn; // only GM can see players that are spirits
if(GetGroup() && pObj->GetGroup() == GetGroup() // can see invisible group members except when dueling them
&& DuelingWith != pObj)
return true;
if(pObj->stalkedby == GetGUID()) // Hunter's Mark / MindVision is visible to the caster
return true;
if(m_invisDetect[INVIS_FLAG_NORMAL] < 1 // can't see invisible without proper detection
|| pObj->m_isGmInvisible) // can't see invisible GM
return bGMTagOn; // GM can see invisible players
}
if( m_invisible && pObj->m_invisDetect[m_invisFlag] < 1 ) // Invisible - can see those that detect, but not others
return m_isGmInvisible;
if(pObj->IsStealth()) // Stealth Detection ( I Hate Rogues :P )
{
if(GetGroup() && pObj->GetGroup() == GetGroup() // can see stealthed group members except when dueling them
&& DuelingWith != pObj)
return true;
if(pObj->stalkedby == GetGUID()) // Hunter's Mark / MindVision is visible to the caster
return true;
if(isInFront(pObj)) // stealthed player is in front of us
{
// Detection Range = 5yds + (Detection Skill - Stealth Skill)/5
if(getLevel() < PLAYER_LEVEL_CAP)
detectRange = 5.0f + getLevel() + 0.2f * (float)(GetStealthDetectBonus() - pObj->GetStealthLevel());
else
detectRange = 75.0f + 0.2f * (float)(GetStealthDetectBonus() - pObj->GetStealthLevel());
// Hehe... stealth skill is increased by 5 each level and detection skill is increased by 5 each level too.
// This way, a level 70 should easily be able to detect a level 4 rogue (level 4 because that's when you get stealth)
// detectRange += 0.2f * ( getLevel() - pObj->getLevel() );
if(detectRange < 1.0f) detectRange = 1.0f; // Minimum Detection Range = 1yd
}
else // stealthed player is behind us
{
if(GetStealthDetectBonus() > 1000) return true; // immune to stealth
else detectRange = 0.0f;
}
detectRange += GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); // adjust range for size of player
detectRange += pObj->GetFloatValue(UNIT_FIELD_BOUNDINGRADIUS); // adjust range for size of stealthed player
//sLog.outString( "Player::CanSee(%s): detect range = %f yards (%f ingame units), cansee = %s , distance = %f" , pObj->GetName() , detectRange , detectRange * detectRange , ( GetDistance2dSq(pObj) > detectRange * detectRange ) ? "yes" : "no" , GetDistanceSq(pObj) );
if(GetDistanceSq(pObj) > detectRange * detectRange)
return bGMTagOn; // GM can see stealthed players
}
return !pObj->m_isGmInvisible;
}
//------------------------------------------------------------------
case TYPEID_UNIT:
{
Unit *uObj = static_cast<Unit *>(obj);
if(uObj->IsSpiritHealer()) // can't see spirit-healers when alive
return false;
if(uObj->m_invisible // Invisibility - Detection of Units
&& m_invisDetect[uObj->m_invisFlag] < 1) // can't see invisible without proper detection
return bGMTagOn; // GM can see invisible units
if( m_invisible && uObj->m_invisDetect[m_invisFlag] < 1 ) // Invisible - can see those that detect, but not others
return m_isGmInvisible;
return true;
}
//------------------------------------------------------------------
case TYPEID_GAMEOBJECT:
{
GameObject *gObj = static_cast<GameObject *>(obj);
if(gObj->invisible) // Invisibility - Detection of GameObjects
{
uint64 owner = gObj->GetUInt64Value(OBJECT_FIELD_CREATED_BY);
if(GetGUID() == owner) // the owner of an object can always see it
return true;
if(GetGroup())
{
PlayerInfo * inf = objmgr.GetPlayerInfo((uint32)owner);
if(inf && GetGroup()->HasMember(inf))
return true;
}
if(m_invisDetect[gObj->invisibilityFlag] < 1) // can't see invisible without proper detection
return bGMTagOn; // GM can see invisible objects
}
return true;
}
//------------------------------------------------------------------
default:
return true;
}
}
void Player::AddInRangeObject(Object* pObj)
{
//Send taxi move if we're on a taxi
if (m_CurrentTaxiPath && (pObj->GetTypeId() == TYPEID_PLAYER))
{
uint32 ntime = getMSTime();
if (ntime > m_taxi_ride_time)
m_CurrentTaxiPath->SendMoveForTime( this, static_cast< Player* >( pObj ), ntime - m_taxi_ride_time);
/*else
m_CurrentTaxiPath->SendMoveForTime( this, static_cast< Player* >( pObj ), m_taxi_ride_time - ntime);*/
}
Unit::AddInRangeObject(pObj);
//if the object is a unit send a move packet if they have a destination
if(pObj->GetTypeId() == TYPEID_UNIT)
{
//add an event to send move update have to send guid as pointer was causing a crash :(
//sEventMgr.AddEvent( static_cast< Creature* >( pObj )->GetAIInterface(), &AIInterface::SendCurrentMove, this->GetGUID(), EVENT_UNIT_SENDMOVE, 200, 1);
static_cast< Creature* >( pObj )->GetAIInterface()->SendCurrentMove(this);
}
}
void Player::OnRemoveInRangeObject(Object* pObj)
{
//if (/*!CanSee(pObj) && */IsVisible(pObj))
//{
//RemoveVisibleObject(pObj);
//}
//object was deleted before reaching here
if (pObj == NULL)
return;
if (pObj->GetGUID() == GetUInt64Value(UNIT_FIELD_SUMMON))
{
RemoveFieldSummon();
}
m_visibleObjects.erase(pObj);
Unit::OnRemoveInRangeObject(pObj);
if( pObj->GetGUID() == m_CurrentCharm )
{
Unit *p =GetMapMgr()->GetUnit( m_CurrentCharm );
if( !p )
return;
UnPossess();
if(m_currentSpell)
m_currentSpell->cancel(); // cancel the spell
m_CurrentCharm=0;
if( p->m_temp_summon && p->GetTypeId() == TYPEID_UNIT )
static_cast< Creature* >( p )->SafeDelete();
}
if(pObj == m_Summon)
{
if(m_Summon->IsSummon())
{
m_Summon->Dismiss(true);
}
else
{
m_Summon->Remove(true, true, false);
}
if(m_Summon)
{
m_Summon->ClearPetOwner();
m_Summon = 0;
}
}
/* wehee loop unrolling */
/* if(m_spellTypeTargets[0] == pObj)
m_spellTypeTargets[0] = NULL;
if(m_spellTypeTargets[1] == pObj)
m_spellTypeTargets[1] = NULL;
if(m_spellTypeTargets[2] == pObj)
m_spellTypeTargets[2] = NULL;*/
if(pObj->IsUnit())
{
for(uint32 x = 0; x < NUM_SPELL_TYPE_INDEX; ++x)
if(m_spellIndexTypeTargets[x] == pObj->GetGUID())
m_spellIndexTypeTargets[x] = 0;
}
}
void Player::ClearInRangeSet()
{
m_visibleObjects.clear();
Unit::ClearInRangeSet();
}
void Player::EventCannibalize(uint32 amount)
{
uint32 amt = (GetUInt32Value(UNIT_FIELD_MAXHEALTH)*amount)/100;
uint32 newHealth = GetUInt32Value(UNIT_FIELD_HEALTH) + amt;
if(newHealth <= GetUInt32Value(UNIT_FIELD_MAXHEALTH))
SetUInt32Value(UNIT_FIELD_HEALTH, newHealth);
else
SetUInt32Value(UNIT_FIELD_HEALTH, GetUInt32Value(UNIT_FIELD_MAXHEALTH));
cannibalizeCount++;
if(cannibalizeCount == 5)
SetUInt32Value(UNIT_NPC_EMOTESTATE, 0);
WorldPacket data(SMSG_PERIODICAURALOG, 38);
data << GetNewGUID(); // caster guid
data << GetNewGUID(); // target guid
data << (uint32)(20577); // spellid
data << (uint32)1; // unknown?? need resource?
data << (uint32)FLAG_PERIODIC_HEAL; // aura school
data << amt; // amount of done to target / heal / damage
data << (uint32)0; // unknown in some sniff this was 0x0F
SendMessageToSet(&data, true);
}
void Player::EventReduceDrunk(bool full)
{
uint8 drunk = ((GetUInt32Value(PLAYER_BYTES_3) >> 8) & 0xFF);
if(full) drunk = 0;
else drunk -= 10;
SetUInt32Value(PLAYER_BYTES_3, ((GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF00FF) | (drunk << 8)));
if(drunk == 0) sEventMgr.RemoveEvents(this, EVENT_PLAYER_REDUCEDRUNK);
}
void Player::LoadTaxiMask(const char* data)
{
vector<string> tokens = StrSplit(data, " ");
int index;
vector<string>::iterator iter;
for (iter = tokens.begin(), index = 0;
(index < 8) && (iter != tokens.end()); ++iter, ++index)
{
m_taximask[index] = atol((*iter).c_str());
}
}
bool Player::HasQuestForItem(uint32 itemid)
{
Quest *qst;
for( uint32 i = 0; i < 25; ++i )
{
if( m_questlog[i] != NULL )
{
qst = m_questlog[i]->GetQuest();
// Check the item_quest_association table for an entry related to this item
QuestAssociationList *tempList = QuestMgr::getSingleton().GetQuestAssociationListForItemId( itemid );
if( tempList != NULL )
{
QuestAssociationList::iterator it;
for (it = tempList->begin(); it != tempList->end(); ++it)
{
if ( ((*it)->qst == qst) && (GetItemInterface()->GetItemCount( itemid ) < (*it)->item_count) )
{
return true;
} // end if
} // end for
} // end if
// No item_quest association found, check the quest requirements
if( !qst->count_required_item )
continue;
for( uint32 j = 0; j < 4; ++j )
if( qst->required_item[j] == itemid && ( GetItemInterface()->GetItemCount( itemid ) < qst->required_itemcount[j] ) )
return true;
}
}
return false;
}
//scriptdev2
bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
{
return (m_ItemInterface->GetItemCount(item, inBankAlso) == count);
}
/*Loot type MUST be
1-corpse, go
2-skinning/herbalism/minning
3-Fishing
*/
void Player::SendLoot(uint64 guid,uint8 loot_type)
{
Group * m_Group = m_playerInfo->m_Group;
if(!IsInWorld()) return;
Loot * pLoot = NULL;
uint32 guidtype = GET_TYPE_FROM_GUID(guid);
int8 loot_method = -1;
if(guidtype == HIGHGUID_TYPE_UNIT)
{
Creature* pCreature = GetMapMgr()->GetCreature(GET_LOWGUID_PART(guid));
if(!pCreature)return;
pLoot=&pCreature->loot;
m_currentLoot = pCreature->GetGUID();
loot_method = pCreature->m_lootMethod;
if ( loot_method < 0 )
{
loot_method = PARTY_LOOT_FFA;
pCreature->m_lootMethod = PARTY_LOOT_FFA;
}
}else if(guidtype == HIGHGUID_TYPE_GAMEOBJECT)
{
GameObject* pGO = GetMapMgr()->GetGameObject(GET_LOWGUID_PART(guid));
if(!pGO)return;
pGO->SetUInt32Value(GAMEOBJECT_STATE,0);
pLoot=&pGO->loot;
m_currentLoot = pGO->GetGUID();
}
else if((guidtype == HIGHGUID_TYPE_PLAYER) )
{
Player *p=GetMapMgr()->GetPlayer((uint32)guid);
if(!p)return;
pLoot=&p->loot;
m_currentLoot = p->GetGUID();
}
else if( (guidtype == HIGHGUID_TYPE_CORPSE))
{
Corpse *pCorpse = objmgr.GetCorpse((uint32)guid);
if(!pCorpse)return;
pLoot=&pCorpse->loot;
m_currentLoot = pCorpse->GetGUID();
}
else if( (guidtype == HIGHGUID_TYPE_ITEM) )
{
Item *pItem = GetItemInterface()->GetItemByGUID(guid);
if(!pItem)
return;
pLoot = pItem->loot;
m_currentLoot = pItem->GetGUID();
}
if(!pLoot)
{
// something whack happened.. damn cheaters..
return;
}
// add to looter set
pLoot->looters.insert(GetLowGUID());
WorldPacket data, data2(28);
data.SetOpcode (SMSG_LOOT_RESPONSE);
m_lootGuid = guid;
data << guid;
data << loot_type;//loot_type;
data << pLoot->gold;
data << (uint8) 0;//loot size reserve
std::vector<__LootItem>::iterator iter=pLoot->items.begin();
uint32 count=0;
uint8 slottype = 0;
for(uint32 x=0;iter!=pLoot->items.end();iter++,x++)
{
if (iter->iItemsCount == 0)
continue;
LooterSet::iterator itr = iter->has_looted.find(GetLowGUID());
if (iter->has_looted.end() != itr)
continue;
ItemPrototype* itemProto =iter->item.itemproto;
if (!itemProto)
continue;
// check if it's on ML if so only quest items and ffa loot should be shown based on mob
if ( loot_method == PARTY_LOOT_MASTER && m_Group && m_Group->GetLooter() != m_playerInfo )
// pass on all ffa_loot and the grey / white items
if ( !iter->ffa_loot && !(itemProto->Quality < m_Group->GetThreshold()) )
continue;
//quest items check. type 4/5
//quest items that dont start quests.
if((itemProto->Bonding == ITEM_BIND_QUEST) && !(itemProto->QuestId) && !HasQuestForItem(iter->item.itemproto->ItemId))
continue;
if((itemProto->Bonding == ITEM_BIND_QUEST2) && !(itemProto->QuestId) && !HasQuestForItem(iter->item.itemproto->ItemId))
continue;
//quest items that start quests need special check to avoid drops all the time.
if((itemProto->Bonding == ITEM_BIND_QUEST) && (itemProto->QuestId) && GetQuestLogForEntry(itemProto->QuestId))
continue;
if((itemProto->Bonding == ITEM_BIND_QUEST2) && (itemProto->QuestId) && GetQuestLogForEntry(itemProto->QuestId))
continue;
if((itemProto->Bonding == ITEM_BIND_QUEST) && (itemProto->QuestId) && HasFinishedQuest(itemProto->QuestId))
continue;
if((itemProto->Bonding == ITEM_BIND_QUEST2) && (itemProto->QuestId) && HasFinishedQuest(itemProto->QuestId))
continue;
//check for starting item quests that need questlines.
if((itemProto->QuestId && itemProto->Bonding != ITEM_BIND_QUEST && itemProto->Bonding != ITEM_BIND_QUEST2))
{
bool HasRequiredQuests = true;
Quest * pQuest = QuestStorage.LookupEntry(itemProto->QuestId);
if(pQuest)
{
uint32 finishedCount = 0;
//check if its a questline.
for(uint32 i = 0; i < pQuest->count_requiredquests; i++)
{
if(pQuest->required_quests[i])
{
if(!HasFinishedQuest(pQuest->required_quests[i]) || GetQuestLogForEntry(pQuest->required_quests[i]))
{
if (!(pQuest->quest_flags & QUEST_FLAG_ONLY_ONE_REQUIRED)) {
HasRequiredQuests = false;
break;
}
}
else
{
finishedCount++;
}
}
}
if (pQuest->quest_flags & QUEST_FLAG_ONLY_ONE_REQUIRED) {
if (finishedCount == 0) continue;
} else {
if(!HasRequiredQuests)
continue;
}
}
}
slottype = 0;
if(m_Group != NULL && loot_type < 2)
{
switch(loot_method)
{
case PARTY_LOOT_MASTER:
slottype = 2;
break;
case PARTY_LOOT_GROUP:
case PARTY_LOOT_RR:
case PARTY_LOOT_NBG:
slottype = 1;
break;
default:
slottype = 0;
break;
}
// only quality items are distributed
if(itemProto->Quality < m_Group->GetThreshold())
{
slottype = 0;
}
/* if all people passed anyone can loot it? :P */
if(iter->passed)
slottype = 0; // All players passed on the loot
//if it is ffa loot and not an masterlooter
if(iter->ffa_loot)
slottype = 0;
}
data << uint8(x);
data << uint32(itemProto->ItemId);
data << uint32(iter->iItemsCount);//nr of items of this type
data << uint32(iter->item.displayid);
//data << uint32(iter->iRandomSuffix ? iter->iRandomSuffix->id : 0);
//data << uint32(iter->iRandomProperty ? iter->iRandomProperty->ID : 0);
if(iter->iRandomSuffix)
{
data << Item::GenerateRandomSuffixFactor(itemProto);
data << uint32(-int32(iter->iRandomSuffix->id));
}
else if(iter->iRandomProperty)
{
data << uint32(0);
data << uint32(iter->iRandomProperty->ID);
}
else
{
data << uint32(0);
data << uint32(0);
}
data << slottype; // "still being rolled for" flag
if(slottype == 1)
{
if(iter->roll == NULL && !iter->passed)
{
int32 ipid = 0;
uint32 factor=0;
if(iter->iRandomProperty)
ipid=iter->iRandomProperty->ID;
else if(iter->iRandomSuffix)
{
ipid = -int32(iter->iRandomSuffix->id);
factor=Item::GenerateRandomSuffixFactor(iter->item.itemproto);
}
if(iter->item.itemproto)
{
iter->roll = new LootRoll(60000, (m_Group != NULL ? m_Group->MemberCount() : 1), guid, x, iter->item.itemproto->ItemId, factor, uint32(ipid), GetMapMgr());
data2.Initialize(SMSG_LOOT_START_ROLL);
data2 << guid;
data2 << x;
data2 << uint32(iter->item.itemproto->ItemId);
data2 << uint32(factor);
if(iter->iRandomProperty)
data2 << uint32(iter->iRandomProperty->ID);
else if(iter->iRandomSuffix)
data2 << uint32(ipid);
else
data2 << uint32(0);
data2 << uint32(60000); // countdown
}
Group * pGroup = m_playerInfo->m_Group;
if(pGroup)
{
pGroup->Lock();
for(uint32 i = 0; i < pGroup->GetSubGroupCount(); ++i)
{
for(GroupMembersSet::iterator itr = pGroup->GetSubGroup(i)->GetGroupMembersBegin(); itr != pGroup->GetSubGroup(i)->GetGroupMembersEnd(); ++itr)
{
if((*itr)->m_loggedInPlayer && (*itr)->m_loggedInPlayer->GetItemInterface()->CanReceiveItem(itemProto, iter->iItemsCount) == 0)
{
if( (*itr)->m_loggedInPlayer->m_passOnLoot )
iter->roll->PlayerRolled( (*itr)->m_loggedInPlayer, 3 ); // passed
else
(*itr)->m_loggedInPlayer->GetSession()->SendPacket(&data2);
}
}
}
pGroup->Unlock();
}
else
{
GetSession()->SendPacket(&data2);
}
}
}
count++;
}
data.wpos (13);
data << (uint8)count;
GetSession ()->SendPacket(&data);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
}
void Player::EventAllowTiggerPort(bool enable)
{
m_AllowAreaTriggerPort = enable;
}
uint32 Player::CalcTalentResetCost(uint32 resetnum)
{
if(resetnum ==0 )
return 10000;
else
{
if(resetnum>10)
return 500000;
else return resetnum*50000;
}
}
void Player::SendTalentResetConfirm()
{
WorldPacket data(MSG_TALENT_WIPE_CONFIRM, 12);
data << GetGUID();
data << CalcTalentResetCost(GetTalentResetTimes());
GetSession()->SendPacket(&data);
}
void Player::SendPetUntrainConfirm()
{
Pet* pPet = GetSummon();
if( pPet == NULL )
return;
WorldPacket data( SMSG_PET_UNLEARN_CONFIRM, 12 );
data << pPet->GetGUID();
data << pPet->GetUntrainCost();
GetSession()->SendPacket( &data );
}
int32 Player::CanShootRangedWeapon( uint32 spellid, Unit* target, bool autoshot )
{
SpellEntry* spellinfo = dbcSpell.LookupEntry( spellid );
if( spellinfo == NULL )
return -1;
//sLog.outString( "Canshootwithrangedweapon!?!? spell: [%u] %s" , spellinfo->Id , spellinfo->Name );
// Check if Morphed
if( polySpell > 0 )
return SPELL_FAILED_NOT_SHAPESHIFT;
// Check ammo
Item* itm = GetItemInterface()->GetInventoryItem( EQUIPMENT_SLOT_RANGED );
if( itm == NULL )
return SPELL_FAILED_NO_AMMO;
// Check ammo level
ItemPrototype * iprot=ItemPrototypeStorage.LookupEntry(GetUInt32Value(PLAYER_AMMO_ID));
if( iprot && getLevel()< iprot->RequiredLevel)
return SPELL_FAILED_LOWLEVEL;
// Check ammo type
ItemPrototype * iprot1 = ItemPrototypeStorage.LookupEntry(itm->GetEntry());
if( iprot && iprot1 && iprot->SubClass != iprot1->AmmoType )
return SPELL_FAILED_NEED_AMMO;
// Player has clicked off target. Fail spell.
if( m_curSelection != m_AutoShotTarget )
return SPELL_FAILED_INTERRUPTED;
// Check if target is allready dead
if( target->isDead() )
return SPELL_FAILED_TARGETS_DEAD;
// Check if in line of sight (need collision detection).
if (sWorld.Collision) {
if (GetMapId() == target->GetMapId() && !CollideInterface.CheckLOS(GetMapId(),GetPositionNC(),target->GetPositionNC()))
return SPELL_FAILED_LINE_OF_SIGHT;
}
// Check if we aren't casting another spell allready
if( GetCurrentSpell() )
return -1;
// Supalosa - The hunter ability Auto Shot is using Shoot range, which is 5 yards shorter.
// So we'll use 114, which is the correct 35 yard range used by the other Hunter abilities (arcane shot, concussive shot...)
uint8 fail = 0;
uint32 rIndex = autoshot ? 114 : spellinfo->rangeIndex;
SpellRange* range = dbcSpellRange.LookupEntry( rIndex );
float minrange = GetMinRange( range );
float dist = CalcDistance( this, target );
float maxr = GetMaxRange( range ) + 2.52f;
if( spellinfo->SpellGroupType )
{
SM_FFValue( this->SM_FRange, &maxr, spellinfo->SpellGroupType );
SM_PFValue( this->SM_PRange, &maxr, spellinfo->SpellGroupType );
#ifdef COLLECTION_OF_UNTESTED_STUFF_AND_TESTERS
float spell_flat_modifers=0;
float spell_pct_modifers=0;
SM_FFValue(this->SM_FRange,&spell_flat_modifers,spellinfo->SpellGroupType);
SM_FFValue(this->SM_PRange,&spell_pct_modifers,spellinfo->SpellGroupType);
if(spell_flat_modifers!=0 || spell_pct_modifers!=0)
printf("!!!!!spell range bonus mod flat %f , spell range bonus pct %f , spell range %f, spell group %u\n",spell_flat_modifers,spell_pct_modifers,maxr,spellinfo->SpellGroupType);
#endif
}
//float bonusRange = 0;
// another hackfix: bonus range from hunter talent hawk eye: +2/4/6 yard range to ranged weapons
//if(autoshot)
//SM_FFValue( SM_FRange, &bonusRange, dbcSpell.LookupEntry( 75 )->SpellGroupType ); // HORRIBLE hackfixes :P
// Partha: +2.52yds to max range, this matches the range the client is calculating.
// see extra/supalosa_range_research.txt for more info
//bonusRange = 2.52f;
//sLog.outString( "Bonus range = %f" , bonusRange );
// check if facing target
if(!isInFront(target))
{
fail = SPELL_FAILED_UNIT_NOT_INFRONT;
}
// Check ammo count
if( iprot && itm->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_WAND )
{
uint32 ammocount = GetItemInterface()->GetItemCount(iprot->ItemId);
if(ammocount == 0)
fail = SPELL_FAILED_NO_AMMO;
}
// Check for too close
if( spellid != SPELL_RANGED_WAND )//no min limit for wands
if( minrange > dist )
fail = SPELL_FAILED_TOO_CLOSE;
if( dist > maxr )
{
// sLog.outString( "Auto shot failed: out of range (Maxr: %f, Dist: %f)" , maxr , dist );
fail = SPELL_FAILED_OUT_OF_RANGE;
}
if( spellid == SPELL_RANGED_THROW )
{
if( itm != NULL ) // no need for this
if( itm->GetProto() )
if( GetItemInterface()->GetItemCount( itm->GetProto()->ItemId ) == 0 )
fail = SPELL_FAILED_NO_AMMO;
}
/* else
{
if(GetUInt32Value(PLAYER_AMMO_ID))//for wand
if(this->GetItemInterface()->GetItemCount(GetUInt32Value(PLAYER_AMMO_ID)) == 0)
fail = SPELL_FAILED_NO_AMMO;
}
*/
if( fail > 0 )// && fail != SPELL_FAILED_OUT_OF_RANGE)
{
//SendCastResult( autoshot ? 75 : spellid, fail, 0, 0 );
packetSMSG_CASTRESULT cr;
cr.SpellId = autoshot ? 75 : spellid;
cr.ErrorMessage = fail;
cr.MultiCast = 0;
m_session->OutPacket( SMSG_CAST_RESULT, sizeof(packetSMSG_CASTRESULT), &cr );
if( fail != SPELL_FAILED_OUT_OF_RANGE )
{
uint32 spellid2 = autoshot ? 75 : spellid;
m_session->OutPacket( SMSG_CANCEL_AUTO_REPEAT, 4, &spellid2 );
}
//sLog.outString( "Result for CanShootWIthRangedWeapon: %u" , fail );
//sLog.outDebug( "Can't shoot with ranged weapon: %u (Timer: %u)" , fail , m_AutoShotAttackTimer );
return fail;
}
return 0;
}
void Player::EventRepeatSpell()
{
if( !m_curSelection || !IsInWorld() )
return;
Unit* target = GetMapMgr()->GetUnit( m_curSelection );
if( target == NULL )
{
m_AutoShotAttackTimer = 0; //avoid flooding client with error mesages
m_onAutoShot = false;
//sLog.outDebug( "Can't cast Autoshot: Target changed! (Timer: %u)" , m_AutoShotAttackTimer );
return;
}
m_AutoShotDuration = m_uint32Values[UNIT_FIELD_RANGEDATTACKTIME];
if( m_isMoving )
{
//sLog.outDebug( "HUNTER AUTOSHOT 2) %i, %i", m_AutoShotAttackTimer, m_AutoShotDuration );
//m_AutoShotAttackTimer = m_AutoShotDuration;//avoid flooding client with error mesages
//sLog.outDebug( "Can't cast Autoshot: You're moving! (Timer: %u)" , m_AutoShotAttackTimer );
m_AutoShotAttackTimer = 100; // shoot when we can
return;
}
int32 f = this->CanShootRangedWeapon( m_AutoShotSpell->Id, target, true );
if( f != 0 )
{
if( f != SPELL_FAILED_OUT_OF_RANGE )
{
m_AutoShotAttackTimer = 0;
m_onAutoShot=false;
}
else if( m_isMoving )
{
m_AutoShotAttackTimer = 100;
}
else
{
m_AutoShotAttackTimer = m_AutoShotDuration;//avoid flooding client with error mesages
}
return;
}
else
{
m_AutoShotAttackTimer = m_AutoShotDuration;
Spell* sp = SpellPool.PooledNew();
sp->Init( this, m_AutoShotSpell, true, NULL );
SpellCastTargets tgt;
tgt.m_unitTarget = m_curSelection;
tgt.m_targetMask = TARGET_FLAG_UNIT;
sp->prepare( &tgt );
}
}
bool Player::HasSpell(uint32 spell)
{
return mSpells.find(spell) != mSpells.end();
}
bool Player::HasSpellwithNameHash(uint32 hash)
{
SpellSet::iterator it,iter;
for(iter= mSpells.begin();iter != mSpells.end();)
{
it = iter++;
uint32 SpellID = *it;
SpellEntry *e = dbcSpell.LookupEntry(SpellID);
if(e->NameHash == hash)
return true;
}
return false;
}
bool Player::HasDeletedSpell(uint32 spell)
{
return (mDeletedSpells.count(spell) > 0);
}
void Player::removeSpellByHashName(uint32 hash)
{
SpellSet::iterator it,iter;
for(iter= mSpells.begin();iter != mSpells.end();)
{
it = iter++;
uint32 SpellID = *it;
SpellEntry *e = dbcSpell.LookupEntry(SpellID);
if(e->NameHash == hash)
{
if(info->spell_list.find(e->Id) != info->spell_list.end())
continue;
RemoveAura(SpellID,GetGUID());
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(SpellID);
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &swapped);
#else
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &SpellID);
#endif
mSpells.erase(it);
}
}
for(iter= mDeletedSpells.begin();iter != mDeletedSpells.end();)
{
it = iter++;
uint32 SpellID = *it;
SpellEntry *e = dbcSpell.LookupEntry(SpellID);
if(e->NameHash == hash)
{
if(info->spell_list.find(e->Id) != info->spell_list.end())
continue;
RemoveAura(SpellID,GetGUID());
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(SpellID);
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &swapped);
#else
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &SpellID);
#endif
mDeletedSpells.erase(it);
}
}
}
bool Player::removeSpell(uint32 SpellID, bool MoveToDeleted, bool SupercededSpell, uint32 SupercededSpellID)
{
SpellSet::iterator it,iter = mSpells.find(SpellID);
if(iter != mSpells.end())
{
mSpells.erase(iter);
RemoveAura(SpellID,GetGUID());
}
else
{
iter = mDeletedSpells.find(SpellID);
if(iter != mDeletedSpells.end())
{
mDeletedSpells.erase(iter);
}
else
{
return false;
}
}
if(MoveToDeleted)
mDeletedSpells.insert(SpellID);
if(!IsInWorld())
return true;
if(SupercededSpell)
{
WorldPacket data(SMSG_SUPERCEDED_SPELL, 8);
data << SpellID << SupercededSpellID;
m_session->SendPacket(&data);
}
else
{
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(SpellID);
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &swapped);
#else
m_session->OutPacket(SMSG_REMOVED_SPELL, 4, &SpellID);
#endif
}
return true;
}
bool Player::removeDeletedSpell( uint32 SpellID )
{
SpellSet::iterator it = mDeletedSpells.find( SpellID );
if ( it == mDeletedSpells.end() )
return false;
mDeletedSpells.erase( it );
return true;
}
void Player::EventActivateGameObject(GameObject* obj)
{
obj->BuildFieldUpdatePacket(this, GAMEOBJECT_DYN_FLAGS, 1);
}
void Player::EventDeActivateGameObject(GameObject* obj)
{
obj->BuildFieldUpdatePacket(this, GAMEOBJECT_DYN_FLAGS, 0);
}
void Player::EventTimedQuestExpire(Quest *qst, QuestLogEntry *qle, uint32 log_slot)
{
WorldPacket fail;
sQuestMgr.BuildQuestFailed(&fail, qst->id);
GetSession()->SendPacket(&fail);
CALL_QUESTSCRIPT_EVENT(qle, OnQuestCancel)(this);
qle->Finish();
}
//scriptdev2
void Player::AreaExploredOrEventHappens( uint32 questId )
{
sQuestMgr.AreaExplored(this,questId);
}
void Player::SendInitialLogonPackets()
{
// Initial Packets... they seem to be re-sent on port.
m_session->OutPacket(SMSG_SET_REST_START, 4, &m_timeLogoff);
StackWorldPacket<32> data(SMSG_BINDPOINTUPDATE);
data << m_bind_pos_x;
data << m_bind_pos_y;
data << m_bind_pos_z;
data << m_bind_mapid;
data << m_bind_zoneid;
GetSession()->SendPacket( &data );
//Proficiencies
//SendSetProficiency(4,armor_proficiency);
//SendSetProficiency(2,weapon_proficiency);
packetSMSG_SET_PROFICICENCY pr;
pr.ItemClass = 4;
pr.Profinciency = armor_proficiency;
m_session->OutPacket( SMSG_SET_PROFICIENCY, sizeof(packetSMSG_SET_PROFICICENCY), &pr );
pr.ItemClass = 2;
pr.Profinciency = weapon_proficiency;
m_session->OutPacket( SMSG_SET_PROFICIENCY, sizeof(packetSMSG_SET_PROFICICENCY), &pr );
//Tutorial Flags
data.Initialize( SMSG_TUTORIAL_FLAGS );
for (int i = 0; i < 8; i++)
data << uint32( m_Tutorials[i] );
GetSession()->SendPacket(&data);
//Initial Spells
smsg_InitialSpells();
//Initial Actions
SendInitialActions();
//Factions
smsg_InitialFactions();
/* Some minor documentation about the time field
// MOVE THIS DOCUMENTATION TO THE WIKI
minute's = 0x0000003F 00000000000000000000000000111111
hour's = 0x000007C0 00000000000000000000011111000000
weekdays = 0x00003800 00000000000000000011100000000000
days = 0x000FC000 00000000000011111100000000000000
months = 0x00F00000 00000000111100000000000000000000
years = 0x1F000000 00011111000000000000000000000000
unk = 0xE0000000 11100000000000000000000000000000
*/
data.Initialize(SMSG_LOGIN_SETTIMESPEED);
time_t minutes = sWorld.GetGameTime( ) / 60;
time_t hours = minutes / 60; minutes %= 60;
time_t gameTime = 0;
// TODO: Add stuff to handle these variable's
uint32 DayOfTheWeek = static_cast<uint32>(-1); // (0b111 = (any) day, 0 = Monday ect)
uint32 DayOfTheMonth = 20-1; // Day - 1 (0 is actual 1) its now the 20e here. TODO: replace this one with the proper date
uint32 CurrentMonth = 9-1; // Month - 1 (0 is actual 1) same as above. TODO: replace it with the proper code
uint32 CurrentYear = 7; // 2000 + this number results in a correct value for this crap. TODO: replace this with the propper code
#define MINUTE_BITMASK 0x0000003F
#define HOUR_BITMASK 0x000007C0
#define WEEKDAY_BITMASK 0x00003800
#define DAY_BITMASK 0x000FC000
#define MONTH_BITMASK 0x00F00000
#define YEAR_BITMASK 0x1F000000
#define UNK_BITMASK 0xE0000000
#define MINUTE_SHIFTMASK 0
#define HOUR_SHIFTMASK 6
#define WEEKDAY_SHIFTMASK 11
#define DAY_SHIFTMASK 14
#define MONTH_SHIFTMASK 20
#define YEAR_SHIFTMASK 24
#define UNK_SHIFTMASK 29
gameTime = ((minutes << MINUTE_SHIFTMASK) & MINUTE_BITMASK);
gameTime|= ((hours << HOUR_SHIFTMASK) & HOUR_BITMASK);
gameTime|= ((DayOfTheWeek << WEEKDAY_SHIFTMASK) & WEEKDAY_BITMASK);
gameTime|= ((DayOfTheMonth << DAY_SHIFTMASK) & DAY_BITMASK);
gameTime|= ((CurrentMonth << MONTH_SHIFTMASK) & MONTH_BITMASK);
gameTime|= ((CurrentYear << YEAR_SHIFTMASK) & YEAR_BITMASK);
data << (uint32)gameTime;
data << (float)0.0166666669777748f; // Normal Game Speed
GetSession()->SendPacket( &data );
// cebernic for speedhack bug
m_lastRunSpeed = 0;
UpdateSpeed();
sLog.outDetail("WORLD: Sent initial logon packets for %s.", GetName());
}
void Player::Reset_Spells()
{
PlayerCreateInfo *info = objmgr.GetPlayerCreateInfo(getRace(), getClass());
ASSERT(info);
std::list<uint32> spelllist;
for(SpellSet::iterator itr = mSpells.begin(); itr!=mSpells.end(); itr++)
{
spelllist.push_back((*itr));
}
for(std::list<uint32>::iterator itr = spelllist.begin(); itr!=spelllist.end(); itr++)
{
removeSpell((*itr), false, false, 0);
}
for(std::set<uint32>::iterator sp = info->spell_list.begin();sp!=info->spell_list.end();sp++)
{
if(*sp)
{
addSpell(*sp);
}
}
// cebernic ResetAll ? don't forget DeletedSpells
mDeletedSpells.clear();
}
void Player::Reset_Talents()
{
unsigned int numRows = dbcTalent.GetNumRows();
for (unsigned int i = 0; i < numRows; i++) // Loop through all talents.
{
TalentEntry *tmpTalent = dbcTalent.LookupRow(i);
if(!tmpTalent)
continue; //should not ocur
//this is a normal talent (i hope )
for (int j = 0; j < 5; j++)
{
if (tmpTalent->RankID[j] != 0)
{
SpellEntry *spellInfo;
spellInfo = dbcSpell.LookupEntry( tmpTalent->RankID[j] );
if(spellInfo)
{
if (spellInfo->NameHash == SPELL_HASH_DUAL_WIELD)
{
if (getClass() != SHAMAN)
continue; //only shamans should lose it when they reset talents - opti
}
for(int k=0;k<3;k++)
if(spellInfo->Effect[k] == SPELL_EFFECT_LEARN_SPELL)
{
//removeSpell(spellInfo->EffectTriggerSpell[k], false, 0, 0);
//remove higher ranks of this spell too (like earth shield lvl 1 is talent and the rest is thought from trainer)
SpellEntry *spellInfo2;
spellInfo2 = dbcSpell.LookupEntry( spellInfo->EffectTriggerSpell[k] );
if(spellInfo2)
removeSpellByHashName(spellInfo2->NameHash);
}
//remove them all in 1 shot
removeSpellByHashName(spellInfo->NameHash);
}
}
else
break;
}
}
uint32 l=getLevel();
if(l>9)
{
SetUInt32Value(PLAYER_CHARACTER_POINTS1, l - 9);
}
else
{
SetUInt32Value(PLAYER_CHARACTER_POINTS1, 0);
}
}
void Player::Reset_ToLevel1()
{
RemoveAllAuras();
// clear aura fields
for(int i=UNIT_FIELD_AURA;i<UNIT_FIELD_AURASTATE;++i)
{
SetUInt32Value(i, 0);
}
SetUInt32Value(UNIT_FIELD_LEVEL, 1);
PlayerCreateInfo *info = objmgr.GetPlayerCreateInfo(getRace(), getClass());
ASSERT(info);
SetUInt32Value(UNIT_FIELD_HEALTH, info->health);
SetUInt32Value(UNIT_FIELD_POWER1, info->mana );
SetUInt32Value(UNIT_FIELD_POWER2, 0 ); // this gets devided by 10
SetUInt32Value(UNIT_FIELD_POWER3, info->focus );
SetUInt32Value(UNIT_FIELD_POWER4, info->energy );
SetUInt32Value(UNIT_FIELD_MAXHEALTH, info->health);
SetUInt32Value(UNIT_FIELD_BASE_HEALTH, info->health);
SetUInt32Value(UNIT_FIELD_BASE_MANA, info->mana);
SetUInt32Value(UNIT_FIELD_MAXPOWER1, info->mana );
SetUInt32Value(UNIT_FIELD_MAXPOWER2, info->rage );
SetUInt32Value(UNIT_FIELD_MAXPOWER3, info->focus );
SetUInt32Value(UNIT_FIELD_MAXPOWER4, info->energy );
SetUInt32Value(UNIT_FIELD_STAT0, info->strength );
SetUInt32Value(UNIT_FIELD_STAT1, info->ability );
SetUInt32Value(UNIT_FIELD_STAT2, info->stamina );
SetUInt32Value(UNIT_FIELD_STAT3, info->intellect );
SetUInt32Value(UNIT_FIELD_STAT4, info->spirit );
SetUInt32Value(UNIT_FIELD_ATTACK_POWER, info->attackpower );
SetUInt32Value(PLAYER_CHARACTER_POINTS1,0);
SetUInt32Value(PLAYER_CHARACTER_POINTS2,2);
for(uint32 x=0;x<7;x++)
SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+x, 1.00);
}
void Player::CalcResistance(uint32 type)
{
int32 res;
int32 pos;
int32 neg;
ASSERT(type < 7);
pos=(BaseResistance[type]*BaseResistanceModPctPos[type])/100;
neg=(BaseResistance[type]*BaseResistanceModPctNeg[type])/100;
pos+=FlatResistanceModifierPos[type];
neg+=FlatResistanceModifierNeg[type];
res=BaseResistance[type]+pos-neg;
if(type==0)res+=m_uint32Values[UNIT_FIELD_STAT1]*2;//fix armor from agi
if(res<0)res=0;
pos+=(res*ResistanceModPctPos[type])/100;
neg+=(res*ResistanceModPctNeg[type])/100;
res=pos-neg+BaseResistance[type];
if(type==0)res+=m_uint32Values[UNIT_FIELD_STAT1]*2;//fix armor from agi
if( res < 0 )
res = 1;
SetUInt32Value(UNIT_FIELD_RESISTANCEBUFFMODSPOSITIVE+type,pos);
SetUInt32Value(UNIT_FIELD_RESISTANCEBUFFMODSNEGATIVE+type,neg);
SetUInt32Value(UNIT_FIELD_RESISTANCES+type,res>0?res:0);
if( GetSummon() )
GetSummon()->CalcResistance( type );//Re-calculate pet's too.
}
void Player::UpdateNearbyGameObjects()
{
this->AquireInrangeLock(); //make sure to release lock before exit function !
for (Object::InRangeSet::iterator itr = GetInRangeSetBegin(); itr != GetInRangeSetEnd(); ++itr)
{
if((*itr)->GetTypeId() == TYPEID_GAMEOBJECT)
{
bool activate_quest_object = false;
GameObject *go = ((GameObject*)*itr);
QuestLogEntry *qle;
GameObjectInfo *info;
info = go->GetInfo();
bool deactivate = false;
if(info &&
(info->goMap.size() || info->itemMap.size()) )
{
for(GameObjectGOMap::iterator itr = go->GetInfo()->goMap.begin();
itr != go->GetInfo()->goMap.end();
++itr)
{
if((qle = GetQuestLogForEntry(itr->first->id)) != 0)
{
for(uint32 i = 0; i < qle->GetQuest()->count_required_mob; ++i)
{
if(qle->GetQuest()->required_mob[i] == go->GetEntry() &&
qle->GetMobCount(i) < qle->GetQuest()->required_mobcount[i])
{
activate_quest_object = true;
break;
}
}
if(activate_quest_object)
break;
}
}
if(!activate_quest_object)
{
for(GameObjectItemMap::iterator itr = go->GetInfo()->itemMap.begin();
itr != go->GetInfo()->itemMap.end();
++itr)
{
for(std::map<uint32, uint32>::iterator it2 = itr->second.begin();
it2 != itr->second.end();
++it2)
{
if(GetItemInterface()->GetItemCount(it2->first) < it2->second)
{
activate_quest_object = true;
break;
}
}
if(activate_quest_object)
break;
}
}
if(!activate_quest_object)
{
deactivate = true;
}
}
bool bPassed = !deactivate;
if((*itr)->GetUInt32Value(GAMEOBJECT_TYPE_ID) == GAMEOBJECT_TYPE_QUESTGIVER)
{
if(((GameObject*)(*itr))->m_quests)
{
if(((GameObject*)(*itr))->m_quests->size() > 0)
{
std::list<QuestRelation*>::iterator itr2 = ((GameObject*)(*itr))->m_quests->begin();
for(;itr2!=((GameObject*)(*itr))->m_quests->end();++itr2)
{
uint32 status = sQuestMgr.CalcQuestStatus(NULL, this, (*itr2)->qst, (*itr2)->type, false);
if(status == QMGR_QUEST_CHAT || status == QMGR_QUEST_AVAILABLE || status == QMGR_QUEST_REPEATABLE || status == QMGR_QUEST_FINISHED)
{
// Activate gameobject
EventActivateGameObject((GameObject*)(*itr));
bPassed = true;
break;
}
}
}
}
}
if(!bPassed)
EventDeActivateGameObject((GameObject*)(*itr));
}
}
this->ReleaseInrangeLock();
}
void Player::EventTaxiInterpolate()
{
if(!m_CurrentTaxiPath || m_mapMgr==NULL) return;
float x,y,z = 0.0f;
uint32 ntime = getMSTime();
if (ntime > m_taxi_ride_time)
m_CurrentTaxiPath->SetPosForTime(x, y, z, ntime - m_taxi_ride_time, &lastNode, m_mapId);
/*else
m_CurrentTaxiPath->SetPosForTime(x, y, z, m_taxi_ride_time - ntime, &lastNode);*/
if(x < _minX || x > _maxX || y < _minY || y > _maxX)
return;
SetPosition(x,y,z,0);
}
void Player::TaxiStart(TaxiPath *path, uint32 modelid, uint32 start_node)
{
int32 mapchangeid = -1;
float mapchangex = 0.0f,mapchangey = 0.0f,mapchangez = 0.0f;
uint32 cn = m_taxiMapChangeNode;
m_taxiMapChangeNode = 0;
if(this->m_MountSpellId)
RemoveAura(m_MountSpellId);
//also remove morph spells
if(GetUInt32Value(UNIT_FIELD_DISPLAYID)!=GetUInt32Value(UNIT_FIELD_NATIVEDISPLAYID))
{
RemoveAllAuraType(SPELL_AURA_TRANSFORM);
RemoveAllAuraType(SPELL_AURA_MOD_SHAPESHIFT);
}
SetUInt32Value( UNIT_FIELD_MOUNTDISPLAYID, modelid );
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER);
SetTaxiPath(path);
SetTaxiPos();
SetTaxiState(true);
m_taxi_ride_time = getMSTime();
//uint32 traveltime = uint32(path->getLength() * TAXI_TRAVEL_SPEED); // 36.7407
float traveldist = 0;
float lastx = 0, lasty = 0, lastz = 0;
TaxiPathNode *firstNode = path->GetPathNode(start_node);
uint32 add_time = 0;
// temporary workaround for taximodes with changing map
if (path->GetID() == 766 || path->GetID() == 767 || path->GetID() == 771 || path->GetID() == 772)
{
JumpToEndTaxiNode(path);
return;
}
if(start_node)
{
TaxiPathNode *pn = path->GetPathNode(0);
float dist = 0;
lastx = pn->x;
lasty = pn->y;
lastz = pn->z;
for(uint32 i = 1; i <= start_node; ++i)
{
pn = path->GetPathNode(i);
if(!pn)
{
JumpToEndTaxiNode(path);
return;
}
dist += CalcDistance(lastx, lasty, lastz, pn->x, pn->y, pn->z);
lastx = pn->x;
lasty = pn->y;
lastz = pn->z;
}
add_time = uint32( dist * TAXI_TRAVEL_SPEED );
lastx = lasty = lastz = 0;
}
size_t endn = path->GetNodeCount();
if(m_taxiPaths.size())
endn-= 2;
for(uint32 i = start_node; i < endn; ++i)
{
TaxiPathNode *pn = path->GetPathNode(i);
// temporary workaround for taximodes with changing map
if (!pn || path->GetID() == 766 || path->GetID() == 767 || path->GetID() == 771 || path->GetID() == 772)
{
JumpToEndTaxiNode(path);
return;
}
if( pn->mapid != m_mapId )
{
endn = (i - 1);
m_taxiMapChangeNode = i;
mapchangeid = (int32)pn->mapid;
mapchangex = pn->x;
mapchangey = pn->y;
mapchangez = pn->z;
break;
}
if(!lastx || !lasty || !lastz)
{
lastx = pn->x;
lasty = pn->y;
lastz = pn->z;
} else {
float dist = CalcDistance(lastx,lasty,lastz,
pn->x,pn->y,pn->z);
traveldist += dist;
lastx = pn->x;
lasty = pn->y;
lastz = pn->z;
}
}
uint32 traveltime = uint32(traveldist * TAXI_TRAVEL_SPEED);
if( start_node > endn || (endn - start_node) > 200 )
return;
WorldPacket data(SMSG_MONSTER_MOVE, 38 + ( (endn - start_node) * 12 ) );
data << GetNewGUID();
data << firstNode->x << firstNode->y << firstNode->z;
data << m_taxi_ride_time;
data << uint8( 0 );
data << uint32( 0x00000300 );
data << uint32( traveltime );
if(!cn)
m_taxi_ride_time -= add_time;
data << uint32( endn - start_node );
// uint32 timer = 0, nodecount = 0;
// TaxiPathNode *lastnode = NULL;
for(uint32 i = start_node; i < endn; i++)
{
TaxiPathNode *pn = path->GetPathNode(i);
if(!pn)
{
JumpToEndTaxiNode(path);
return;
}
data << pn->x << pn->y << pn->z;
}
SendMessageToSet(&data, true);
sEventMgr.AddEvent(this, &Player::EventTaxiInterpolate,
EVENT_PLAYER_TAXI_INTERPOLATE, 900, 0,0);
if( mapchangeid < 0 )
{
TaxiPathNode *pn = path->GetPathNode((uint32)path->GetNodeCount() - 1);
sEventMgr.AddEvent(this, &Player::EventDismount, path->GetPrice(),
pn->x, pn->y, pn->z, EVENT_PLAYER_TAXI_DISMOUNT, traveltime, 1,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
else
{
sEventMgr.AddEvent( this, &Player::EventTeleportTaxi, (uint32)mapchangeid, mapchangex, mapchangey, mapchangez, EVENT_PLAYER_TELEPORT, traveltime, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
}
void Player::JumpToEndTaxiNode(TaxiPath * path)
{
// this should *always* be safe in case it cant build your position on the path!
TaxiPathNode * pathnode = path->GetPathNode((uint32)path->GetNodeCount()-1);
if(!pathnode) return;
ModUnsigned32Value( PLAYER_FIELD_COINAGE , -(int32)path->GetPrice());
SetTaxiState(false);
SetTaxiPath(NULL);
UnSetTaxiPos();
m_taxi_ride_time = 0;
SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID , 0);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER);
SetPlayerSpeed(RUN, m_runSpeed);
SafeTeleport(pathnode->mapid, 0, LocationVector(pathnode->x, pathnode->y, pathnode->z));
// Start next path if any remaining
if(m_taxiPaths.size())
{
TaxiPath * p = *m_taxiPaths.begin();
m_taxiPaths.erase(m_taxiPaths.begin());
TaxiStart(p, taxi_model_id, 0);
}
}
void Player::RemoveSpellsFromLine(uint32 skill_line)
{
uint32 cnt = dbcSkillLineSpell.GetNumRows();
for(uint32 i=0; i < cnt; i++)
{
skilllinespell * sp = dbcSkillLineSpell.LookupRow(i);
if(sp)
{
if(sp->skilline == skill_line)
{
// Check ourselves for this spell, and remove it..
if ( !removeSpell(sp->spell, 0, 0, 0) )
// if we didnt unlearned spell check deleted spells
removeDeletedSpell( sp->spell );
}
}
}
}
void Player::CalcStat( uint32 type )
{
int32 res;
ASSERT( type < 5 );
int32 pos = (int32)((int32)BaseStats[type] * (int32)StatModPctPos[type] ) / 100 + (int32)FlatStatModPos[type];
int32 neg = (int32)((int32)BaseStats[type] * (int32)StatModPctNeg[type] ) / 100 + (int32)FlatStatModNeg[type];
res = pos + (int32)BaseStats[type] - neg;
pos += ( res * (int32)static_cast< Player* >( this )->TotalStatModPctPos[type] ) / 100;
neg += ( res * (int32)static_cast< Player* >( this )->TotalStatModPctNeg[type] ) / 100;
res = pos + BaseStats[type] - neg;
if( res <= 0 )
res = 1;
SetUInt32Value( UNIT_FIELD_POSSTAT0 + type, pos );
SetUInt32Value( UNIT_FIELD_NEGSTAT0 + type, neg );
SetUInt32Value( UNIT_FIELD_STAT0 + type, res > 0 ?res : 0 );
if( type == 1 )
CalcResistance( 0 );
if( GetSummon() && ( type == 2 || type == 3 ) )
GetSummon()->CalcStat( type );//Re-calculate pet's too
}
void Player::RegenerateMana(bool is_interrupted)
{
//if (m_interruptRegen)
// return;
uint32 cur = GetUInt32Value(UNIT_FIELD_POWER1);
uint32 mm = GetUInt32Value(UNIT_FIELD_MAXPOWER1);
if(cur >= mm)return;
float amt = (is_interrupted) ? GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT) : GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN);
amt *= 2; //floats are Mana Regen Per Sec. Regen Applied every 2 secs so real value =X*2 . Shady
//Apply shit from conf file
amt *= sWorld.getRate(RATE_POWER1);
if((amt<=1.0)&&(amt>0))//this fixes regen like 0.98
{
if(is_interrupted)
return;
cur++;
}
else
cur += float2int32(amt);
SetUInt32Value(UNIT_FIELD_POWER1,(cur >= mm) ? mm : cur);
}
void Player::RegenerateHealth( bool inCombat )
{
gtFloat* HPRegenBase = dbcHPRegenBase.LookupEntry(getLevel()-1 + (getClass()-1)*100);
gtFloat* HPRegen = dbcHPRegen.LookupEntry(getLevel()-1 + (getClass()-1)*100);
uint32 cur = GetUInt32Value(UNIT_FIELD_HEALTH);
uint32 mh = GetUInt32Value(UNIT_FIELD_MAXHEALTH);
if ( cur==0 ) return; // cebernic: bugfix diying but regenerated?
if(cur >= mh)
return;
float amt = (m_uint32Values[UNIT_FIELD_STAT4]*HPRegen->val+HPRegenBase->val*100);
if (PctRegenModifier)
amt+= (amt * PctRegenModifier) / 100;
amt *= sWorld.getRate(RATE_HEALTH);//Apply shit from conf file
//Near values from official
// wowwiki: Health Regeneration is increased by 33% while sitting.
if(m_isResting)
amt = amt * 1.33f;
if(inCombat)
amt *= PctIgnoreRegenModifier;
if(amt != 0)
{
if(amt > 0)
{
if(amt <= 1.0f)//this fixes regen like 0.98
cur++;
else
cur += float2int32(amt);
SetUInt32Value(UNIT_FIELD_HEALTH,(cur>=mh) ? mh : cur);
}
else
DealDamage(this, float2int32(-amt), 0, 0, 0);
}
}
void Player::LooseRage(int32 decayValue)
{
//Rage is lost at a rate of 3 rage every 3 seconds.
//The Anger Management talent changes this to 2 rage every 3 seconds.
uint32 cur = GetUInt32Value(UNIT_FIELD_POWER2);
uint32 newrage = ((int)cur <= decayValue) ? 0 : cur-decayValue;
if (newrage > 1000 )
newrage = 1000;
SetUInt32Value(UNIT_FIELD_POWER2,newrage);
}
void Player::RegenerateEnergy()
{
uint32 cur = GetUInt32Value(UNIT_FIELD_POWER4);
uint32 mh = GetUInt32Value(UNIT_FIELD_MAXPOWER4);
if(cur >= mh)
return;
float amt = 20.0f * PctPowerRegenModifier[POWER_TYPE_ENERGY];
cur += float2int32(amt);
SetUInt32Value(UNIT_FIELD_POWER4,(cur>=mh) ? mh : cur);
}
uint32 Player::GeneratePetNumber()
{
uint32 val = m_PetNumberMax + 1;
for (uint32 i = 1; i < m_PetNumberMax; i++)
if(m_Pets.find(i) == m_Pets.end())
return i; // found a free one
return val;
}
void Player::RemovePlayerPet(uint32 pet_number)
{
std::map<uint32, PlayerPet*>::iterator itr = m_Pets.find(pet_number);
if(itr != m_Pets.end())
{
delete itr->second;
m_Pets.erase(itr);
EventDismissPet();
}
}
#ifndef CLUSTERING
void Player::_Relocate(uint32 mapid, const LocationVector & v, bool sendpending, bool force_new_world, uint32 instance_id)
{
//this func must only be called when switching between maps!
WorldPacket data(41);
if(sendpending && mapid != m_mapId && force_new_world)
{
data.SetOpcode(SMSG_TRANSFER_PENDING);
data << mapid;
GetSession()->SendPacket(&data);
}
if(m_mapId != mapid || force_new_world)
{
uint32 status = sInstanceMgr.PreTeleport(mapid, this, instance_id);
if(status != INSTANCE_OK)
{
data.Initialize(SMSG_TRANSFER_ABORTED);
data << mapid << status;
GetSession()->SendPacket(&data);
return;
}
if(instance_id)
m_instanceId=instance_id;
if(IsInWorld())
{
RemoveFromWorld();
}
data.Initialize(SMSG_NEW_WORLD);
data << (uint32)mapid << v << v.o;
GetSession()->SendPacket( &data );
SetMapId(mapid);
}
else
{
// via teleport ack msg
WorldPacket * data = BuildTeleportAckMsg(v);
m_session->SendPacket(data);
delete data;
}
SetPlayerStatus(TRANSFER_PENDING);
m_sentTeleportPosition = v;
SetPosition(v);
SpeedCheatReset();
z_axisposition = 0.0f;
//Dismount before teleport
if( m_MountSpellId )
RemoveAura( m_MountSpellId );
}
#endif
// Player::AddItemsToWorld
// Adds all items to world, applies any modifiers for them.
void Player::AddItemsToWorld()
{
Item * pItem;
for(uint32 i = 0; i < INVENTORY_KEYRING_END; i++)
{
pItem = GetItemInterface()->GetInventoryItem(i);
if( pItem != NULL )
{
pItem->PushToWorld(m_mapMgr);
if(i < INVENTORY_SLOT_BAG_END) // only equipment slots get mods.
{
_ApplyItemMods(pItem, i, true, false, true);
}
if(pItem->IsContainer() && GetItemInterface()->IsBagSlot(i))
{
for(uint32 e=0; e < pItem->GetProto()->ContainerSlots; e++)
{
Item *item = ((Container*)pItem)->GetItem(e);
if(item)
{
item->PushToWorld(m_mapMgr);
}
}
}
}
}
UpdateStats();
}
// Player::RemoveItemsFromWorld
// Removes all items from world, reverses any modifiers.
void Player::RemoveItemsFromWorld()
{
Item * pItem;
for(uint32 i = 0; i < INVENTORY_KEYRING_END; i++)
{
pItem = m_ItemInterface->GetInventoryItem((int8)i);
if(pItem)
{
if(pItem->IsInWorld())
{
if(i < INVENTORY_SLOT_BAG_END) // only equipment+bags slots get mods.
{
_ApplyItemMods(pItem, i, false, false, true);
}
pItem->RemoveFromWorld();
}
if(pItem->IsContainer() && GetItemInterface()->IsBagSlot(i))
{
for(uint32 e=0; e < pItem->GetProto()->ContainerSlots; e++)
{
Item *item = ((Container*)pItem)->GetItem(e);
if(item && item->IsInWorld())
{
item->RemoveFromWorld();
}
}
}
}
}
UpdateStats();
}
uint32 Player::BuildCreateUpdateBlockForPlayer(ByteBuffer *data, Player *target )
{
int count = 0;
if(target == this)
{
// we need to send create objects for all items.
count += GetItemInterface()->m_CreateForPlayer(data);
}
count += Unit::BuildCreateUpdateBlockForPlayer(data, target);
return count;
}
void Player::Kick(uint32 delay /* = 0 */)
{
if(!delay)
{
m_KickDelay = 0;
_Kick();
} else {
m_KickDelay = delay;
sEventMgr.AddEvent(this, &Player::_Kick, EVENT_PLAYER_KICK, 1000, 0, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
}
void Player::_Kick()
{
if(!m_KickDelay)
{
sEventMgr.RemoveEvents(this, EVENT_PLAYER_KICK);
// remove now
GetSession()->LogoutPlayer(true);
} else {
if(m_KickDelay < 1500)
{
m_KickDelay = 0;
} else {
m_KickDelay -= 1000;
}
sChatHandler.BlueSystemMessageToPlr(this, "You will be removed from the server in %u seconds.", (uint32)(m_KickDelay/1000));
}
}
void Player::ClearCooldownForSpell(uint32 spell_id)
{
WorldPacket data(12);
data.SetOpcode(SMSG_CLEAR_COOLDOWN);
data << spell_id << GetGUID();
GetSession()->SendPacket(&data);
// remove cooldown data from Server side lists
uint32 i;
PlayerCooldownMap::iterator itr, itr2;
SpellEntry * spe = dbcSpell.LookupEntry(spell_id);
if(!spe) return;
for(i = 0; i < NUM_COOLDOWN_TYPES; ++i)
{
for( itr = m_cooldownMap[i].begin(); itr != m_cooldownMap[i].end(); )
{
itr2 = itr++;
if( ( i == COOLDOWN_TYPE_CATEGORY && itr2->first == spe->Category ) ||
( i == COOLDOWN_TYPE_SPELL && itr2->first == spe->Id ) )
{
m_cooldownMap[i].erase( itr2 );
}
}
}
}
void Player::ClearCooldownsOnLine(uint32 skill_line, uint32 called_from)
{
// found an easier way.. loop spells, check skill line
SpellSet::const_iterator itr = mSpells.begin();
skilllinespell *sk;
for(; itr != mSpells.end(); ++itr)
{
if((*itr) == called_from) // skip calling spell.. otherwise spammies! :D
continue;
sk = objmgr.GetSpellSkill((*itr));
if(sk && sk->skilline == skill_line)
ClearCooldownForSpell((*itr));
}
}
void Player::ResetAllCooldowns()
{
uint32 guid = (uint32)GetSelection();
switch(getClass())
{
case WARRIOR:
{
ClearCooldownsOnLine(26, guid);
ClearCooldownsOnLine(256, guid);
ClearCooldownsOnLine(257 , guid);
} break;
case PALADIN:
{
ClearCooldownsOnLine(594, guid);
ClearCooldownsOnLine(267, guid);
ClearCooldownsOnLine(184, guid);
} break;
case HUNTER:
{
ClearCooldownsOnLine(50, guid);
ClearCooldownsOnLine(51, guid);
ClearCooldownsOnLine(163, guid);
} break;
case ROGUE:
{
ClearCooldownsOnLine(253, guid);
ClearCooldownsOnLine(38, guid);
ClearCooldownsOnLine(39, guid);
} break;
case PRIEST:
{
ClearCooldownsOnLine(56, guid);
ClearCooldownsOnLine(78, guid);
ClearCooldownsOnLine(613, guid);
} break;
case SHAMAN:
{
ClearCooldownsOnLine(373, guid);
ClearCooldownsOnLine(374, guid);
ClearCooldownsOnLine(375, guid);
} break;
case MAGE:
{
ClearCooldownsOnLine(6, guid);
ClearCooldownsOnLine(8, guid);
ClearCooldownsOnLine(237, guid);
} break;
case WARLOCK:
{
ClearCooldownsOnLine(355, guid);
ClearCooldownsOnLine(354, guid);
ClearCooldownsOnLine(593, guid);
} break;
case DRUID:
{
ClearCooldownsOnLine(573, guid);
ClearCooldownsOnLine(574, guid);
ClearCooldownsOnLine(134, guid);
} break;
default: return; break;
}
}
void Player::PushUpdateData(ByteBuffer *data, uint32 updatecount)
{
// imagine the bytebuffer getting appended from 2 threads at once! :D
_bufferS.Acquire();
// unfortunately there is no guarantee that all data will be compressed at a ratio
// that will fit into 2^16 bytes ( stupid client limitation on server packets )
// so if we get more than 63KB of update data, force an update and then append it
// to the clean buffer.
if( (data->size() + bUpdateBuffer.size() ) >= 63000 )
ProcessPendingUpdates();
mUpdateCount += updatecount;
bUpdateBuffer.append(*data);
// add to process queue
if(m_mapMgr && !bProcessPending)
{
bProcessPending = true;
m_mapMgr->PushToProcessed(this);
}
_bufferS.Release();
}
void Player::PushOutOfRange(const WoWGuid & guid)
{
_bufferS.Acquire();
mOutOfRangeIds << guid;
++mOutOfRangeIdCount;
// add to process queue
if(m_mapMgr && !bProcessPending)
{
bProcessPending = true;
m_mapMgr->PushToProcessed(this);
}
_bufferS.Release();
}
void Player::PushCreationData(ByteBuffer *data, uint32 updatecount)
{
// imagine the bytebuffer getting appended from 2 threads at once! :D
_bufferS.Acquire();
// unfortunately there is no guarantee that all data will be compressed at a ratio
// that will fit into 2^16 bytes ( stupid client limitation on server packets )
// so if we get more than 63KB of update data, force an update and then append it
// to the clean buffer.
if( (data->size() + bCreationBuffer.size() + mOutOfRangeIds.size() ) >= 63000 )
ProcessPendingUpdates();
mCreationCount += updatecount;
bCreationBuffer.append(*data);
// add to process queue
if(m_mapMgr && !bProcessPending)
{
bProcessPending = true;
m_mapMgr->PushToProcessed(this);
}
_bufferS.Release();
}
void Player::ProcessPendingUpdates()
{
_bufferS.Acquire();
if(!bUpdateBuffer.size() && !mOutOfRangeIds.size() && !bCreationBuffer.size())
{
_bufferS.Release();
return;
}
size_t bBuffer_size = (bCreationBuffer.size() > bUpdateBuffer.size() ? bCreationBuffer.size() : bUpdateBuffer.size()) + 10 + (mOutOfRangeIds.size() * 9);
uint8 * update_buffer = new uint8[bBuffer_size];
size_t c = 0;
//build out of range updates if creation updates are queued
if(bCreationBuffer.size() || mOutOfRangeIdCount)
{
#ifdef USING_BIG_ENDIAN
*(uint32*)&update_buffer[c] = swap32(uint32(((mOutOfRangeIds.size() > 0) ? (mCreationCount + 1) : mCreationCount))); c += 4;
#else
*(uint32*)&update_buffer[c] = ((mOutOfRangeIds.size() > 0) ? (mCreationCount + 1) : mCreationCount); c += 4;
#endif
update_buffer[c] = 1; ++c;
// append any out of range updates
if(mOutOfRangeIdCount)
{
update_buffer[c] = UPDATETYPE_OUT_OF_RANGE_OBJECTS; ++c;
#ifdef USING_BIG_ENDIAN
*(uint32*)&update_buffer[c] = swap32(mOutOfRangeIdCount); c += 4;
#else
*(uint32*)&update_buffer[c] = mOutOfRangeIdCount; c += 4;
#endif
memcpy(&update_buffer[c], mOutOfRangeIds.contents(), mOutOfRangeIds.size()); c += mOutOfRangeIds.size();
mOutOfRangeIds.clear();
mOutOfRangeIdCount = 0;
}
if(bCreationBuffer.size())
memcpy(&update_buffer[c], bCreationBuffer.contents(), bCreationBuffer.size()); c += bCreationBuffer.size();
// clear our update buffer
bCreationBuffer.clear();
mCreationCount = 0;
// compress update packet
// while we said 350 before, i'm gonna make it 500 :D
if(c < (size_t)sWorld.compression_threshold || !CompressAndSendUpdateBuffer((uint32)c, update_buffer))
{
// send uncompressed packet -> because we failed
m_session->OutPacket(SMSG_UPDATE_OBJECT, (uint16)c, update_buffer);
}
}
if(bUpdateBuffer.size())
{
c = 0;
#ifdef USING_BIG_ENDIAN
*(uint32*)&update_buffer[c] = swap32(uint32(((mOutOfRangeIds.size() > 0) ? (mUpdateCount + 1) : mUpdateCount))); c += 4;
#else
*(uint32*)&update_buffer[c] = ((mOutOfRangeIds.size() > 0) ? (mUpdateCount + 1) : mUpdateCount); c += 4;
#endif
update_buffer[c] = 1; ++c;
memcpy(&update_buffer[c], bUpdateBuffer.contents(), bUpdateBuffer.size()); c += bUpdateBuffer.size();
// clear our update buffer
bUpdateBuffer.clear();
mUpdateCount = 0;
// compress update packet
// while we said 350 before, i'm gonna make it 500 :D
if(c < (size_t)sWorld.compression_threshold || !CompressAndSendUpdateBuffer((uint32)c, update_buffer))
{
// send uncompressed packet -> because we failed
m_session->OutPacket(SMSG_UPDATE_OBJECT, (uint16)c, update_buffer);
}
}
bProcessPending = false;
_bufferS.Release();
delete [] update_buffer;
// send any delayed packets
WorldPacket * pck;
while(delayedPackets.size())
{
pck = delayedPackets.next();
//printf("Delayed packet opcode %u sent.\n", pck->GetOpcode());
m_session->SendPacket(pck);
delete pck;
}
// resend speed if needed
if(resend_speed)
{
SetPlayerSpeed(RUN, m_runSpeed);
SetPlayerSpeed(FLY, m_flySpeed);
resend_speed=false;
}
}
bool Player::CompressAndSendUpdateBuffer(uint32 size, const uint8* update_buffer)
{
uint32 destsize = size + size/10 + 16;
int rate = sWorld.getIntRate(INTRATE_COMPRESSION);
if(size >= 40000 && rate < 6)
rate = 6;
// set up stream
z_stream stream;
stream.zalloc = 0;
stream.zfree = 0;
stream.opaque = 0;
if(deflateInit(&stream, rate) != Z_OK)
{
sLog.outError("deflateInit failed.");
return false;
}
uint8 *buffer = new uint8[destsize];
//memset(buffer,0,destsize); /* fix umr - burlex */
// set up stream pointers
stream.next_out = (Bytef*)buffer+4;
stream.avail_out = destsize;
stream.next_in = (Bytef*)update_buffer;
stream.avail_in = size;
// call the actual process
if(deflate(&stream, Z_NO_FLUSH) != Z_OK ||
stream.avail_in != 0)
{
sLog.outError("deflate failed.");
delete [] buffer;
return false;
}
// finish the deflate
if(deflate(&stream, Z_FINISH) != Z_STREAM_END)
{
sLog.outError("deflate failed: did not end stream");
delete [] buffer;
return false;
}
// finish up
if(deflateEnd(&stream) != Z_OK)
{
sLog.outError("deflateEnd failed.");
delete [] buffer;
return false;
}
// fill in the full size of the compressed stream
#ifdef USING_BIG_ENDIAN
*(uint32*)&buffer[0] = swap32(size);
#else
*(uint32*)&buffer[0] = size;
#endif
// send it
m_session->OutPacket(SMSG_COMPRESSED_UPDATE_OBJECT, (uint16)stream.total_out + 4, buffer);
// cleanup memory
delete [] buffer;
return true;
}
void Player::ClearAllPendingUpdates()
{
_bufferS.Acquire();
bProcessPending = false;
mUpdateCount = 0;
bUpdateBuffer.clear();
_bufferS.Release();
}
void Player::AddSplinePacket(uint64 guid, ByteBuffer* packet)
{
SplineMap::iterator itr = _splineMap.find(guid);
if(itr != _splineMap.end())
{
delete itr->second;
_splineMap.erase(itr);
}
_splineMap.insert( SplineMap::value_type( guid, packet ) );
}
ByteBuffer* Player::GetAndRemoveSplinePacket(uint64 guid)
{
SplineMap::iterator itr = _splineMap.find(guid);
if(itr != _splineMap.end())
{
ByteBuffer *buf = itr->second;
_splineMap.erase(itr);
return buf;
}
return NULL;
}
void Player::ClearSplinePackets()
{
SplineMap::iterator it2;
for(SplineMap::iterator itr = _splineMap.begin(); itr != _splineMap.end();)
{
it2 = itr;
++itr;
delete it2->second;
_splineMap.erase(it2);
}
_splineMap.clear();
}
bool Player::ExitInstance()
{
if(!m_bgEntryPointX)
return false;
RemoveFromWorld();
SafeTeleport(m_bgEntryPointMap, m_bgEntryPointInstance, LocationVector(
m_bgEntryPointX, m_bgEntryPointY, m_bgEntryPointZ, m_bgEntryPointO));
return true;
}
void Player::SaveEntryPoint(uint32 mapId)
{
if(IS_INSTANCE(GetMapId()))
return; // dont save if we're not on the main continent.
//otherwise we could end up in an endless loop :P
MapInfo * pMapinfo = WorldMapInfoStorage.LookupEntry(mapId);
if(pMapinfo)
{
m_bgEntryPointX = pMapinfo->repopx;
m_bgEntryPointY = pMapinfo->repopy;
m_bgEntryPointZ = pMapinfo->repopz;
m_bgEntryPointO = GetOrientation();
m_bgEntryPointMap = pMapinfo->repopmapid;
m_bgEntryPointInstance = GetInstanceID();
}
else
{
m_bgEntryPointMap = 0;
m_bgEntryPointX = 0;
m_bgEntryPointY = 0;
m_bgEntryPointZ = 0;
m_bgEntryPointO = 0;
m_bgEntryPointInstance = 0;
}
}
void Player::CleanupGossipMenu()
{
if(CurrentGossipMenu)
{
delete CurrentGossipMenu;
CurrentGossipMenu = NULL;
}
}
void Player::Gossip_Complete()
{
GetSession()->OutPacket(SMSG_GOSSIP_COMPLETE, 0, NULL);
CleanupGossipMenu();
}
void Player::CloseGossip()
{
Gossip_Complete();
}
void Player::PrepareQuestMenu(uint64 guid )
{
uint32 TextID = 820;
objmgr.CreateGossipMenuForPlayer(&PlayerTalkClass, guid, TextID, this);
}
void Player::SendGossipMenu( uint32 TitleTextId, uint64 npcGUID )
{
PlayerTalkClass->SetTextID(TitleTextId);
PlayerTalkClass->SendTo(this);
}
QuestStatus Player::GetQuestStatus( uint32 quest_id )
{
uint32 status = sQuestMgr.CalcQuestStatus( this, quest_id);
switch (status)
{
case QMGR_QUEST_NOT_FINISHED: return QUEST_STATUS_INCOMPLETE;
case QMGR_QUEST_FINISHED: return QUEST_STATUS_COMPLETE;
case QMGR_QUEST_NOT_AVAILABLE: return QUEST_STATUS_UNAVAILABLE;
}
return QUEST_STATUS_UNAVAILABLE;
}
void Player::ZoneUpdate(uint32 ZoneId)
{
m_zoneId = ZoneId;
/* how the f*ck is this happening */
if( m_playerInfo == NULL )
{
m_playerInfo = objmgr.GetPlayerInfo(GetLowGUID());
if( m_playerInfo == NULL )
{
m_session->Disconnect();
return;
}
}
m_playerInfo->lastZone = ZoneId;
sHookInterface.OnZone(this, ZoneId);
AreaTable * at = dbcArea.LookupEntry(GetAreaID());
if(at && at->category == AREAC_SANCTUARY || at->AreaFlags & AREA_SANCTUARY)
{
Unit * pUnit = (GetSelection() == 0) ? 0 : (m_mapMgr ? m_mapMgr->GetUnit(GetSelection()) : 0);
if(pUnit && DuelingWith != pUnit)
{
EventAttackStop();
smsg_AttackStop(pUnit);
}
if(m_currentSpell)
{
Unit * target = m_currentSpell->GetUnitTarget();
if(target && target != DuelingWith && target != this)
m_currentSpell->cancel();
}
}
#ifdef OPTIMIZED_PLAYER_SAVING
save_Zone();
#endif
/*std::map<uint32, AreaTable*>::iterator iter = sWorld.mZoneIDToTable.find(ZoneId);
if(iter == sWorld.mZoneIDToTable.end())
return;
AreaTable *p = iter->second;
if(p->AreaId != m_AreaID)
{
m_AreaID = p->AreaId;
UpdatePVPStatus(m_AreaID);
}
sLog.outDetail("ZONE_UPDATE: Player %s entered zone %s", GetName(), sAreaStore.LookupString((int)p->name));*/
}
void Player::SendTradeUpdate()
{
Player * pTarget = GetTradeTarget();
if( !pTarget )
return;
WorldPacket data( SMSG_TRADE_STATUS_EXTENDED, 532 );
/*data << uint8(1);
data << uint32(2) << uint32(2);
data << mTradeGold << uint32(0);*/
data << uint8(1);
data << uint32(0x19);
data << m_tradeSequence;
data << m_tradeSequence++;
data << mTradeGold << uint32(0);
uint8 count = 0;
// Items
for( uint32 Index = 0; Index < 7; ++Index )
{
Item * pItem = mTradeItems[ Index ];
if(pItem != 0)
{
count++;
ItemPrototype * pProto = pItem->GetProto();
ASSERT( pProto != 0 );
data << uint8( Index );
data << pProto->ItemId;
data << pProto->DisplayInfoID;
data << pItem->GetUInt32Value( ITEM_FIELD_STACK_COUNT ); // Amount OK
// Enchantment stuff
data << uint32(0); // unknown
data << pItem->GetUInt64Value( ITEM_FIELD_GIFTCREATOR ); // gift creator OK
data << pItem->GetUInt32Value( ITEM_FIELD_ENCHANTMENT ); // Item Enchantment OK
for( uint8 i = 2; i < 5; i++ ) // Gem enchantments
{
if( pItem->GetEnchantment(i) != NULL && pItem->GetEnchantment(i)->Enchantment != NULL )
data << pItem->GetEnchantment(i)->Enchantment->Id;
else
data << uint32( 0 );
}
data << pItem->GetUInt64Value( ITEM_FIELD_CREATOR ); // item creator OK
data << pItem->GetUInt32Value( ITEM_FIELD_SPELL_CHARGES ); // Spell Charges OK
data << uint32(0); // seems like time stamp or something like that
data << pItem->GetUInt32Value( ITEM_FIELD_RANDOM_PROPERTIES_ID );
data << pProto->LockId; // lock ID OK
data << pItem->GetUInt32Value( ITEM_FIELD_MAXDURABILITY );
data << pItem->GetUInt32Value( ITEM_FIELD_DURABILITY );
}
}
data.resize( 21 + count * 73 );
pTarget->GetSession()->SendPacket(&data);
}
void Player::RequestDuel(Player *pTarget)
{
// We Already Dueling or have already Requested a Duel
if( DuelingWith != NULL )
return;
if( m_duelState != DUEL_STATE_FINISHED )
return;
SetDuelState( DUEL_STATE_REQUESTED );
//Setup Duel
pTarget->DuelingWith = this;
DuelingWith = pTarget;
//Get Flags position
float dist = CalcDistance(pTarget);
dist = dist * 0.5f; //half way
float x = (GetPositionX() + pTarget->GetPositionX()*dist)/(1+dist) + cos(GetOrientation()+(float(M_PI)/2))*2;
float y = (GetPositionY() + pTarget->GetPositionY()*dist)/(1+dist) + sin(GetOrientation()+(float(M_PI)/2))*2;
float z = (GetPositionZ() + pTarget->GetPositionZ()*dist)/(1+dist);
//Create flag/arbiter
GameObject* pGameObj = GetMapMgr()->CreateGameObject(21680);
pGameObj->CreateFromProto(21680,GetMapId(), x, y, z, GetOrientation());
pGameObj->SetInstanceID(GetInstanceID());
//Spawn the Flag
pGameObj->SetUInt64Value(OBJECT_FIELD_CREATED_BY, GetGUID());
pGameObj->SetUInt32Value(GAMEOBJECT_FACTION, GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE));
pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, GetUInt32Value(UNIT_FIELD_LEVEL));
//Assign the Flag
SetUInt64Value(PLAYER_DUEL_ARBITER,pGameObj->GetGUID());
pTarget->SetUInt64Value(PLAYER_DUEL_ARBITER,pGameObj->GetGUID());
pGameObj->PushToWorld(m_mapMgr);
WorldPacket data(SMSG_DUEL_REQUESTED, 16);
data << pGameObj->GetGUID();
data << GetGUID();
pTarget->GetSession()->SendPacket(&data);
}
void Player::DuelCountdown()
{
if( DuelingWith == NULL )
return;
m_duelCountdownTimer -= 1000;
if( m_duelCountdownTimer < 0 )
m_duelCountdownTimer = 0;
if( m_duelCountdownTimer == 0 )
{
// Start Duel.
SetUInt32Value( UNIT_FIELD_POWER2, 0 );
DuelingWith->SetUInt32Value( UNIT_FIELD_POWER2, 0 );
//Give the players a Team
DuelingWith->SetUInt32Value( PLAYER_DUEL_TEAM, 1 ); // Duel Requester
SetUInt32Value( PLAYER_DUEL_TEAM, 2 );
SetDuelState( DUEL_STATE_STARTED );
DuelingWith->SetDuelState( DUEL_STATE_STARTED );
sEventMgr.AddEvent( this, &Player::DuelBoundaryTest, EVENT_PLAYER_DUEL_BOUNDARY_CHECK, 500, 0, 0 );
sEventMgr.AddEvent( DuelingWith, &Player::DuelBoundaryTest, EVENT_PLAYER_DUEL_BOUNDARY_CHECK, 500, 0, 0 );
}
}
void Player::DuelBoundaryTest()
{
//check if in bounds
if(!IsInWorld())
return;
GameObject * pGameObject = GetMapMgr()->GetGameObject(GetUInt32Value(PLAYER_DUEL_ARBITER));
if(!pGameObject)
{
EndDuel(DUEL_WINNER_RETREAT);
return;
}
float Dist = CalcDistance((Object*)pGameObject);
if(Dist > 75.0f)
{
// Out of bounds
if(m_duelStatus == DUEL_STATUS_OUTOFBOUNDS)
{
// we already know, decrease timer by 500
m_duelCountdownTimer -= 500;
if(m_duelCountdownTimer == 0)
{
// Times up :p
DuelingWith->EndDuel(DUEL_WINNER_RETREAT);
}
}
else
{
// we just went out of bounds
// set timer
m_duelCountdownTimer = 10000;
// let us know
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(m_duelCountdownTimer);
m_session->OutPacket(SMSG_DUEL_OUTOFBOUNDS, 4, &swapped);
#else
m_session->OutPacket(SMSG_DUEL_OUTOFBOUNDS, 4, &m_duelCountdownTimer);
#endif
m_duelStatus = DUEL_STATUS_OUTOFBOUNDS;
}
}
else
{
// we're in range
if(m_duelStatus == DUEL_STATUS_OUTOFBOUNDS)
{
// just came back in range
m_session->OutPacket(SMSG_DUEL_INBOUNDS);
m_duelStatus = DUEL_STATUS_INBOUNDS;
}
}
}
void Player::EndDuel(uint8 WinCondition)
{
if( m_duelState == DUEL_STATE_FINISHED )
{
//if loggingout player requested a duel then we have to make the cleanups
if( GetUInt32Value(PLAYER_DUEL_ARBITER) )
{
GameObject* arbiter = m_mapMgr ? GetMapMgr()->GetGameObject(GetUInt32Value(PLAYER_DUEL_ARBITER)) : 0;
if( arbiter != NULL )
{
arbiter->RemoveFromWorld( true );
delete arbiter;
}
//we do not wish to lock the other player in duel state
DuelingWith->SetUInt64Value( PLAYER_DUEL_ARBITER, 0 );
DuelingWith->SetUInt32Value( PLAYER_DUEL_TEAM, 0 );
SetUInt64Value( PLAYER_DUEL_ARBITER, 0 );
SetUInt32Value( PLAYER_DUEL_TEAM, 0 );
sEventMgr.RemoveEvents( DuelingWith, EVENT_PLAYER_DUEL_BOUNDARY_CHECK );
sEventMgr.RemoveEvents( DuelingWith, EVENT_PLAYER_DUEL_COUNTDOWN );
DuelingWith->DuelingWith = NULL;
DuelingWith = NULL;
//the duel did not start so we are not in combat or cast any spells yet.
}
return;
}
// Remove the events
sEventMgr.RemoveEvents( this, EVENT_PLAYER_DUEL_COUNTDOWN );
sEventMgr.RemoveEvents( this, EVENT_PLAYER_DUEL_BOUNDARY_CHECK );
for( uint32 x = MAX_POSITIVE_AURAS_EXTEDED_START; x < MAX_POSITIVE_AURAS_EXTEDED_END; ++x )
{
if( m_auras[x] == NULL )
continue;
if( m_auras[x]->WasCastInDuel() )
m_auras[x]->Remove();
}
m_duelState = DUEL_STATE_FINISHED;
if( DuelingWith == NULL )
return;
sEventMgr.RemoveEvents( DuelingWith, EVENT_PLAYER_DUEL_BOUNDARY_CHECK );
sEventMgr.RemoveEvents( DuelingWith, EVENT_PLAYER_DUEL_COUNTDOWN );
// spells waiting to hit
sEventMgr.RemoveEvents(this, EVENT_SPELL_DAMAGE_HIT);
for( uint32 x = MAX_POSITIVE_AURAS_EXTEDED_START; x < MAX_POSITIVE_AURAS_EXTEDED_END; ++x )
{
if( DuelingWith->m_auras[x] == NULL )
continue;
if( DuelingWith->m_auras[x]->WasCastInDuel() )
DuelingWith->m_auras[x]->Remove();
}
DuelingWith->m_duelState = DUEL_STATE_FINISHED;
//Announce Winner
WorldPacket data( SMSG_DUEL_WINNER, 500 );
data << uint8( WinCondition );
data << GetName() << DuelingWith->GetName();
SendMessageToSet( &data, true );
data.Initialize( SMSG_DUEL_COMPLETE );
data << uint8( 1 );
SendMessageToSet( &data, true );
//Clear Duel Related Stuff
GameObject* arbiter = m_mapMgr ? GetMapMgr()->GetGameObject(GetUInt32Value(PLAYER_DUEL_ARBITER)) : 0;
if( arbiter != NULL )
{
arbiter->RemoveFromWorld( true );
delete arbiter;
}
SetUInt64Value( PLAYER_DUEL_ARBITER, 0 );
DuelingWith->SetUInt64Value( PLAYER_DUEL_ARBITER, 0 );
SetUInt32Value( PLAYER_DUEL_TEAM, 0 );
DuelingWith->SetUInt32Value( PLAYER_DUEL_TEAM, 0 );
EventAttackStop();
DuelingWith->EventAttackStop();
// Call off pet
if( this->GetSummon() != NULL )
{
this->GetSummon()->CombatStatus.Vanished();
this->GetSummon()->GetAIInterface()->SetUnitToFollow( this );
this->GetSummon()->GetAIInterface()->HandleEvent( EVENT_FOLLOWOWNER, this->GetSummon(), 0 );
this->GetSummon()->GetAIInterface()->WipeTargetList();
}
// removing auras that kills players after if low HP
/*RemoveNegativeAuras(); NOT NEEDED. External targets can always gank both duelers with DoTs. :D
DuelingWith->RemoveNegativeAuras();*/
//Stop Players attacking so they don't kill the other player
m_session->OutPacket( SMSG_CANCEL_COMBAT );
DuelingWith->m_session->OutPacket( SMSG_CANCEL_COMBAT );
smsg_AttackStop( DuelingWith );
DuelingWith->smsg_AttackStop( this );
DuelingWith->m_duelCountdownTimer = 0;
m_duelCountdownTimer = 0;
DuelingWith->DuelingWith = NULL;
DuelingWith = NULL;
}
void Player::StopMirrorTimer(uint32 Type)
{
#ifdef USING_BIG_ENDIAN
uint32 swapped = swap32(Type);
m_session->OutPacket(SMSG_STOP_MIRROR_TIMER, 4, &swapped);
#else
m_session->OutPacket(SMSG_STOP_MIRROR_TIMER, 4, &Type);
#endif
}
void Player::EventTeleport(uint32 mapid, float x, float y, float z)
{
SafeTeleport(mapid, 0, LocationVector(x, y, z));
}
void Player::EventTeleportTaxi(uint32 mapid, float x, float y, float z)
{
if(mapid == 530 && !m_session->HasFlag(ACCOUNT_FLAG_XPACK_01))
{
WorldPacket msg(SMSG_BROADCAST_MSG, 50);
msg << uint32(3) << "You must have The Burning Crusade Expansion to access this content." << uint8(0);
m_session->SendPacket(&msg);
RepopAtGraveyard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId());
return;
}
_Relocate(mapid, LocationVector(x, y, z), (mapid==GetMapId() ? false:true), true, 0);
ForceZoneUpdate();
}
void Player::ApplyLevelInfo(LevelInfo* Info, uint32 Level)
{
ASSERT(Info != NULL);
// Apply level
SetUInt32Value(UNIT_FIELD_LEVEL, Level);
// Set next level conditions
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, Info->XPToNextLevel);
// Set stats
for(uint32 i = 0; i < 5; ++i)
{
BaseStats[i] = Info->Stat[i];
CalcStat(i);
}
// Set health / mana
SetUInt32Value(UNIT_FIELD_HEALTH, Info->HP);
SetUInt32Value(UNIT_FIELD_MAXHEALTH, Info->HP);
SetUInt32Value(UNIT_FIELD_POWER1, Info->Mana);
SetUInt32Value(UNIT_FIELD_MAXPOWER1, Info->Mana);
// Calculate talentpoints
uint32 TalentPoints = 0;
if(Level >= 10)
TalentPoints = Level - 9;
SetUInt32Value(PLAYER_CHARACTER_POINTS1, TalentPoints);
// Set base fields
SetUInt32Value(UNIT_FIELD_BASE_HEALTH, Info->HP);
SetUInt32Value(UNIT_FIELD_BASE_MANA, Info->Mana);
_UpdateMaxSkillCounts();
UpdateStats();
//UpdateChances();
m_playerInfo->lastLevel = Level;
sLog.outDetail("Player %s set parameters to level %u", GetName(), Level);
}
void Player::BroadcastMessage(const char* Format, ...)
{
va_list l;
va_start(l, Format);
char Message[1024];
vsnprintf(Message, 1024, Format, l);
va_end(l);
WorldPacket * data = sChatHandler.FillSystemMessageData(Message);
m_session->SendPacket(data);
delete data;
}
/*
const double BaseRating []= {
2.5,//weapon_skill_ranged!!!!
1.5,//defense=comba_r_1
12,//dodge
20,//parry=3
5,//block=4
10,//melee hit
10,//ranged hit
8,//spell hit=7
14,//melee critical strike=8
14,//ranged critical strike=9
14,//spell critical strike=10
0,//
0,
0,
25,//resilience=14
25,//resil .... meaning unknown
25,//resil .... meaning unknown
10,//MELEE_HASTE_RATING=17
10,//RANGED_HASTE_RATING=18
10,//spell_haste_rating = 19???
2.5,//melee weapon skill==20
2.5,//melee second hand=21
};
*/
float Player::CalcRating( uint32 index )
{
uint32 relative_index = index - (PLAYER_FIELD_COMBAT_RATING_1);
float rating = float(m_uint32Values[index]);
/*if( relative_index <= 10 || ( relative_index >= 14 && relative_index <= 21 ) )
{
double rating = (double)m_uint32Values[index];
int level = getLevel();
if( level < 10 )//this is not dirty fix -> it is from wowwiki
level = 10;
double cost;
if( level < 60 )
cost = ( double( level ) - 8.0 ) / 52.0;
else
cost = 82.0 / ( 262.0 - 3.0 * double( level ) );
return float( rating / ( BaseRating[relative_index] * cost ) );
}
else
return 0.0f;*/
uint32 level = m_uint32Values[UNIT_FIELD_LEVEL];
if( level > 100 )
level = 100;
CombatRatingDBC * pDBCEntry = dbcCombatRating.LookupEntryForced( relative_index * 100 + level - 1 );
if( pDBCEntry == NULL )
return rating;
else
return (rating / pDBCEntry->val);
}
bool Player::SafeTeleport(uint32 MapID, uint32 InstanceID, float X, float Y, float Z, float O)
{
return SafeTeleport(MapID, InstanceID, LocationVector(X, Y, Z, O));
}
bool Player::SafeTeleport(uint32 MapID, uint32 InstanceID, const LocationVector & vec)
{
SpeedCheatDelay(10000);
if ( GetTaxiState() )
{
sEventMgr.RemoveEvents( this, EVENT_PLAYER_TELEPORT );
sEventMgr.RemoveEvents( this, EVENT_PLAYER_TAXI_DISMOUNT );
sEventMgr.RemoveEvents( this, EVENT_PLAYER_TAXI_INTERPOLATE );
SetTaxiState( false );
SetTaxiPath( NULL );
UnSetTaxiPos();
m_taxi_ride_time = 0;
SetUInt32Value( UNIT_FIELD_MOUNTDISPLAYID , 0 );
RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_MOUNTED_TAXI );
RemoveFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER );
SetPlayerSpeed( RUN, m_runSpeed );
}
if ( m_TransporterGUID )
{
Transporter * pTrans = objmgr.GetTransporter( GUID_LOPART( m_TransporterGUID ) );
if ( pTrans && !m_lockTransportVariables )
{
pTrans->RemovePlayer( this );
m_CurrentTransporter = NULL;
m_TransporterGUID = 0;
}
}
#ifdef CLUSTERING
/* Clustering Version */
MapInfo * mi = WorldMapInfoStorage.LookupEntry(MapID);
// Lookup map info
if(mi && mi->flags & WMI_INSTANCE_XPACK_01 && !m_session->HasFlag(ACCOUNT_FLAG_XPACK_01))
{
WorldPacket msg(SMSG_BROADCAST_MSG, 50);
msg << uint32(3) << "You must have The Burning Crusade Expansion to access this content." << uint8(0);
m_session->SendPacket(&msg);
return false;
}
uint32 instance_id;
bool map_change = false;
if(mi && mi->type == 0)
{
// single instance map
if(MapID != m_mapId)
{
map_change = true;
instance_id = 0;
}
}
else
{
// instanced map
if(InstanceID != GetInstanceID())
map_change = true;
instance_id = InstanceID;
}
if(map_change)
{
WorldPacket data(SMSG_TRANSFER_PENDING, 4);
data << uint32(MapID);
GetSession()->SendPacket(&data);
sClusterInterface.RequestTransfer(this, MapID, instance_id, vec);
return;
}
m_sentTeleportPosition = vec;
SetPosition(vec);
ResetHeartbeatCoords();
WorldPacket * data = BuildTeleportAckMsg(vec);
m_session->SendPacket(data);
delete data;
#else
/* Normal Version */
bool instance = false;
MapInfo * mi = WorldMapInfoStorage.LookupEntry(MapID);
if(InstanceID && (uint32)m_instanceId != InstanceID)
{
instance = true;
this->SetInstanceID(InstanceID);
}
else if(m_mapId != MapID)
{
instance = true;
}
if (sWorld.Collision == 0) {
// if we are mounted remove it
if( m_MountSpellId )
RemoveAura( m_MountSpellId );
}
// make sure player does not drown when teleporting from under water
if (m_UnderwaterState & UNDERWATERSTATE_UNDERWATER)
m_UnderwaterState &= ~UNDERWATERSTATE_UNDERWATER;
if(flying_aura && MapID != 530)
{
RemoveAura(flying_aura);
flying_aura = 0;
}
// Lookup map info
if(mi && mi->flags & WMI_INSTANCE_XPACK_01 && !m_session->HasFlag(ACCOUNT_FLAG_XPACK_01))
{
WorldPacket msg(SMSG_BROADCAST_MSG, 50);
msg << uint32(3) << "You must have The Burning Crusade Expansion to access this content." << uint8(0);
m_session->SendPacket(&msg);
return false;
}
// cebernic: cleanup before teleport
// seems BFleaveOpcode was breakdown,that will be causing big BUG with player leaving from the BG
// now this much better:D RemoveAura & BG_DESERTER going to well as you go out from BG.
if( m_bg && m_bg->GetMapMgr() && GetMapMgr()->GetMapInfo()->mapid != MapID )
{
m_bg->RemovePlayer(this, false);
m_bg = NULL;
}
_Relocate(MapID, vec, true, instance, InstanceID);
SpeedCheatReset();
ForceZoneUpdate();
return true;
#endif
}
void Player::ForceZoneUpdate()
{
if(!GetMapMgr()) return;
uint16 areaId = GetMapMgr()->GetAreaID(GetPositionX(), GetPositionY());
AreaTable * at = dbcArea.LookupEntry(areaId);
if(!at) return;
if(at->ZoneId && at->ZoneId != m_zoneId)
ZoneUpdate(at->ZoneId);
}
void Player::SafeTeleport(MapMgr * mgr, const LocationVector & vec)
{
if( mgr == NULL )
return;
SpeedCheatDelay(10000);
if(flying_aura && mgr->GetMapId()!=530) {
RemoveAura(flying_aura);
flying_aura=0;
}
if(IsInWorld())
RemoveFromWorld();
m_mapId = mgr->GetMapId();
m_instanceId = mgr->GetInstanceID();
WorldPacket data(SMSG_TRANSFER_PENDING, 20);
data << mgr->GetMapId();
GetSession()->SendPacket(&data);
data.Initialize(SMSG_NEW_WORLD);
data << mgr->GetMapId() << vec << vec.o;
GetSession()->SendPacket(&data);
SetPlayerStatus(TRANSFER_PENDING);
m_sentTeleportPosition = vec;
SetPosition(vec);
SpeedCheatReset();
ForceZoneUpdate();
}
void Player::SetGuildId(uint32 guildId)
{
if(IsInWorld())
{
const uint32 field = PLAYER_GUILDID;
sEventMgr.AddEvent(((Object*)this), &Object::EventSetUInt32Value, field, guildId, EVENT_PLAYER_SEND_PACKET, 1,
1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
else
{
SetUInt32Value(PLAYER_GUILDID,guildId);
}
}
void Player::SetGuildRank(uint32 guildRank)
{
if(IsInWorld())
{
const uint32 field = PLAYER_GUILDRANK;
sEventMgr.AddEvent(((Object*)this), &Object::EventSetUInt32Value, field, guildRank, EVENT_PLAYER_SEND_PACKET, 1,
1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
else
{
SetUInt32Value(PLAYER_GUILDRANK,guildRank);
}
}
void Player::UpdatePvPArea()
{
AreaTable * at = dbcArea.LookupEntry(m_AreaID);
if(at == 0)
return;
#ifdef PVP_REALM_MEANS_CONSTANT_PVP
//zack : This might be huge crap. I have no idea how it is on blizz but i think a pvp realm should alow me to gank anybody anywhere :(
if(sWorld.GetRealmType() == REALM_PVP)
{
SetPvPFlag();
return;
}
#endif
// This is where all the magic happens :P
if((at->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || (at->category == AREAC_HORDE_TERRITORY && GetTeam() == 1))
{
if(!HasFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE) && !m_pvpTimer)
{
// I'm flagged and I just walked into a zone of my type. Start the 5min counter.
ResetPvPTimer();
}
return;
}
else
{
//Enemy city check
if(at->AreaFlags & AREA_CITY_AREA || at->AreaFlags & AREA_CITY)
{
if((at->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 1) || (at->category == AREAC_HORDE_TERRITORY && GetTeam() == 0))
{
if(!IsPvPFlagged()) SetPvPFlag();
StopPvPTimer();
return;
}
}
//fix for zone areas.
if(at->ZoneId)
{
AreaTable * at2 = dbcArea.LookupEntry(at->ZoneId);
if(at2 && (at2->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || at2 && (at2->category == AREAC_HORDE_TERRITORY && GetTeam() == 1))
{
if(!HasFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE) && !m_pvpTimer)
{
// I'm flagged and I just walked into a zone of my type. Start the 5min counter.
ResetPvPTimer();
}
return;
}
//enemy territory check
if(at2 && at2->AreaFlags & AREA_CITY_AREA || at2 && at2->AreaFlags & AREA_CITY)
{
if(at2 && (at2->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 1) || at2 && (at2->category == AREAC_HORDE_TERRITORY && GetTeam() == 0))
{
if(!IsPvPFlagged()) SetPvPFlag();
StopPvPTimer();
return;
}
}
}
// I just walked into either an enemies town, or a contested zone.
// Force flag me if i'm not already.
if(at->category == AREAC_SANCTUARY || at->AreaFlags & AREA_SANCTUARY)
{
if(IsPvPFlagged()) RemovePvPFlag();
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_FREE_FOR_ALL_PVP);
StopPvPTimer();
}
else
{
//contested territory
if(sWorld.GetRealmType() == REALM_PVP)
{
//automaticaly sets pvp flag on contested territorys.
if(!IsPvPFlagged()) SetPvPFlag();
StopPvPTimer();
}
if(sWorld.GetRealmType() == REALM_PVE)
{
if(HasFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE))
{
if(!IsPvPFlagged()) SetPvPFlag();
}
else if(!HasFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE) && IsPvPFlagged() && !m_pvpTimer)
{
ResetPvPTimer();
}
}
if(at->AreaFlags & AREA_PVP_ARENA) /* ffa pvp arenas will come later */
{
if(!IsPvPFlagged()) SetPvPFlag();
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_FREE_FOR_ALL_PVP);
}
else
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_FREE_FOR_ALL_PVP);
}
}
}
}
void Player::BuildFlagUpdateForNonGroupSet(uint32 index, uint32 flag)
{
Object *curObj;
this->AquireInrangeLock(); //make sure to release lock before exit function !
for (Object::InRangeSet::iterator iter = GetInRangeSetBegin(); iter != GetInRangeSetEnd();)
{
curObj = *iter;
iter++;
if(curObj->IsPlayer())
{
Group* pGroup = static_cast< Player* >( curObj )->GetGroup();
if( pGroup != NULL && pGroup == GetGroup())
{
//TODO: huh? if this is unneeded change the if to the inverse and don't waste jmp space
}
else
{
BuildFieldUpdatePacket( static_cast< Player* >( curObj ), index, flag );
}
}
}
this->ReleaseInrangeLock();
}
void Player::LoginPvPSetup()
{
// Make sure we know our area ID.
_EventExploration();
AreaTable * at = dbcArea.LookupEntry( ( m_AreaID != 0 ) ? m_AreaID : m_zoneId );
if ( at != NULL && isAlive() && ( at->category == AREAC_CONTESTED || ( GetTeam() == 0 && at->category == AREAC_HORDE_TERRITORY ) || ( GetTeam() == 1 && at->category == AREAC_ALLIANCE_TERRITORY ) ) )
CastSpell(this, PLAYER_HONORLESS_TARGET_SPELL, true);
#ifdef PVP_REALM_MEANS_CONSTANT_PVP
//zack : This might be huge crap. I have no idea how it is on blizz but i think a pvp realm should alow me to gank anybody anywhere :(
if(sWorld.GetRealmType() == REALM_PVP)
{
SetPvPFlag();
return;
}
#endif
}
void Player::PvPToggle()
{
if(sWorld.GetRealmType() == REALM_PVE)
{
if(m_pvpTimer > 0)
{
// Means that we typed /pvp while we were "cooling down". Stop the timer.
StopPvPTimer();
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
if(!IsPvPFlagged()) SetPvPFlag();
}
else
{
if(IsPvPFlagged())
{
AreaTable * at = dbcArea.LookupEntry(m_AreaID);
if(at && at->AreaFlags & AREA_CITY_AREA || at && at->AreaFlags & AREA_CITY)
{
if(at && (at->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 1) || at && (at->category == AREAC_HORDE_TERRITORY && GetTeam() == 0))
{
}
else
{
// Start the "cooldown" timer.
ResetPvPTimer();
}
}
else
{
// Start the "cooldown" timer.
ResetPvPTimer();
}
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
}
else
{
// Move into PvP state.
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
StopPvPTimer();
SetPvPFlag();
}
}
}
#ifdef PVP_REALM_MEANS_CONSTANT_PVP
//zack : This might be huge crap. I have no idea how it is on blizz but i think a pvp realm should alow me to gank anybody anywhere :(
else if(sWorld.GetRealmType() == REALM_PVP)
{
SetPvPFlag();
return;
}
#else
else if(sWorld.GetRealmType() == REALM_PVP)
{
AreaTable * at = dbcArea.LookupEntry(m_AreaID);
if(at == 0)
return;
// This is where all the magic happens :P
if((at->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || (at->category == AREAC_HORDE_TERRITORY && GetTeam() == 1))
{
if(m_pvpTimer > 0)
{
// Means that we typed /pvp while we were "cooling down". Stop the timer.
StopPvPTimer();
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
if(!IsPvPFlagged()) SetPvPFlag();
}
else
{
if(IsPvPFlagged())
{
// Start the "cooldown" timer.
ResetPvPTimer();
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
}
else
{
// Move into PvP state.
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
StopPvPTimer();
SetPvPFlag();
}
}
}
else
{
if(at->ZoneId)
{
AreaTable * at2 = dbcArea.LookupEntry(at->ZoneId);
if(at2 && (at2->category == AREAC_ALLIANCE_TERRITORY && GetTeam() == 0) || at2 && (at2->category == AREAC_HORDE_TERRITORY && GetTeam() == 1))
{
if(m_pvpTimer > 0)
{
// Means that we typed /pvp while we were "cooling down". Stop the timer.
StopPvPTimer();
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
if(!IsPvPFlagged()) SetPvPFlag();
}
else
{
if(IsPvPFlagged())
{
// Start the "cooldown" timer.
ResetPvPTimer();
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
}
else
{
// Move into PvP state.
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
StopPvPTimer();
SetPvPFlag();
}
}
return;
}
}
if(!HasFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE))
SetFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
else
{
RemoveFlag(PLAYER_FLAGS, PLAYER_FLAG_PVP_TOGGLE);
}
}
}
#endif
}
void Player::ResetPvPTimer()
{
m_pvpTimer = sWorld.getIntRate(INTRATE_PVPTIMER);
}
void Player::CalculateBaseStats()
{
if(!lvlinfo) return;
memcpy(BaseStats, lvlinfo->Stat, sizeof(uint32) * 5);
LevelInfo * levelone = objmgr.GetLevelInfo(this->getRace(),this->getClass(),1);
if (levelone == NULL)
{
sLog.outError("%s (%d): NULL pointer", __FUNCTION__, __LINE__);
return;
}
SetUInt32Value(UNIT_FIELD_MAXHEALTH, lvlinfo->HP);
SetUInt32Value(UNIT_FIELD_BASE_HEALTH, lvlinfo->HP - (lvlinfo->Stat[2]-levelone->Stat[2])*10);
SetUInt32Value(PLAYER_NEXT_LEVEL_XP, lvlinfo->XPToNextLevel);
if(GetPowerType() == POWER_TYPE_MANA)
{
SetUInt32Value(UNIT_FIELD_BASE_MANA, lvlinfo->Mana - (lvlinfo->Stat[3]-levelone->Stat[3])*15);
SetUInt32Value(UNIT_FIELD_MAXPOWER1, lvlinfo->Mana);
}
}
void Player::CompleteLoading()
{
// cast passive initial spells -- grep note: these shouldnt require plyr to be in world
SpellSet::iterator itr;
SpellEntry *info;
SpellCastTargets targets;
targets.m_unitTarget = this->GetGUID();
targets.m_targetMask = 0x2;
// warrior has to have battle stance
if( getClass() == WARRIOR )
{
// battle stance passive
CastSpell(this, dbcSpell.LookupEntry(2457), true);
}
for (itr = mSpells.begin(); itr != mSpells.end(); ++itr)
{
info = dbcSpell.LookupEntry(*itr);
if( info
&& (info->Attributes & ATTRIBUTES_PASSIVE) // passive
&& !( info->c_is_flags & SPELL_FLAG_IS_EXPIREING_WITH_PET ) //on pet summon talents
)
{
if( info->RequiredShapeShift )
{
if( !( ((uint32)1 << (GetShapeShift()-1)) & info->RequiredShapeShift ) )
continue;
}
Spell * spell=SpellPool.PooledNew();
spell->Init(this,info,true,NULL);
spell->prepare(&targets);
}
}
std::list<LoginAura>::iterator i = loginauras.begin();
for ( ; i != loginauras.end(); i++ )
{
//check if we already have this aura
// if(this->HasActiveAura((*i).id))
// continue;
//how many times do we intend to put this oura on us
/* uint32 count_appearence=0;
std::list<LoginAura>::iterator i2 = i;
for(;i2!=loginauras.end();i2++)
if((*i).id==(*i2).id)
{
count_appearence++;
}
*/
SpellEntry * sp = dbcSpell.LookupEntry((*i).id);
if ( sp->c_is_flags & SPELL_FLAG_IS_EXPIREING_WITH_PET )
continue; //do not load auras that only exist while pet exist. We should recast these when pet is created anyway
Aura * aura = AuraPool.PooledNew();
aura->Init(sp,(*i).dur,this,this);
//if ( !(*i).positive ) // do we need this? - vojta
// aura->SetNegative();
for ( uint32 x = 0; x < 3; x++ )
{
if ( sp->Effect[x]==SPELL_EFFECT_APPLY_AURA )
{
aura->AddMod( sp->EffectApplyAuraName[x], sp->EffectBasePoints[x]+1, sp->EffectMiscValue[x], x );
}
}
if ( sp->procCharges > 0 && (*i).charges > 0 )
{
Aura * a = NULL;
for ( uint32 x = 0; x < (*i).charges - 1; x++ )
{
a = AuraPool.PooledNew();
a->Init( sp, (*i).dur, this, this );
this->AddAura( a );
a = NULL;
}
if ( m_chargeSpells.find( sp->Id ) == m_chargeSpells.end() && !( sp->procFlags & PROC_REMOVEONUSE ) )
{
SpellCharge charge;
if ( sp->proc_interval == 0 )
charge.count = (*i).charges;
else
charge.count = sp->procCharges;
charge.spellId = sp->Id;
charge.ProcFlag = sp->procFlags;
charge.lastproc = 0;
m_chargeSpells.insert( make_pair( sp->Id , charge ) );
}
}
this->AddAura( aura );
//Somehow we should restore number of appearence. Right now i have no idea how :(
// if(count_appearence>1)
// this->AddAuraVisual((*i).id,count_appearence-1,a->IsPositive());
}
// this needs to be after the cast of passive spells, because it will cast ghost form, after the remove making it in ghost alive, if no corpse.
//death system checkout
if(GetUInt32Value(UNIT_FIELD_HEALTH) <= 0 && !HasFlag(PLAYER_FLAGS, PLAYER_FLAG_DEATH_WORLD_ENABLE))
{
setDeathState(CORPSE);
}
else if(HasFlag(PLAYER_FLAGS, PLAYER_FLAG_DEATH_WORLD_ENABLE))
{
// Check if we have an existing corpse.
Corpse * corpse = objmgr.GetCorpseByOwner(GetLowGUID());
if(corpse == 0)
{
sEventMgr.AddEvent(this, &Player::RepopAtGraveyard, GetPositionX(),GetPositionY(),GetPositionZ(), GetMapId(), EVENT_PLAYER_CHECKFORCHEATS, 1000, 1,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
else
{
// Set proper deathstate
setDeathState(CORPSE);
}
}
if( isDead() )
{
if ( myCorpse!=NULL ) {
// cebernic: tempfix. This send a counter for player with just logging in.
// TODO: counter will be follow with death time.
myCorpse->ResetDeathClock();
WorldPacket SendCounter( SMSG_CORPSE_RECLAIM_DELAY, 4 );
SendCounter << (uint32)( CORPSE_RECLAIM_TIME_MS );
GetSession()->SendPacket( &SendCounter );
}
//RepopRequestedPlayer();
//sEventMgr.AddEvent(this, &Player::RepopRequestedPlayer, EVENT_PLAYER_CHECKFORCHEATS, 2000, 1,EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
}
if(iActivePet)
SpawnPet(iActivePet); // cebernic in OA: only spawn if >0
// useless logon spell
Spell *logonspell = SpellPool.PooledNew();
logonspell->Init(this, dbcSpell.LookupEntry(836), false, NULL);
logonspell->prepare(&targets);
// Banned
if(IsBanned())
{
Kick(10000);
BroadcastMessage("This character is not allowed to play.");
BroadcastMessage("You have been banned for: %s", GetBanReason().c_str());
}
if(m_playerInfo->m_Group)
{
sEventMgr.AddEvent(this, &Player::EventGroupFullUpdate, EVENT_UNK, 100, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
//m_playerInfo->m_Group->Update();
}
if(raidgrouponlysent)
{
WorldPacket data2(SMSG_RAID_GROUP_ONLY, 8);
data2 << uint32(0xFFFFFFFF) << uint32(0);
GetSession()->SendPacket(&data2);
raidgrouponlysent=false;
}
sInstanceMgr.BuildSavedInstancesForPlayer(this);
CombatStatus.UpdateFlag();
}
void Player::OnWorldPortAck()
{
//only rezz if player is porting to a instance portal
MapInfo *pMapinfo = WorldMapInfoStorage.LookupEntry(GetMapId());
if(isDead())
{
if(pMapinfo)
{
if(pMapinfo->type != INSTANCE_NULL)
{
// resurrector = 0; // ceberwow: This should be seriously BUG.It makes player statz stackable.
ResurrectPlayer();
}
}
}
if(pMapinfo)
{
WorldPacket data(4);
if(pMapinfo->HasFlag(WMI_INSTANCE_WELCOME) && GetMapMgr())
{
std::string welcome_msg;
welcome_msg = string(GetSession()->LocalizedWorldSrv(62))+" ";
welcome_msg += string(GetSession()->LocalizedMapName(pMapinfo->mapid));
welcome_msg += ". ";
if(pMapinfo->type != INSTANCE_NONRAID && !(pMapinfo->type == INSTANCE_MULTIMODE && iInstanceType >= MODE_HEROIC) && m_mapMgr->pInstance)
{
/*welcome_msg += "This instance is scheduled to reset on ";
welcome_msg += asctime(localtime(&m_mapMgr->pInstance->m_expiration));*/
welcome_msg += string(GetSession()->LocalizedWorldSrv(66))+" ";
welcome_msg += ConvertTimeStampToDataTime((uint32)m_mapMgr->pInstance->m_expiration);
}
sChatHandler.SystemMessage(m_session, welcome_msg.c_str());
}
}
SpeedCheatReset();
}
void Player::ModifyBonuses( uint32 type, int32 val, bool apply )
{
// Added some updateXXXX calls so when an item modifies a stat they get updated
// also since this is used by auras now it will handle it for those
int32 _val = val;
if( !apply )
val = -val;
switch ( type )
{
case POWER:
{
ModUnsigned32Value( UNIT_FIELD_MAXPOWER1, val );
m_manafromitems += val;
}break;
case HEALTH:
{
ModUnsigned32Value( UNIT_FIELD_MAXHEALTH, val );
m_healthfromitems += val;
}break;
case AGILITY: //modify agility
case STRENGTH: //modify strength
case INTELLECT: //modify intellect
case SPIRIT: //modify spirit
case STAMINA: //modify stamina
{
uint8 convert[] = {1, 0, 3, 4, 2};
if( _val > 0 )
FlatStatModPos[ convert[ type - 3 ] ] += val;
else
FlatStatModNeg[ convert[ type - 3 ] ] -= val;
CalcStat( convert[ type - 3 ] );
}break;
case WEAPON_SKILL_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_SKILL, val ); // ranged
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_MAIN_HAND_SKILL, val ); // melee main hand
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_OFF_HAND_SKILL, val ); // melee off hand
}break;
case DEFENSE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_DEFENCE, val );
}break;
case DODGE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_DODGE, val );
}break;
case PARRY_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_PARRY, val );
}break;
case SHIELD_BLOCK_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_BLOCK, val );
}break;
case MELEE_HIT_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_HIT, val );
}break;
case RANGED_HIT_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_HIT, val );
}break;
case SPELL_HIT_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_SPELL_HIT, val );
}break;
case MELEE_CRITICAL_STRIKE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_CRIT, val );
}break;
case RANGED_CRITICAL_STRIKE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_CRIT, val );
}break;
case SPELL_CRITICAL_STRIKE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_SPELL_CRIT, val );
}break;
case MELEE_HIT_AVOIDANCE_RATING:
{
}break;
case RANGED_HIT_AVOIDANCE_RATING:
{
}break;
case SPELL_HIT_AVOIDANCE_RATING:
{
}break;
case MELEE_CRITICAL_AVOIDANCE_RATING:
{
}break;
case RANGED_CRITICAL_AVOIDANCE_RATING:
{
}break;
case SPELL_CRITICAL_AVOIDANCE_RATING:
{
}break;
case MELEE_HASTE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_HASTE, val );//melee
}break;
case RANGED_HASTE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_HASTE, val );//ranged
}break;
case SPELL_HASTE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_SPELL_HASTE, val );//spell
}break;
case HIT_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_HIT, val );//melee
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_HIT, val );//ranged
// maybe should do spell here? (7)
}break;
case CRITICAL_STRIKE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_CRIT, val );//melee
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_CRIT, val );//ranged
// maybe should do spell here? (10)
}break;
case HIT_AVOIDANCE_RATING:// this is guessed based on layout of other fields
{
//ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_HIT_AVOIDANCE, val );//melee
//ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_HIT_AVOIDANCE, val );//ranged
//ModUnsigned32Value( PLAYER_RATING_MODIFIER_SPELL_HIT_AVOIDANCE, val );//spell
}break;
case EXPERTISE_RATING:
case EXPERTISE_RATING_2:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_EXPERTISE, val );
ModUnsigned32Value( PLAYER_RATING_MODIFIER_EXPERTISE2, val );
//ModUnsigned32Value( PLAYER_EXPERTISE, val );
}break;
case RESILIENCE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_CRIT_RESILIENCE, val );//melee
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_CRIT_RESILIENCE, val );//ranged
ModUnsigned32Value( PLAYER_RATING_MODIFIER_SPELL_CRIT_RESILIENCE, val );//spell
}break;
case HASTE_RATING:
{
ModUnsigned32Value( PLAYER_RATING_MODIFIER_MELEE_HASTE, val );//melee
ModUnsigned32Value( PLAYER_RATING_MODIFIER_RANGED_HASTE, val );//ranged
// maybe should do spell here? (19)
}break;
}
}
bool Player::CanSignCharter(Charter * charter, Player * requester)
{
if(charter->CharterType >= CHARTER_TYPE_ARENA_2V2 && m_arenaTeams[charter->CharterType-1] != NULL)
return false;
if(charter->CharterType == CHARTER_TYPE_GUILD && IsInGuild())
return false;
if(m_charters[charter->CharterType] || requester->GetTeam() != GetTeam())
return false;
else
return true;
}
void Player::SaveAuras(stringstream &ss)
{
uint32 charges = 0, prevX = 0;
//cebernic: save all auras why only just positive?
for ( uint32 x = MAX_POSITIVE_AURAS_EXTEDED_START; x < MAX_NEGATIVE_AURAS_EXTEDED_END; x++ )
{
if ( m_auras[x] != NULL && m_auras[x]->GetTimeLeft() > 3000 )
{
Aura * aur = m_auras[x];
bool skip = false;
for ( uint32 i = 0; i < 3; ++i )
{
if(aur->m_spellProto->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA || aur->m_spellProto->Effect[i] == SPELL_EFFECT_ADD_FARSIGHT)
{
skip = true;
break;
}
}
if( aur->pSpellId )
skip = true; //these auras were gained due to some proc. We do not save these eighter to avoid exploits of not removing them
if ( aur->m_spellProto->c_is_flags & SPELL_FLAG_IS_EXPIREING_WITH_PET )
skip = true;
//we are going to cast passive spells anyway on login so no need to save auras for them
if ( aur->IsPassive() && !( aur->GetSpellProto()->AttributesEx & 1024 ) )
skip = true;
if ( skip ) continue;
if ( charges > 0 && aur->GetSpellId() != m_auras[prevX]->GetSpellId() )
{
ss << m_auras[prevX]->GetSpellId() << "," << m_auras[prevX]->GetTimeLeft() << "," << m_auras[prevX]->IsPositive() << "," << charges << ",";
charges = 0;
}
if ( aur->GetSpellProto()->procCharges == 0 )
ss << aur->GetSpellId() << "," << aur->GetTimeLeft() << "," << aur->IsPositive() << "," << 0 << ",";
else
charges++;
prevX = x;
}
}
if ( charges > 0 && m_auras[prevX] != NULL )
{
ss << m_auras[prevX]->GetSpellId() << "," << m_auras[prevX]->GetTimeLeft() << "," << m_auras[prevX]->IsPositive() << "," << charges << ",";
}
}
void Player::SetShapeShift(uint8 ss)
{
uint8 old_ss = GetByte( UNIT_FIELD_BYTES_2, 3 );
SetByte( UNIT_FIELD_BYTES_2, 3, ss );
//remove auras that we should not have
for( uint32 x = MAX_TOTAL_AURAS_START; x < MAX_TOTAL_AURAS_END; x++ )
{
if( m_auras[x] != NULL )
{
uint32 reqss = m_auras[x]->GetSpellProto()->RequiredShapeShift;
if( reqss != 0 && m_auras[x]->IsPositive() )
{
if( old_ss > 0 && old_ss != 28 ) // 28 = FORM_SHADOW - Didn't find any aura that required this form
// not sure why all priest spell proto's RequiredShapeShift are set [to 134217728]
{
if( ( ((uint32)1 << (old_ss-1)) & reqss ) && // we were in the form that required it
!( ((uint32)1 << (ss-1) & reqss) ) ) // new form doesnt have the right form
{
m_auras[x]->Remove();
continue;
}
}
}
if( this->getClass() == DRUID )
{
switch( m_auras[x]->GetSpellProto()->MechanicsType)
{
case MECHANIC_ROOTED: //Rooted
case MECHANIC_ENSNARED: //Movement speed
case MECHANIC_POLYMORPHED: //Polymorphed
{
m_auras[x]->Remove();
}
break;
default:
break;
}
/*Shady: is this check neccessary? anyway m_auras[x]!=NULL check already done in next iteration. Commented*/
//if( m_auras[x] == NULL )
// break;
}
}
}
// apply any talents/spells we have that apply only in this form.
set<uint32>::iterator itr;
SpellEntry * sp;
Spell * spe;
SpellCastTargets t(GetGUID());
for( itr = mSpells.begin(); itr != mSpells.end(); ++itr )
{
sp = dbcSpell.LookupEntry( *itr );
if( sp->apply_on_shapeshift_change || sp->Attributes & 64 ) // passive/talent
{
if( sp->RequiredShapeShift && ((uint32)1 << (ss-1)) & sp->RequiredShapeShift )
{
spe = SpellPool.PooledNew();
spe->Init( this, sp, true, NULL );
spe->prepare( &t );
}
}
}
// now dummy-handler stupid hacky fixed shapeshift spells (leader of the pack, etc)
for( itr = mShapeShiftSpells.begin(); itr != mShapeShiftSpells.end(); ++itr )
{
sp = dbcSpell.LookupEntry( *itr );
if( sp->RequiredShapeShift && ((uint32)1 << (ss-1)) & sp->RequiredShapeShift )
{
spe = SpellPool.PooledNew();
spe->Init( this, sp, true, NULL );
spe->prepare( &t );
}
}
UpdateStats();
UpdateChances();
}
void Player::CalcDamage()
{
float delta;
float r;
int ss = GetShapeShift();
/////////////////MAIN HAND
float ap_bonus = GetAP()/14000.0f;
delta = (float)GetUInt32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_POS ) - (float)GetUInt32Value( PLAYER_FIELD_MOD_DAMAGE_DONE_NEG );
if(IsInFeralForm())
{
float tmp = 1; // multiplicative damage modifier
for (map<uint32, WeaponModifier>::iterator i = damagedone.begin(); i!=damagedone.end();i++)
{
if (i->second.wclass == (uint32) - 1) // applying only "any weapon" modifiers
tmp += i->second.value;
}
uint32 lev = getLevel();
float feral_damage; // average base damage before bonuses and modifiers
uint32 x; // itemlevel of the two hand weapon with dps equal to cat or bear dps
if (ss == FORM_CAT)
{
if (lev < 42) x = lev - 1;
else if (lev < 46) x = lev;
else if (lev < 49) x = 2 * lev - 45;
else if (lev < 60) x = lev + 4;
else x = 64;
// 3rd grade polinom for calculating blue two-handed weapon dps based on itemlevel (from Hyzenthlei)
if (x <= 28) feral_damage = 1.563e-03f * x*x*x - 1.219e-01f * x*x + 3.802e+00f * x - 2.227e+01f;
else if (x <= 41) feral_damage = -3.817e-03f * x*x*x + 4.015e-01f * x*x - 1.289e+01f * x + 1.530e+02f;
else feral_damage = 1.829e-04f * x*x*x - 2.692e-02f * x*x + 2.086e+00f * x - 1.645e+01f;
r = feral_damage * 0.79f + delta + ap_bonus * 1000.0f;
r *= tmp;
SetFloatValue(UNIT_FIELD_MINDAMAGE,r>0?r:0);
r = feral_damage * 1.21f + delta + ap_bonus * 1000.0f;
r *= tmp;
SetFloatValue(UNIT_FIELD_MAXDAMAGE,r>0?r:0);
}
else // Bear or Dire Bear Form
{
if (ss == FORM_BEAR) x = lev;
else x = lev + 5; // DIRE_BEAR dps is slightly better than bear dps
if (x > 70) x = 70;
// 3rd grade polinom for calculating green two-handed weapon dps based on itemlevel (from Hyzenthlei)
if (x <= 30) feral_damage = 7.638e-05f * x*x*x + 1.874e-03f * x*x + 4.967e-01f * x + 1.906e+00f;
else if (x <= 44) feral_damage = -1.412e-03f * x*x*x + 1.870e-01f * x*x - 7.046e+00f * x + 1.018e+02f;
else feral_damage = 2.268e-04f * x*x*x - 3.704e-02f * x*x + 2.784e+00f * x - 3.616e+01f;
feral_damage *= 2.5f; // Bear Form attack speed
r = feral_damage * 0.79f + delta + ap_bonus * 2500.0f;
r *= tmp;
SetFloatValue(UNIT_FIELD_MINDAMAGE,r>0?r:0);
r = feral_damage * 1.21f + delta + ap_bonus * 2500.0f;
r *= tmp;
SetFloatValue(UNIT_FIELD_MAXDAMAGE,r>0?r:0);
}
return;
}
//////no druid ss
uint32 speed=2000;
Item *it = GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
if(!disarmed)
{
if(it)
speed = it->GetProto()->Delay;
}
float bonus=ap_bonus*speed;
float tmp = 1;
map<uint32, WeaponModifier>::iterator i;
for(i = damagedone.begin();i!=damagedone.end();i++)
{
if((i->second.wclass == (uint32)-1) || //any weapon
(it && ((1 << it->GetProto()->SubClass) & i->second.subclass) )
)
tmp+=i->second.value;
}
r = BaseDamage[0]+delta+bonus;
r *= tmp;
SetFloatValue(UNIT_FIELD_MINDAMAGE,r>0?r:0);
r = BaseDamage[1]+delta+bonus;
r *= tmp;
SetFloatValue(UNIT_FIELD_MAXDAMAGE,r>0?r:0);
uint32 cr = 0;
if( it )
{
if( static_cast< Player* >( this )->m_wratings.size() )
{
std::map<uint32, uint32>::iterator itr = m_wratings.find( it->GetProto()->SubClass );
if( itr != m_wratings.end() )
cr=itr->second;
}
}
SetUInt32Value( PLAYER_RATING_MODIFIER_MELEE_MAIN_HAND_SKILL, cr );
/////////////// MAIN HAND END
/////////////// OFF HAND START
cr = 0;
it = static_cast< Player* >( this )->GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_OFFHAND);
if(it)
{
if(!disarmed)
{
speed =it->GetProto()->Delay;
}
else speed = 2000;
bonus = ap_bonus * speed;
i = damagedone.begin();
tmp = 1;
for(;i!=damagedone.end();i++)
{
if((i->second.wclass==(uint32)-1) || //any weapon
(( (1 << it->GetProto()->SubClass) & i->second.subclass) )
)
tmp+=i->second.value;
}
r = (BaseOffhandDamage[0]+delta+bonus)*offhand_dmg_mod;
r *= tmp;
SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE,r>0?r:0);
r = (BaseOffhandDamage[1]+delta+bonus)*offhand_dmg_mod;
r *= tmp;
SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE,r>0?r:0);
if(m_wratings.size ())
{
std::map<uint32, uint32>::iterator itr=m_wratings.find(it->GetProto()->SubClass);
if(itr!=m_wratings.end())
cr=itr->second;
}
}
SetUInt32Value( PLAYER_RATING_MODIFIER_MELEE_OFF_HAND_SKILL, cr );
/////////////second hand end
///////////////////////////RANGED
cr=0;
if((it = GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_RANGED)) != 0)
{
i = damagedone.begin();
tmp = 1;
for(;i != damagedone.end();i++)
{
if(
(i->second.wclass == (uint32)-1) || //any weapon
( ((1 << it->GetProto()->SubClass) & i->second.subclass) )
)
{
tmp+=i->second.value;
}
}
if(it->GetProto()->SubClass != 19)//wands do not have bonuses from RAP & ammo
{
// ap_bonus = (GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER)+(int32)GetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS))/14000.0;
//modified by Zack : please try to use premade functions if possible to avoid forgetting stuff
ap_bonus = GetRAP()/14000.0f;
bonus = ap_bonus*it->GetProto()->Delay;
if( GetUInt32Value(PLAYER_AMMO_ID) && !m_requiresNoAmmo )
{
ItemPrototype * xproto=ItemPrototypeStorage.LookupEntry(GetUInt32Value(PLAYER_AMMO_ID));
if(xproto)
{
bonus+=((xproto->Damage[0].Min+xproto->Damage[0].Max)*it->GetProto()->Delay)/2000.0f;
}
}
}else bonus =0;
r = BaseRangedDamage[0]+delta+bonus;
r *= tmp;
SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE,r>0?r:0);
r = BaseRangedDamage[1]+delta+bonus;
r *= tmp;
SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE,r>0?r:0);
if(m_wratings.size ())
{
std::map<uint32, uint32>::iterator i=m_wratings.find(it->GetProto()->SubClass);
if(i != m_wratings.end())
cr=i->second;
}
}
SetUInt32Value( PLAYER_RATING_MODIFIER_RANGED_SKILL, cr );
/////////////////////////////////RANGED end
if( GetSummon() )
GetSummon()->CalcDamage();//Re-calculate pet's too
}
uint32 Player::GetMainMeleeDamage(uint32 AP_owerride)
{
float r;
int ss = GetShapeShift();
/////////////////MAIN HAND
float ap_bonus;
if(AP_owerride)
ap_bonus = AP_owerride/14000.0f;
else
ap_bonus = GetAP()/14000.0f;
if(IsInFeralForm())
{
if(ss == FORM_CAT)
r = ap_bonus * 1000.0f;
else
r = ap_bonus * 2500.0f;
return float2int32(r);
}
//////no druid ss
uint32 speed=2000;
Item *it = GetItemInterface()->GetInventoryItem(EQUIPMENT_SLOT_MAINHAND);
if(!disarmed)
{
if(it)
speed = it->GetProto()->Delay;
}
r = ap_bonus*speed;
return float2int32(r);
}
void Player::EventPortToGM(Player *p)
{
SafeTeleport(p->GetMapId(),p->GetInstanceID(),p->GetPosition());
}
void Player::UpdateComboPoints()
{
// fuck bytebuffers :D
unsigned char buffer[10];
uint32 c = 2;
// check for overflow
if(m_comboPoints > 5)
m_comboPoints = 5;
if(m_comboPoints < 0)
m_comboPoints = 0;
if(m_comboTarget != 0)
{
Unit * target = (m_mapMgr != NULL) ? m_mapMgr->GetUnit(m_comboTarget) : NULL;
if(!target || target->isDead() || GetSelection() != m_comboTarget)
{
buffer[0] = buffer[1] = 0;
}
else
{
c = FastGUIDPack(m_comboTarget, buffer, 0);
buffer[c++] = m_comboPoints;
}
}
else
buffer[0] = buffer[1] = 0;
m_session->OutPacket(SMSG_SET_COMBO_POINTS, c, buffer);
}
void Player::SendAreaTriggerMessage(const char * message, ...)
{
va_list ap;
va_start(ap, message);
char msg[500];
vsnprintf(msg, 500, message, ap);
va_end(ap);
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 6 + strlen(msg));
data << (uint32)0 << msg << (uint8)0x00;
m_session->SendPacket(&data);
}
void Player::removeSoulStone()
{
if(!this->SoulStone) return;
uint32 sSoulStone = 0;
switch(this->SoulStone)
{
case 3026:
{
sSoulStone = 20707;
}break;
case 20758:
{
sSoulStone = 20762;
}break;
case 20759:
{
sSoulStone = 20763;
}break;
case 20760:
{
sSoulStone = 20764;
}break;
case 20761:
{
sSoulStone = 20765;
}break;
case 27240:
{
sSoulStone = 27239;
}break;
}
this->RemoveAura(sSoulStone);
this->SoulStone = this->SoulStoneReceiver = 0; //just incase
}
void Player::SoftDisconnect()
{
sEventMgr.RemoveEvents(this, EVENT_PLAYER_SOFT_DISCONNECT);
WorldSession *session=GetSession();
session->LogoutPlayer(true);
session->Disconnect();
}
void Player::SetNoseLevel()
{
// Set the height of the player
switch (getRace())
{
case RACE_HUMAN:
// female
if (getGender()) m_noseLevel = 1.72f;
// male
else m_noseLevel = 1.78f;
break;
case RACE_ORC:
if (getGender()) m_noseLevel = 1.82f;
else m_noseLevel = 1.98f;
break;
case RACE_DWARF:
if (getGender()) m_noseLevel = 1.27f;
else m_noseLevel = 1.4f;
break;
case RACE_NIGHTELF:
if (getGender()) m_noseLevel = 1.84f;
else m_noseLevel = 2.13f;
break;
case RACE_UNDEAD:
if (getGender()) m_noseLevel = 1.61f;
else m_noseLevel = 1.8f;
break;
case RACE_TAUREN:
if (getGender()) m_noseLevel = 2.48f;
else m_noseLevel = 2.01f;
break;
case RACE_GNOME:
if (getGender()) m_noseLevel = 1.06f;
else m_noseLevel = 1.04f;
break;
case RACE_TROLL:
if (getGender()) m_noseLevel = 2.02f;
else m_noseLevel = 1.93f;
break;
case RACE_BLOODELF:
if (getGender()) m_noseLevel = 1.83f;
else m_noseLevel = 1.93f;
break;
case RACE_DRAENEI:
if (getGender()) m_noseLevel = 2.09f;
else m_noseLevel = 2.36f;
break;
}
}
void Player::Possess(Unit * pTarget)
{
if( m_CurrentCharm)
return;
m_CurrentCharm = pTarget->GetGUID();
if(pTarget->GetTypeId() == TYPEID_UNIT)
{
// unit-only stuff.
pTarget->setAItoUse(false);
pTarget->GetAIInterface()->StopMovement(0);
pTarget->m_redirectSpellPackets = this;
}
m_noInterrupt++;
SetUInt64Value(UNIT_FIELD_CHARM, pTarget->GetGUID());
SetUInt64Value(PLAYER_FARSIGHT, pTarget->GetGUID());
pTarget->SetUInt64Value(UNIT_FIELD_CHARMEDBY, GetGUID());
pTarget->SetCharmTempVal(pTarget->GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE));
pTarget->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, GetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE));
pTarget->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED_CREATURE);
SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER);
/* send "switch mover" packet */
WorldPacket data1( SMSG_CLIENT_CONTROL_UPDATE, 10 );
data1 << pTarget->GetNewGUID() << uint8(1);
m_session->SendPacket(&data1);
/* update target faction set */
pTarget->_setFaction();
pTarget->UpdateOppFactionSet();
/* build + send pet_spells packet */
if(pTarget->m_temp_summon)
return;
if( !( pTarget->m_isPet && static_cast< Pet* >( pTarget ) == m_Summon ) )
{
list<uint32> avail_spells;
for(list<AI_Spell*>::iterator itr = pTarget->GetAIInterface()->m_spells.begin(); itr != pTarget->GetAIInterface()->m_spells.end(); ++itr)
{
if((*itr)->agent == AGENT_SPELL)
avail_spells.push_back((*itr)->spell->Id);
}
list<uint32>::iterator itr = avail_spells.begin();
WorldPacket data(SMSG_PET_SPELLS, pTarget->GetAIInterface()->m_spells.size() * 4 + 20);
data << pTarget->GetGUID();
data << uint32(0x00000000);//unk1
data << uint32(0x00000101);//unk2
// First spell is attack.
data << uint32(PET_SPELL_ATTACK);
// Send the actionbar
for(uint32 i = 1; i < 10; ++i)
{
if(itr != avail_spells.end())
{
data << uint16((*itr)) << uint16(DEFAULT_SPELL_STATE);
++itr;
}
else
data << uint16(0) << uint8(0) << uint8(i+5);
}
// Send the rest of the spells.
data << uint8(avail_spells.size());
for(itr = avail_spells.begin(); itr != avail_spells.end(); ++itr)
data << uint16(*itr) << uint16(DEFAULT_SPELL_STATE);
data << uint64(0);
m_session->SendPacket(&data);
}
}
void Player::UnPossess()
{
if( !m_CurrentCharm )
return;
Unit * pTarget = GetMapMgr()->GetUnit( m_CurrentCharm );
if( !pTarget )
return;
m_CurrentCharm = 0;
SpeedCheatReset();
if(pTarget->GetTypeId() == TYPEID_UNIT)
{
// unit-only stuff.
pTarget->setAItoUse(true);
pTarget->m_redirectSpellPackets = 0;
}
m_noInterrupt--;
SetUInt64Value(PLAYER_FARSIGHT, 0);
SetUInt64Value(UNIT_FIELD_CHARM, 0);
pTarget->SetUInt64Value(UNIT_FIELD_CHARMEDBY, 0);
RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOCK_PLAYER);
pTarget->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PLAYER_CONTROLLED_CREATURE);
pTarget->SetUInt32Value(UNIT_FIELD_FACTIONTEMPLATE, pTarget->GetCharmTempVal());
pTarget->_setFaction();
pTarget->UpdateOppFactionSet();
/* send "switch mover" packet */
WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, 10);
data << pTarget->GetNewGUID() << uint8(0);
m_session->SendPacket(&data);
if(pTarget->m_temp_summon)
return;
if( pTarget->m_isPet && static_cast< Pet* >( pTarget ) != m_Summon )
{
data.Initialize( SMSG_PET_SPELLS );
data << uint64( 0 );
m_session->SendPacket( &data );
}
}
void Player::SummonRequest(uint32 Requestor, uint32 ZoneID, uint32 MapID, uint32 InstanceID, const LocationVector & Position)
{
m_summonInstanceId = InstanceID;
m_summonPos = Position;
m_summoner = Requestor;
m_summonMapId = MapID;
WorldPacket data(SMSG_SUMMON_REQUEST, 16);
data << uint64(Requestor) << ZoneID << uint32(120000); // 2 minutes
m_session->SendPacket(&data);
}
void Player::RemoveFromBattlegroundQueue()
{
if(!m_pendingBattleground)
return;
m_pendingBattleground->RemovePendingPlayer(this);
sChatHandler.SystemMessage(m_session, "You were removed from the queue for the battleground for not joining after 2 minutes.");
m_pendingBattleground = 0;
}
#ifdef CLUSTERING
void Player::EventRemoveAndDelete()
{
}
#endif
void Player::_AddSkillLine(uint32 SkillLine, uint32 Curr_sk, uint32 Max_sk)
{
skilllineentry * CheckedSkill = dbcSkillLine.LookupEntry(SkillLine);
if (!CheckedSkill) //skill doesn't exist, exit here
return;
// force to be within limits
#if PLAYER_LEVEL_CAP==80
Curr_sk = ( Curr_sk > 400 ? 400 : ( Curr_sk <1 ? 1 : Curr_sk ) );
Max_sk = ( Max_sk > 400 ? 400 : Max_sk );
#else
Curr_sk = ( Curr_sk > 375 ? 375 : ( Curr_sk <1 ? 1 : Curr_sk ) );
Max_sk = ( Max_sk > 375 ? 375 : Max_sk );
#endif
ItemProf * prof;
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr != m_skills.end())
{
if( (Curr_sk > itr->second.CurrentValue && Max_sk >= itr->second.MaximumValue) || (Curr_sk == itr->second.CurrentValue && Max_sk > itr->second.MaximumValue) )
{
itr->second.CurrentValue = Curr_sk;
itr->second.MaximumValue = Max_sk;
_UpdateMaxSkillCounts();
}
}
else
{
PlayerSkill inf;
inf.Skill = CheckedSkill;
inf.MaximumValue = Max_sk;
inf.CurrentValue = ( inf.Skill->id != SKILL_RIDING ? Curr_sk : Max_sk );
inf.BonusValue = 0;
m_skills.insert( make_pair( SkillLine, inf ) );
_UpdateSkillFields();
}
//Add to proficiency
if((prof=(ItemProf *)GetProficiencyBySkill(SkillLine)) != 0)
{
packetSMSG_SET_PROFICICENCY pr;
pr.ItemClass = prof->itemclass;
if(prof->itemclass==4)
{
armor_proficiency|=prof->subclass;
//SendSetProficiency(prof->itemclass,armor_proficiency);
pr.Profinciency = armor_proficiency;
}
else
{
weapon_proficiency|=prof->subclass;
//SendSetProficiency(prof->itemclass,weapon_proficiency);
pr.Profinciency = weapon_proficiency;
}
m_session->OutPacket( SMSG_SET_PROFICIENCY, sizeof( packetSMSG_SET_PROFICICENCY ), &pr );
}
// hackfix for poisons
if(SkillLine==SKILL_POISONS && !HasSpell(2842))
addSpell(2842);
// Displaying bug fix
_UpdateSkillFields();
}
void Player::_UpdateSkillFields()
{
uint32 f = PLAYER_SKILL_INFO_1_1;
/* Set the valid skills */
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end();)
{
if(!itr->first)
{
SkillMap::iterator it2 = itr++;
m_skills.erase(it2);
continue;
}
ASSERT(f <= PLAYER_CHARACTER_POINTS1);
if(itr->second.Skill->type == SKILL_TYPE_PROFESSION)
SetUInt32Value(f++, itr->first | 0x10000);
else
SetUInt32Value(f++, itr->first);
SetUInt32Value(f++, (itr->second.MaximumValue << 16) | itr->second.CurrentValue);
SetUInt32Value(f++, itr->second.BonusValue);
++itr;
}
/* Null out the rest of the fields */
for(; f < PLAYER_CHARACTER_POINTS1; ++f)
{
if(m_uint32Values[f] != 0)
SetUInt32Value(f, 0);
}
}
bool Player::_HasSkillLine(uint32 SkillLine)
{
return (m_skills.find(SkillLine) != m_skills.end());
}
void Player::_AdvanceSkillLine(uint32 SkillLine, uint32 Count /* = 1 */)
{
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr == m_skills.end())
{
/* Add it */
_AddSkillLine(SkillLine, Count, getLevel() * 5);
_UpdateMaxSkillCounts();
sHookInterface.OnAdvanceSkillLine(this, SkillLine, Count);
}
else
{
uint32 curr_sk = itr->second.CurrentValue;
itr->second.CurrentValue = min(curr_sk + Count,itr->second.MaximumValue);
if (itr->second.CurrentValue != curr_sk)
{
_UpdateSkillFields();
sHookInterface.OnAdvanceSkillLine(this, SkillLine, curr_sk);
}
}
}
uint32 Player::_GetSkillLineMax(uint32 SkillLine)
{
SkillMap::iterator itr = m_skills.find(SkillLine);
return (itr == m_skills.end()) ? 0 : itr->second.MaximumValue;
}
uint32 Player::_GetSkillLineCurrent(uint32 SkillLine, bool IncludeBonus /* = true */)
{
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr == m_skills.end())
return 0;
return (IncludeBonus ? itr->second.CurrentValue + itr->second.BonusValue : itr->second.CurrentValue);
}
void Player::_RemoveSkillLine(uint32 SkillLine)
{
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr == m_skills.end())
return;
m_skills.erase(itr);
_UpdateSkillFields();
}
void Player::_UpdateMaxSkillCounts()
{
bool dirty = false;
uint32 new_max;
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->second.Skill->type == SKILL_TYPE_WEAPON || itr->second.Skill->id == SKILL_LOCKPICKING || itr->second.Skill->id == SKILL_POISONS)
{
new_max = 5 * getLevel();
}
else if (itr->second.Skill->type == SKILL_TYPE_LANGUAGE)
{
new_max = 300;
}
else if (itr->second.Skill->type == SKILL_TYPE_PROFESSION || itr->second.Skill->type == SKILL_TYPE_SECONDARY)
{
new_max = itr->second.MaximumValue;
if (new_max >= 350)
new_max = 375;
}
else
{
new_max = 1;
}
// force to be within limits
#if PLAYER_LEVEL_CAP==80
if (new_max > 400)
new_max = 400;
#else
if (new_max > 1275)
new_max = 1275;
#endif
if (new_max < 1)
new_max = 1;
if(itr->second.MaximumValue != new_max)
{
dirty = true;
itr->second.MaximumValue = new_max;
}
if (itr->second.CurrentValue > new_max)
{
dirty = true;
itr->second.CurrentValue = new_max;
}
}
if(dirty)
_UpdateSkillFields();
}
void Player::_ModifySkillBonus(uint32 SkillLine, int32 Delta)
{
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr == m_skills.end())
return;
itr->second.BonusValue += Delta;
_UpdateSkillFields();
}
void Player::_ModifySkillBonusByType(uint32 SkillType, int32 Delta)
{
bool dirty = false;
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->second.Skill->type == SkillType)
{
itr->second.BonusValue += Delta;
dirty=true;
}
}
if(dirty)
_UpdateSkillFields();
}
/** Maybe this formula needs to be checked?
* - Burlex
*/
float PlayerSkill::GetSkillUpChance()
{
float diff = float(MaximumValue - CurrentValue);
return (diff * 100.0f / float(MaximumValue));
}
void Player::_RemoveLanguages()
{
for(SkillMap::iterator itr = m_skills.begin(), it2; itr != m_skills.end();)
{
if(itr->second.Skill->type == SKILL_TYPE_LANGUAGE)
{
it2 = itr++;
m_skills.erase(it2);
}
else
++itr;
}
}
void PlayerSkill::Reset(uint32 Id)
{
MaximumValue = 0;
CurrentValue = 0;
BonusValue = 0;
Skill = (Id == 0) ? NULL : dbcSkillLine.LookupEntry(Id);
}
void Player::_AddLanguages(bool All)
{
/** This function should only be used at login, and after _RemoveLanguages is called.
* Otherwise weird stuff could happen :P
* - Burlex
*/
PlayerSkill sk;
skilllineentry * en;
uint32 spell_id;
static uint32 skills[] = { SKILL_LANG_COMMON, SKILL_LANG_ORCISH, SKILL_LANG_DWARVEN, SKILL_LANG_DARNASSIAN, SKILL_LANG_TAURAHE, SKILL_LANG_THALASSIAN,
SKILL_LANG_TROLL, SKILL_LANG_GUTTERSPEAK, SKILL_LANG_DRAENEI, 0 };
if(All)
{
for(uint32 i = 0; skills[i] != 0; ++i)
{
if(!skills[i])
break;
sk.Reset(skills[i]);
sk.MaximumValue = sk.CurrentValue = 300;
m_skills.insert( make_pair(skills[i], sk) );
if((spell_id = ::GetSpellForLanguage(skills[i])) != 0)
addSpell(spell_id);
}
}
else
{
for(list<CreateInfo_SkillStruct>::iterator itr = info->skills.begin(); itr != info->skills.end(); ++itr)
{
en = dbcSkillLine.LookupEntry(itr->skillid);
if(en->type == SKILL_TYPE_LANGUAGE)
{
sk.Reset(itr->skillid);
sk.MaximumValue = sk.CurrentValue = 300;
m_skills.insert( make_pair(itr->skillid, sk) );
if((spell_id = ::GetSpellForLanguage(itr->skillid)) != 0)
addSpell(spell_id);
}
}
}
_UpdateSkillFields();
}
float Player::GetSkillUpChance(uint32 id)
{
SkillMap::iterator itr = m_skills.find(id);
if(itr == m_skills.end())
return 0.0f;
return itr->second.GetSkillUpChance();
}
void Player::_RemoveAllSkills()
{
m_skills.clear();
_UpdateSkillFields();
}
void Player::_AdvanceAllSkills(uint32 count)
{
bool dirty=false;
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->second.CurrentValue != itr->second.MaximumValue)
{
itr->second.CurrentValue += count;
if(itr->second.CurrentValue >= itr->second.MaximumValue)
itr->second.CurrentValue = itr->second.MaximumValue;
dirty=true;
}
}
if(dirty)
_UpdateSkillFields();
}
void Player::_ModifySkillMaximum(uint32 SkillLine, uint32 NewMax)
{
// force to be within limits
#if PLAYER_LEVEL_CAP==80
NewMax = ( NewMax > 400 ? 400 : NewMax );
#else
NewMax = ( NewMax > 375 ? 375 : NewMax );
#endif
SkillMap::iterator itr = m_skills.find(SkillLine);
if(itr == m_skills.end())
return;
if(NewMax > itr->second.MaximumValue)
{
if(SkillLine == SKILL_RIDING)
itr->second.CurrentValue = NewMax;
itr->second.MaximumValue = NewMax;
_UpdateSkillFields();
}
}
void Player::RemoveSpellTargets(uint32 Type, Unit* target)
{
if( m_spellIndexTypeTargets[Type] != 0 )
{
Unit * pUnit = m_mapMgr ? m_mapMgr->GetUnit(m_spellIndexTypeTargets[Type]) : NULL;
if( pUnit != NULL && pUnit != target ) //some auras can stack on target. There is no need to remove them if target is same as previous one
{
pUnit->RemoveAurasByBuffIndexType(Type, GetGUID());
m_spellIndexTypeTargets[Type] = 0;
}
}
}
void Player::RemoveSpellIndexReferences(uint32 Type)
{
m_spellIndexTypeTargets[Type] = 0;
}
void Player::SetSpellTargetType(uint32 Type, Unit* target)
{
m_spellIndexTypeTargets[Type] = target->GetGUID();
}
void Player::RecalculateHonor()
{
HonorHandler::RecalculateHonorFields(this);
}
//wooot, crapy code rulez.....NOT
void Player::EventTalentHearthOfWildChange(bool apply)
{
if(!hearth_of_wild_pct)
return;
//druid hearth of the wild should add more features based on form
int tval;
if(apply)
tval = hearth_of_wild_pct;
else tval = -hearth_of_wild_pct;
uint32 SS=GetShapeShift();
//increase stamina if :
if(SS==FORM_BEAR || SS==FORM_DIREBEAR)
{
TotalStatModPctPos[STAT_STAMINA] += tval;
CalcStat(STAT_STAMINA);
UpdateStats();
UpdateChances();
}
//increase attackpower if :
else if(SS==FORM_CAT)
{
SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,GetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER)+float(tval/200.0f));
SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER, GetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER)+float(tval/200.0f));
UpdateStats();
UpdateChances();
}
}
/************************************************************************/
/* New Save System */
/************************************************************************/
#ifdef OPTIMIZED_PLAYER_SAVING
void Player::save_LevelXP()
{
CharacterDatabase.Execute("UPDATE characters SET level = %u, xp = %u WHERE guid = %u", m_uint32Values[UNIT_FIELD_LEVEL], m_uint32Values[PLAYER_XP], m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_PositionHP()
{
CharacterDatabase.Execute("UPDATE characters SET current_hp = %u, current_power = %u, positionX = '%f', positionY = '%f', positionZ = '%f', orientation = '%f', mapId = %u, instance_id = %u WHERE guid = %u",
m_uint32Values[UNIT_FIELD_HEALTH], m_uint32Values[UNIT_FIELD_POWER1+GetPowerType()], m_position.x, m_position.y, m_position.z, m_position.o, m_mapId, m_instanceId, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Gold()
{
CharacterDatabase.Execute("UPDATE characters SET gold = %u WHERE guid = %u", m_uint32Values[PLAYER_FIELD_COINAGE], m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_GuildData()
{
if(myGuild)
{
string escaped_note = m_playerInfo->publicNote ? CharacterDatabase.EscapeString(m_playerInfo->publicNote) : "";
string escaped_note2 = m_playerInfo->officerNote ? CharacterDatabase.EscapeString(m_playerInfo->officerNote) : "";
CharacterDatabase.Execute("UPDATE characters SET guildid=%u, guildRank=%u, publicNote='%s', officerNote='%s' WHERE guid = %u",
GetGuildId(), GetGuildRank(), escaped_note.c_str(), escaped_note2.c_str(), m_uint32Values[OBJECT_FIELD_GUID]);
}
else
{
CharacterDatabase.Execute("UPDATE characters SET guildid = 0, guildRank = 0, publicNote = '', officerNote = '' WHERE guid = %u",
m_uint32Values[OBJECT_FIELD_GUID]);
}
}
void Player::save_ExploreData()
{
char buffer[2048] = {0};
int p = 0;
for(uint32 i = 0; i < 64; ++i)
{
p += sprintf(&buffer[p], "%u,", m_uint32Values[PLAYER_EXPLORED_ZONES_1 + i]);
}
ASSERT(p < 2048);
CharacterDatabase.Execute("UPDATE characters SET exploration_data = '%s' WHERE guid = %u", buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Honor()
{
CharacterDatabase.Execute("UPDATE characters SET honorPointsToAdd = %u, killsToday = %u, killsYesterday = %u, killsLifeTime = %u, honorToday = %u, honorYesterday = %u, honorPoints = %u, arenaPoints = %u WHERE guid = %u",
m_honorPointsToAdd, m_killsToday, m_killsYesterday, m_killsLifetime, m_honorToday, m_honorYesterday, m_honorPoints, m_arenaPoints, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Skills()
{
char buffer[6000] = {0};
int p = 0;
for(SkillMap::iterator itr = m_skills.begin(); itr != m_skills.end(); ++itr)
{
if(itr->first && itr->second.Skill->type != SKILL_TYPE_LANGUAGE)
p += sprintf(&buffer[p], "%u;%u;%u;", itr->first, itr->second.CurrentValue, itr->second.MaximumValue);
}
ASSERT(p < 6000);
CharacterDatabase.Execute("UPDATE characters SET skills = '%s' WHERE guid = %u", buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Reputation()
{
char buffer[10000] = {0};
int p = 0;
ReputationMap::iterator iter = m_reputation.begin();
for(; iter != m_reputation.end(); ++iter)
{
p += sprintf(&buffer[p], "%d,%d,%d,%d,",
iter->first, iter->second->flag, iter->second->baseStanding, iter->second->standing);
}
ASSERT(p < 10000);
CharacterDatabase.Execute("UPDATE characters SET reputation = '%s' WHERE guid = %u", buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Actions()
{
char buffer[2048] = {0};
int p = 0;
for(uint32 i = 0; i < 120; ++i)
{
p += sprintf(&buffer[p], "%u,%u,%u,", mActions[i].Action, mActions[i].Misc, mActions[i].Type);
}
ASSERT(p < 2048);
CharacterDatabase.Execute("UPDATE characters SET actions = '%s' WHERE guid = %u", buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_BindPosition()
{
CharacterDatabase.Execute("UPDATE characters SET bindpositionX = '%f', bindpositionY = '%f', bindpositionZ = '%f', bindmapId = %u, bindzoneId = %u WHERE guid = %u",
m_bind_pos_x, m_bind_pos_y, m_bind_pos_z, m_bind_mapid, m_bind_zoneid, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_EntryPoint()
{
CharacterDatabase.Execute("UPDATE characters SET entrypointmap = %u, entrypointx = '%f', entrypointy = '%f', entrypointz = '%f', entrypointo = '%f', entrypointinstance = %u WHERE guid = %u",
m_bgEntryPointMap, m_bgEntryPointX, m_bgEntryPointY, m_bgEntryPointZ, m_bgEntryPointO, m_bgEntryPointInstance, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Taxi()
{
char buffer[1024] = {0};
int p = 0;
for(uint32 i = 0; i < 8; ++i)
p += sprintf(&buffer[p], "%u ", m_taximask[i]);
if(m_onTaxi) {
CharacterDatabase.Execute("UPDATE characters SET taximask = '%s', taxi_path = %u, taxi_lastnode = %u, taxi_mountid = %u WHERE guid = %u",
buffer, m_CurrentTaxiPath->GetID(), lastNode, m_uint32Values[UNIT_FIELD_MOUNTDISPLAYID], m_uint32Values[OBJECT_FIELD_GUID]);
}
else
{
CharacterDatabase.Execute("UPDATE characters SET taximask = '%s', taxi_path = 0, taxi_lastnode = 0, taxi_mountid = 0 WHERE guid = %u",
buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
}
void Player::save_Zone()
{
CharacterDatabase.Execute("UPDATE characters SET zoneId = %u WHERE guid = %u", m_zoneId, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Spells()
{
char buffer[10000] = {0};
char buffer2[10000] = {0};
uint32 p=0,q=0;
SpellSet::iterator itr = mSpells.begin();
for(; itr != mSpells.end(); ++itr)
{
p += sprintf(&buffer[p], "%u,", *itr);
}
for(itr = mDeletedSpells.begin(); itr != mDeletedSpells.end(); ++itr)
{
q += sprintf(&buffer2[q], "%u,", *itr);
}
CharacterDatabase.Execute("UPDATE characters SET spells = '%s', deleted_spells = '%s' WHERE guid = %u",
buffer, buffer2, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_InstanceType()
{
CharacterDatabase.Execute("UPDATE characters SET instancetype = %u WHERE guid = %u", iInstanceType, m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Misc()
{
uint32 playedt = UNIXTIME - m_playedtime[2];
m_playedtime[0] += playedt;
m_playedtime[1] += playedt;
m_playedtime[2] += playedt;
uint32 player_flags = m_uint32Values[PLAYER_FLAGS];
{
// Remove un-needed and problematic player flags from being saved :p
if(player_flags & PLAYER_FLAG_PARTY_LEADER)
player_flags &= ~PLAYER_FLAG_PARTY_LEADER;
if(player_flags & PLAYER_FLAG_AFK)
player_flags &= ~PLAYER_FLAG_AFK;
if(player_flags & PLAYER_FLAG_DND)
player_flags &= ~PLAYER_FLAG_DND;
if(player_flags & PLAYER_FLAG_GM)
player_flags &= ~PLAYER_FLAG_GM;
if(player_flags & PLAYER_FLAG_PVP_TOGGLE)
player_flags &= ~PLAYER_FLAG_PVP_TOGGLE;
if(player_flags & PLAYER_FLAG_FREE_FOR_ALL_PVP)
player_flags &= ~PLAYER_FLAG_FREE_FOR_ALL_PVP;
}
CharacterDatabase.Execute("UPDATE characters SET totalstableslots = %u, first_login = 0, TalentResetTimes = %u, playedTime = '%u %u %u ', isResting = %u, restState = %u, restTime = %u, timestamp = %u, watched_faction_index = %u, ammo_id = %u, available_prof_points = %u, available_talent_points = %u, bytes = %u, bytes2 = %u, player_flags = %u, player_bytes = %u",
GetStableSlotCount(), GetTalentResetTimes(), m_playedtime[0], m_playedtime[1], playedt, uint32(m_isResting), uint32(m_restState), m_restAmount, UNIXTIME,
m_uint32Values[PLAYER_FIELD_WATCHED_FACTION_INDEX], m_uint32Values[PLAYER_AMMO_ID], m_uint32Values[PLAYER_CHARACTER_POINTS2],
m_uint32Values[PLAYER_CHARACTER_POINTS1], m_uint32Values[PLAYER_BYTES], m_uint32Values[PLAYER_BYTES_2], player_flags,
m_uint32Values[PLAYER_FIELD_BYTES],
m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_PVP()
{
CharacterDatabase.Execute("UPDATE characters SET pvprank = %u, selected_pvp_title = %u, available_pvp_title = %u WHERE guid = %u",
uint32(GetPVPRank()), m_uint32Values[PLAYER_CHOSEN_TITLE], GetUInt64Value( PLAYER_FIELD_KNOWN_TITLES ), m_uint32Values[OBJECT_FIELD_GUID]);
}
void Player::save_Auras()
{
char buffer[10000];
uint32 p =0;
for(uint32 x=0;x<MAX_AURAS+MAX_PASSIVE_AURAS;x++)
{
if(m_auras[x])
{
Aura *aur=m_auras[x];
bool skip = false;
for(uint32 i = 0; i < 3; ++i)
{
if(aur->m_spellProto->Effect[i] == SPELL_EFFECT_APPLY_AREA_AURA ||
aur->m_spellProto->Effect[i] == SPELL_EFFECT_ADD_FARSIGHT)
{
skip = true;
break;
}
}
// skipped spells due to bugs
switch(aur->m_spellProto->Id)
{
case 12043: // Presence of mind
case 11129: // Combustion
case 28682: // Combustion proc
case 16188: // Natures Swiftness
case 17116: // Natures Swiftness
case 34936: // Backlash
case 35076: // Blessing of A'dal
case 23333: // WSG
case ARENA_PREPARATION: // battleground preparation
case 32724: // Arena Flags
case 32725: // Arena Flags
case 35774: // Arena Flags
case 35775: // Arena Flags
skip = true;
break;
}
//disabled proc spells until proper loading is fixed. Some spells tend to block or not remove when restored
if(aur->GetSpellProto()->procFlags)
{
// sLog.outDebug("skipping aura %d because has flags %d",aur->GetSpellId(),aur->GetSpellProto()->procFlags);
skip = true;
}
//disabled proc spells until proper loading is fixed. We cannot recover the charges that were used up. Will implement later
if(aur->GetSpellProto()->procCharges)
{
// sLog.outDebug("skipping aura %d because has proccharges %d",aur->GetSpellId(),aur->GetSpellProto()->procCharges);
skip = true;
}
//we are going to cast passive spells anyway on login so no need to save auras for them
if(aur->IsPassive() && !(aur->GetSpellProto()->AttributesEx & 1024))
skip = true;
if(skip)continue;
uint32 d=aur->GetTimeLeft();
if(d>3000)
p += sprintf(buffer, "%u,%u,", aur->GetSpellId(), d);
}
}
CharacterDatabase.Execute("UPDATE characters SET auras = '%s' WHERE guid = %u", buffer, m_uint32Values[OBJECT_FIELD_GUID]);
}
#endif
#ifdef CLUSTERING
#endif
void Player::EventGroupFullUpdate()
{
if(m_playerInfo->m_Group)
{
//m_playerInfo->m_Group->Update();
m_playerInfo->m_Group->UpdateAllOutOfRangePlayersFor(this);
}
}
void Player::EjectFromInstance()
{
if(m_bgEntryPointX && m_bgEntryPointY && m_bgEntryPointZ && !IS_INSTANCE(m_bgEntryPointMap))
{
if(SafeTeleport(m_bgEntryPointMap, m_bgEntryPointInstance, m_bgEntryPointX, m_bgEntryPointY, m_bgEntryPointZ, m_bgEntryPointO))
return;
}
SafeTeleport(m_bind_mapid, 0, m_bind_pos_x, m_bind_pos_y, m_bind_pos_z, 0);
}
bool Player::HasQuestSpell(uint32 spellid) //Only for Cast Quests
{
if (quest_spells.size()>0 && quest_spells.find(spellid) != quest_spells.end())
return true;
return false;
}
void Player::RemoveQuestSpell(uint32 spellid) //Only for Cast Quests
{
if (quest_spells.size()>0)
quest_spells.erase(spellid);
}
bool Player::HasQuestMob(uint32 entry) //Only for Kill Quests
{
if (quest_mobs.size()>0 && quest_mobs.find(entry) != quest_mobs.end())
return true;
return false;
}
bool Player::HasQuest(uint32 entry)
{
for(uint32 i=0;i<25;i++)
{
if ( m_questlog[i] != NULL && m_questlog[i]->GetQuest()->id == entry)
return true;
}
return false;
}
void Player::RemoveQuestMob(uint32 entry) //Only for Kill Quests
{
if (quest_mobs.size()>0)
quest_mobs.erase(entry);
}
PlayerInfo::~PlayerInfo()
{
if(m_Group)
m_Group->RemovePlayer(this);
}
void Player::CopyAndSendDelayedPacket(WorldPacket * data)
{
WorldPacket * data2 = new WorldPacket(*data);
delayedPackets.add(data2);
}
void Player::SendMeetingStoneQueue(uint32 DungeonId, uint8 Status)
{
WorldPacket data(SMSG_MEETINGSTONE_SETQUEUE, 5);
data << DungeonId << Status;
m_session->SendPacket(&data);
}
void Player::PartLFGChannel()
{
Channel * pChannel = channelmgr.GetChannel("LookingForGroup", this);
if( pChannel == NULL )
return;
/*for(list<Channel*>::iterator itr = m_channels.begin(); itr != m_channels.end(); ++itr)
{
if( (*itr) == pChannel )
{
pChannel->Part(this);
return;
}
}*/
if( m_channels.find( pChannel) == m_channels.end() )
return;
pChannel->Part( this );
}
//if we charmed or simply summoned a pet, this function should get called
void Player::EventSummonPet( Pet *new_pet )
{
if ( !new_pet )
return ; //another wtf error
SpellSet::iterator it,iter;
for(iter= mSpells.begin();iter != mSpells.end();)
{
it = iter++;
uint32 SpellID = *it;
SpellEntry *spellInfo = dbcSpell.LookupEntry(SpellID);
if( spellInfo->c_is_flags & SPELL_FLAG_IS_CASTED_ON_PET_SUMMON_PET_OWNER )
{
this->RemoveAllAuras( SpellID, this->GetGUID() ); //this is required since unit::addaura does not check for talent stacking
SpellCastTargets targets( this->GetGUID() );
Spell *spell = SpellPool.PooledNew();
spell->Init(this, spellInfo ,true, NULL); //we cast it as a proc spell, maybe we should not !
spell->prepare(&targets);
}
if( spellInfo->c_is_flags & SPELL_FLAG_IS_CASTED_ON_PET_SUMMON_ON_PET )
{
this->RemoveAllAuras( SpellID, this->GetGUID() ); //this is required since unit::addaura does not check for talent stacking
SpellCastTargets targets( new_pet->GetGUID() );
Spell *spell = SpellPool.PooledNew();
spell->Init(this, spellInfo ,true, NULL); //we cast it as a proc spell, maybe we should not !
spell->prepare(&targets);
}
}
//there are talents that stop working after you gain pet
for(uint32 x=MAX_TOTAL_AURAS_START;x<MAX_TOTAL_AURAS_END;x++)
if(m_auras[x] && m_auras[x]->GetSpellProto()->c_is_flags & SPELL_FLAG_IS_EXPIREING_ON_PET)
m_auras[x]->Remove();
//pet should inherit some of the talents from caster
//new_pet->InheritSMMods(); //not required yet. We cast full spell to have visual effect too
}
//if pet/charm died or whatever hapened we should call this function
//!! note function might get called multiple times :P
void Player::EventDismissPet()
{
for(uint32 x=MAX_TOTAL_AURAS_START;x<MAX_TOTAL_AURAS_END;x++)
if(m_auras[x] && m_auras[x]->GetSpellProto()->c_is_flags & SPELL_FLAG_IS_EXPIREING_WITH_PET)
m_auras[x]->Remove();
}
#ifdef ENABLE_COMPRESSED_MOVEMENT
CMovementCompressorThread *MovementCompressor;
void Player::AppendMovementData(uint32 op, uint32 sz, const uint8* data)
{
//printf("AppendMovementData(%u, %u, 0x%.8X)\n", op, sz, data);
m_movementBufferLock.Acquire();
m_movementBuffer << uint8(sz + 2);
m_movementBuffer << uint16(op);
m_movementBuffer.append( data, sz );
m_movementBufferLock.Release();
}
bool CMovementCompressorThread::run()
{
set<Player*>::iterator itr;
while(running)
{
m_listLock.Acquire();
for(itr = m_players.begin(); itr != m_players.end(); ++itr)
{
(*itr)->EventDumpCompressedMovement();
}
m_listLock.Release();
Sleep(World::m_movementCompressInterval);
}
return true;
}
void CMovementCompressorThread::AddPlayer(Player * pPlayer)
{
m_listLock.Acquire();
m_players.insert(pPlayer);
m_listLock.Release();
}
void CMovementCompressorThread::RemovePlayer(Player * pPlayer)
{
m_listLock.Acquire();
m_players.erase(pPlayer);
m_listLock.Release();
}
void Player::EventDumpCompressedMovement()
{
if( m_movementBuffer.size() == 0 )
return;
m_movementBufferLock.Acquire();
uint32 size = (uint32)m_movementBuffer.size();
uint32 destsize = size + size/10 + 16;
int rate = World::m_movementCompressRate;
if(size >= 40000 && rate < 6)
rate = 6;
if(size <= 100)
rate = 0; // don't bother compressing packet smaller than this, zlib doesnt really handle them well
// set up stream
z_stream stream;
stream.zalloc = 0;
stream.zfree = 0;
stream.opaque = 0;
if(deflateInit(&stream, rate) != Z_OK)
{
sLog.outError("deflateInit failed.");
m_movementBufferLock.Release();
return;
}
uint8 *buffer = new uint8[destsize];
// set up stream pointers
stream.next_out = (Bytef*)buffer+4;
stream.avail_out = destsize;
stream.next_in = (Bytef*)m_movementBuffer.contents();
stream.avail_in = size;
// call the actual process
if(deflate(&stream, Z_NO_FLUSH) != Z_OK ||
stream.avail_in != 0)
{
sLog.outError("deflate failed.");
delete [] buffer;
m_movementBufferLock.Release();
return;
}
// finish the deflate
if(deflate(&stream, Z_FINISH) != Z_STREAM_END)
{
sLog.outError("deflate failed: did not end stream");
delete [] buffer;
m_movementBufferLock.Release();
return;
}
// finish up
if(deflateEnd(&stream) != Z_OK)
{
sLog.outError("deflateEnd failed.");
delete [] buffer;
m_movementBufferLock.Release();
return;
}
// fill in the full size of the compressed stream
#ifdef USING_BIG_ENDIAN
*(uint32*)&buffer[0] = swap32(size);
#else
*(uint32*)&buffer[0] = size;
#endif
// send it
m_session->OutPacket(763, (uint16)stream.total_out + 4, buffer);
//printf("Compressed move compressed from %u bytes to %u bytes.\n", m_movementBuffer.size(), stream.total_out + 4);
// cleanup memory
delete [] buffer;
m_movementBuffer.clear();
m_movementBufferLock.Release();
}
#endif
void Player::AddShapeShiftSpell(uint32 id)
{
SpellEntry * sp = dbcSpell.LookupEntry( id );
mShapeShiftSpells.insert( id );
if( sp->RequiredShapeShift && ((uint32)1 << (GetShapeShift()-1)) & sp->RequiredShapeShift )
{
Spell * spe = SpellPool.PooledNew();
spe->Init( this, sp, true, NULL );
SpellCastTargets t(this->GetGUID());
spe->prepare( &t );
}
}
void Player::RemoveShapeShiftSpell(uint32 id)
{
mShapeShiftSpells.erase( id );
RemoveAura( id );
}
// COOLDOWNS
void Player::_Cooldown_Add(uint32 Type, uint32 Misc, uint32 Time, uint32 SpellId, uint32 ItemId)
{
PlayerCooldownMap::iterator itr = m_cooldownMap[Type].find( Misc );
if( itr != m_cooldownMap[Type].end( ) )
{
if( itr->second.ExpireTime < Time )
{
itr->second.ExpireTime = Time;
itr->second.ItemId = ItemId;
itr->second.SpellId = SpellId;
}
}
else
{
PlayerCooldown cd;
cd.ExpireTime = Time;
cd.ItemId = ItemId;
cd.SpellId = SpellId;
m_cooldownMap[Type].insert( make_pair( Misc, cd ) );
}
#ifdef _DEBUG
Log.Debug("Cooldown", "added cooldown for type %u misc %u time %u item %u spell %u", Type, Misc, Time - getMSTime(), ItemId, SpellId);
#endif
}
void Player::Cooldown_Add(SpellEntry * pSpell, Item * pItemCaster)
{
uint32 mstime = getMSTime();
int32 cool_time;
if( pSpell->CategoryRecoveryTime > 0 && pSpell->Category )
{
cool_time = pSpell->CategoryRecoveryTime;
if( pSpell->SpellGroupType )
{
SM_FIValue(SM_FCooldownTime, &cool_time, pSpell->SpellGroupType);
SM_PIValue(SM_PCooldownTime, &cool_time, pSpell->SpellGroupType);
}
_Cooldown_Add( COOLDOWN_TYPE_CATEGORY, pSpell->Category, mstime + cool_time, pSpell->Id, pItemCaster ? pItemCaster->GetProto()->ItemId : 0 );
}
if( pSpell->RecoveryTime > 0 )
{
cool_time = pSpell->RecoveryTime;
if( pSpell->SpellGroupType )
{
SM_FIValue(SM_FCooldownTime, &cool_time, pSpell->SpellGroupType);
SM_PIValue(SM_PCooldownTime, &cool_time, pSpell->SpellGroupType);
}
_Cooldown_Add( COOLDOWN_TYPE_SPELL, pSpell->Id, mstime + cool_time, pSpell->Id, pItemCaster ? pItemCaster->GetProto()->ItemId : 0 );
}
}
void Player::Cooldown_AddStart(SpellEntry * pSpell)
{
if( pSpell->StartRecoveryTime == 0 )
return;
uint32 mstime = getMSTime();
int32 atime = float2int32( float( pSpell->StartRecoveryTime ) / SpellHasteRatingBonus );
if( atime < 1000 ) // global cooldown is limited to 1s
atime = 1000;
if( pSpell->StartRecoveryCategory ) // if we have a different cool category to the actual spell category - only used by few spells
_Cooldown_Add( COOLDOWN_TYPE_CATEGORY, pSpell->StartRecoveryCategory, mstime + atime, pSpell->Id, 0 );
/*else if( pSpell->Category ) // cooldowns are grouped
_Cooldown_Add( COOLDOWN_TYPE_CATEGORY, pSpell->Category, mstime + pSpell->StartRecoveryTime, pSpell->Id, 0 );*/
else // no category, so it's a gcd
{
#ifdef _DEBUG
Log.Debug("Cooldown", "Global cooldown adding: %u ms", atime );
#endif
m_globalCooldown = mstime + atime;
}
}
bool Player::Cooldown_CanCast(SpellEntry * pSpell)
{
PlayerCooldownMap::iterator itr;
uint32 mstime = getMSTime();
if( pSpell->Category )
{
itr = m_cooldownMap[COOLDOWN_TYPE_CATEGORY].find( pSpell->Category );
if( itr != m_cooldownMap[COOLDOWN_TYPE_CATEGORY].end( ) )
{
if( mstime < itr->second.ExpireTime )
return false;
else
m_cooldownMap[COOLDOWN_TYPE_CATEGORY].erase( itr );
}
}
itr = m_cooldownMap[COOLDOWN_TYPE_SPELL].find( pSpell->Id );
if( itr != m_cooldownMap[COOLDOWN_TYPE_SPELL].end( ) )
{
if( mstime < itr->second.ExpireTime )
return false;
else
m_cooldownMap[COOLDOWN_TYPE_SPELL].erase( itr );
}
if( pSpell->StartRecoveryTime && m_globalCooldown && !this->CooldownCheat /* cebernic:GCD also cheat :D */ ) /* gcd doesn't affect spells without a cooldown it seems */
{
if( mstime < m_globalCooldown )
return false;
else
m_globalCooldown = 0;
}
return true;
}
void Player::Cooldown_AddItem(ItemPrototype * pProto, uint32 x)
{
if( pProto->Spells[x].CategoryCooldown <= 0 && pProto->Spells[x].Cooldown <= 0 )
return;
ItemSpell * isp = &pProto->Spells[x];
uint32 mstime = getMSTime();
if( isp->CategoryCooldown > 0)
_Cooldown_Add( COOLDOWN_TYPE_CATEGORY, isp->Category, isp->CategoryCooldown + mstime, isp->Id, pProto->ItemId );
if( isp->Cooldown > 0 )
_Cooldown_Add( COOLDOWN_TYPE_SPELL, isp->Id, isp->Cooldown + mstime, isp->Id, pProto->ItemId );
}
bool Player::Cooldown_CanCast(ItemPrototype * pProto, uint32 x)
{
PlayerCooldownMap::iterator itr;
ItemSpell * isp = &pProto->Spells[x];
uint32 mstime = getMSTime();
if( isp->Category )
{
itr = m_cooldownMap[COOLDOWN_TYPE_CATEGORY].find( isp->Category );
if( itr != m_cooldownMap[COOLDOWN_TYPE_CATEGORY].end( ) )
{
if( mstime < itr->second.ExpireTime )
return false;
else
m_cooldownMap[COOLDOWN_TYPE_CATEGORY].erase( itr );
}
}
itr = m_cooldownMap[COOLDOWN_TYPE_SPELL].find( isp->Id );
if( itr != m_cooldownMap[COOLDOWN_TYPE_SPELL].end( ) )
{
if( mstime < itr->second.ExpireTime )
return false;
else
m_cooldownMap[COOLDOWN_TYPE_SPELL].erase( itr );
}
return true;
}
#define COOLDOWN_SKIP_SAVE_IF_MS_LESS_THAN 10000
void Player::_SavePlayerCooldowns(QueryBuffer * buf)
{
PlayerCooldownMap::iterator itr;
PlayerCooldownMap::iterator itr2;
uint32 i;
uint32 seconds;
uint32 mstime = getMSTime();
// clear them (this should be replaced with an update queue later)
if( buf != NULL )
buf->AddQuery("DELETE FROM playercooldowns WHERE player_guid = %u", m_uint32Values[OBJECT_FIELD_GUID] ); // 0 is guid always
else
CharacterDatabase.Execute("DELETE FROM playercooldowns WHERE player_guid = %u", m_uint32Values[OBJECT_FIELD_GUID] ); // 0 is guid always
for( i = 0; i < NUM_COOLDOWN_TYPES; ++i )
{
itr = m_cooldownMap[i].begin( );
for( ; itr != m_cooldownMap[i].end( ); )
{
itr2 = itr++;
// expired ones - no point saving, nor keeping them around, wipe em
if( mstime >= itr2->second.ExpireTime )
{
m_cooldownMap[i].erase( itr2 );
continue;
}
// skip small cooldowns which will end up expiring by the time we log in anyway
if( ( itr2->second.ExpireTime - mstime ) < COOLDOWN_SKIP_SAVE_IF_MS_LESS_THAN )
continue;
// work out the cooldown expire time in unix timestamp format
// burlex's reason: 30 day overflow of 32bit integer, also
// under windows we use GetTickCount() which is the system uptime, if we reboot
// the server all these timestamps will appear to be messed up.
seconds = (itr2->second.ExpireTime - mstime) / 1000;
// this shouldnt ever be nonzero because of our check before, so no check needed
if( buf != NULL )
{
buf->AddQuery( "INSERT INTO playercooldowns VALUES(%u, %u, %u, %u, %u, %u)", m_uint32Values[OBJECT_FIELD_GUID],
i, itr2->first, seconds + (uint32)UNIXTIME, itr2->second.SpellId, itr2->second.ItemId );
}
else
{
CharacterDatabase.Execute( "INSERT INTO playercooldowns VALUES(%u, %u, %u, %u, %u, %u)", m_uint32Values[OBJECT_FIELD_GUID],
i, itr2->first, seconds + (uint32)UNIXTIME, itr2->second.SpellId, itr2->second.ItemId );
}
}
}
}
void Player::_LoadPlayerCooldowns(QueryResult * result)
{
if( result == NULL )
return;
// we should only really call getMSTime() once to avoid user->system transitions, plus
// the cost of calling a function for every cooldown the player has
uint32 mstime = getMSTime();
uint32 type;
uint32 misc;
uint32 rtime;
uint32 realtime;
uint32 itemid;
uint32 spellid;
PlayerCooldown cd;
do
{
type = result->Fetch()[0].GetUInt32();
misc = result->Fetch()[1].GetUInt32();
rtime = result->Fetch()[2].GetUInt32();
spellid = result->Fetch()[3].GetUInt32();
itemid = result->Fetch()[4].GetUInt32();
if( type >= NUM_COOLDOWN_TYPES )
continue;
// remember the cooldowns were saved in unix timestamp format for the reasons outlined above,
// so restore them back to mstime upon loading
if( (uint32)UNIXTIME > rtime )
continue;
rtime -= (uint32)UNIXTIME;
if( rtime < 10 )
continue;
realtime = mstime + ( ( rtime ) * 1000 );
// apply it back into cooldown map
cd.ExpireTime = realtime;
cd.ItemId = itemid;
cd.SpellId = spellid;
m_cooldownMap[type].insert( make_pair( misc, cd ) );
} while ( result->NextRow( ) );
}
void Player::_FlyhackCheck()
{
if(!sWorld.antihack_flight || m_TransporterGUID != 0 || GetTaxiState() || (sWorld.no_antihack_on_gm && GetSession()->HasGMPermissions()))
return;
MovementInfo * mi = GetSession()->GetMovementInfo();
if(!mi) return; //wtf?
// Falling, CCs, etc. All stuff that could potentially trap a player in mid-air.
if(!(mi->flags & (MOVEFLAG_FALLING | MOVEFLAG_SWIMMING | MOVEFLAG_LEVITATE | MOVEFLAG_FEATHER_FALL)) &&
!(m_special_state & (UNIT_STATE_CHARM | UNIT_STATE_FEAR | UNIT_STATE_ROOT | UNIT_STATE_STUN | UNIT_STATE_POLYMORPH | UNIT_STATE_CONFUSE | UNIT_STATE_FROZEN))
&& !flying_aura && !FlyCheat)
{
float t_height = CollideInterface.GetHeight(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ() + 2.0f);
if(t_height == 999999.0f || t_height == NO_WMO_HEIGHT )
t_height = GetMapMgr()->GetLandHeight(GetPositionX(), GetPositionY());
if(t_height == 999999.0f || t_height == 0.0f) // Can't rely on anyone these days...
return;
float p_height = GetPositionZ();
int32 diff = float2int32(p_height - t_height);
if(diff < 0)
diff = -diff;
if(t_height != p_height && (uint32)diff > sWorld.flyhack_threshold)
{
// Fly hax!
EventTeleport(GetMapId(), GetPositionX(), GetPositionY(), t_height + 2.0f); // relog fix.
sCheatLog.writefromsession(GetSession(), "Caught fly hacking on map %u hovering %u over the terrain.", GetMapId(), diff);
GetSession()->Disconnect();
}
}
}
/************************************************************************/
/* SOCIAL */
/************************************************************************/
void Player::Social_AddFriend(const char * name, const char * note)
{
WorldPacket data(SMSG_FRIEND_STATUS, 10);
map<uint32, char*>::iterator itr;
// lookup the player
PlayerInfo* info = objmgr.GetPlayerInfoByName(name);
Player* player = objmgr.GetPlayer(name, false);
if( info == NULL || ( player != NULL && player->bGMTagOn ) )
{
data << uint8(FRIEND_NOT_FOUND);
m_session->SendPacket(&data);
return;
}
// team check
if( info->team != m_playerInfo->team && m_session->permissioncount == 0 && !sWorld.interfaction_friend)
{
data << uint8(FRIEND_ENEMY) << uint64(info->guid);
m_session->SendPacket(&data);
return;
}
// are we ourselves?
if( info == m_playerInfo )
{
data << uint8(FRIEND_SELF) << GetGUID();
m_session->SendPacket(&data);
return;
}
m_socialLock.Acquire();
itr = m_friends.find(info->guid);
if( itr != m_friends.end() )
{
data << uint8(FRIEND_ALREADY) << uint64(info->guid);
m_session->SendPacket(&data);
m_socialLock.Release();
return;
}
if( info->m_loggedInPlayer != NULL )
{
data << uint8(FRIEND_ADDED_ONLINE);
data << uint64(info->guid);
if( note != NULL )
data << note;
else
data << uint8(0);
data << uint8(1);
data << info->m_loggedInPlayer->GetZoneId();
data << info->lastLevel;
data << uint32(info->cl);
info->m_loggedInPlayer->m_socialLock.Acquire();
info->m_loggedInPlayer->m_hasFriendList.insert( GetLowGUID() );
info->m_loggedInPlayer->m_socialLock.Release();
}
else
{
data << uint8(FRIEND_ADDED_OFFLINE);
data << uint64(info->guid);
}
if( note != NULL )
m_friends.insert( make_pair(info->guid, strdup(note)) );
else
m_friends.insert( make_pair(info->guid, (char*)NULL) );
m_socialLock.Release();
m_session->SendPacket(&data);
// dump into the db
CharacterDatabase.Execute("INSERT INTO social_friends VALUES(%u, %u, \"%s\")",
GetLowGUID(), info->guid, note ? CharacterDatabase.EscapeString(string(note)).c_str() : "");
}
void Player::Social_RemoveFriend(uint32 guid)
{
WorldPacket data(SMSG_FRIEND_STATUS, 10);
map<uint32, char*>::iterator itr;
// are we ourselves?
if( guid == GetLowGUID() )
{
data << uint8(FRIEND_SELF) << GetGUID();
m_session->SendPacket(&data);
return;
}
m_socialLock.Acquire();
itr = m_friends.find(guid);
if( itr != m_friends.end() )
{
if( itr->second != NULL )
free(itr->second);
m_friends.erase(itr);
}
data << uint8(FRIEND_REMOVED);
data << uint64(guid);
m_socialLock.Release();
Player * pl = objmgr.GetPlayer( (uint32)guid );
if( pl != NULL )
{
pl->m_socialLock.Acquire();
pl->m_hasFriendList.erase( GetLowGUID() );
pl->m_socialLock.Release();
}
m_session->SendPacket(&data);
// remove from the db
CharacterDatabase.Execute("DELETE FROM social_friends WHERE character_guid = %u AND friend_guid = %u",
GetLowGUID(), (uint32)guid);
}
void Player::Social_SetNote(uint32 guid, const char * note)
{
map<uint32,char*>::iterator itr;
m_socialLock.Acquire();
itr = m_friends.find(guid);
if( itr == m_friends.end() )
{
m_socialLock.Release();
return;
}
if( itr->second != NULL )
free(itr->second);
if( note != NULL )
itr->second = strdup( note );
else
itr->second = NULL;
m_socialLock.Release();
CharacterDatabase.Execute("UPDATE social_friends SET note = \"%s\" WHERE character_guid = %u AND friend_guid = %u",
note ? CharacterDatabase.EscapeString(string(note)).c_str() : "", GetLowGUID(), guid);
}
void Player::Social_AddIgnore(const char * name)
{
WorldPacket data(SMSG_FRIEND_STATUS, 10);
set<uint32>::iterator itr;
PlayerInfo * info;
// lookup the player
info = objmgr.GetPlayerInfoByName(name);
if( info == NULL )
{
data << uint8(FRIEND_IGNORE_NOT_FOUND);
m_session->SendPacket(&data);
return;
}
// are we ourselves?
if( info == m_playerInfo )
{
data << uint8(FRIEND_IGNORE_SELF) << GetGUID();
m_session->SendPacket(&data);
return;
}
m_socialLock.Acquire();
itr = m_ignores.find(info->guid);
if( itr != m_ignores.end() )
{
data << uint8(FRIEND_IGNORE_ALREADY) << uint64(info->guid);
m_session->SendPacket(&data);
m_socialLock.Release();
return;
}
data << uint8(FRIEND_IGNORE_ADDED);
data << uint64(info->guid);
m_ignores.insert( info->guid );
m_socialLock.Release();
m_session->SendPacket(&data);
// dump into db
CharacterDatabase.Execute("INSERT INTO social_ignores VALUES(%u, %u)", GetLowGUID(), info->guid);
}
void Player::Social_RemoveIgnore(uint32 guid)
{
WorldPacket data(SMSG_FRIEND_STATUS, 10);
set<uint32>::iterator itr;
// are we ourselves?
if( guid == GetLowGUID() )
{
data << uint8(FRIEND_IGNORE_SELF) << GetGUID();
m_session->SendPacket(&data);
return;
}
m_socialLock.Acquire();
itr = m_ignores.find(guid);
if( itr != m_ignores.end() )
{
m_ignores.erase(itr);
}
data << uint8(FRIEND_IGNORE_REMOVED);
data << uint64(guid);
m_socialLock.Release();
m_session->SendPacket(&data);
// remove from the db
CharacterDatabase.Execute("DELETE FROM social_ignores WHERE character_guid = %u AND ignore_guid = %u",
GetLowGUID(), (uint32)guid);
}
bool Player::Social_IsIgnoring(PlayerInfo * m_info)
{
bool res;
m_socialLock.Acquire();
if( m_ignores.find( m_info->guid ) == m_ignores.end() )
res = false;
else
res = true;
m_socialLock.Release();
return res;
}
bool Player::Social_IsIgnoring(uint32 guid)
{
bool res;
m_socialLock.Acquire();
if( m_ignores.find( guid ) == m_ignores.end() )
res = false;
else
res = true;
m_socialLock.Release();
return res;
}
void Player::Social_TellFriendsOnline()
{
if( m_hasFriendList.empty() )
return;
WorldPacket data(SMSG_FRIEND_STATUS, 22);
set<uint32>::iterator itr;
Player * pl;
data << uint8( FRIEND_ONLINE ) << GetGUID() << uint8( 1 );
data << GetAreaID() << getLevel() << uint32(getClass());
m_socialLock.Acquire();
for( itr = m_hasFriendList.begin(); itr != m_hasFriendList.end(); ++itr )
{
pl = objmgr.GetPlayer(*itr);
if( pl != NULL )
pl->GetSession()->SendPacket(&data);
}
m_socialLock.Release();
}
void Player::Social_TellFriendsOffline()
{
if( m_hasFriendList.empty() )
return;
WorldPacket data(SMSG_FRIEND_STATUS, 10);
set<uint32>::iterator itr;
Player * pl;
data << uint8( FRIEND_OFFLINE ) << GetGUID() << uint8( 0 );
m_socialLock.Acquire();
for( itr = m_hasFriendList.begin(); itr != m_hasFriendList.end(); ++itr )
{
pl = objmgr.GetPlayer(*itr);
if( pl != NULL )
pl->GetSession()->SendPacket(&data);
}
m_socialLock.Release();
}
void Player::Social_SendFriendList(uint32 flag)
{
WorldPacket data(SMSG_FRIEND_LIST, 500);
map<uint32,char*>::iterator itr;
set<uint32>::iterator itr2;
Player * plr;
m_socialLock.Acquire();
data << flag;
data << uint32( m_friends.size() + m_ignores.size() );
for( itr = m_friends.begin(); itr != m_friends.end(); ++itr )
{
// guid
data << uint64( itr->first );
// friend/ignore flag.
// 1 - friend
// 2 - ignore
// 3 - muted?
data << uint32( 1 );
// player note
if( itr->second != NULL )
data << itr->second;
else
data << uint8(0);
// online/offline flag
plr = objmgr.GetPlayer( itr->first );
if( plr != NULL )
{
data << uint8( 1 );
data << plr->GetZoneId();
data << plr->getLevel();
data << uint32( plr->getClass() );
}
else
data << uint8( 0 );
}
for( itr2 = m_ignores.begin(); itr2 != m_ignores.end(); ++itr2 )
{
// guid
data << uint64( (*itr2) );
// ignore flag - 2
data << uint32( 2 );
// no note
data << uint8( 0 );
}
m_socialLock.Release();
m_session->SendPacket(&data);
}
void Player::VampiricSpell(uint32 dmg, Unit* pTarget)
{
float fdmg = float(dmg);
uint32 bonus;
int32 perc;
Group * pGroup = GetGroup();
SubGroup * pSubGroup = (pGroup != NULL) ? pGroup->GetSubGroup(GetSubGroup()) : NULL;
GroupMembersSet::iterator itr;
if( ( !m_vampiricEmbrace && !m_vampiricTouch ) || getClass() != PRIEST )
return;
if( m_vampiricEmbrace > 0 && pTarget->m_hasVampiricEmbrace > 0 && pTarget->HasVisialPosAurasOfNameHashWithCaster(SPELL_HASH_VAMPIRIC_EMBRACE, this) )
{
perc = 15;
SM_FIValue(SM_FMiscEffect, &perc, 4);
bonus = float2int32(fdmg * (float(perc)/100.0f));
if( bonus > 0 )
{
Heal(this, 15286, bonus);
// loop party
if( pSubGroup != NULL )
{
for( itr = pSubGroup->GetGroupMembersBegin(); itr != pSubGroup->GetGroupMembersEnd(); ++itr )
{
if( (*itr)->m_loggedInPlayer != NULL && (*itr) != m_playerInfo && (*itr)->m_loggedInPlayer->isAlive() )
Heal( (*itr)->m_loggedInPlayer, 15286, bonus );
}
}
}
}
if( m_vampiricTouch > 0 && pTarget->m_hasVampiricTouch > 0 && pTarget->HasVisialPosAurasOfNameHashWithCaster(SPELL_HASH_VAMPIRIC_TOUCH, this) )
{
perc = 5;
bonus = float2int32(fdmg * (float(perc)/100.0f));
if( bonus > 0 )
{
Energize(this, 34919, bonus, POWER_TYPE_MANA);
// loop party
if( pSubGroup != NULL )
{
for( itr = pSubGroup->GetGroupMembersBegin(); itr != pSubGroup->GetGroupMembersEnd(); ++itr )
{
if( (*itr)->m_loggedInPlayer != NULL && (*itr) != m_playerInfo && (*itr)->m_loggedInPlayer->isAlive() && (*itr)->m_loggedInPlayer->GetPowerType() == POWER_TYPE_MANA )
Energize((*itr)->m_loggedInPlayer, 34919, bonus, POWER_TYPE_MANA);
}
}
}
}
}
void Player::SpeedCheatDelay(uint32 ms_delay)
{
// SDetector->SkipSamplingUntil( getMSTime() + ms_delay );
//add tripple latency to avoid client handleing the spell effect with delay and we detect as cheat
// SDetector->SkipSamplingUntil( getMSTime() + ms_delay + GetSession()->GetLatency() * 3 );
//add constant value to make sure the effect packet was sent to client from network pool
SDetector->SkipSamplingUntil( getMSTime() + ms_delay + GetSession()->GetLatency() * 2 + 2000 ); //2 second should be enough to send our packets to client
}
void Player::SpeedCheatReset()
{
SDetector->EventSpeedChange();
}
uint32 Player::GetMaxPersonalRating()
{
uint32 maxrating = 0;
int i;
ASSERT(m_playerInfo != NULL);
for (i=0; i<NUM_ARENA_TEAM_TYPES; i++)
{
if(m_arenaTeams[i] != NULL)
{
ArenaTeamMember *m = m_arenaTeams[i]->GetMemberByGuid(m_playerInfo->guid);
if (m)
{
if (m->PersonalRating > maxrating) maxrating = m->PersonalRating;
}
else
{
sLog.outError("%s: GetMemberByGuid returned NULL for player guid = %u\n", __FUNCTION__, m_playerInfo->guid);
}
}
}
return maxrating;
}
void Player::SetKnownTitle( RankTitles title, bool set )
{
if( !( HasKnownTitle( title ) ^ set ) )
return;
uint64 current = GetUInt64Value( PLAYER_FIELD_KNOWN_TITLES );
if( set )
SetUInt64Value( PLAYER_FIELD_KNOWN_TITLES, current | uint64(1) << uint8( title ) );
else
SetUInt64Value( PLAYER_FIELD_KNOWN_TITLES, current & ~uint64(1) << uint8( title ) );
if( title >= PVPTITLE_INVISIBLE_NAME ) // to avoid client crash
return;
WorldPacket data( SMSG_TITLE_EARNED, 8 );
data << uint32( title ) << uint32( set ? 1 : 0 );
m_session->SendPacket( &data );
}
void Player::FullHPMP()
{
if(isDead())
ResurrectPlayer();
SetUInt32Value(UNIT_FIELD_HEALTH, GetUInt32Value(UNIT_FIELD_MAXHEALTH));
SetUInt32Value(UNIT_FIELD_POWER1, GetUInt32Value(UNIT_FIELD_MAXPOWER1));
SetUInt32Value(UNIT_FIELD_POWER4, GetUInt32Value(UNIT_FIELD_MAXPOWER4));
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1
],
[
5,
26
],
[
29,
38
],
[
45,
45
],
[
47,
47
],
[
49,
49
],
[
51,
52
],
[
56,
56
],
[
72,
82
],
[
85,
85
],
[
87,
87
],
[
92,
92
],
[
94,
94
],
[
96,
96
],
[
99,
99
],
[
101,
103
],
[
105,
109
],
[
114,
143
],
[
146,
210
],
[
212,
223
],
[
236,
237
],
[
245,
245
],
[
252,
254
],
[
256,
256
],
[
260,
269
],
[
271,
283
],
[
285,
289
],
[
292,
297
],
[
299,
305
],
[
307,
314
],
[
317,
323
],
[
325,
325
],
[
327,
343
],
[
345,
345
],
[
348,
352
],
[
355,
362
],
[
364,
394
],
[
397,
404
],
[
406,
406
],
[
452,
473
],
[
475,
475
],
[
479,
491
],
[
495,
497
],
[
500,
511
],
[
513,
517
],
[
519,
519
],
[
521,
521
],
[
524,
526
],
[
529,
533
],
[
536,
541
],
[
543,
544
],
[
546,
673
],
[
675,
710
],
[
719,
740
],
[
742,
756
],
[
758,
782
],
[
784,
804
],
[
806,
809
],
[
811,
836
],
[
839,
952
],
[
955,
955
],
[
957,
957
],
[
967,
969
],
[
975,
975
],
[
998,
1035
],
[
1038,
1042
],
[
1044,
1110
],
[
1113,
1113
],
[
1115,
1127
],
[
1129,
1151
],
[
1158,
1166
],
[
1168,
1191
],
[
1193,
1193
],
[
1195,
1197
],
[
1202,
1202
],
[
1204,
1219
],
[
1221,
1355
],
[
1357,
1377
],
[
1383,
1383
],
[
1385,
1392
],
[
1395,
1413
],
[
1416,
1498
],
[
1500,
1561
],
[
1563,
1583
],
[
1585,
1613
],
[
1619,
1621
],
[
1630,
1734
],
[
1736,
1766
],
[
1768,
1780
],
[
1785,
1881
],
[
1885,
1909
],
[
1947,
2093
],
[
2096,
2110
],
[
2112,
2122
],
[
2124,
2127
],
[
2130,
2131
],
[
2139,
2238
],
[
2241,
2313
],
[
2315,
2390
],
[
2395,
2395
],
[
2397,
2397
],
[
2399,
2422
],
[
2427,
2552
],
[
2566,
2622
],
[
2629,
2631
],
[
2634,
2787
],
[
2799,
2799
],
[
2805,
2811
],
[
2813,
2854
],
[
2856,
2906
],
[
2908,
3048
],
[
3050,
3058
],
[
3060,
3101
],
[
3112,
3125
],
[
3128,
3130
],
[
3135,
3144
],
[
3146,
3228
],
[
3234,
3238
],
[
3336,
3502
],
[
3504,
3508
],
[
3510,
3516
],
[
3520,
3524
],
[
3527,
3528
],
[
3530,
3599
],
[
3601,
3614
],
[
3616,
3616
],
[
3619,
3622
],
[
3624,
3625
],
[
3627,
3683
],
[
3685,
3702
],
[
3704,
3799
],
[
3802,
3802
],
[
3804,
3890
],
[
3892,
3931
],
[
3933,
3937
],
[
3940,
3940
],
[
3942,
3954
],
[
3959,
3971
],
[
3973,
3996
],
[
4007,
4148
],
[
4150,
4156
],
[
4158,
4158
],
[
4168,
4171
],
[
4176,
4178
],
[
4180,
4182
],
[
4186,
4190
],
[
4193,
4207
],
[
4215,
4215
],
[
4218,
4229
],
[
4231,
4245
],
[
4247,
4247
],
[
4249,
4249
],
[
4255,
4255
],
[
4264,
4266
],
[
4270,
4271
],
[
4273,
4276
],
[
4279,
4279
],
[
4281,
4289
],
[
4300,
4313
],
[
4318,
4321
],
[
4326,
4326
],
[
4328,
4328
],
[
4330,
4330
],
[
4343,
4364
],
[
4368,
4369
],
[
4371,
4442
],
[
4444,
4506
],
[
4508,
4551
],
[
4553,
4557
],
[
4560,
4654
],
[
4657,
4696
],
[
4703,
4789
],
[
4791,
4791
],
[
4793,
4793
],
[
4797,
4797
],
[
4800,
4800
],
[
4803,
4803
],
[
4809,
4809
],
[
4812,
4812
],
[
4815,
4815
],
[
4818,
4818
],
[
4821,
4821
],
[
4824,
4824
],
[
4830,
4830
],
[
4909,
4911
],
[
4913,
4913
],
[
4922,
4922
],
[
4931,
4957
],
[
4972,
4973
],
[
4975,
4975
],
[
4978,
4979
],
[
4982,
4984
],
[
4986,
4990
],
[
4993,
4994
],
[
4996,
4997
],
[
5000,
5000
],
[
5002,
5006
],
[
5008,
5030
],
[
5051,
5052
],
[
5054,
5054
],
[
5058,
5058
],
[
5060,
5061
],
[
5063,
5063
],
[
5068,
5069
],
[
5076,
5076
],
[
5079,
5079
],
[
5085,
5086
],
[
5088,
5088
],
[
5092,
5092
],
[
5094,
5095
],
[
5098,
5127
],
[
5130,
5145
],
[
5147,
5163
],
[
5165,
5165
],
[
5172,
5173
],
[
5177,
5177
],
[
5182,
5182
],
[
5184,
5191
],
[
5193,
5199
],
[
5210,
5353
],
[
5355,
5370
],
[
5374,
5385
],
[
5387,
5407
],
[
5409,
5418
],
[
5420,
5421
],
[
5425,
5491
],
[
5499,
5503
],
[
5505,
5505
],
[
5509,
5509
],
[
5511,
5512
],
[
5514,
5514
],
[
5516,
5584
],
[
5586,
5632
],
[
5634,
5640
],
[
5649,
5668
],
[
5674,
5677
],
[
5679,
5742
],
[
5751,
5774
],
[
5777,
5783
],
[
5793,
5794
],
[
5802,
5833
],
[
5835,
5968
],
[
5970,
5970
],
[
5972,
5973
],
[
5975,
5978
],
[
5980,
5983
],
[
5985,
5986
],
[
5992,
5992
],
[
5994,
5996
],
[
5998,
6000
],
[
6005,
6006
],
[
6008,
6013
],
[
6060,
6060
],
[
6064,
6064
],
[
6066,
6066
],
[
6082,
6082
],
[
6084,
6087
],
[
6089,
6093
],
[
6096,
6103
],
[
6105,
6130
],
[
6132,
6135
],
[
6140,
6149
],
[
6152,
6152
],
[
6154,
6158
],
[
6183,
6231
],
[
6233,
6239
],
[
6249,
6275
],
[
6286,
6287
],
[
6289,
6292
],
[
6294,
6304
],
[
6312,
6352
],
[
6354,
6370
],
[
6372,
6375
],
[
6377,
6402
],
[
6407,
6433
],
[
6437,
6455
],
[
6461,
6494
],
[
6499,
6551
],
[
6556,
6560
],
[
6562,
6579
],
[
6581,
6622
],
[
6624,
6647
],
[
6649,
6655
],
[
6657,
6672
],
[
6674,
6820
],
[
6822,
6865
],
[
6869,
6873
],
[
6875,
6877
],
[
6884,
6892
],
[
6896,
6904
],
[
6907,
6917
],
[
6920,
6928
],
[
6932,
6934
],
[
6940,
6959
],
[
6961,
6979
],
[
6982,
6984
],
[
6986,
7054
],
[
7056,
7057
],
[
7061,
7111
],
[
7113,
7167
],
[
7169,
7372
],
[
7374,
7413
],
[
7415,
7623
],
[
7655,
7672
],
[
7674,
7675
],
[
7677,
7684
],
[
7686,
7711
],
[
7713,
7714
],
[
7716,
7723
],
[
7726,
7726
],
[
7728,
7728
],
[
7730,
7731
],
[
7733,
7733
],
[
7735,
7735
],
[
7737,
7739
],
[
7741,
7742
],
[
7755,
7755
],
[
7761,
7762
],
[
7764,
7824
],
[
7827,
7898
],
[
7922,
7922
],
[
7924,
7928
],
[
7930,
7944
],
[
7949,
7969
],
[
7971,
7972
],
[
7977,
7995
],
[
7999,
8000
],
[
8003,
8028
],
[
8043,
8044
],
[
8047,
8059
],
[
8066,
8093
],
[
8095,
8161
],
[
8189,
8194
],
[
8196,
8226
],
[
8228,
8249
],
[
8253,
8261
],
[
8263,
8265
],
[
8267,
8270
],
[
8272,
8276
],
[
8286,
8286
],
[
8289,
8292
],
[
8305,
8306
],
[
8312,
8332
],
[
8335,
8370
],
[
8380,
8406
],
[
8408,
8416
],
[
8418,
8418
],
[
8420,
8476
],
[
8479,
8494
],
[
8496,
8502
],
[
8516,
8535
],
[
8537,
8537
],
[
8539,
8563
],
[
8572,
8613
],
[
8615,
8654
],
[
8656,
8669
],
[
8675,
8692
],
[
8694,
8699
],
[
8701,
8708
],
[
8710,
8712
],
[
8714,
8714
],
[
8716,
8718
],
[
8721,
8726
],
[
8728,
8743
],
[
8745,
8746
],
[
8751,
8751
],
[
8753,
8753
],
[
8758,
8758
],
[
8761,
8761
],
[
8782,
8782
],
[
8787,
8808
],
[
8811,
8811
],
[
8820,
8820
],
[
8822,
8824
],
[
8826,
8828
],
[
8831,
8856
],
[
8858,
8868
],
[
8871,
8871
],
[
8873,
8881
],
[
8884,
8884
],
[
8886,
8888
],
[
8890,
8895
],
[
8897,
8898
],
[
8900,
8900
],
[
8906,
8906
],
[
9056,
9069
],
[
9073,
9073
],
[
9075,
9075
],
[
9077,
9077
],
[
9079,
9079
],
[
9081,
9092
],
[
9095,
9096
],
[
9100,
9100
],
[
9103,
9104
],
[
9111,
9112
],
[
9117,
9124
],
[
9126,
9128
],
[
9130,
9131
],
[
9134,
9145
],
[
9147,
9147
],
[
9151,
9151
],
[
9153,
9153
],
[
9157,
9157
],
[
9162,
9169
],
[
9171,
9174
],
[
9176,
9176
],
[
9178,
9178
],
[
9181,
9189
],
[
9191,
9191
],
[
9194,
9212
],
[
9219,
9219
],
[
9222,
9222
],
[
9264,
9266
],
[
9268,
9285
],
[
9287,
9328
],
[
9330,
9349
],
[
9351,
9360
],
[
9362,
9371
],
[
9373,
9401
],
[
9404,
9419
],
[
9421,
9421
],
[
9424,
9432
],
[
9435,
9470
],
[
9472,
9584
],
[
9586,
9605
],
[
9607,
9617
],
[
9628,
9628
],
[
9633,
9633
],
[
9636,
9636
],
[
9639,
9639
],
[
9647,
9647
],
[
9655,
9660
],
[
9666,
9669
],
[
9672,
9690
],
[
9693,
9696
],
[
9706,
9741
],
[
9746,
9747
],
[
9749,
9770
],
[
9772,
9792
],
[
9796,
9842
],
[
9844,
9849
],
[
9851,
9851
],
[
9854,
9907
],
[
9915,
9967
],
[
9969,
10015
],
[
10017,
10029
],
[
10031,
10074
],
[
10078,
10078
],
[
10080,
10094
],
[
10108,
10139
],
[
10141,
10351
],
[
10353,
10376
],
[
10378,
10386
],
[
10392,
10394
],
[
10396,
10408
],
[
10410,
10472
],
[
10474,
10538
],
[
10542,
10546
],
[
10550,
10553
],
[
10555,
10564
],
[
10566,
10620
],
[
10622,
10700
],
[
10702,
10702
],
[
10706,
10748
],
[
10750,
10750
],
[
10757,
10760
],
[
10762,
10762
],
[
10769,
10775
],
[
10777,
10779
],
[
10785,
10788
],
[
10790,
10795
],
[
10797,
10825
],
[
10827,
10988
],
[
10990,
10995
],
[
10998,
11000
],
[
11002,
11002
],
[
11004,
11016
],
[
11018,
11031
],
[
11034,
11034
],
[
11036,
11039
],
[
11041,
11042
],
[
11044,
11319
],
[
11321,
11386
],
[
11388,
11389
],
[
11391,
11408
],
[
11410,
11430
],
[
11438,
11439
],
[
11443,
11469
]
],
[
[
2,
4
],
[
27,
28
],
[
39,
44
],
[
46,
46
],
[
48,
48
],
[
50,
50
],
[
53,
55
],
[
57,
71
],
[
83,
84
],
[
86,
86
],
[
88,
91
],
[
93,
93
],
[
95,
95
],
[
97,
98
],
[
100,
100
],
[
104,
104
],
[
110,
113
],
[
144,
145
],
[
211,
211
],
[
224,
235
],
[
238,
244
],
[
246,
251
],
[
255,
255
],
[
257,
259
],
[
270,
270
],
[
284,
284
],
[
290,
291
],
[
298,
298
],
[
306,
306
],
[
315,
316
],
[
324,
324
],
[
326,
326
],
[
344,
344
],
[
346,
347
],
[
353,
354
],
[
363,
363
],
[
395,
396
],
[
405,
405
],
[
407,
451
],
[
474,
474
],
[
476,
478
],
[
492,
494
],
[
498,
499
],
[
512,
512
],
[
518,
518
],
[
520,
520
],
[
522,
523
],
[
527,
528
],
[
534,
535
],
[
542,
542
],
[
545,
545
],
[
674,
674
],
[
711,
718
],
[
741,
741
],
[
757,
757
],
[
783,
783
],
[
805,
805
],
[
810,
810
],
[
837,
838
],
[
953,
954
],
[
956,
956
],
[
958,
966
],
[
970,
974
],
[
976,
997
],
[
1036,
1037
],
[
1043,
1043
],
[
1111,
1112
],
[
1114,
1114
],
[
1128,
1128
],
[
1152,
1157
],
[
1167,
1167
],
[
1192,
1192
],
[
1194,
1194
],
[
1198,
1201
],
[
1203,
1203
],
[
1220,
1220
],
[
1356,
1356
],
[
1378,
1382
],
[
1384,
1384
],
[
1393,
1394
],
[
1414,
1415
],
[
1499,
1499
],
[
1562,
1562
],
[
1584,
1584
],
[
1614,
1618
],
[
1622,
1629
],
[
1735,
1735
],
[
1767,
1767
],
[
1781,
1784
],
[
1882,
1884
],
[
1910,
1946
],
[
2094,
2095
],
[
2111,
2111
],
[
2123,
2123
],
[
2128,
2129
],
[
2132,
2138
],
[
2239,
2240
],
[
2314,
2314
],
[
2391,
2394
],
[
2396,
2396
],
[
2398,
2398
],
[
2423,
2426
],
[
2553,
2565
],
[
2623,
2628
],
[
2632,
2633
],
[
2788,
2798
],
[
2800,
2804
],
[
2812,
2812
],
[
2855,
2855
],
[
2907,
2907
],
[
3049,
3049
],
[
3059,
3059
],
[
3102,
3111
],
[
3126,
3127
],
[
3131,
3134
],
[
3145,
3145
],
[
3229,
3233
],
[
3239,
3335
],
[
3503,
3503
],
[
3509,
3509
],
[
3517,
3519
],
[
3525,
3526
],
[
3529,
3529
],
[
3600,
3600
],
[
3615,
3615
],
[
3617,
3618
],
[
3623,
3623
],
[
3626,
3626
],
[
3684,
3684
],
[
3703,
3703
],
[
3800,
3801
],
[
3803,
3803
],
[
3891,
3891
],
[
3932,
3932
],
[
3938,
3939
],
[
3941,
3941
],
[
3955,
3958
],
[
3972,
3972
],
[
3997,
4006
],
[
4149,
4149
],
[
4157,
4157
],
[
4159,
4167
],
[
4172,
4175
],
[
4179,
4179
],
[
4183,
4185
],
[
4191,
4192
],
[
4208,
4214
],
[
4216,
4217
],
[
4230,
4230
],
[
4246,
4246
],
[
4248,
4248
],
[
4250,
4254
],
[
4256,
4263
],
[
4267,
4269
],
[
4272,
4272
],
[
4277,
4278
],
[
4280,
4280
],
[
4290,
4299
],
[
4314,
4317
],
[
4322,
4325
],
[
4327,
4327
],
[
4329,
4329
],
[
4331,
4342
],
[
4365,
4367
],
[
4370,
4370
],
[
4443,
4443
],
[
4507,
4507
],
[
4552,
4552
],
[
4558,
4559
],
[
4655,
4656
],
[
4697,
4702
],
[
4790,
4790
],
[
4792,
4792
],
[
4794,
4796
],
[
4798,
4799
],
[
4801,
4802
],
[
4804,
4808
],
[
4810,
4811
],
[
4813,
4814
],
[
4816,
4817
],
[
4819,
4820
],
[
4822,
4823
],
[
4825,
4829
],
[
4831,
4908
],
[
4912,
4912
],
[
4914,
4921
],
[
4923,
4930
],
[
4958,
4971
],
[
4974,
4974
],
[
4976,
4977
],
[
4980,
4981
],
[
4985,
4985
],
[
4991,
4992
],
[
4995,
4995
],
[
4998,
4999
],
[
5001,
5001
],
[
5007,
5007
],
[
5031,
5050
],
[
5053,
5053
],
[
5055,
5057
],
[
5059,
5059
],
[
5062,
5062
],
[
5064,
5067
],
[
5070,
5075
],
[
5077,
5078
],
[
5080,
5084
],
[
5087,
5087
],
[
5089,
5091
],
[
5093,
5093
],
[
5096,
5097
],
[
5128,
5129
],
[
5146,
5146
],
[
5164,
5164
],
[
5166,
5171
],
[
5174,
5176
],
[
5178,
5181
],
[
5183,
5183
],
[
5192,
5192
],
[
5200,
5209
],
[
5354,
5354
],
[
5371,
5373
],
[
5386,
5386
],
[
5408,
5408
],
[
5419,
5419
],
[
5422,
5424
],
[
5492,
5498
],
[
5504,
5504
],
[
5506,
5508
],
[
5510,
5510
],
[
5513,
5513
],
[
5515,
5515
],
[
5585,
5585
],
[
5633,
5633
],
[
5641,
5648
],
[
5669,
5673
],
[
5678,
5678
],
[
5743,
5750
],
[
5775,
5776
],
[
5784,
5792
],
[
5795,
5801
],
[
5834,
5834
],
[
5969,
5969
],
[
5971,
5971
],
[
5974,
5974
],
[
5979,
5979
],
[
5984,
5984
],
[
5987,
5991
],
[
5993,
5993
],
[
5997,
5997
],
[
6001,
6004
],
[
6007,
6007
],
[
6014,
6059
],
[
6061,
6063
],
[
6065,
6065
],
[
6067,
6081
],
[
6083,
6083
],
[
6088,
6088
],
[
6094,
6095
],
[
6104,
6104
],
[
6131,
6131
],
[
6136,
6139
],
[
6150,
6151
],
[
6153,
6153
],
[
6159,
6182
],
[
6232,
6232
],
[
6240,
6248
],
[
6276,
6285
],
[
6288,
6288
],
[
6293,
6293
],
[
6305,
6311
],
[
6353,
6353
],
[
6371,
6371
],
[
6376,
6376
],
[
6403,
6406
],
[
6434,
6436
],
[
6456,
6460
],
[
6495,
6498
],
[
6552,
6555
],
[
6561,
6561
],
[
6580,
6580
],
[
6623,
6623
],
[
6648,
6648
],
[
6656,
6656
],
[
6673,
6673
],
[
6821,
6821
],
[
6866,
6868
],
[
6874,
6874
],
[
6878,
6883
],
[
6893,
6895
],
[
6905,
6906
],
[
6918,
6919
],
[
6929,
6931
],
[
6935,
6939
],
[
6960,
6960
],
[
6980,
6981
],
[
6985,
6985
],
[
7055,
7055
],
[
7058,
7060
],
[
7112,
7112
],
[
7168,
7168
],
[
7373,
7373
],
[
7414,
7414
],
[
7624,
7654
],
[
7673,
7673
],
[
7676,
7676
],
[
7685,
7685
],
[
7712,
7712
],
[
7715,
7715
],
[
7724,
7725
],
[
7727,
7727
],
[
7729,
7729
],
[
7732,
7732
],
[
7734,
7734
],
[
7736,
7736
],
[
7740,
7740
],
[
7743,
7754
],
[
7756,
7760
],
[
7763,
7763
],
[
7825,
7826
],
[
7899,
7921
],
[
7923,
7923
],
[
7929,
7929
],
[
7945,
7948
],
[
7970,
7970
],
[
7973,
7976
],
[
7996,
7998
],
[
8001,
8002
],
[
8029,
8042
],
[
8045,
8046
],
[
8060,
8065
],
[
8094,
8094
],
[
8162,
8188
],
[
8195,
8195
],
[
8227,
8227
],
[
8250,
8252
],
[
8262,
8262
],
[
8266,
8266
],
[
8271,
8271
],
[
8277,
8285
],
[
8287,
8288
],
[
8293,
8304
],
[
8307,
8311
],
[
8333,
8334
],
[
8371,
8379
],
[
8407,
8407
],
[
8417,
8417
],
[
8419,
8419
],
[
8477,
8478
],
[
8495,
8495
],
[
8503,
8515
],
[
8536,
8536
],
[
8538,
8538
],
[
8564,
8571
],
[
8614,
8614
],
[
8655,
8655
],
[
8670,
8674
],
[
8693,
8693
],
[
8700,
8700
],
[
8709,
8709
],
[
8713,
8713
],
[
8715,
8715
],
[
8719,
8720
],
[
8727,
8727
],
[
8744,
8744
],
[
8747,
8750
],
[
8752,
8752
],
[
8754,
8757
],
[
8759,
8760
],
[
8762,
8781
],
[
8783,
8786
],
[
8809,
8810
],
[
8812,
8819
],
[
8821,
8821
],
[
8825,
8825
],
[
8829,
8830
],
[
8857,
8857
],
[
8869,
8870
],
[
8872,
8872
],
[
8882,
8883
],
[
8885,
8885
],
[
8889,
8889
],
[
8896,
8896
],
[
8899,
8899
],
[
8901,
8905
],
[
8907,
9055
],
[
9070,
9072
],
[
9074,
9074
],
[
9076,
9076
],
[
9078,
9078
],
[
9080,
9080
],
[
9093,
9094
],
[
9097,
9099
],
[
9101,
9102
],
[
9105,
9110
],
[
9113,
9116
],
[
9125,
9125
],
[
9129,
9129
],
[
9132,
9133
],
[
9146,
9146
],
[
9148,
9150
],
[
9152,
9152
],
[
9154,
9156
],
[
9158,
9161
],
[
9170,
9170
],
[
9175,
9175
],
[
9177,
9177
],
[
9179,
9180
],
[
9190,
9190
],
[
9192,
9193
],
[
9213,
9218
],
[
9220,
9221
],
[
9223,
9263
],
[
9267,
9267
],
[
9286,
9286
],
[
9329,
9329
],
[
9350,
9350
],
[
9361,
9361
],
[
9372,
9372
],
[
9402,
9403
],
[
9420,
9420
],
[
9422,
9423
],
[
9433,
9434
],
[
9471,
9471
],
[
9585,
9585
],
[
9606,
9606
],
[
9618,
9627
],
[
9629,
9632
],
[
9634,
9635
],
[
9637,
9638
],
[
9640,
9646
],
[
9648,
9654
],
[
9661,
9665
],
[
9670,
9671
],
[
9691,
9692
],
[
9697,
9705
],
[
9742,
9745
],
[
9748,
9748
],
[
9771,
9771
],
[
9793,
9795
],
[
9843,
9843
],
[
9850,
9850
],
[
9852,
9853
],
[
9908,
9914
],
[
9968,
9968
],
[
10016,
10016
],
[
10030,
10030
],
[
10075,
10077
],
[
10079,
10079
],
[
10095,
10107
],
[
10140,
10140
],
[
10352,
10352
],
[
10377,
10377
],
[
10387,
10391
],
[
10395,
10395
],
[
10409,
10409
],
[
10473,
10473
],
[
10539,
10541
],
[
10547,
10549
],
[
10554,
10554
],
[
10565,
10565
],
[
10621,
10621
],
[
10701,
10701
],
[
10703,
10705
],
[
10749,
10749
],
[
10751,
10756
],
[
10761,
10761
],
[
10763,
10768
],
[
10776,
10776
],
[
10780,
10784
],
[
10789,
10789
],
[
10796,
10796
],
[
10826,
10826
],
[
10989,
10989
],
[
10996,
10997
],
[
11001,
11001
],
[
11003,
11003
],
[
11017,
11017
],
[
11032,
11033
],
[
11035,
11035
],
[
11040,
11040
],
[
11043,
11043
],
[
11320,
11320
],
[
11387,
11387
],
[
11390,
11390
],
[
11409,
11409
],
[
11431,
11437
],
[
11440,
11442
],
[
11470,
11497
]
]
]
|
eed8a56b33c524d9429d5b063f0e9e44e35cca64 | a5cbc2c1c12b3df161d9028791c8180838fbf2fb | /Heimdall/heimdall/source/EndFileTransferPacket.h | 3f3d689250a4ea21e123eb17fcae6faabd0558ec | [
"MIT"
]
| permissive | atinm/Heimdall | e8659fe869172baceb590bc445f383d8bcb72b82 | 692cda38c99834384c4f0c7687c209f432300993 | refs/heads/master | 2020-03-27T12:29:58.609089 | 2010-12-03T19:25:19 | 2010-12-03T19:25:19 | 1,136,137 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,467 | h | /* Copyright (c) 2010 Benjamin Dobell, Glass Echidna
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/
#ifndef ENDFILETRANSFERPACKET_H
#define ENDFILETRANSFERPACKET_H
// Heimdall
#include "FileTransferPacket.h"
namespace Heimdall
{
class EndFileTransferPacket : public FileTransferPacket
{
public:
enum
{
kDestinationPhone = 0x00,
kDestinationModem = 0x01
};
protected:
enum
{
kDataSize = FileTransferPacket::kDataSize + 16
};
private:
unsigned int destination; // Chip identifier perhaps
unsigned short partialPacketLength; // Length or (length - 65536) if lastFullPacket is odd.
unsigned int lastFullPacketIndex;
unsigned short unknown1;
unsigned int unknown2;
protected:
EndFileTransferPacket(unsigned int destination, unsigned int partialPacketLength, unsigned int lastFullPacketIndex,
unsigned short unknown1, unsigned int unknown2)
: FileTransferPacket(FileTransferPacket::kRequestEnd)
{
this->destination = destination;
if (partialPacketLength > 65535)
{
this->partialPacketLength = (partialPacketLength - 65536);
this->lastFullPacketIndex = lastFullPacketIndex + 1;
}
else
{
this->partialPacketLength = partialPacketLength;
this->lastFullPacketIndex = lastFullPacketIndex;
}
this->unknown1 = unknown1;
this->unknown2 = unknown2;
}
public:
unsigned int GetDestination(void) const
{
return (destination);
}
unsigned int GetPartialPacketLength(void) const
{
if (lastFullPacketIndex % 2 == 0)
return (partialPacketLength);
else
return (partialPacketLength + 65536);
}
unsigned int GetLastFullPacketIndex(void) const
{
return (lastFullPacketIndex - lastFullPacketIndex % 2);
}
unsigned short GetUnknown1(void) const
{
return (unknown1);
}
unsigned int GetUnknown2(void) const
{
return (unknown2);
}
virtual void Pack(void)
{
FileTransferPacket::Pack();
PackInteger(FileTransferPacket::kDataSize, destination);
PackShort(FileTransferPacket::kDataSize + 4, partialPacketLength);
PackInteger(FileTransferPacket::kDataSize + 6, lastFullPacketIndex);
PackShort(FileTransferPacket::kDataSize + 10, unknown1);
PackInteger(FileTransferPacket::kDataSize + 12, unknown2);
}
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
120
]
]
]
|
7d26e46c9c3fd392c17db563baf3d38dc431afc6 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/ConstraintSolver/Solve/hkpSolverResults.inl | ea82ce4a00e0cba12fa361879c4f6c335d07dd51 | []
| 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,434 | inl | /*
*
* 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.
*
*/
inline void hkpSolverResults::init()
{
m_impulseApplied = 0.0f;
m_internalSolverData = 0.0f;
}
inline hkpSolverResults::hkpSolverResults()
{
init();
}
inline hkReal hkpSolverResults::getImpulseApplied() const
{
return m_impulseApplied;
}
/*
* 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,
38
]
]
]
|
0e77b1177ae2a631ca94b2184426d92914327650 | fd4f996b64c1994c5e6d8c8ff78a2549255aacb7 | / nicolinorochetaller --username adrianachelotti/trunk/tp2/Graficador/Figura.h | ce42372edebe4ab6f0c51ca2ea5f7f5bc2fe879a | []
| no_license | adrianachelotti/nicolinorochetaller | 026f32476e41cdc5ac5c621c483d70af7b397fb0 | d3215dfdfa70b6226b3616c78121f36606135a5f | refs/heads/master | 2021-01-10T19:45:15.378823 | 2009-08-05T14:54:42 | 2009-08-05T14:54:42 | 32,193,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | h | // Figura.h: interface for the Figura class.
//
//////////////////////////////////////////////////////////////////////
#if !defined FIGURA_H
#define FIGURA_H
#define COLOR_VACIO 0xFF000000
#include <iostream>
#include <SDL.h>
typedef struct punto
{ int x;
int y;
}Punto;
using namespace std;
class Figura
{
private:
string id;
string idTextura;
Uint32 colorLinea;
Uint32 colorFondo;
bool colorPropio;
public:
/*Constructor */
Figura();
/*Constructor con parametros*/
Figura(string identificador,string idTextura,Uint32 colorLinea,Uint32 colorFondo);
/*Constructor con parametros*/
Figura(string identificador);
/*Destructor */
virtual ~Figura();
/*Setea el identificador de la figura */
void setId(string id);
/*Retorna el identificador de la figura */
string getId();
/*Setea el identificador de la textura de la figura */
void setIdTextura(string idTextura);
/*Retorna el identificador de la textura de la figura */
string getIdTextura();
/*Setea el color de linea de la figura */
void setColorLinea(Uint32 colorLinea);
/*Retorna el color de linea de la figura */
Uint32 getColorLinea();
void establecerColores();
/*Setea el color de fondo de la figura */
void setColorFondo(Uint32 colorFondo);
/*Retorna el color de fondo la figura */
Uint32 getColorFondo();
/*Metodo encargado de dibujar la figura */
virtual int dibujar()=0;
/* Setea un flag para saber si tiene color propio o adopta el del escenario*/
void setColorPropio(bool tiene);
/* Retorna un flag para saber si tiene color propio o adopta el del escenario*/
bool esColorPropio();
};
#endif
| [
"dmpstaltari@0b808588-0f27-11de-aab3-ff745001d230",
"[email protected]@0b808588-0f27-11de-aab3-ff745001d230"
]
| [
[
[
1,
26
],
[
28,
71
],
[
78,
80
]
],
[
[
27,
27
],
[
72,
77
]
]
]
|
c3afce88031e088f66e8af626290735a9e16ef8d | ce81d9179fa1c1867e4bb08a0840d366212fed63 | /thread_boost.cpp | a9cdd3f94297397894722a18e3e5429fbfa63922 | []
| no_license | CyberShadow/kwirk | 18613ac11bbbee1f8fd89216da467c40fecf398f | 48fce1f43e4a43aa5b80ace626f547e3659169f3 | HEAD | 2016-09-05T15:55:44.613775 | 2010-01-03T06:43:42 | 2010-01-03T06:43:42 | 392,870 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | #include <boost/thread/thread.hpp>
#define THREAD boost::thread*
#define THREAD_CREATE(delegate) new boost::thread(delegate)
#define THREAD_JOIN(thread) (thread)->join()
#define THREAD_DESTROY(thread) delete (thread)
| [
"[email protected]"
]
| [
[
[
1,
7
]
]
]
|
e60bd33bca069ecece3284ff52c80b524e83c29f | b8c3d2d67e983bd996b76825f174bae1ba5741f2 | /RTMP/projects/HttpPseudoStreaming/src/posix_main.cpp | 2676a58eda8a64f5a68613c78919e119dcab8fba | []
| no_license | wangscript007/rtmp-cpp | 02172f7a209790afec4c00b8855d7a66b7834f23 | 3ec35590675560ac4fa9557ca7a5917c617d9999 | refs/heads/master | 2021-05-30T04:43:19.321113 | 2008-12-24T20:16:15 | 2008-12-24T20:16:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,491 | cpp | #include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include "server.hpp"
#if !defined(_WIN32)
#include <pthread.h>
#include <signal.h>
int main(int argc, char* argv[])
{
try
{
// Check command line arguments.
if (argc != 4)
{
std::cerr << "Usage: http_server <address> <port> <doc_root>\n";
std::cerr << " For IPv4, try:\n";
std::cerr << " receiver 0.0.0.0 80 .\n";
std::cerr << " For IPv6, try:\n";
std::cerr << " receiver 0::0 80 .\n";
return 1;
}
// Block all signals for background thread.
sigset_t new_mask;
sigfillset(&new_mask);
sigset_t old_mask;
pthread_sigmask(SIG_BLOCK, &new_mask, &old_mask);
// Run server in background thread.
http::server::server s(argv[1], argv[2], argv[3]);
boost::thread t(boost::bind(&http::server::server::run, &s));
// Restore previous signals.
pthread_sigmask(SIG_SETMASK, &old_mask, 0);
// Wait for signal indicating time to shut down.
sigset_t wait_mask;
sigemptyset(&wait_mask);
sigaddset(&wait_mask, SIGINT);
sigaddset(&wait_mask, SIGQUIT);
sigaddset(&wait_mask, SIGTERM);
pthread_sigmask(SIG_BLOCK, &wait_mask, 0);
int sig = 0;
sigwait(&wait_mask, &sig);
// Stop the server.
s.stop();
t.join();
}
catch (std::exception& e)
{
std::cerr << "exception: " << e.what() << "\n";
}
return 0;
}
#endif // !defined(_WIN32)
| [
"fpelliccioni@71ea4c15-5055-0410-b3ce-cda77bae7b57"
]
| [
[
[
1,
66
]
]
]
|
3fd0a5904314e93721f4712604ed520db1290335 | fbd2deaa66c52fc8c38baa90dd8f662aabf1f0dd | /totalFirePower/ta demo/code/3DOParser.cpp | 3e5369945eaae8a3f01a36bc6a055864e6787465 | []
| 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 | 10,102 | cpp | // 3DOParser.cpp: implementation of the C3DOParser class.
//
//////////////////////////////////////////////////////////////////////
#include "3DOParser.h"
#include <math.h>
#include <iostream>
#include <ostream>
#include <fstream>
#include <windows.h>
#include "mygl.h"
//#include <gl\glu.h> // Header File For The GLu32 Library
//#include <gl\glaux.h> // Header File For The Glaux Library
#include "globalstuff.h"
#include "tapalette.h"
#include "infoconsole.h"
#include <vector>
#include "vertexarray.h"
#include "hpihandler.h"
#include <set>
using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
C3DOParser* unitparser;
C3DOParser::C3DOParser()
{
scaleFactor=400000.0f;
}
C3DOParser::~C3DOParser()
{
map<string,S3DO*>::iterator ui;
for(ui=units.begin();ui!=units.end();++ui){
DeleteS3DO(ui->second);
delete ui->second;
}
}
C3DOParser::DeleteS3DO(S3DO *o)
{
glDeleteLists(o->displist,1);
std::vector<S3DO>::iterator di;
for(di=o->childs.begin();di!=o->childs.end();di++)
DeleteS3DO(di);
}
S3DO* C3DOParser::Load3DO(const char *name,float scale,int side)
{
scaleFactor=1/(65536.0f);
string sideName(name);
hpiHandler->MakeLower(sideName);
sideName+=side+'0';
map<string,S3DO*>::iterator ui;
if((ui=units.find(sideName))!=units.end()){
return ui->second;
}
// ifstream ifs(name, ios::in|ios::binary);
int size=hpiHandler->GetFileSize(name);
if(size==0){
MessageBox(0,"No file",name,0);
return 0;
}
fileBuf=new unsigned char[size];
hpiHandler->LoadFile(name,fileBuf);
S3DO* object=new S3DO;
// object->name=name;
_3DObject root;
// ifs.seekg(0);
// ifs.read((char*)&root,sizeof(_3DObject));
curOffset=0;
SimStreamRead(&root,sizeof(_3DObject));
std::vector<float3> vertexes;
GetVertexes(&root,object);
GetPrimitives(object,root.OffsetToPrimitiveArray,root.NumberOfPrimitives,&vertexes,root.SelectionPrimitive,side);
CalcNormals(object);
if(root.OffsetToChildObject>0)
if(!ReadChild(root.OffsetToChildObject,object,side))
object->isEmpty=false;
object->offset.x=root.XFromParent*scaleFactor;
object->offset.y=root.YFromParent*scaleFactor;
object->offset.z=root.ZFromParent*scaleFactor;
object->size=FindSize(object,float3(0,0,0));
units[sideName]=object;
if(sideName.find("armcom")!=string::npos || sideName.find("corcom")!=string::npos)
object->writeName=true;
else
object->writeName=false;
CreateLists(object);
// ifs.Close();
delete[] fileBuf;
return object;
}
C3DOParser:: GetVertexes(_3DObject* o,S3DO* object)
{
curOffset=o->OffsetToVertexArray;
for(int a=0;a<o->NumberOfVertices;a++){
_Vertex v;
SimStreamRead(&v,sizeof(_Vertex));
SVertex vertex;
float3 f;
f.x=-(v.x)*scaleFactor;
f.y=(v.y)*scaleFactor;
f.z=(v.z)*scaleFactor;
vertex.pos=f;
object->vertices.push_back(vertex);
}
}
C3DOParser::GetPrimitives(S3DO *obj, int pos, int num,vertex_vector* vv,int excludePrim,int side)
{
map<int,int> prevHashes;
for(int a=0;a<num;a++){
if(excludePrim==a){
continue;
}
curOffset=pos+a*sizeof(_Primitive);
_Primitive p;
SimStreamRead(&p,sizeof(_Primitive));
SPrimitive sp;
sp.numVertex=p.NumberOfVertexIndexes;
if(sp.numVertex<3)
continue;
curOffset=p.OffsetToVertexIndexArray;
WORD w;
list<int> orderVert;
for(int b=0;b<sp.numVertex;b++){
SimStreamRead(&w,2);
sp.vertices.push_back(w);
orderVert.push_back(w);
}
orderVert.sort();
list<int>::iterator vi;
int vertHash=0;
for(vi=orderVert.begin();vi!=orderVert.end();++vi)
vertHash=(vertHash+*vi)**vi;
sp.texture=0;
if(p.OffsetToTextureName!=0){
sp.texture=texturehandler->GetTexture(GetText(p.OffsetToTextureName).c_str(),side);
if(sp.texture==0)
(*info) << "Parser couldnt get texture " << GetText(p.OffsetToTextureName).c_str() << "\n";
} else {
sp.color[0]=palette[p.PaletteEntry][0]/float(255);
sp.color[1]=palette[p.PaletteEntry][1]/float(255);
sp.color[2]=palette[p.PaletteEntry][2]/float(255);
sp.color[3]=palette[p.PaletteEntry][3]/float(255);
}
float3 n=-(obj->vertices[sp.vertices[1]].pos-obj->vertices[sp.vertices[0]].pos).cross(obj->vertices[sp.vertices[2]].pos-obj->vertices[sp.vertices[0]].pos);
n.Normalize();
sp.normal=n;
if(n.dot(float3(0,-1,0))>0.99){
int ignore=true;
for(int a=0;a<sp.numVertex;++a)
if(obj->vertices[sp.vertices[1]].pos.y>0)
ignore=false;
continue;
}
map<int,int>::iterator phi;
if((phi=prevHashes.find(vertHash))!=prevHashes.end()){
if(n.y>0){
obj->prims[phi->second]=sp;
continue;
} else {
continue;
}
} else {
prevHashes[vertHash]=obj->prims.size();
obj->prims.push_back(sp);
obj->isEmpty=false;
}
curOffset=p.OffsetToVertexIndexArray;
for(b=0;b<sp.numVertex;b++){
SimStreamRead(&w,2);
obj->vertices[w].prims.push_back(obj->prims.size()-1);
}
}
}
void C3DOParser::CalcNormals(S3DO *o)
{
std::vector<SVertex>::iterator vi;
for(vi=o->vertices.begin();vi!=o->vertices.end();++vi){
std::vector<int>::iterator pi;
float3 n(0,0,0);
for(pi=vi->prims.begin();pi!=vi->prims.end();++pi){
n+=o->prims[*pi].normal;
}
n.Normalize();
vi->normal=n;
}
}
std::string C3DOParser::GetText(int pos)
{
// ifs->seekg(pos);
curOffset=pos;
char c;
std::string s;
// ifs->read(&c,1);
SimStreamRead(&c,1);
while(c!=0){
s+=c;
// ifs->read(&c,1);
SimStreamRead(&c,1);
}
return s;
}
bool C3DOParser::ReadChild(int pos, S3DO *root,int side)
{
S3DO object;
_3DObject me;
curOffset=pos;
SimStreamRead(&me,sizeof(_3DObject));
object.offset.x=-me.XFromParent*scaleFactor;
object.offset.y=me.YFromParent*scaleFactor;
object.offset.z=me.ZFromParent*scaleFactor;
std::vector<float3> vertexes;
object.isEmpty=true;
GetVertexes(&me,&object);
GetPrimitives(&object,me.OffsetToPrimitiveArray,me.NumberOfPrimitives,&vertexes,me.SelectionPrimitive,side);
CalcNormals(&object);
bool ret=object.isEmpty;
if(me.OffsetToChildObject>0)
if(!ReadChild(me.OffsetToChildObject,&object,side)){
ret=false;
object.isEmpty=false;
}
root->childs.push_back(object);
if(me.OffsetToSiblingObject>0)
if(!ReadChild(me.OffsetToSiblingObject,root,side))
ret=false;
return ret;
}
C3DOParser::DrawSub(S3DO* o)
{
CVertexArray* va=GetVertexArray();
va->Initialize();
bool nonTexFound=false;
std::vector<SPrimitive>::iterator ps;
taTexture* tex;
for(ps=o->prims.begin();ps!=o->prims.end();ps++){
if(ps->texture!=0 && ps->numVertex==4){
tex=ps->texture;
va->AddVertexTN(o->vertices[ps->vertices[0]].pos,tex->xstart,tex->ystart,o->vertices[ps->vertices[0]].normal);
va->AddVertexTN(o->vertices[ps->vertices[1]].pos,tex->xend,tex->ystart,o->vertices[ps->vertices[1]].normal);
va->AddVertexTN(o->vertices[ps->vertices[2]].pos,tex->xend,tex->yend,o->vertices[ps->vertices[2]].normal);
va->AddVertexTN(o->vertices[ps->vertices[3]].pos,tex->xstart,tex->yend,o->vertices[ps->vertices[3]].normal);
} else if(ps->numVertex==4){
if(!nonTexFound){
glDisable(GL_TEXTURE_2D);
nonTexFound=true;
}
glColor3f(ps->color[0],ps->color[1],ps->color[2]);
glBegin(GL_QUADS);
float3 t=o->vertices[ps->vertices[0]].pos;
glNormalf3(o->vertices[ps->vertices[0]].normal);
glVertex3f(t.x,t.y,t.z);
t=o->vertices[ps->vertices[1]].pos;
glNormalf3(o->vertices[ps->vertices[1]].normal);
glVertex3f(t.x,t.y,t.z);
t=o->vertices[ps->vertices[2]].pos;
glNormalf3(o->vertices[ps->vertices[2]].normal);
glVertex3f(t.x,t.y,t.z);
t=o->vertices[ps->vertices[3]].pos;
glNormalf3(o->vertices[ps->vertices[3]].normal);
glVertex3f(t.x,t.y,t.z);
glEnd();
} else if (ps->numVertex==3) {
if(!nonTexFound){
glDisable(GL_TEXTURE_2D);
nonTexFound=true;
}
glColor3f(ps->color[0],ps->color[1],ps->color[2]);
glBegin(GL_TRIANGLES);
float3 t=o->vertices[ps->vertices[0]].pos;
glNormalf3(o->vertices[ps->vertices[0]].normal);
glVertex3f(t.x,t.y,t.z);
t=o->vertices[ps->vertices[1]].pos;
glNormalf3(o->vertices[ps->vertices[1]].normal);
glVertex3f(t.x,t.y,t.z);
t=o->vertices[ps->vertices[2]].pos;
glNormalf3(o->vertices[ps->vertices[2]].normal);
glVertex3f(t.x,t.y,t.z);
glEnd();
} else {
if(!nonTexFound){
glDisable(GL_TEXTURE_2D);
nonTexFound=true;
}
glNormal3f(ps->normal.x,ps->normal.y,ps->normal.z);
glColor3f(ps->color[0],ps->color[1],ps->color[2]);
glBegin(GL_TRIANGLE_FAN);
std::vector<int>::iterator fi;
for(fi=ps->vertices.begin();fi!=ps->vertices.end();fi++){
float3 t=o->vertices[(*fi)].pos;
glNormalf3(o->vertices[*fi].normal);
glVertex3f(t.x,t.y,t.z);
}
glEnd();
}
}
if(nonTexFound){
glEnable(GL_TEXTURE_2D);
glColor3f(1,1,1);
}
va->DrawArrayTN(GL_QUADS);
}
C3DOParser::CreateLists(S3DO *o)
{
o->displist=glGenLists(1);
glNewList(o->displist,GL_COMPILE);
glColor3f(1,1,1);
DrawSub(o);
glEndList();
std::vector<S3DO>::iterator bs;
for(bs=o->childs.begin();bs!=o->childs.end();bs++){
CreateLists(bs);
}
}
void C3DOParser::SimStreamRead(void *buf, int length)
{
memcpy(buf,&fileBuf[curOffset],length);
curOffset+=length;
}
float C3DOParser::FindSize(S3DO *object, float3 offset)
{
offset+=object->offset;
float maxSize=0;
std::vector<SVertex>::iterator vi;
for(vi=object->vertices.begin();vi!=object->vertices.end();++vi){
float dist=(offset+vi->pos).Length();
if(dist>maxSize)
maxSize=dist;
}
std::vector<S3DO>::iterator si;
for(si=object->childs.begin();si!=object->childs.end();++si){
float dist=FindSize(si,offset);
if(dist>maxSize)
maxSize=dist;
}
return maxSize;
}
| [
"[email protected]"
]
| [
[
[
1,
391
]
]
]
|
6a48962461e364b30b44e5b23e980b40979f488b | e5f7a02c92c5a60c924e07813bc0b7b8944c2ce8 | /8-event_serialization/8.6/win32thunk.cpp | cb18fe7d6a81e9f43e260703588d9324000d2d49 | []
| no_license | 7shi/thunkben | b8fe8f29b43c030721e8a08290c91275c9f455fe | 9bc99c5a957e087bb41bd6f87cf7dfa44e7b55f6 | refs/heads/main | 2022-12-27T19:53:39.322464 | 2011-11-30T16:57:45 | 2011-11-30T16:57:45 | 303,163,701 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 5,292 | cpp | // win32thunk.cpp : アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include "win32thunk.h"
static tstring LoadTString(HINSTANCE hInstance, UINT uID) {
const int buflen = 256;
TCHAR buf[buflen];
LoadString(hInstance, uID, buf, buflen);
return buf;
}
class DragHandler {
Coroutine<bool> cr;
std::function<void()> handler;
public:
int x, y;
DragHandler(Window *win) {
win->MouseMove.push_back([&](int x, int y, WPARAM) {
if (cr.value) { this->x = x; this->y = y; cr(); }
});
win->MouseUp.push_back([&](int button, int x, int y, WPARAM) {
if (cr.value) { cr.value = false; cr(); }
});
}
void operator=(const decltype(handler) &h) {
cr = handler = h;
cr.value = false;
}
void start(int x, int y) {
this->x = x;
this->y = y;
if (!cr.value) { cr.reset(); cr(); }
}
};
struct Rect {
int x, y, w, h;
inline int r() { return x + w; }
inline int b() { return y + h; }
Rect(int x, int y, int w, int h): x(x), y(y), w(w), h(h) {}
bool contains(int px, int py) {
return x <= px && px < r() && y <= py && py < b();
}
};
// このコード モジュールに含まれる関数の宣言を転送します:
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: ここにコードを挿入してください。
MSG msg;
HACCEL hAccelTable;
Window win;
win.MyRegisterClass(hInstance, LoadTString(hInstance, IDC_WIN32THUNK));
win.Command.push_back([&](int id, int e)->bool {
// 選択されたメニューの解析:
switch (id)
{
case IDM_ABOUT:
DialogBox(hInstance, MAKEINTRESOURCE(IDD_ABOUTBOX), win.hWnd, About);
return true;
case IDM_EXIT:
DestroyWindow(win.hWnd);
return true;
}
return false;
});
std::vector<Rect> rects;
rects.push_back(Rect(10, 10, 40, 40));
rects.push_back(Rect(60, 60, 40, 40));
win.Paint.push_back([&](HDC hdc) {
auto oldPen = (HPEN)SelectObject(hdc, GetStockObject(BLACK_PEN));
auto oldBrush = (HBRUSH)SelectObject(hdc, GetStockObject(GRAY_BRUSH));
for (auto it = rects.begin(); it != rects.end(); it++)
Rectangle(hdc, it->x, it->y, it->r(), it->b());
SelectObject(hdc, oldPen);
SelectObject(hdc, oldBrush);
});
DragHandler dh(&win), dh2(&win);
decltype(rects.rbegin()) sel;
win.MouseDown.push_back([&](int btn, int x, int y, WPARAM) {
for (auto it = rects.rbegin(); it != rects.rend(); it++) {
if (it->contains(x, y)) {
sel = it;
if (it->r() - x <= 5 && it->b() - y <= 5)
dh2.start(x, y);
else
dh.start(x, y);
return;
}
}
rects.push_back(Rect(x, y, 2, 2));
sel = rects.rbegin();
dh2.start(x, y);
});
dh = [&] {
int x = dh.x, y = dh.y, rx = sel->x, ry = sel->y;
while (yield(true)) {
auto old = *sel;
sel->x = rx + (dh.x - x);
sel->y = ry + (dh.y - y);
RECT r = { min(old.x, sel->x), min(old.y, sel->y),
max(old.r(), sel->r()), max(old.b(), sel->b()) };
InvalidateRect(win.hWnd, &r, true);
}
};
dh2 = [&] {
int x = dh2.x, y = dh2.y, rw = sel->w, rh = sel->h;
while (yield(true)) {
auto old = *sel;
sel->w = max(rw + (dh2.x - x), 2);
sel->h = max(rh + (dh2.y - y), 2);
RECT r = { sel->x, sel->y,
max(old.r(), sel->r()), max(old.b(), sel->b()) };
InvalidateRect(win.hWnd, &r, true);
}
};
// アプリケーションの初期化を実行します:
if (!win.InitInstance(LoadTString(hInstance, IDS_APP_TITLE), nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32THUNK));
// メイン メッセージ ループ:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
// バージョン情報ボックスのメッセージ ハンドラーです。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
| [
"[email protected]"
]
| [
[
[
1,
175
]
]
]
|
48063c9bec4f635753b8ac95de990eba48779d7d | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEManagedFramework/SEManagedMath/SEManagedColorRGBA.cpp | e4edbac96f36006b270aed0604c3a0b11f48b552 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,266 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "SEManagedFrameworkPCH.h"
#include "SEManagedColorRGBA.h"
using namespace Swing;
using namespace Swing::Tools::ManagedFramework;
//---------------------------------------------------------------------------
ManagedColorRGBA::ManagedColorRGBA()
{
}
//---------------------------------------------------------------------------
ManagedColorRGBA::ManagedColorRGBA(float fR, float fG, float fB, float fA)
{
m_fR = fR;
m_fG = fG;
m_fB = fB;
m_fA = fA;
}
//---------------------------------------------------------------------------
ManagedColorRGBA::ManagedColorRGBA(const SEColorRGBA& rColor)
{
FromColorRGBA(rColor);
}
//---------------------------------------------------------------------------
float ManagedColorRGBA::R::get()
{
return m_fR;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::R::set(float fR)
{
m_fR = fR;
}
//---------------------------------------------------------------------------
float ManagedColorRGBA::G::get()
{
return m_fG;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::G::set(float fG)
{
m_fG = fG;
}
//---------------------------------------------------------------------------
float ManagedColorRGBA::B::get()
{
return m_fB;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::B::set(float fB)
{
m_fB = fB;
}
//---------------------------------------------------------------------------
float ManagedColorRGBA::A::get()
{
return m_fA;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::A::set(float fA)
{
m_fA = fA;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::ToColorRGBA(SEColorRGBA& rColor)
{
rColor.R = m_fR;
rColor.G = m_fG;
rColor.B = m_fB;
rColor.A = m_fA;
}
//---------------------------------------------------------------------------
void ManagedColorRGBA::FromColorRGBA(const SEColorRGBA& rColor)
{
m_fR = rColor.R;
m_fG = rColor.G;
m_fB = rColor.B;
m_fA = rColor.A;
}
//--------------------------------------------------------------------------- | [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
100
]
]
]
|
7d057b8786399badbd94e031dabd2f3580a25db5 | 81b7033dd0d0203290795b51513a4014b084d39d | /rapidxml/RapidXMLWrapper.h | 28a17af486d89949a80abe936592e5b00531677c | []
| no_license | starcid/lua-binding-libraries | d27f5c2fccfeae2d667fdb60c86c3244d9ddc065 | e33c85f773d88d3b31b026464066264820e4c302 | refs/heads/master | 2016-08-04T19:57:05.839477 | 2010-11-15T12:02:08 | 2010-11-15T12:02:08 | 35,589,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,111 | h | /**
* \file RapidXMLWrapper.h
* \brief
* \author YangFan
* \date 2010-7-2 22:16:02
*/
#ifndef RapidXMLWrapper_H_
#define RapidXMLWrapper_H_
#include <locale>
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <string>
#include <sstream>
#include <stdexcept>
#include <tchar.h>
#include "rapidxml.hpp"
#include "rapidxml_print.hpp"
#include "rapidxml_utils.hpp"
using namespace std ;
class RapidXMLWrapper
{
public:
static wstring widen( const string& str )
{
std::wstring temp(str.length(),L' ');
mbstowcs(&temp[0], str.c_str(), str.length());
return temp;
}
static string narrow( const wstring& str )
{
std::string temp(str.length() * 2, ' ');
size_t len = wcstombs(&temp[0], str.c_str(), temp.length());
temp.erase(temp.begin() + len, temp.end());
return temp;
}
};
typedef basic_string<TCHAR> tstring;
class CXmlDocumentWrapper
{
private:
rapidxml::xml_document<> m_doc;
rapidxml::file<>* m_file;
public:
CXmlDocumentWrapper()
:m_file(NULL)
{
}
~CXmlDocumentWrapper()
{
delete m_file;
}
rapidxml::xml_node<>* AsNode()
{
// find the first element child
rapidxml::xml_node<> *node = m_doc.first_node();
while (node)
{
if (node->type() == rapidxml::node_element)
{
return node;
}
node = node->next_sibling();
}
return NULL;
}
rapidxml::xml_document<>* Interface()
{
return &m_doc;
}
bool Load(const wchar_t * pwszFile)
{
return Load(RapidXMLWrapper::narrow(std::wstring(pwszFile)).c_str());
}
bool Load(const char * pszFile)
{
delete m_file;
m_file = new rapidxml::file<>(pszFile);
try
{
m_doc.parse<0>(m_file->data());
return true;
}
catch( rapidxml::parse_error& e)
{
e.what();
}
return false;
}
bool LoadXML(const char * pszXML)
{
try
{
m_doc.parse<0>(m_doc.allocate_string(pszXML));
return true;
}
catch( rapidxml::parse_error& e)
{
e.what();
}
return false;
}
bool Save(const char* pszFile, bool bReserved = true)
{
std::ofstream ofs(pszFile);
ofs << m_doc;
ofs.close();
return true;
}
bool Save(const wchar_t* pwszFile, bool bReserved = true)
{
return Save(RapidXMLWrapper::narrow(pwszFile).c_str(), bReserved);
}
std::string GetXML()
{
basic_ostringstream<char> oss;
oss << m_doc;
return oss.str();
}
};
struct DOMNodeList
{
std::vector<rapidxml::xml_node<>*> m_nodes;
};
class CXmlNodeWrapper
{
private:
rapidxml::xml_node<>* m_pNode;
void UUIDFromString( tstring &val, UUID& uuid )
{
basic_istringstream<TCHAR> is;
unsigned long ulData = 0;
is.str(val.substr(0, 8));
is >> hex >> uuid.Data1;
is.clear();
is.str(val.substr(9, 4));
is >> hex >> ulData;
uuid.Data2 = static_cast<unsigned long>(ulData & 0xFFFF);
is.clear();
is.str(val.substr(14, 4));
is >> hex >> ulData;
uuid.Data3 = static_cast<unsigned short>(ulData & 0xFFFF);
is.clear();
is.str(val.substr(19, 4));
is >> hex >> ulData;
uuid.Data4[0] = (unsigned char)(ulData >> 8) & 0xFF;
uuid.Data4[1] = (unsigned char)ulData & 0xFF;
is.clear();
is.str(val.substr(24, 4));
is >> hex >> ulData;
uuid.Data4[2] = (unsigned char)(ulData >> 8) & 0xFF;
uuid.Data4[3] = (unsigned char)ulData & 0xFF;
is.clear();
is.str(val.substr(28, 4));
is >> hex >> ulData;
uuid.Data4[4] = (unsigned char)(ulData >> 24) & 0xFF;
uuid.Data4[5] = (unsigned char)(ulData >> 16) & 0xFF;
uuid.Data4[6] = (unsigned char)(ulData >> 8) & 0xFF;
uuid.Data4[7] = (unsigned char)ulData & 0xFF;
}
public:
CXmlNodeWrapper()
:m_pNode(NULL)
{
}
CXmlNodeWrapper(rapidxml::xml_node<>* node)
:m_pNode(node)
{
}
~CXmlNodeWrapper()
{
}
void operator=(rapidxml::xml_node<>* pNode)
{
m_pNode = pNode;
}
bool operator==(rapidxml::xml_node<>* pNode)
{
return m_pNode == pNode;
}
bool operator!=(rapidxml::xml_node<>* pNode)
{
return m_pNode != pNode;
}
rapidxml::node_type GetNodeType()
{
if (m_pNode)
{
return m_pNode->type();
}
return rapidxml::node_element;
}
bool ExistAttribute(const TCHAR* AttribName)
{
if (m_pNode)
{
#ifdef _UNICODE
return !!m_pNode->first_attribute(RapidXMLWrapper::narrow(AttribName).c_str());
#else
return !!m_pNode->first_attribute(AttribName);
#endif
}
return false;
}
int NumAttributes()
{
if (m_pNode)
{
int nCount = 0;
rapidxml::xml_attribute<>* attr = m_pNode->first_attribute();
while(attr)
{
nCount++;
attr = attr->next_attribute();
}
return nCount;
}
return 0;
}
tstring Name()
{
if (m_pNode)
{
#ifdef _UNICODE
return RapidXMLWrapper::widen(m_pNode->name());
#else
return m_pNode->name();
#endif
}
return tstring();
}
rapidxml::xml_node<>* Parent()
{
if (m_pNode)
{
return m_pNode->parent();
}
return NULL;
}
rapidxml::xml_node<>* Interface()
{
return m_pNode;
}
void ReplaceNode(rapidxml::xml_node<>* pOldNode,rapidxml::xml_node<>* pNewNode)
{
if (m_pNode)
{
m_pNode->insert_node(pOldNode, pNewNode);
m_pNode->remove_node(pOldNode);
}
}
rapidxml::xml_node<>* InsertBefore(rapidxml::xml_node<>* refNode, rapidxml::xml_node<>* pNode)
{
if (m_pNode)
{
m_pNode->insert_node(refNode, pNode);
return pNode;
}
return NULL;
}
rapidxml::xml_node<>* InsertAfter(rapidxml::xml_node<>* refNode, const TCHAR* nodeName, rapidxml::node_type type = rapidxml::node_element)
{
if (m_pNode)
{
rapidxml::xml_node<>* ref = refNode->next_sibling();
rapidxml::xml_document<>* doc = m_pNode->document();
#ifdef _UNICODE
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(RapidXMLWrapper::narrow(nodeName).c_str()));
#else
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(nodeName));
#endif
if (ref)
{
m_pNode->insert_node(ref, newNode);
}
else
{
m_pNode->append_node(newNode);
}
return newNode;
}
return NULL;
}
rapidxml::xml_node<>* InsertBefore(rapidxml::xml_node<>* refNode, const TCHAR* nodeName, rapidxml::node_type type = rapidxml::node_element)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
#ifdef _UNICODE
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(RapidXMLWrapper::narrow(nodeName).c_str()));
#else
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(nodeName));
#endif
m_pNode->insert_node(refNode, newNode);
return newNode;
}
return NULL;
}
rapidxml::xml_node<>* InsertNode(int index,const TCHAR* nodeName, rapidxml::node_type type = rapidxml::node_element)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
#ifdef _UNICODE
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(RapidXMLWrapper::narrow(nodeName).c_str()));
#else
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(nodeName));
#endif
int count = 0;
for (rapidxml::xml_node<>* node = m_pNode->first_node();
node;
node = node->next_sibling(), count++)
{
if (count == index)
{
m_pNode->insert_node(node, newNode);
return newNode;
}
}
m_pNode->append_node(newNode);
return newNode;
}
return NULL;
}
rapidxml::xml_node<>* InsertNode(int index,rapidxml::xml_node<>* pNode)
{
if (m_pNode)
{
int count = 0;
for (rapidxml::xml_node<>* node = m_pNode->first_node();
node;
node = node->next_sibling(), count++)
{
if (count == index)
{
m_pNode->insert_node(node, pNode);
return pNode;
}
}
m_pNode->append_node(pNode);
return pNode;
}
return NULL;
}
rapidxml::xml_node<>* AppendNode(const TCHAR* nodeName, rapidxml::node_type type = rapidxml::node_element)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
#ifdef _UNICODE
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(RapidXMLWrapper::narrow(nodeName).c_str()));
#else
rapidxml::xml_node<>* newNode = doc->allocate_node(type,
doc->allocate_string(nodeName));
#endif
m_pNode->append_node(newNode);
return newNode;
}
return NULL;
}
rapidxml::xml_node<>* AppendNode(rapidxml::xml_node<>* pNode)
{
if (m_pNode)
{
m_pNode->append_node(pNode);
return pNode;
}
return NULL;
}
rapidxml::xml_node<>* RemoveNode(rapidxml::xml_node<>* pNode)
{
if (m_pNode)
{
m_pNode->remove_node(pNode);
return pNode;
}
return NULL;
}
void RemoveNodes(const TCHAR * searchString)
{
if (m_pNode)
{
rapidxml::xml_node<> * node =
#ifdef _UNICODE
m_pNode->first_node(RapidXMLWrapper::narrow(searchString).c_str());
#else
m_pNode->first_node(searchString);
#endif
while (node)
{
m_pNode->remove_node(node);
node =
#ifdef _UNICODE
m_pNode->next_sibling(RapidXMLWrapper::narrow(searchString).c_str());
#else
m_pNode->next_sibling(searchString);
#endif
}
}
}
long NumNodes()
{
long nCount = 0;
if (m_pNode)
{
for (rapidxml::xml_node<>* node = m_pNode->first_node();
node;
node = node->next_sibling())
{
nCount++;
}
}
return nCount;
}
rapidxml::xml_node<>* FindNode(const TCHAR* searchString)
{
if (m_pNode)
{
#ifdef _UNICODE
return m_pNode->first_node(RapidXMLWrapper::narrow(searchString).c_str());
#else
return m_pNode->first_node(searchString);
#endif
}
return NULL;
}
rapidxml::xml_node<>* GetPrevSibling()
{
if (m_pNode)
{
return m_pNode->previous_sibling();
}
return NULL;
}
rapidxml::xml_node<>* GetNextSibling()
{
if (m_pNode)
{
return m_pNode->next_sibling();
}
return NULL;
}
rapidxml::xml_document<>* Document()
{
if (m_pNode)
{
return m_pNode->document();
}
return NULL;
}
void SetValue(const TCHAR* valueName, const TCHAR* value)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
rapidxml::xml_attribute<>* attr =
#ifdef _UNICODE
m_pNode->first_attribute(RapidXMLWrapper::narrow(valueName).c_str());
#else
m_pNode->first_attribute(valueName);
#endif
if (!attr)
{
// append the new attribute
#ifdef _UNICODE
attr = doc->allocate_attribute(
doc->allocate_string(
RapidXMLWrapper::narrow(valueName).c_str()));
#else
attr = doc->allocate_attribute(
doc->allocate_string(valueName));
#endif
m_pNode->append_attribute(attr);
}
// set the value
#ifdef _UNICODE
attr->value(doc->allocate_string(RapidXMLWrapper::narrow(value).c_str()));
#else
attr->value(doc->allocate_string(value));
#endif
}
}
void SetValue(const TCHAR* valueName, int value)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
_countof(val),
_T("%d"),
value);
#else
_stprintf(
val,
_T("%d"),
value);
#endif
SetValue(valueName, val);
}
void SetValue(const TCHAR* valueName, short value)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
_countof(val),
_T("%d"),
value);
#else
_stprintf(
val,
_T("%d"),
value);
#endif
SetValue(valueName, val);
}
void SetValue(const TCHAR* valueName, double value)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
_countof(val),
_T("%f"),
value);
#else
_stprintf(
val,
_T("%f"),
value);
#endif
SetValue(valueName, val);
}
void SetValue(const TCHAR* valueName, float value)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
_countof(val),
_T("%f"),
value);
#else
_stprintf(
val,
_T("%f"),
value);
#endif
SetValue(valueName, val);
}
void SetValue(const TCHAR* valueName, bool value)
{
SetValue(valueName, value ? _T("true") : _T("false"));
}
void SetValue(const TCHAR* valueName, UUID& value)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(val,
sizeof(val)/sizeof(val[0]),
_T("%8.8X-%4.4X-%4.4X-%2.2X%2.2X%-2.2X%2.2X%2.2X%2.2X%2.2X%2.2X"),
value.Data1, value.Data2, value.Data3,
value.Data4[0], value.Data4[1], value.Data4[2],
value.Data4[3], value.Data4[4], value.Data4[5],
value.Data4[6], value.Data4[7] );
#else
_stprintf(val,
_T("%8.8X-%4.4X-%4.4X-%2.2X%2.2X%-2.2X%2.2X%2.2X%2.2X%2.2X%2.2X"),
(unsigned int)value.Data1, value.Data2, value.Data3,
value.Data4[0], value.Data4[1], value.Data4[2],
value.Data4[3], value.Data4[4], value.Data4[5],
value.Data4[6], value.Data4[7] );
#endif
SetValue(valueName,val);
}
void SetText(const TCHAR* text)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
#ifdef _UNICODE
m_pNode->value(doc->allocate_string(RapidXMLWrapper::narrow(text).c_str()));
#else
m_pNode->value(doc->allocate_string(text));
#endif
}
}
void SetText(int text)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
sizeof(val)/sizeof(val[0]),
#else
_stprintf(
val,
#endif
_T("%ds"),
text);
SetText(val);
}
void SetText(short text)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
sizeof(val)/sizeof(val[0]),
#else
_stprintf(
val,
#endif
_T("%d"),
text);
SetText(val);
}
void SetText(double text)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
sizeof(val)/sizeof(val[0]),
#else
_stprintf(
val,
#endif
_T("%f"),
text);
SetText(val);
}
void SetText(float text)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
sizeof(val)/sizeof(val[0]),
#else
_stprintf(
val,
#endif
_T("%f"),
text);
SetText(val);
}
void SetText(bool text)
{
SetText(text ? _T("true") : _T("false"));
}
void SetText(UUID& text)
{
TCHAR val[100] = {0};
#if _MSC_VER >=1400
_stprintf_s(
val,
sizeof(val)/sizeof(val[0]),
#else
_stprintf(
val,
#endif
_T("%8.8X-%4.4X-%4.4X-%2.2X%2.2X%-2.2X%2.2X%2.2X%2.2X%2.2X%2.2X"),
(unsigned int)text.Data1, text.Data2, text.Data3,
text.Data4[0], text.Data4[1], text.Data4[2],
text.Data4[3], text.Data4[4], text.Data4[5],
text.Data4[6], text.Data4[7] );
SetText(val);
}
tstring GetValue(const TCHAR* valueName)
{
if (m_pNode)
{
rapidxml::xml_document<>* doc = m_pNode->document();
rapidxml::xml_attribute<>* attr =
#ifdef _UNICODE
m_pNode->first_attribute( doc->allocate_string(RapidXMLWrapper::narrow(valueName).c_str()));
#else
m_pNode->first_attribute( doc->allocate_string(valueName));
#endif
if (attr)
{
#ifdef _UNICODE
return RapidXMLWrapper::widen(attr->value());
#else
return string(attr->value());
#endif
}
}
return tstring();
}
int GetIntValue(const TCHAR* valueName)
{
tstring val = GetValue(valueName);
if (!val.empty())
{
return _ttoi(val.c_str());
}
return 0xFFFFFFFF;
}
DWORD GetHexValue(const TCHAR* valueName)
{
unsigned int dwRet = 0xFFFFFFFF;
tstring val = GetValue(valueName);
if (!val.empty())
{
transform(val.begin(), val.end(), val.begin(), ::tolower);
#if _MSC_VER >=1400
_stscanf_s
#else
_stscanf
#endif
(val.c_str(),_T("0x%x"), &dwRet);
}
return dwRet;
}
COLORREF GetColorValue(const TCHAR* valueName)
{
COLORREF crRet = RGB(0,0,0);
DWORD dwColor = GetHexValue(valueName);
crRet = RGB((dwColor & 0xFF0000)>> 16, (dwColor & 0x00FF00) >> 8, dwColor & 0xff);
return crRet;
}
UUID GetUUIDValue(const TCHAR* valueName)
{
UUID uuid = {0};
tstring val = GetValue(valueName);
if (!val.empty())
{
UUIDFromString(val, uuid);
}
return uuid;
}
tstring GetText()
{
if (m_pNode)
{
tstring text =
#ifdef _UNICODE
RapidXMLWrapper::widen(m_pNode->value());
#else
m_pNode->value();
#endif
return text;
}
return tstring();
}
int GetIntText()
{
int nRet = 0xFFFFFFFF;
if (m_pNode)
{
tstring text =
#ifdef _UNICODE
RapidXMLWrapper::widen(m_pNode->value());
#else
m_pNode->value();
#endif
if (!text.empty())
{
nRet = _ttoi(text.c_str());
}
}
return nRet;
}
DWORD GetHexText()
{
unsigned int dwRet = 0xFFFFFFFF;
if (m_pNode)
{
tstring text =
#ifdef _UNICODE
RapidXMLWrapper::widen(m_pNode->value());
#else
m_pNode->value();
#endif
if (!text.empty())
{
transform(text.begin(), text.end(), text.begin(), ::tolower);
#if _MSC_VER >=1400
_stscanf_s
#else
_stscanf
#endif
(text.c_str(),_T("0x%x"), &dwRet);
}
}
return dwRet;
}
COLORREF GetColorText()
{
COLORREF crRet = RGB(0,0,0);
if (m_pNode)
{
tstring text =
#ifdef _UNICODE
RapidXMLWrapper::widen(m_pNode->value());
#else
m_pNode->value();
#endif
if (!text.empty())
{
transform(text.begin(), text.end(), text.begin(), ::tolower);
unsigned int dwRet = 0;
#if _MSC_VER >=1400
_stscanf_s
#else
_stscanf
#endif
(text.c_str(),_T("0x%x"), &dwRet);
crRet = RGB((dwRet & 0xFF0000)>> 16, (dwRet & 0x00FF00) >> 8, dwRet & 0xff);
}
}
return crRet;
}
UUID GetUUIDText()
{
UUID uuid = {0};
if (m_pNode)
{
tstring text =
#ifdef _UNICODE
RapidXMLWrapper::widen(m_pNode->value());
#else
m_pNode->value();
#endif
UUIDFromString(text, uuid);
}
return uuid;
}
bool IsValid()
{
return (m_pNode != NULL);
}
DOMNodeList FindNodes(const TCHAR* searchString)
{
if (m_pNode)
{
DOMNodeList nl;
#ifdef _UNICODE
string searchStr = RapidXMLWrapper::narrow(searchString);
for (rapidxml::xml_node<>* node = m_pNode->first_node(
searchStr.c_str());
node;
node = node->next_sibling(searchStr.c_str()))
#else
for (rapidxml::xml_node<>* node = m_pNode->first_node(searchString);
node;
node = node->next_sibling(searchString))
#endif
{
nl.m_nodes.push_back(node);
}
return nl;
}
return DOMNodeList();
}
DOMNodeList ChildNodes()
{
if (m_pNode)
{
DOMNodeList nl;
for (rapidxml::xml_node<>* node = m_pNode->first_node();
node;
node = node->next_sibling())
{
nl.m_nodes.push_back(node);
}
return nl;
}
return DOMNodeList();
}
};
class CXmlNodelistWrapper;
class CXmlNodeIterator
: public std::iterator<std::bidirectional_iterator_tag, CXmlNodeWrapper>
{
private:
std::vector<rapidxml::xml_node<>*> m_nodelist;
size_t m_nIndex;
CXmlNodeWrapper m_refNode;
public:
explicit CXmlNodeIterator(size_t index,std::vector<rapidxml::xml_node<>*>& nodelist)
:m_nodelist(nodelist)
,m_nIndex(index)
{
if ( m_nIndex >= nodelist.size() || m_nIndex == 0xFFFFFFFF)
{
m_nIndex = 0xFFFFFFFF;
}
}
~CXmlNodeIterator()
{
}
size_t Index() const { return m_nIndex; }
void Index(size_t val) { m_nIndex = val; }
CXmlNodeIterator& operator++() // prefix
{
size_t nIndex = ++m_nIndex;
if (nIndex == 0 || nIndex >= m_nodelist.size())
{
m_nIndex = 0xFFFFFFFF;
}
return *this;
}
CXmlNodeIterator operator++(int) // postfix
{
CXmlNodeIterator old = *this;
size_t nIndex = ++m_nIndex;
if (nIndex == 0 || nIndex >= m_nodelist.size())
{
m_nIndex = 0xFFFFFFFF;
}
return old;
}
CXmlNodeIterator& operator--() // prefix
{
size_t nIndex = m_nIndex--;
if (nIndex == 0xFFFFFFFF || m_nIndex == 0xFFFFFFFF )
{
m_nIndex = 0xFFFFFFFF;
}
return *this;
}
CXmlNodeIterator operator--(int) // postfix
{
CXmlNodeIterator old = *this;
size_t nIndex = m_nIndex--;
if (nIndex == 0xFFFFFFFF ||m_nIndex == 0xFFFFFFFF )
{
m_nIndex = 0xFFFFFFFF;
}
return old;
}
CXmlNodeIterator& operator+=(int n)
{
if(m_nIndex == 0xFFFFFFFF)
{
return *this;
}
m_nIndex += n;
if (++m_nIndex >= m_nodelist.size())
{
m_nIndex = 0xFFFFFFFF;
}
return *this;
}
CXmlNodeIterator& operator-=(int n)
{
if (m_nIndex < (size_t)n)
{
m_nIndex = 0xFFFFFFFF;
return *this;
}
m_nIndex -= n;
if (--m_nIndex < 0)
{
m_nIndex = 0xFFFFFFFF;
}
return *this;
}
CXmlNodeIterator operator+(CXmlNodeIterator& iter)
{
return CXmlNodeIterator(iter.Index() + m_nIndex, m_nodelist);
}
CXmlNodeIterator operator-(CXmlNodeIterator& iter)
{
return CXmlNodeIterator(iter.Index() - m_nIndex, m_nodelist);
}
bool operator>(CXmlNodeIterator& iter)
{
return m_nIndex > iter.Index();
}
bool operator>=(CXmlNodeIterator& iter)
{
return m_nIndex >= iter.Index();
}
bool operator<(CXmlNodeIterator& iter)
{
return m_nIndex < iter.Index();
}
bool operator<=(CXmlNodeIterator& iter)
{
return m_nIndex <= iter.Index();
}
bool operator==(CXmlNodeIterator& iter)
{
return m_nIndex == iter.Index();
}
bool operator!=(CXmlNodeIterator& iter)
{
return m_nIndex != iter.Index();
}
reference operator*()
{
m_refNode = m_nodelist.at(m_nIndex);
return m_refNode;
}
pointer operator->()
{
m_refNode = m_nodelist.at(m_nIndex);
return &m_refNode;
}
};
class CXmlNodelistWrapper
{
private:
rapidxml::xml_node<>* m_refNode;
DOMNodeList m_pNodelist;
public:
typedef rapidxml::xml_node<>* value_type;
typedef CXmlNodeIterator iterator;
typedef const CXmlNodeIterator const_iterator;
typedef CXmlNodeWrapper& reference;
typedef const CXmlNodeWrapper const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
CXmlNodelistWrapper(const DOMNodeList& Nodelist)
:m_refNode(NULL)
,m_pNodelist(Nodelist)
{
}
CXmlNodelistWrapper(DOMNodeList* pNodelist)
:m_refNode(NULL)
,m_pNodelist(*pNodelist)
{
}
CXmlNodelistWrapper()
:m_refNode(NULL)
{
}
virtual ~CXmlNodelistWrapper()
{
}
rapidxml::xml_document<>* AsDocument()
{
if (!m_pNodelist.m_nodes.empty())
{
rapidxml::xml_node<>* node = m_pNodelist.m_nodes.at(0);
return node->document();
}
return NULL;
}
rapidxml::xml_node<>* Node(size_t nIndex)
{
if (m_pNodelist.m_nodes.size() > nIndex)
{
return m_pNodelist.m_nodes.at(nIndex);
}
return NULL;
}
bool IsValid()
{
return (m_pNodelist.m_nodes.empty() == false);
}
int Count()
{
return m_pNodelist.m_nodes.size();
}
iterator begin()
{
iterator iter(0, m_pNodelist.m_nodes);
return iter;
}
const_iterator begin() const
{
const_iterator iter(0, (std::vector<rapidxml::xml_node<>*>&)m_pNodelist.m_nodes);
return iter;
}
iterator end()
{
iterator iter(0xFFFFFFFF, m_pNodelist.m_nodes);
return iter;
}
reference operator[](size_type index)
{
m_refNode = IsValid() ? m_pNodelist.m_nodes.at(index) : NULL;
return (reference)m_refNode;
}
const_reference operator[](size_type index) const
{
CXmlNodeIterator refNode(index, (std::vector<rapidxml::xml_node<>*>&)m_pNodelist.m_nodes);
return *refNode;
}
reference at(size_type index)
{
if (index >= m_pNodelist.m_nodes.size())
{
std::string err_msg = "out of XMLrapidxml::xml_node<>list range";
throw std::out_of_range(err_msg);
}
m_refNode = IsValid() ? m_pNodelist.m_nodes.at(index) : NULL;
return reference(m_refNode);
}
reference front()
{
m_refNode = IsValid() ? m_pNodelist.m_nodes.at(0) : NULL;
return (reference)m_refNode;
}
const_reference front() const
{
CXmlNodeIterator refNode(0, (std::vector<rapidxml::xml_node<>*>&)m_pNodelist.m_nodes);
return *refNode;
}
reference back()
{
m_refNode = IsValid() ? m_pNodelist.m_nodes.at(m_pNodelist.m_nodes.size() -1) : NULL;
return (reference)m_refNode;
}
const_reference back() const
{
CXmlNodeIterator refNode(m_pNodelist.m_nodes.size() -1, (std::vector<rapidxml::xml_node<>*>&)m_pNodelist.m_nodes);
return *refNode;
}
size_type size()
{
return (size_type)(IsValid() ? m_pNodelist.m_nodes.size() : 0);
}
bool empty()
{
return IsValid() ? (m_pNodelist.m_nodes.size() == 0) : true;
}
void operator=(DOMNodeList& pNode)
{
m_pNodelist = pNode;
}
void operator=(DOMNodeList* pNode)
{
m_pNodelist = *pNode;
}
};
#endif | [
"missdeer@959521e0-e54e-11de-9298-fbd6a473cdd1"
]
| [
[
[
1,
1313
]
]
]
|
a64099bb4f78f022437bcaa1b9f6036792a35f05 | c9efecddc566c701b4b24b9d0997eb3cf929e5f5 | /OgreMetaballs/MetaballsAbstractScene.cpp | c704d3949774446972d15cb7443309a55706842e | []
| no_license | vlalo001/metaballs3d | f8ee9404f28cda009654f8edf2f322c72d5bfe8a | a24fddce4ec73fc7348287e2074268cc2920cc2f | refs/heads/master | 2021-01-20T16:56:20.721059 | 2009-07-24T16:33:36 | 2009-07-24T16:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 267 | cpp | #include "MetaballsAbstractScene.h"
//-----------------------------------
// MetaballsAbstractScene
//-----------------------------------
MetaballsAbstractScene::MetaballsAbstractScene(void)
{
}
MetaballsAbstractScene::~MetaballsAbstractScene(void)
{
} | [
"garry.wls@99a8374a-4571-11de-aeda-3f4d37dfb5fa"
]
| [
[
[
1,
13
]
]
]
|
eb7c7aed5b39a1cb0c0e4c2959e4103b973b60c5 | 2e5fd1fc05c0d3b28f64abc99f358145c3ddd658 | /mqfeeder/source/main.cpp | e39c759b92047303691bd660c97a3ff9c9d58124 | []
| no_license | indraj/fixfeed | 9365c51e2b622eaff4ce5fac5b86bea86415c1e4 | 5ea71aab502c459da61862eaea2b78859b0c3ab3 | refs/heads/master | 2020-12-25T10:41:39.427032 | 2011-02-15T13:38:34 | 2011-02-15T20:50:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | #include <stdlib.h>
#include <iostream>
#include <quickfix/SocketInitiator.h>
#include <quickfix/SessionSettings.h>
#include <quickfix/FileStore.h>
#include <zmq.hpp>
#include <zmq_tick_publisher.h>
#include <MQFeederApplication.h>
using namespace fixlib;
int main() {
try{
FIX::SessionSettings settings( "../mqfeed.cfg" );
zmq::context_t zmq_ctx(1);
std::string bind_address = settings.get().getString("BindAddress");
boost::shared_ptr<tick_publisher> publisher(new zmq_tick_publisher(zmq_ctx, bind_address));
boost::shared_ptr<MQFeederApplication> app(new MQFeederApplication(settings, publisher));
// FIX::FileStoreFactory storeFactory(settings);
FIX::MemoryStoreFactory storeFactory;
FIX::ScreenLogFactory logFactory( settings );
FIX::SocketInitiator initiator( *app, storeFactory, settings, logFactory );
initiator.start();
std::cout << "Running FIX MQ feeder (Ctrl-C to quit)" << std::endl;
while(true)
FIX::process_sleep(1);
initiator.stop();
return EXIT_SUCCESS;
}
catch ( std::exception & e )
{
std::cout << e.what() << std::endl;
return EXIT_FAILURE;
}
}
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
c982df3ed8bea48fe5bb4e81744f335a6bf94528 | 3bf3c2da2fd334599a80aa09420dbe4c187e71a0 | /TrapTower.cpp | 39cde99a10adde094d6473b4a2b2ab15fe48703a | []
| no_license | xiongchiamiov/virus-td | 31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f | a7b24ce50d07388018f82d00469cb331275f429b | refs/heads/master | 2020-12-24T16:50:11.991795 | 2010-06-10T05:05:48 | 2010-06-10T05:05:48 | 668,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | #include "TrapTower.h"
#include "constants.h"
#include "models.h"
#include "Particles.h"
#include "shadow.h"
namespace tr_tower{
const int MAX_UPGRADES = 3;
const int MAX_HP[MAX_UPGRADES] = {12, 16, 18};
const int ATK[MAX_UPGRADES] = {1, 3, 5};
const int ATK_DT[MAX_UPGRADES] = {3000, 3000, 3000}; //Milleseconds between attacks
const float RANGE[MAX_UPGRADES] = {1.5, 1.5, 1.5};
const int BUILD_TIME = 3000;
char* SOUND = "media/sounds/big_laser2.wav";
}
using namespace tr_tower;
TrapTower::TrapTower(float inx, float iny, float inz, int gx, int gy):
Tower(inx, iny, inz, gx, gy)/*, hp(MAX_HP), max_hp(MAX_HP), atk_dmg(ATK),
type(T_BASIC), build_time(BUILD_TIME), stage(0)*/
{
hp = MAX_HP[0];
max_hp = MAX_HP[0];
ai.atk_dmg = ATK[0];
ai.atk_dt = ATK_DT[0];
ai.range = RANGE[0];
type = T_TRAP;
build_time = BUILD_TIME;
stage = 0;
sound = SOUND;
ai.hasTarget = false;
weapon = new Particles(0.2);
weapon->setWeaponType(particle_texture[2]);
weapon->setSpread(0.0);
weapon->setDirection(1.0, 0.0, 1.0, false);
weapon->setAoE(true, true);
weapon->setSpeed(10.0);
weapon->setCutOffs(8, 8, 8);
weapon->reset(); // must call reset before animating to get latest values.
}
TrapTower::~TrapTower(void)
{
}
void TrapTower::draw(GLuint id, GLenum mode){
glPushMatrix();
setMaterial(Exp);
glTranslatef(x, y, z);
glPushMatrix();
glPushMatrix();
glTranslatef(-0.2, 0.25, 0.0);
glScaled(0.15, 0.15, 0.15);
if(mode == GL_RENDER)
weapon->drawParticles();
glPopMatrix();
setMaterial(Black);
glScalef(.5,.5,.5);
if(mode == GL_SELECT)
glLoadName(id);
double dist = sqrt((getX() - cam.getCamX()) * (getX() - cam.getCamX())
+ (getY() - cam.getCamY()) * (getY() - cam.getCamY())
+ (getZ() - cam.getCamZ()) * (getZ() - cam.getCamZ()));
if (dist <= 8) {
glCallList(vtd_dl::blkhatL3DL);
} else if (dist <= 11) {
glCallList(vtd_dl::blkhatL2DL);
} else {
glCallList(vtd_dl::blkhatL1DL);
}
//glutSolidTorus(0.2, 0.25, 10, 10);
glPopMatrix();
glPushMatrix();
if(mode == GL_RENDER)
draw_shadow(6);
glPopMatrix();
glPopMatrix();
}
void TrapTower::step(float dt){
}
bool TrapTower::shoot(){
bool ret = false;
std::list<Unit*>::iterator i;
for(i = ai.targetList->begin(); i != ai.targetList->end(); ++i){
if(!(*i)->isDead() && ai.range > ai.getDistance(**i)){
(*i)->takeDamage(ai.atk_dmg);
ret = true;
}
}
return ret;
}
bool TrapTower::upgrade(){
if(stage < MAX_UPGRADES){
hp = MAX_HP[stage++];
max_hp = MAX_HP[stage];
ai.atk_dmg = ATK[stage];
ai.atk_dt = ATK_DT[stage];
ai.range = RANGE[stage];
return true;
}
return false;
} | [
"agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9",
"jlangloi@05766cc9-4f33-4ba7-801d-bd015708efd9",
"kehung@05766cc9-4f33-4ba7-801d-bd015708efd9",
"tcasella@05766cc9-4f33-4ba7-801d-bd015708efd9"
]
| [
[
[
1,
2
],
[
6,
10
],
[
12,
32
],
[
41,
46
],
[
48,
50
],
[
81,
110
]
],
[
[
3,
3
],
[
5,
5
],
[
51,
51
],
[
58,
59
],
[
75,
77
],
[
80,
80
]
],
[
[
4,
4
],
[
33,
40
],
[
52,
54
],
[
57,
57
],
[
62,
74
]
],
[
[
11,
11
],
[
47,
47
],
[
55,
56
],
[
60,
61
],
[
78,
79
]
]
]
|
fb80e9bc02999d6911c99c4892b329e9e9843fe9 | f8b364974573f652d7916c3a830e1d8773751277 | /emulator/allegrex/instructions/VPFXS.h | 12c3216e6abd711c0a5ce701b10be18e16383b16 | []
| no_license | lemmore22/pspe4all | 7a234aece25340c99f49eac280780e08e4f8ef49 | 77ad0acf0fcb7eda137fdfcb1e93a36428badfd0 | refs/heads/master | 2021-01-10T08:39:45.222505 | 2009-08-02T11:58:07 | 2009-08-02T11:58:07 | 55,047,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | h | template< > struct AllegrexInstructionTemplate< 0xdc000000, 0xff000000 > : AllegrexInstructionUnknown
{
static AllegrexInstructionTemplate &self()
{
static AllegrexInstructionTemplate insn;
return insn;
}
static AllegrexInstruction *get_instance()
{
return &AllegrexInstructionTemplate::self();
}
virtual AllegrexInstruction *instruction(u32 opcode)
{
return this;
}
virtual char const *opcode_name()
{
return "VPFXS";
}
virtual void interpret(Processor &processor, u32 opcode);
virtual void disassemble(u32 address, u32 opcode, char *opcode_name, char *operands, char *comment);
protected:
AllegrexInstructionTemplate() {}
};
typedef AllegrexInstructionTemplate< 0xdc000000, 0xff000000 >
AllegrexInstruction_VPFXS;
namespace Allegrex
{
extern AllegrexInstruction_VPFXS &VPFXS;
}
#ifdef IMPLEMENT_INSTRUCTION
AllegrexInstruction_VPFXS &Allegrex::VPFXS =
AllegrexInstruction_VPFXS::self();
#endif
| [
"[email protected]"
]
| [
[
[
1,
41
]
]
]
|
4e09fecb9f51a09526d73c628dcde62fce3b19bb | 93176e72508a8b04769ee55bece71095d814ec38 | /Utilities/BGL/boost/math/distributions/normal.hpp | e41594c20fb5393c378cdb2a0b002b1a39fe682f | []
| no_license | inglada/OTB | a0171a19be1428c0f3654c48fe5c35442934cf13 | 8b6d8a7df9d54c2b13189e00ba8fcb070e78e916 | refs/heads/master | 2021-01-19T09:23:47.919676 | 2011-06-29T17:29:21 | 2011-06-29T17:29:21 | 1,982,100 | 4 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 10,158 | hpp | // Copyright John Maddock 2006, 2007.
// Copyright Paul A. Bristow 2006, 2007.
// 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)
#ifndef BOOST_STATS_NORMAL_HPP
#define BOOST_STATS_NORMAL_HPP
// http://en.wikipedia.org/wiki/Normal_distribution
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm
// Also:
// Weisstein, Eric W. "Normal Distribution."
// From MathWorld--A Wolfram Web Resource.
// http://mathworld.wolfram.com/NormalDistribution.html
#include <boost/math/distributions/fwd.hpp>
#include <boost/math/special_functions/erf.hpp> // for erf/erfc.
#include <boost/math/distributions/complement.hpp>
#include <boost/math/distributions/detail/common_error_handling.hpp>
#include <utility>
namespace boost{ namespace math{
template <class RealType = double, class Policy = policies::policy<> >
class normal_distribution
{
public:
typedef RealType value_type;
typedef Policy policy_type;
normal_distribution(RealType mean = 0, RealType sd = 1)
: m_mean(mean), m_sd(sd)
{ // Default is a 'standard' normal distribution N01.
static const char* function = "boost::math::normal_distribution<%1%>::normal_distribution";
RealType result;
detail::check_scale(function, sd, &result, Policy());
detail::check_location(function, mean, &result, Policy());
}
RealType mean()const
{ // alias for location.
return m_mean;
}
RealType standard_deviation()const
{ // alias for scale.
return m_sd;
}
// Synonyms, provided to allow generic use of find_location and find_scale.
RealType location()const
{ // location.
return m_mean;
}
RealType scale()const
{ // scale.
return m_sd;
}
private:
//
// Data members:
//
RealType m_mean; // distribution mean or location.
RealType m_sd; // distribution standard deviation or scale.
}; // class normal_distribution
typedef normal_distribution<double> normal;
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> range(const normal_distribution<RealType, Policy>& /*dist*/)
{ // Range of permissible values for random variable x.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>()); // - to + max value.
}
template <class RealType, class Policy>
inline const std::pair<RealType, RealType> support(const normal_distribution<RealType, Policy>& /*dist*/)
{ // Range of supported values for random variable x.
// This is range where cdf rises from 0 to 1, and outside it, the pdf is zero.
using boost::math::tools::max_value;
return std::pair<RealType, RealType>(-max_value<RealType>(), max_value<RealType>()); // - to + max value.
}
template <class RealType, class Policy>
inline RealType pdf(const normal_distribution<RealType, Policy>& dist, const RealType& x)
{
BOOST_MATH_STD_USING // for ADL of std functions
RealType sd = dist.standard_deviation();
RealType mean = dist.mean();
static const char* function = "boost::math::pdf(const normal_distribution<%1%>&, %1%)";
if((boost::math::isinf)(x))
{
return 0; // pdf + and - infinity is zero.
}
// Below produces MSVC 4127 warnings, so the above used instead.
//if(std::numeric_limits<RealType>::has_infinity && abs(x) == std::numeric_limits<RealType>::infinity())
//{ // pdf + and - infinity is zero.
// return 0;
//}
RealType result;
if(false == detail::check_scale(function, sd, &result, Policy()))
{
return result;
}
if(false == detail::check_location(function, mean, &result, Policy()))
{
return result;
}
if(false == detail::check_x(function, x, &result, Policy()))
{
return result;
}
RealType exponent = x - mean;
exponent *= -exponent;
exponent /= 2 * sd * sd;
result = exp(exponent);
result /= sd * sqrt(2 * constants::pi<RealType>());
return result;
} // pdf
template <class RealType, class Policy>
inline RealType cdf(const normal_distribution<RealType, Policy>& dist, const RealType& x)
{
BOOST_MATH_STD_USING // for ADL of std functions
RealType sd = dist.standard_deviation();
RealType mean = dist.mean();
static const char* function = "boost::math::cdf(const normal_distribution<%1%>&, %1%)";
RealType result;
if(false == detail::check_scale(function, sd, &result, Policy()))
{
return result;
}
if(false == detail::check_location(function, mean, &result, Policy()))
{
return result;
}
if((boost::math::isinf)(x))
{
if(x < 0) return 0; // -infinity
return 1; // + infinity
}
// These produce MSVC 4127 warnings, so the above used instead.
//if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())
//{ // cdf +infinity is unity.
// return 1;
//}
//if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())
//{ // cdf -infinity is zero.
// return 0;
//}
if(false == detail::check_x(function, x, &result, Policy()))
{
return result;
}
RealType diff = (x - mean) / (sd * constants::root_two<RealType>());
result = boost::math::erfc(-diff, Policy()) / 2;
return result;
} // cdf
template <class RealType, class Policy>
inline RealType quantile(const normal_distribution<RealType, Policy>& dist, const RealType& p)
{
BOOST_MATH_STD_USING // for ADL of std functions
RealType sd = dist.standard_deviation();
RealType mean = dist.mean();
static const char* function = "boost::math::quantile(const normal_distribution<%1%>&, %1%)";
RealType result;
if(false == detail::check_scale(function, sd, &result, Policy()))
return result;
if(false == detail::check_location(function, mean, &result, Policy()))
return result;
if(false == detail::check_probability(function, p, &result, Policy()))
return result;
result= boost::math::erfc_inv(2 * p, Policy());
result = -result;
result *= sd * constants::root_two<RealType>();
result += mean;
return result;
} // quantile
template <class RealType, class Policy>
inline RealType cdf(const complemented2_type<normal_distribution<RealType, Policy>, RealType>& c)
{
BOOST_MATH_STD_USING // for ADL of std functions
RealType sd = c.dist.standard_deviation();
RealType mean = c.dist.mean();
RealType x = c.param;
static const char* function = "boost::math::cdf(const complement(normal_distribution<%1%>&), %1%)";
if((boost::math::isinf)(x))
{
if(x < 0) return 1; // cdf complement -infinity is unity.
return 0; // cdf complement +infinity is zero
}
// These produce MSVC 4127 warnings, so the above used instead.
//if(std::numeric_limits<RealType>::has_infinity && x == std::numeric_limits<RealType>::infinity())
//{ // cdf complement +infinity is zero.
// return 0;
//}
//if(std::numeric_limits<RealType>::has_infinity && x == -std::numeric_limits<RealType>::infinity())
//{ // cdf complement -infinity is unity.
// return 1;
//}
RealType result;
if(false == detail::check_scale(function, sd, &result, Policy()))
return result;
if(false == detail::check_location(function, mean, &result, Policy()))
return result;
if(false == detail::check_x(function, x, &result, Policy()))
return result;
RealType diff = (x - mean) / (sd * constants::root_two<RealType>());
result = boost::math::erfc(diff, Policy()) / 2;
return result;
} // cdf complement
template <class RealType, class Policy>
inline RealType quantile(const complemented2_type<normal_distribution<RealType, Policy>, RealType>& c)
{
BOOST_MATH_STD_USING // for ADL of std functions
RealType sd = c.dist.standard_deviation();
RealType mean = c.dist.mean();
static const char* function = "boost::math::quantile(const complement(normal_distribution<%1%>&), %1%)";
RealType result;
if(false == detail::check_scale(function, sd, &result, Policy()))
return result;
if(false == detail::check_location(function, mean, &result, Policy()))
return result;
RealType q = c.param;
if(false == detail::check_probability(function, q, &result, Policy()))
return result;
result = boost::math::erfc_inv(2 * q, Policy());
result *= sd * constants::root_two<RealType>();
result += mean;
return result;
} // quantile
template <class RealType, class Policy>
inline RealType mean(const normal_distribution<RealType, Policy>& dist)
{
return dist.mean();
}
template <class RealType, class Policy>
inline RealType standard_deviation(const normal_distribution<RealType, Policy>& dist)
{
return dist.standard_deviation();
}
template <class RealType, class Policy>
inline RealType mode(const normal_distribution<RealType, Policy>& dist)
{
return dist.mean();
}
template <class RealType, class Policy>
inline RealType median(const normal_distribution<RealType, Policy>& dist)
{
return dist.mean();
}
template <class RealType, class Policy>
inline RealType skewness(const normal_distribution<RealType, Policy>& /*dist*/)
{
return 0;
}
template <class RealType, class Policy>
inline RealType kurtosis(const normal_distribution<RealType, Policy>& /*dist*/)
{
return 3;
}
template <class RealType, class Policy>
inline RealType kurtosis_excess(const normal_distribution<RealType, Policy>& /*dist*/)
{
return 0;
}
} // namespace math
} // namespace boost
// This include must be at the end, *after* the accessors
// for this distribution have been defined, in order to
// keep compilers that support two-phase lookup happy.
#include <boost/math/distributions/detail/derived_accessors.hpp>
#endif // BOOST_STATS_NORMAL_HPP
| [
"[email protected]"
]
| [
[
[
1,
308
]
]
]
|
e95fe5900d91c3ca7ea3372b023ce4c528a34197 | 741b36f4ddf392c4459d777930bc55b966c2111a | /incubator/deeppurple/lwplugins/lwwrapper/Panel/ControlPercent.h | fa5fa001d45149eec36365495242a6802f9d3412 | []
| no_license | BackupTheBerlios/lwpp-svn | d2e905641f60a7c9ca296d29169c70762f5a9281 | fd6f80cbba14209d4ca639f291b1a28a0ed5404d | refs/heads/master | 2021-01-17T17:01:31.802187 | 2005-10-16T22:12:52 | 2005-10-16T22:12:52 | 40,805,554 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 761 | h | // ControlPercent.h: interface for the ControlPercent class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CONTROLPERCENT_H__F4913AB0_2EAD_4FCF_931E_79C11DA9BD01__INCLUDED_)
#define AFX_CONTROLPERCENT_H__F4913AB0_2EAD_4FCF_931E_79C11DA9BD01__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "ControlDouble.h"
class ControlPercent : public ControlDouble
{
public:
ControlPercent();
virtual ~ControlPercent();
virtual bool RegisterWithPanel(LWPanelID pan);
virtual void Initialize(const char *name, Panel* SetOwner, int min=0, int max=100);
int Min,Max;
};
#endif // !defined(AFX_CONTROLPERCENT_H__F4913AB0_2EAD_4FCF_931E_79C11DA9BD01__INCLUDED_)
| [
"deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61"
]
| [
[
[
1,
24
]
]
]
|
c7c34f3a019b17962949662cb85b843252899f3d | 99527557aee4f1db979a7627e77bd7d644098411 | /utils/graphics.h | 94222ddf61f74e7c238b7ce52268024a46c8e3b7 | []
| no_license | GunioRobot/2deffects | 7aeb02400090bb7118d23f1fc435ffbdd4417c59 | 39d8e335102d6a51cab0d47a3a2dc7686d7a7c67 | refs/heads/master | 2021-01-18T14:10:32.049756 | 2008-09-15T15:56:50 | 2008-09-15T15:56:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,045 | h | #ifndef _SYD_GRAPHICS_H_
#define _SYD_GRAPHICS_H_
#include "utils/color.h"
#include "utils/types.h"
#include <memory>
namespace syd {
class bltparam {
uint16_t destX_, destY_,
srcX_, srcY_,
width_, height_;
public:
bltparam() {
destX_=destY_=
srcX_=srcY_=
width_=height_=0;
}
public:
uint16_t destX() const { return destX_; }
uint16_t destY() const { return destY_; }
uint16_t srcX() const { return srcX_; }
uint16_t srcY() const { return srcY_; }
uint16_t width() const { return width_; }
uint16_t height() const { return height_; }
public:
bltparam& destX(uint16_t x) { destX_=x; return *this; }
bltparam& destY(uint16_t y) { destY_=y; return *this; }
bltparam& srcX(uint16_t x) { srcX_=x; return *this; }
bltparam& srcY(uint16_t y) { srcY_=y; return *this; }
bltparam& width(uint16_t w) { width_=w; return *this; }
bltparam& height(uint16_t h) { height_=h; return *this; }
};
class lineparam {
uint16_t startx_,starty_,endx_,endy_;
public:
lineparam() {
startx_=starty_=
endx_=endy_=0;
}
lineparam( uint16_t startx, uint16_t starty,
uint16_t endx, uint16_t endy )
: startx_( startx ), starty_( starty ),
endx_( endx ) , endy_( endy ) {}
public:
uint16_t startX() const { return startx_; }
uint16_t startY() const { return starty_; }
uint16_t endX() const { return endx_; }
uint16_t endY() const { return endy_; }
public:
lineparam& start(uint16_t x, uint16_t y) { startx_=x; starty_=y; return *this; }
lineparam& end(uint16_t x, uint16_t y) { endx_=x; endy_=y; return *this; }
};
class Bitmap;
Bitmap& blt(Bitmap& out, Bitmap& in, const bltparam& binfo);
Bitmap& blt2(Bitmap& out, Bitmap& in, const bltparam& binfo);
Bitmap& hblur2(Bitmap& out, Bitmap& in, const bltparam& binfo);
Bitmap& hblur4(Bitmap& out, Bitmap& in, const bltparam& binfo);
Bitmap& line(Bitmap& out, color_t& col, const lineparam& param);
std::auto_ptr<Bitmap> load_bmp(const char* filename);
}; //syd
#endif //_SYD_GRAPHICS_H_
| [
"[email protected]"
]
| [
[
[
1,
76
]
]
]
|
ddad2905f0c16371f23bc80a990ca745c3e4a898 | 024d621c20595be82b4622f534278009a684e9b7 | /WinClass.h | fce3cc9726906652ab48700f8869671253add620 | []
| no_license | tj10200/Simple-Soccer | 98a224c20b5e0b66f0e420d7c312a6cf6527069b | 486a4231ddf66ae5984713a177297b0f9c83015f | refs/heads/master | 2021-01-19T09:02:02.791225 | 2011-03-15T01:38:15 | 2011-03-15T01:38:15 | 1,480,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | h | #include <windows.h>
class WinClass
{
private:
//initialize window settings
WNDCLASSEX wc;
public:
WinClass (string ClassName,
WNDPROC WinProc,
HINSTANCE hInst)
{
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WinProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = NULL;
wc.lpszClassName = ClassName.c_str();
wc.hIconSm = NULL;
RegisterClassEx(&wc);
}
}; | [
"[email protected]"
]
| [
[
[
1,
28
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.