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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5aded2bddd0558867c995336c3f8fd2ade9e067b | d1dc408f6b65c4e5209041b62cd32fb5083fe140 | /src/drawers/cUpgradeDrawer.cpp | 17235dd3b34c5a14071916b931be9afa37210af0 | []
| no_license | dmitrygerasimuk/dune2themaker-fossfriendly | 7b4bed2dfb2b42590e4b72bd34bb0f37f6c81e37 | 89a6920b216f3964241eeab7cf1a631e1e63f110 | refs/heads/master | 2020-03-12T03:23:40.821001 | 2011-02-19T12:01:30 | 2011-02-19T12:01:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,431 | cpp | /*
* cUpgradeDrawer.cpp
*
* Created on: 3-aug-2010
* Author: Stefan
*/
#include "../include/d2tmh.h"
cUpgradeDrawer::cUpgradeDrawer() {
}
cUpgradeDrawer::~cUpgradeDrawer() {
}
bool cUpgradeDrawer::shouldDrawButtonForSelectedList(cPlayer * thePlayer, cBuildingList * theSelectedList) {
assert(thePlayer);
assert(theSelectedList);
int techLevel = thePlayer->getTechLevel();
int upgradeLevel = theSelectedList->getUpgradeLevel();
cUpgradeUtils upgradeUtils;
return upgradeUtils.canUpgradeList(thePlayer, theSelectedList->getType(),techLevel, upgradeLevel);
}
void cUpgradeDrawer::drawUpgradeButtonForSelectedListIfNeeded(cPlayer * thePlayer, cBuildingList * theSelectedList) {
assert(thePlayer);
if (theSelectedList == NULL) return;
bool shouldDrawButton = shouldDrawButtonForSelectedList(thePlayer, theSelectedList);
if (shouldDrawButton) {
drawUpgradeButton(thePlayer, theSelectedList);
if (theSelectedList->isUpgrading()) {
drawUpgradeProgress(thePlayer, theSelectedList);
}
}
}
void cUpgradeDrawer::drawUpgradeButton(cPlayer * thePlayer, cBuildingList * theSelectedList) {
assert(thePlayer);
assert(theSelectedList);
int techLevel = thePlayer->getTechLevel();
int upgradeLevel = theSelectedList->getUpgradeLevel();
cUpgradeUtils upgradeUtils;
bool canPayForUpgrade = upgradeUtils.canPlayerPayForUpgradeForList(thePlayer, theSelectedList->getType(), techLevel, upgradeLevel);
bool isBuildingItem = theSelectedList->isBuildingItem();
if (canPayForUpgrade && !isBuildingItem) {
draw_sprite(bmp_screen, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 29, 0);
} else {
// draw a dark version
// TODO: optimize this, by making a dark version once and then re-draw that one, instead of constructing
// it over and over again
BITMAP *bmp_trans=create_bitmap(((BITMAP *)gfxinter[BTN_UPGRADE].dat)->w,((BITMAP *)gfxinter[BTN_UPGRADE].dat)->h);
clear_to_color(bmp_trans, makecol(255,0,255));
// copy
draw_sprite(bmp_trans, (BITMAP *)gfxinter[BTN_UPGRADE].dat, 0, 0);
// make black
rectfill(bmp_screen, 29, 0, 187, 29, makecol(0,0,0));
// set blender
set_trans_blender(0,0,0,128);
// trans (makes upgrade button show like it is disabled)
draw_trans_sprite(bmp_screen, bmp_trans, 29, 0);
// destroy
destroy_bitmap(bmp_trans);
}
}
void cUpgradeDrawer::drawUpgradeProgress(cPlayer * thePlayer, cBuildingList * theSelectedList) {
assert(thePlayer);
assert(theSelectedList);
int listId = theSelectedList->getType();
cListUpgrade * upgrade = thePlayer->getUpgradeBuilder()->getListUpgrade(listId);
assert(upgrade);
if (upgrade) {
int iDrawXLimit = (int)health_bar(157, upgrade->getProgress(), upgrade->getProgressLimit());
if (iDrawXLimit > -1)
{
int iColor=makecol(255,255,255);
BITMAP *temp = create_bitmap(157, 28);
clear_to_color(temp, makecol(255,0,255));
// TODO: make util function for this (duplicate code!)
if (thePlayer->getHouse() == ATREIDES) iColor = makecol(0,0,255);
if (thePlayer->getHouse() == HARKONNEN) iColor = makecol(255,0,0);
if (thePlayer->getHouse() == ORDOS) iColor = makecol(0,255,0);
if (thePlayer->getHouse() == SARDAUKAR) iColor = makecol(255,0,255);
rectfill(temp, 0, 0, (157-iDrawXLimit), 30, iColor);
draw_trans_sprite(bmp_screen, temp, 30, 1);
destroy_bitmap(temp);
}
}
}
| [
"stefanhen83@52bf4e17-6a1c-0410-83a1-9b5866916151"
]
| [
[
[
1,
107
]
]
]
|
42131fa0bb99564be75825ab06f87973c968a8ad | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgrePhysXMeshData.h | 3c068186379871a73dc980f78b6bc69a29f564a4 | []
| no_license | TimelineX/balyoz | c154d4de9129a8a366c1b8257169472dc02c5b19 | 5a0f2ee7402a827bbca210d7c7212a2eb698c109 | refs/heads/master | 2021-01-01T05:07:59.597755 | 2010-04-20T19:53:52 | 2010-04-20T19:53:52 | 56,454,260 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,593 | h | /** File: NxOgreXXX.h
Created on: X-XXX-XX
Author: Robin Southern "betajaen"
SVN: $Id$
© Copyright, 2008-2009 by Robin Southern, http://www.nxogre.org
This file is part of NxOgre.
NxOgre 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.
NxOgre 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 NxOgre. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef NXOGRE_PHYSXMESHDATA_H
#define NXOGRE_PHYSXMESHDATA_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
namespace NxOgre_Namespace
{
/** \brief
*/
class NxOgrePublicClass PhysXMeshData : public NxOgre::PointerClass<Classes::_PhysXMeshData>
{
public: // Functions
/** \brief Text
*/
PhysXMeshData(Mesh*, size_t modifier = 2);
/** \brief Text
*/
~PhysXMeshData(void);
/** \internal Do not use in User App.
*/
NxMeshData getMeshData();
/** \brief Get the vertices as three floats. Use getNbVertices() as a count. Vertices size will be 3 * getNbVertices().
*/
float* getVertices();
/** \brief Get the vertices as three floats. Use getNbVertices() as a count. Normals size will be 3 * getNbVertices().
*/
float* getNormals();
/** \brief Get the indexes as 32 bit integers. Use getNbIndices() as a count.
*/
unsigned int* getIndices();
/** \brief Get the current number of vertices, normals and texture coordinates.
*/
unsigned int getNbVertices();
/** \brief Get the current indices
*/
unsigned int getNbIndices();
/** \brief Get the current parent indices
*/
unsigned int getNbParentIndices();
protected:
void _configure(size_t verts, size_t indices, size_t parent_indices);
Buffer<float> mVertices;
Buffer<float> mNormals;
Buffer<unsigned int> mIndices;
Buffer<unsigned int> mParentIndices;
unsigned int* mNbVertices;
unsigned int* mNbIndices;
unsigned int* mNbParentIndices;
}; // class PhysXMeshData
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
]
| [
[
[
1,
110
]
]
]
|
deea544f018be01a4c0c8a97b5d7cc742bfdc355 | 81e051c660949ac0e89d1e9cf286e1ade3eed16a | /quake3ce/code/botlib/be_ai_move.cpp | 77285be2d5df628f3609c0389e7c66616aa96f3e | []
| no_license | crioux/q3ce | e89c3b60279ea187a2ebcf78dbe1e9f747a31d73 | 5e724f55940ac43cb25440a65f9e9e12220c9ada | refs/heads/master | 2020-06-04T10:29:48.281238 | 2008-11-16T15:00:38 | 2008-11-16T15:00:38 | 32,103,416 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 121,168 | cpp | /*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Quake III Arena source code.
Quake III Arena source code 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.
Quake III Arena source code 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 Foobar; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
/*****************************************************************************
* name: be_ai_move.c
*
* desc: bot movement AI
*
* $Archive: /MissionPack/code/botlib/be_ai_move.c $
*
*****************************************************************************/
#include"botlib_pch.h"
//#define DEBUG_AI_MOVE
//#define DEBUG_ELEVATOR
//#define DEBUG_GRAPPLE
// bk001204 - redundant bot_avoidspot_t, see ../game/be_ai_move.h
//movement state
//NOTE: the moveflags MFL_ONGROUND, MFL_TELEPORTED, MFL_WATERJUMP and
// MFL_GRAPPLEPULL must be set outside the movement code
typedef struct bot_movestate_s
{
//input vars (all set outside the movement code)
bvec3_t origin; //origin of the bot
bvec3_t velocity; //velocity of the bot
bvec3_t viewoffset; //view offset
int entitynum; //entity number of the bot
int client; //client number of the bot
gfixed thinktime; //time the bot thinks
int presencetype; //presencetype of the bot
avec3_t viewangles; //view angles of the bot
//state vars
int areanum; //area the bot is in
int lastareanum; //last area the bot was in
int lastgoalareanum; //last goal area number
int lastreachnum; //last reachability number
bvec3_t lastorigin; //origin previous cycle
int reachareanum; //area number of the reachabilty
int moveflags; //movement flags
int jumpreach; //set when jumped
gfixed grapplevisible_time; //last time the grapple was visible
bfixed lastgrappledist; //last distance to the grapple end
gfixed reachability_time; //time to use current reachability
int avoidreach[MAX_AVOIDREACH]; //reachabilities to avoid
gfixed avoidreachtimes[MAX_AVOIDREACH]; //times to avoid the reachabilities
int avoidreachtries[MAX_AVOIDREACH]; //number of tries before avoiding
//
bot_avoidspot_t avoidspots[MAX_AVOIDSPOTS]; //spots to avoid
int numavoidspots;
} bot_movestate_t;
//used to avoid reachability links for some time after being used
#define AVOIDREACH
#define AVOIDREACH_TIME 6 //avoid links for 6 seconds after use
#define AVOIDREACH_TRIES 4
//prediction times
#define PREDICTIONTIME_JUMP 3 //in seconds
#define PREDICTIONTIME_MOVE 2 //in seconds
//weapon indexes for weapon jumping
#define WEAPONINDEX_ROCKET_LAUNCHER 5
#define WEAPONINDEX_BFG 9
#define MODELTYPE_FUNC_PLAT 1
#define MODELTYPE_FUNC_BOB 2
#define MODELTYPE_FUNC_DOOR 3
#define MODELTYPE_FUNC_STATIC 4
libvar_t *sv_maxstep;
libvar_t *sv_maxbarrier;
libvar_t *sv_gravity;
libvar_t *weapindex_rocketlauncher;
libvar_t *weapindex_bfg10k;
libvar_t *weapindex_grapple;
libvar_t *entitytypemissile;
libvar_t *offhandgrapple;
libvar_t *cmd_grappleoff;
libvar_t *cmd_grappleon;
//type of model, func_plat or func_bobbing
int modeltypes[MAX_MODELS];
bot_movestate_t *botmovestates[MAX_CLIENTS+1];
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
int BotAllocMoveState(void)
{
int i;
for (i = 1; i <= MAX_CLIENTS; i++)
{
if (!botmovestates[i])
{
botmovestates[i] = (bot_movestate_t *)GetClearedMemory(sizeof(bot_movestate_t));
return i;
} //end if
} //end for
return 0;
} //end of the function BotAllocMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotFreeMoveState(int handle)
{
if (handle <= 0 || handle > MAX_CLIENTS)
{
botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
return;
} //end if
if (!botmovestates[handle])
{
botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
return;
} //end if
FreeMemory(botmovestates[handle]);
botmovestates[handle] = NULL;
} //end of the function BotFreeMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
bot_movestate_t *BotMoveStateFromHandle(int handle)
{
if (handle <= 0 || handle > MAX_CLIENTS)
{
botimport.Print(PRT_FATAL, "move state handle %d out of range\n", handle);
return NULL;
} //end if
if (!botmovestates[handle])
{
botimport.Print(PRT_FATAL, "invalid move state %d\n", handle);
return NULL;
} //end if
return botmovestates[handle];
} //end of the function BotMoveStateFromHandle
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotInitMoveState(int handle, bot_initmove_t *initmove)
{
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(handle);
if (!ms) return;
VectorCopy(initmove->origin, ms->origin);
VectorCopy(initmove->velocity, ms->velocity);
VectorCopy(initmove->viewoffset, ms->viewoffset);
ms->entitynum = initmove->entitynum;
ms->client = initmove->client;
ms->thinktime = initmove->thinktime;
ms->presencetype = initmove->presencetype;
VectorCopy(initmove->viewangles, ms->viewangles);
//
ms->moveflags &= ~MFL_ONGROUND;
if (initmove->or_moveflags & MFL_ONGROUND) ms->moveflags |= MFL_ONGROUND;
ms->moveflags &= ~MFL_TELEPORTED;
if (initmove->or_moveflags & MFL_TELEPORTED) ms->moveflags |= MFL_TELEPORTED;
ms->moveflags &= ~MFL_WATERJUMP;
if (initmove->or_moveflags & MFL_WATERJUMP) ms->moveflags |= MFL_WATERJUMP;
ms->moveflags &= ~MFL_WALK;
if (initmove->or_moveflags & MFL_WALK) ms->moveflags |= MFL_WALK;
ms->moveflags &= ~MFL_GRAPPLEPULL;
if (initmove->or_moveflags & MFL_GRAPPLEPULL) ms->moveflags |= MFL_GRAPPLEPULL;
} //end of the function BotInitMoveState
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
afixed AngleDiff(afixed ang1, afixed ang2)
{
afixed diff;
diff = ang1 - ang2;
if (ang1 > ang2)
{
if (diff > AFIXED(180,0)) diff -= AFIXED(360,0);
} //end if
else
{
if (diff < -AFIXED(180,0)) diff += AFIXED(360,0);
} //end else
return diff;
} //end of the function AngleDiff
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotFuzzyPointReachabilityArea(bvec3_t origin)
{
int firstareanum, j, x, y, z;
int areas[10], numareas, areanum, bestareanum;
bfixed dist, bestdist;
bvec3_t points[10], v, end;
firstareanum = 0;
areanum = AAS_PointAreaNum(origin);
if (areanum)
{
firstareanum = areanum;
if (AAS_AreaReachability(areanum)) return areanum;
} //end if
VectorCopy(origin, end);
end[2] += BFIXED(4,0);
numareas = AAS_TraceAreas(origin, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j])) return areas[j];
} //end for
bestdist = BFIXED(999999,0);
bestareanum = 0;
for (z = 1; z >= -1; z -= 1)
{
for (x = 1; x >= -1; x -= 1)
{
for (y = 1; y >= -1; y -= 1)
{
VectorCopy(origin, end);
end[0] += MAKE_BFIXED(x * 8);
end[1] += MAKE_BFIXED(y * 8);
end[2] += MAKE_BFIXED(z * 12);
numareas = AAS_TraceAreas(origin, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j]))
{
VectorSubtract(points[j], origin, v);
dist = FIXED_VEC3LEN(v);
if (dist < bestdist)
{
bestareanum = areas[j];
bestdist = dist;
} //end if
} //end if
if (!firstareanum) firstareanum = areas[j];
} //end for
} //end for
} //end for
if (bestareanum) return bestareanum;
} //end for
return firstareanum;
} //end of the function BotFuzzyPointReachabilityArea
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotReachabilityArea(bvec3_t origin, int client)
{
int modelnum, modeltype, reachnum, areanum;
aas_reachability_t reach;
bvec3_t org, end, mins, maxs;
avec3_t up = {AFIXED_0, AFIXED_0, AFIXED_1};
bsp_trace_t bsptrace;
aas_trace_t trace;
//check if the bot is standing on something
AAS_PresenceTypeBoundingBox(PRESENCE_CROUCH, mins, maxs);
FIXED_VEC3MA_R(origin, -BFIXED(3,0), up, end);
bsptrace = AAS_Trace(origin, mins, maxs, end, client, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
if (!bsptrace.startsolid && bsptrace.fraction < GFIXED_1 && bsptrace.ent != ENTITYNUM_NONE)
{
//if standing on the world the bot should be in a valid area
if (bsptrace.ent == ENTITYNUM_WORLD)
{
return BotFuzzyPointReachabilityArea(origin);
} //end if
modelnum = AAS_EntityModelindex(bsptrace.ent);
modeltype = modeltypes[modelnum];
//if standing on a func_plat or func_bobbing then the bot is assumed to be
//in the area the reachability points to
if (modeltype == MODELTYPE_FUNC_PLAT || modeltype == MODELTYPE_FUNC_BOB)
{
reachnum = AAS_NextModelReachability(0, modelnum);
if (reachnum)
{
AAS_ReachabilityFromNum(reachnum, &reach);
return reach.areanum;
} //end if
} //end else if
//if the bot is swimming the bot should be in a valid area
if (AAS_Swimming(origin))
{
return BotFuzzyPointReachabilityArea(origin);
} //end if
//
areanum = BotFuzzyPointReachabilityArea(origin);
//if the bot is in an area with reachabilities
if (areanum && AAS_AreaReachability(areanum)) return areanum;
//trace down till the ground is hit because the bot is standing on some other entity
VectorCopy(origin, org);
VectorCopy(org, end);
end[2] -= BFIXED(800,0);
trace = AAS_TraceClientBBox(org, end, PRESENCE_CROUCH, -1);
if (!trace.startsolid)
{
VectorCopy(trace.endpos, org);
} //end if
//
return BotFuzzyPointReachabilityArea(org);
} //end if
//
return BotFuzzyPointReachabilityArea(origin);
} //end of the function BotReachabilityArea
//===========================================================================
// returns the reachability area the bot is in
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
/*
int BotReachabilityArea(bvec3_t origin, int testground)
{
int firstareanum, i, j, x, y, z;
int areas[10], numareas, areanum, bestareanum;
bfixed dist, bestdist;
bvec3_t org, end, points[10], v;
aas_trace_t trace;
firstareanum = 0;
for (i = 0; i < 2; i++)
{
VectorCopy(origin, org);
//if test at the ground (used when bot is standing on an entity)
if (i > 0)
{
VectorCopy(origin, end);
end[2] -= 800;
trace = AAS_TraceClientBBox(origin, end, PRESENCE_CROUCH, -1);
if (!trace.startsolid)
{
VectorCopy(trace.endpos, org);
} //end if
} //end if
firstareanum = 0;
areanum = AAS_PointAreaNum(org);
if (areanum)
{
firstareanum = areanum;
if (AAS_AreaReachability(areanum)) return areanum;
} //end if
bestdist = 999999;
bestareanum = 0;
for (z = 1; z >= -1; z -= 1)
{
for (x = 1; x >= -1; x -= 1)
{
for (y = 1; y >= -1; y -= 1)
{
VectorCopy(org, end);
end[0] += x * 8;
end[1] += y * 8;
end[2] += z * 12;
numareas = AAS_TraceAreas(org, end, areas, points, 10);
for (j = 0; j < numareas; j++)
{
if (AAS_AreaReachability(areas[j]))
{
VectorSubtract(points[j], org, v);
dist = FIXED_VEC3LEN(v);
if (dist < bestdist)
{
bestareanum = areas[j];
bestdist = dist;
} //end if
} //end if
} //end for
} //end for
} //end for
if (bestareanum) return bestareanum;
} //end for
if (!testground) break;
} //end for
//#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "no reachability area\n");
//#endif //DEBUG
return firstareanum;
} //end of the function BotReachabilityArea*/
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotOnMover(bvec3_t origin, int entnum, aas_reachability_t *reach)
{
int i, modelnum;
bvec3_t mins, maxs, modelorigin, org, end;
avec3_t angles = {AFIXED_0, AFIXED_0, AFIXED_0};
bvec3_t boxmins = {-BFIXED(16,0), -BFIXED(16,0), -BFIXED(8,0)}, boxmaxs = {BFIXED(16,0), BFIXED(16,0), BFIXED(8,0)};
bsp_trace_t trace;
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL);
//
if (!AAS_OriginOfMoverWithModelNum(modelnum, modelorigin))
{
botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
return qfalse;
} //end if
//
for (i = 0; i < 2; i++)
{
if (origin[i] > modelorigin[i] + maxs[i] + BFIXED(16,0)) return qfalse;
if (origin[i] < modelorigin[i] + mins[i] - BFIXED(16,0)) return qfalse;
} //end for
//
VectorCopy(origin, org);
org[2] += BFIXED(24,0);
VectorCopy(origin, end);
end[2] -= BFIXED(48,0);
//
trace = AAS_Trace(org, boxmins, boxmaxs, end, entnum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
if (!trace.startsolid && !trace.allsolid)
{
//NOTE: the reachability face number is the model number of the elevator
if (trace.ent != ENTITYNUM_NONE && AAS_EntityModelNum(trace.ent) == modelnum)
{
return qtrue;
} //end if
} //end if
return qfalse;
} //end of the function BotOnMover
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int MoverDown(aas_reachability_t *reach)
{
int modelnum;
bvec3_t mins, maxs, origin;
avec3_t angles = {AFIXED_0, AFIXED_0, AFIXED_0};
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
//
if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
{
botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
return qfalse;
} //end if
//if the top of the plat is below the reachability start point
if (origin[2] + maxs[2] < reach->start[2]) return qtrue;
return qfalse;
} //end of the function MoverDown
//========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//========================================================================
void BotSetBrushModelTypes(void)
{
int ent, modelnum;
char classname[MAX_EPAIRKEY], model[MAX_EPAIRKEY];
Com_Memset(modeltypes, 0, MAX_MODELS * sizeof(int));
//
for (ent = AAS_NextBSPEntity(0); ent; ent = AAS_NextBSPEntity(ent))
{
if (!AAS_ValueForBSPEpairKey(ent, "classname", classname, MAX_EPAIRKEY)) continue;
if (!AAS_ValueForBSPEpairKey(ent, "model", model, MAX_EPAIRKEY)) continue;
if (model[0]) modelnum = atoi(model+1);
else modelnum = 0;
if (modelnum < 0 || modelnum > MAX_MODELS)
{
botimport.Print(PRT_MESSAGE, "entity %s model number out of range\n", classname);
continue;
} //end if
if (!Q_stricmp(classname, "func_bobbing"))
modeltypes[modelnum] = MODELTYPE_FUNC_BOB;
else if (!Q_stricmp(classname, "func_plat"))
modeltypes[modelnum] = MODELTYPE_FUNC_PLAT;
else if (!Q_stricmp(classname, "func_door"))
modeltypes[modelnum] = MODELTYPE_FUNC_DOOR;
else if (!Q_stricmp(classname, "func_static"))
modeltypes[modelnum] = MODELTYPE_FUNC_STATIC;
} //end for
} //end of the function BotSetBrushModelTypes
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotOnTopOfEntity(bot_movestate_t *ms)
{
bvec3_t mins, maxs, end;
avec3_t up = {AFIXED_0, AFIXED_0, AFIXED_1};
bsp_trace_t trace;
AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
FIXED_VEC3MA_R(ms->origin, -BFIXED(3,0), up, end);
trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
{
return trace.ent;
} //end if
return -1;
} //end of the function BotOnTopOfEntity
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotValidTravel(bvec3_t origin, aas_reachability_t *reach, int travelflags)
{
//if the reachability uses an unwanted travel type
if (AAS_TravelFlagForType(reach->traveltype) & ~travelflags) return qfalse;
//don't go into areas with bad travel types
if (AAS_AreaContentsTravelFlags(reach->areanum) & ~travelflags) return qfalse;
return qtrue;
} //end of the function BotValidTravel
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotAddToAvoidReach(bot_movestate_t *ms, int number, gfixed avoidtime)
{
int i;
for (i = 0; i < MAX_AVOIDREACH; i++)
{
if (ms->avoidreach[i] == number)
{
if (ms->avoidreachtimes[i] > AAS_Time()) ms->avoidreachtries[i]++;
else ms->avoidreachtries[i] = 1;
ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
return;
} //end if
} //end for
//add the reachability to the reachabilities to avoid for a while
for (i = 0; i < MAX_AVOIDREACH; i++)
{
if (ms->avoidreachtimes[i] < AAS_Time())
{
ms->avoidreach[i] = number;
ms->avoidreachtimes[i] = AAS_Time() + avoidtime;
ms->avoidreachtries[i] = 1;
return;
} //end if
} //end for
} //end of the function BotAddToAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bfixed DistanceFromLineSquared(bvec3_t p, bvec3_t lp1, bvec3_t lp2)
{
bvec3_t proj, dir;
int j;
AAS_ProjectPointOntoVector(p, lp1, lp2, proj);
for (j = 0; j < 3; j++)
if ((proj[j] > lp1[j] && proj[j] > lp2[j]) ||
(proj[j] < lp1[j] && proj[j] < lp2[j]))
break;
if (j < 3) {
if (FIXED_ABS(proj[j] - lp1[j]) < FIXED_ABS(proj[j] - lp2[j]))
VectorSubtract(p, lp1, dir);
else
VectorSubtract(p, lp2, dir);
return FIXED_VEC3LEN_SQ(dir);
}
VectorSubtract(p, proj, dir);
return FIXED_VEC3LEN_SQ(dir);
} //end of the function DistanceFromLineSquared
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bfixed VectorDistanceSquared(bvec3_t p1, bvec3_t p2)
{
bvec3_t dir;
VectorSubtract(p2, p1, dir);
return FIXED_VEC3LEN_SQ(dir);
} //end of the function VectorDistanceSquared
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotAvoidSpots(bvec3_t origin, aas_reachability_t *reach, bot_avoidspot_t *avoidspots, int numavoidspots)
{
int checkbetween, i, type;
bfixed squareddist, squaredradius;
switch(reach->traveltype & TRAVELTYPE_MASK)
{
case TRAVEL_WALK: checkbetween = qtrue; break;
case TRAVEL_CROUCH: checkbetween = qtrue; break;
case TRAVEL_BARRIERJUMP: checkbetween = qtrue; break;
case TRAVEL_LADDER: checkbetween = qtrue; break;
case TRAVEL_WALKOFFLEDGE: checkbetween = qfalse; break;
case TRAVEL_JUMP: checkbetween = qfalse; break;
case TRAVEL_SWIM: checkbetween = qtrue; break;
case TRAVEL_WATERJUMP: checkbetween = qtrue; break;
case TRAVEL_TELEPORT: checkbetween = qfalse; break;
case TRAVEL_ELEVATOR: checkbetween = qfalse; break;
case TRAVEL_GRAPPLEHOOK: checkbetween = qfalse; break;
case TRAVEL_ROCKETJUMP: checkbetween = qfalse; break;
case TRAVEL_BFGJUMP: checkbetween = qfalse; break;
case TRAVEL_JUMPPAD: checkbetween = qfalse; break;
case TRAVEL_FUNCBOB: checkbetween = qfalse; break;
default: checkbetween = qtrue; break;
} //end switch
type = AVOID_CLEAR;
for (i = 0; i < numavoidspots; i++)
{
squaredradius = Square(avoidspots[i].radius);
squareddist = DistanceFromLineSquared(avoidspots[i].origin, origin, reach->start);
// if moving towards the avoid spot
if (squareddist < squaredradius &&
VectorDistanceSquared(avoidspots[i].origin, origin) > squareddist)
{
type = avoidspots[i].type;
} //end if
else if (checkbetween) {
squareddist = DistanceFromLineSquared(avoidspots[i].origin, reach->start, reach->end);
// if moving towards the avoid spot
if (squareddist < squaredradius &&
VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist)
{
type = avoidspots[i].type;
} //end if
} //end if
else
{
VectorDistanceSquared(avoidspots[i].origin, reach->end);
// if the reachability leads closer to the avoid spot
if (squareddist < squaredradius &&
VectorDistanceSquared(avoidspots[i].origin, reach->start) > squareddist)
{
type = avoidspots[i].type;
} //end if
} //end else
if (type == AVOID_ALWAYS)
return type;
} //end for
return type;
} //end of the function BotAvoidSpots
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotAddAvoidSpot(int movestate, bvec3_t origin, bfixed radius, int type)
{
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return;
if (type == AVOID_CLEAR)
{
ms->numavoidspots = 0;
return;
} //end if
if (ms->numavoidspots >= MAX_AVOIDSPOTS)
return;
VectorCopy(origin, ms->avoidspots[ms->numavoidspots].origin);
ms->avoidspots[ms->numavoidspots].radius = radius;
ms->avoidspots[ms->numavoidspots].type = type;
ms->numavoidspots++;
} //end of the function BotAddAvoidSpot
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotGetReachabilityToGoal(bvec3_t origin, int areanum,
int lastgoalareanum, int lastareanum,
int *avoidreach, gfixed *avoidreachtimes, int *avoidreachtries,
bot_goal_t *goal, int travelflags, int movetravelflags,
struct bot_avoidspot_s *avoidspots, int numavoidspots, int *flags)
{
int i, t, besttime, bestreachnum, reachnum;
aas_reachability_t reach;
//if not in a valid area
if (!areanum) return 0;
//
if (AAS_AreaDoNotEnter(areanum) || AAS_AreaDoNotEnter(goal->areanum))
{
travelflags |= TFL_DONOTENTER;
movetravelflags |= TFL_DONOTENTER;
} //end if
//use the routing to find the next area to go to
besttime = 0;
bestreachnum = 0;
//
for (reachnum = AAS_NextAreaReachability(areanum, 0); reachnum;
reachnum = AAS_NextAreaReachability(areanum, reachnum))
{
#ifdef AVOIDREACH
//check if it isn't an reachability to avoid
for (i = 0; i < MAX_AVOIDREACH; i++)
{
if (avoidreach[i] == reachnum && avoidreachtimes[i] >= AAS_Time()) break;
} //end for
if (i != MAX_AVOIDREACH && avoidreachtries[i] > AVOIDREACH_TRIES)
{
#ifdef DEBUG
if (bl_bot_developer)
{
botimport.Print(PRT_MESSAGE, "avoiding reachability %d\n", avoidreach[i]);
} //end if
#endif //DEBUG
continue;
} //end if
#endif //AVOIDREACH
//get the reachability from the number
AAS_ReachabilityFromNum(reachnum, &reach);
//NOTE: do not go back to the previous area if the goal didn't change
//NOTE: is this actually avoidance of local routing minima between two areas???
if (lastgoalareanum == goal->areanum && reach.areanum == lastareanum) continue;
//if (AAS_AreaContentsTravelFlags(reach.areanum) & ~travelflags) continue;
//if the travel isn't valid
if (!BotValidTravel(origin, &reach, movetravelflags)) continue;
//get the travel time
t = AAS_AreaTravelTimeToGoalArea(reach.areanum, reach.end, goal->areanum, travelflags);
//if the goal area isn't reachable from the reachable area
if (!t) continue;
//if the bot should not use this reachability to avoid bad spots
if (BotAvoidSpots(origin, &reach, avoidspots, numavoidspots)) {
if (flags) {
*flags |= MOVERESULT_BLOCKEDBYAVOIDSPOT;
}
continue;
}
//add the travel time towards the area
t += reach.traveltime;// + AAS_AreaTravelTime(areanum, origin, reach.start);
//if the travel time is better than the ones already found
if (!besttime || t < besttime)
{
besttime = t;
bestreachnum = reachnum;
} //end if
} //end for
//
return bestreachnum;
} //end of the function BotGetReachabilityToGoal
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotAddToTarget(bvec3_t start, bvec3_t end, bfixed maxdist, bfixed *dist, bvec3_t target)
{
avec3_t dir;
bvec3_t tmp;
bfixed curdist;
VectorSubtract(end, start, tmp);
curdist = VectorNormalizeB2A(tmp,dir);
if (*dist + curdist < maxdist)
{
VectorCopy(end, target);
*dist += curdist;
return qfalse;
} //end if
else
{
FIXED_VEC3MA_R(start, maxdist - *dist, dir, target);
*dist = maxdist;
return qtrue;
} //end else
} //end of the function BotAddToTarget
int BotMovementViewTarget(int movestate, bot_goal_t *goal, int travelflags, bfixed lookahead, bvec3_t target)
{
aas_reachability_t reach;
int reachnum, lastareanum;
bot_movestate_t *ms;
bvec3_t end;
bfixed dist;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return qfalse;
reachnum = 0;
//if the bot has no goal or no last reachability
if (!ms->lastreachnum || !goal) return qfalse;
reachnum = ms->lastreachnum;
VectorCopy(ms->origin, end);
lastareanum = ms->lastareanum;
dist = BFIXED_0;
while(reachnum && dist < lookahead)
{
AAS_ReachabilityFromNum(reachnum, &reach);
if (BotAddToTarget(end, reach.start, lookahead, &dist, target)) return qtrue;
//never look beyond teleporters
if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_TELEPORT) return qtrue;
//never look beyond the weapon jump point
if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ROCKETJUMP) return qtrue;
if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_BFGJUMP) return qtrue;
//don't add jump pad distances
if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_JUMPPAD &&
(reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR &&
(reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB)
{
if (BotAddToTarget(reach.start, reach.end, lookahead, &dist, target)) return qtrue;
} //end if
reachnum = BotGetReachabilityToGoal(reach.end, reach.areanum,
ms->lastgoalareanum, lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, travelflags, NULL, 0, NULL);
VectorCopy(reach.end, end);
lastareanum = reach.areanum;
if (lastareanum == goal->areanum)
{
BotAddToTarget(reach.end, goal->origin, lookahead, &dist, target);
return qtrue;
} //end if
} //end while
//
return qfalse;
} //end of the function BotMovementViewTarget
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotVisible(int ent, bvec3_t eye, bvec3_t target)
{
bsp_trace_t trace;
trace = AAS_Trace(eye, NULL, NULL, target, ent, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
if (trace.fraction >= GFIXED_1) return qtrue;
return qfalse;
} //end of the function BotVisible
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotPredictVisiblePosition(bvec3_t origin, int areanum, bot_goal_t *goal, int travelflags, bvec3_t target)
{
aas_reachability_t reach;
int reachnum, lastgoalareanum, lastareanum, i;
int avoidreach[MAX_AVOIDREACH];
gfixed avoidreachtimes[MAX_AVOIDREACH];
int avoidreachtries[MAX_AVOIDREACH];
bvec3_t end;
//if the bot has no goal or no last reachability
if (!goal) return qfalse;
//if the areanum is not valid
if (!areanum) return qfalse;
//if the goal areanum is not valid
if (!goal->areanum) return qfalse;
Com_Memset(avoidreach, 0, MAX_AVOIDREACH * sizeof(int));
lastgoalareanum = goal->areanum;
lastareanum = areanum;
VectorCopy(origin, end);
//only do 20 hops
for (i = 0; i < 20 && (areanum != goal->areanum); i++)
{
//
reachnum = BotGetReachabilityToGoal(end, areanum,
lastgoalareanum, lastareanum,
avoidreach, avoidreachtimes, avoidreachtries,
goal, travelflags, travelflags, NULL, 0, NULL);
if (!reachnum) return qfalse;
AAS_ReachabilityFromNum(reachnum, &reach);
//
if (BotVisible(goal->entitynum, goal->origin, reach.start))
{
VectorCopy(reach.start, target);
return qtrue;
} //end if
//
if (BotVisible(goal->entitynum, goal->origin, reach.end))
{
VectorCopy(reach.end, target);
return qtrue;
} //end if
//
if (reach.areanum == goal->areanum)
{
VectorCopy(reach.end, target);
return qtrue;
} //end if
//
lastareanum = areanum;
areanum = reach.areanum;
VectorCopy(reach.end, end);
//
} //end while
//
return qfalse;
} //end of the function BotPredictVisiblePosition
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void MoverBottomCenter(aas_reachability_t *reach, bvec3_t bottomcenter)
{
int modelnum;
bvec3_t mins, maxs, origin, mids;
avec3_t angles = {AFIXED_0, AFIXED_0, AFIXED_0};
modelnum = reach->facenum & 0x0000FFFF;
//get some bsp model info
AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, origin);
//
if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
{
botimport.Print(PRT_MESSAGE, "no entity with model %d\n", modelnum);
} //end if
//get a point just above the plat in the bottom position
VectorAdd(mins, maxs, mids);
FIXED_VEC3MA(origin, BFIXED(0,5), mids, bottomcenter);
bottomcenter[2] = reach->start[2];
} //end of the function MoverBottomCenter
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bfixed BotGapDistance(bvec3_t origin, avec3_t hordir, int entnum)
{
bfixed dist, startz;
bvec3_t start, end;
aas_trace_t trace;
//do gap checking
startz = origin[2];
//this enables walking down stairs more fluidly
{
VectorCopy(origin, start);
VectorCopy(origin, end);
end[2] -= BFIXED(60,0);
trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum);
if (trace.fraction >= GFIXED_1) return BFIXED_1;
startz = trace.endpos[2] + BFIXED_1;
}
//
for (dist = BFIXED(8,0); dist <= BFIXED(100,0); dist += BFIXED(8,0))
{
FIXED_VEC3MA_R(origin, dist, hordir, start);
start[2] = startz + BFIXED(24,0);
VectorCopy(start, end);
end[2] -= BFIXED(48,0) + MAKE_BFIXED(sv_maxbarrier->value);
trace = AAS_TraceClientBBox(start, end, PRESENCE_CROUCH, entnum);
//if solid is found the bot can't walk any further and fall into a gap
if (!trace.startsolid)
{
//if it is a gap
if (trace.endpos[2] < startz - MAKE_BFIXED(sv_maxstep->value) - BFIXED(8,0))
{
VectorCopy(trace.endpos, end);
end[2] -= BFIXED(20,0);
if (AAS_PointContents(end) & CONTENTS_WATER) break;
//if a gap is found slow down
//botimport.Print(PRT_MESSAGE, "gap at %f\n", FIXED_TO_DOUBLE(dist));
return dist;
} //end if
startz = trace.endpos[2];
} //end if
} //end for
return BFIXED_0;
} //end of the function BotGapDistance
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotCheckBarrierJump(bot_movestate_t *ms, avec3_t dir, bfixed speed)
{
bvec3_t start, end;
avec3_t hordir;
aas_trace_t trace;
VectorCopy(ms->origin, end);
end[2] += MAKE_BFIXED(sv_maxbarrier->value);
//trace right up
trace = AAS_TraceClientBBox(ms->origin, end, PRESENCE_NORMAL, ms->entitynum);
//this shouldn't happen... but we check anyway
if (trace.startsolid) return qfalse;
//if very low ceiling it isn't possible to jump up to a barrier
if (trace.endpos[2] - ms->origin[2] < MAKE_BFIXED(sv_maxstep->value)) return qfalse;
//
hordir[0] = dir[0];
hordir[1] = dir[1];
hordir[2] = AFIXED_0;
VectorNormalize(hordir);
FIXED_VEC3MA_R(ms->origin, MAKE_BFIXED(ms->thinktime) * speed * BFIXED(0,5), hordir, end);
VectorCopy(trace.endpos, start);
end[2] = trace.endpos[2];
//trace from previous trace end pos horizontally in the move direction
trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum);
//again this shouldn't happen
if (trace.startsolid) return qfalse;
//
VectorCopy(trace.endpos, start);
VectorCopy(trace.endpos, end);
end[2] = ms->origin[2];
//trace down from the previous trace end pos
trace = AAS_TraceClientBBox(start, end, PRESENCE_NORMAL, ms->entitynum);
//if solid
if (trace.startsolid) return qfalse;
//if no obstacle at all
if (trace.fraction >= GFIXED_1) return qfalse;
//if less than the maximum step height
if (trace.endpos[2] - ms->origin[2] < MAKE_BFIXED(sv_maxstep->value)) return qfalse;
//
EA_Jump(ms->client);
EA_Move(ms->client, hordir, speed);
ms->moveflags |= MFL_BARRIERJUMP;
//there is a barrier
return qtrue;
} //end of the function BotCheckBarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotSwimInDirection(bot_movestate_t *ms, avec3_t dir, bfixed speed, int type)
{
avec3_t normdir;
VectorCopy(dir, normdir);
VectorNormalize(normdir);
EA_Move(ms->client, normdir, speed);
return qtrue;
} //end of the function BotSwimInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotWalkInDirection(bot_movestate_t *ms, avec3_t dir, bfixed speed, int type)
{
avec3_t hordir, atmpdir;
bvec3_t cmdmove, velocity, origin, btmpdir;
int presencetype, maxframes, cmdframes, stopevent;
aas_clientmove_t move;
bfixed dist;
if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND;
//if the bot is on the ground
if (ms->moveflags & MFL_ONGROUND)
{
//if there is a barrier the bot can jump on
if (BotCheckBarrierJump(ms, dir, speed)) return qtrue;
//remove barrier jump flag
ms->moveflags &= ~MFL_BARRIERJUMP;
//get the presence type for the movement
if ((type & MOVE_CROUCH) && !(type & MOVE_JUMP)) presencetype = PRESENCE_CROUCH;
else presencetype = PRESENCE_NORMAL;
//horizontal direction
hordir[0] = dir[0];
hordir[1] = dir[1];
hordir[2] = AFIXED_0;
VectorNormalize(hordir);
//if the bot is not supposed to jump
if (!(type & MOVE_JUMP))
{
//if there is a gap, try to jump over it
if (BotGapDistance(ms->origin, hordir, ms->entitynum) > BFIXED_0) type |= MOVE_JUMP;
} //end if
//get command movement
FIXED_VEC3SCALE_R(hordir, speed, cmdmove);
VectorCopy(ms->velocity, velocity);
//
if (type & MOVE_JUMP)
{
//botimport.Print(PRT_MESSAGE, "trying jump\n");
cmdmove[2] = BFIXED(400,0);
maxframes = PREDICTIONTIME_JUMP * 10;
cmdframes = 1;
stopevent = PSE_HITGROUND|PSE_HITGROUNDDAMAGE|
PSE_ENTERWATER|PSE_ENTERSLIME|PSE_ENTERLAVA;
} //end if
else
{
maxframes = 2;
cmdframes = 2;
stopevent = PSE_HITGROUNDDAMAGE|
PSE_ENTERWATER|PSE_ENTERSLIME|PSE_ENTERLAVA;
} //end else
//AAS_ClearShownDebugLines();
//
VectorCopy(ms->origin, origin);
origin[2] += BFIXED(0,5);
AAS_PredictClientMovement(&move, ms->entitynum, origin, presencetype, qtrue,
velocity, cmdmove, cmdframes, maxframes, GFIXED(0,1),
stopevent, 0, qfalse);//qtrue);
//if prediction time wasn't enough to fully predict the movement
if (move.frames >= maxframes && (type & MOVE_JUMP))
{
//botimport.Print(PRT_MESSAGE, "client %d: max prediction frames\n", ms->client);
return qfalse;
} //end if
//don't enter slime or lava and don't fall from too high
if (move.stopevent & (PSE_ENTERSLIME|PSE_ENTERLAVA|PSE_HITGROUNDDAMAGE))
{
//botimport.Print(PRT_MESSAGE, "client %d: would be hurt ", ms->client);
//if (move.stopevent & PSE_ENTERSLIME) botimport.Print(PRT_MESSAGE, "slime\n");
//if (move.stopevent & PSE_ENTERLAVA) botimport.Print(PRT_MESSAGE, "lava\n");
//if (move.stopevent & PSE_HITGROUNDDAMAGE) botimport.Print(PRT_MESSAGE, "hitground\n");
return qfalse;
} //end if
//if ground was hit
if (move.stopevent & PSE_HITGROUND)
{
//check for nearby gap
VectorNormalizeB2A(move.velocity, atmpdir);
dist = BotGapDistance(move.endpos, atmpdir, ms->entitynum);
if (dist > BFIXED_0) return qfalse;
//
dist = BotGapDistance(move.endpos, hordir, ms->entitynum);
if (dist > BFIXED_0) return qfalse;
} //end if
//get horizontal movement
btmpdir[0] = move.endpos[0] - ms->origin[0];
btmpdir[1] = move.endpos[1] - ms->origin[1];
btmpdir[2] = BFIXED_0;
//
//AAS_DrawCross(move.endpos, 4, LINECOLOR_BLUE);
//the bot is blocked by something
if (FIXED_VEC3LEN(btmpdir) < FIXED_DIVPOW2(speed * MAKE_BFIXED(ms->thinktime),1)) return qfalse;
//perform the movement
if (type & MOVE_JUMP) EA_Jump(ms->client);
if (type & MOVE_CROUCH) EA_Crouch(ms->client);
EA_Move(ms->client, hordir, speed);
//movement was succesfull
return qtrue;
} //end if
else
{
if (ms->moveflags & MFL_BARRIERJUMP)
{
//if near the top or going down
if (ms->velocity[2] < BFIXED(50,0))
{
EA_Move(ms->client, dir, speed);
} //end if
} //end if
//FIXME: do air control to avoid hazards
return qtrue;
} //end else
} //end of the function BotWalkInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotMoveInDirection(int movestate, avec3_t dir, bfixed speed, int type)
{
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return qfalse;
//if swimming
if (AAS_Swimming(ms->origin))
{
return BotSwimInDirection(ms, dir, speed, type);
} //end if
else
{
return BotWalkInDirection(ms, dir, speed, type);
} //end else
} //end of the function BotMoveInDirection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int Intersection(bvec2_t p1, bvec2_t p2, bvec2_t p3, bvec2_t p4, bvec2_t out)
{
bfixed x1, dx1, dy1, x2, dx2, dy2, d;
dx1 = p2[0] - p1[0];
dy1 = p2[1] - p1[1];
dx2 = p4[0] - p3[0];
dy2 = p4[1] - p3[1];
d = dy1 * dx2 - dx1 * dy2;
if (d != BFIXED_0)
{
x1 = p1[1] * dx1 - p1[0] * dy1;
x2 = p3[1] * dx2 - p3[0] * dy2;
out[0] = FIXED_SNAP ((dx1 * x2 - dx2 * x1) / d);
out[1] = FIXED_SNAP ((dy1 * x2 - dy2 * x1) / d);
return qtrue;
} //end if
else
{
return qfalse;
} //end else
} //end of the function Intersection
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotCheckBlocked(bot_movestate_t *ms, avec3_t dir, int checkbottom, bot_moveresult_t *result)
{
bvec3_t mins, maxs, end;
avec3_t up = {AFIXED_0, AFIXED_0, AFIXED_1};
bsp_trace_t trace;
//test for entities obstructing the bot's path
AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
//
if (FIXED_ABS(FIXED_VEC3DOT(dir, up)) < AFIXED(0,7))
{
mins[2] += MAKE_BFIXED(sv_maxstep->value); //if the bot can step on
maxs[2] -= BFIXED(10,0); //a little lower to avoid low ceiling
} //end if
FIXED_VEC3MA_R(ms->origin, BFIXED(3,0), dir, end);
trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP|CONTENTS_BODY);
//if not started in solid and not hitting the world entity
if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
{
result->blocked = qtrue;
result->blockentity = trace.ent;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
#endif //DEBUG
} //end if
//if not in an area with reachability
else if (checkbottom && !AAS_AreaReachability(ms->areanum))
{
//check if the bot is standing on something
AAS_PresenceTypeBoundingBox(ms->presencetype, mins, maxs);
FIXED_VEC3MA_R(ms->origin, -BFIXED(3,0), up, end);
trace = AAS_Trace(ms->origin, mins, maxs, end, ms->entitynum, CONTENTS_SOLID|CONTENTS_PLAYERCLIP);
if (!trace.startsolid && (trace.ent != ENTITYNUM_WORLD && trace.ent != ENTITYNUM_NONE) )
{
result->blocked = qtrue;
result->blockentity = trace.ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%d: BotCheckBlocked: I'm blocked\n", ms->client);
#endif //DEBUG
} //end if
} //end else
} //end of the function BotCheckBlocked
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotClearMoveResult(bot_moveresult_t *moveresult)
{
moveresult->failure = qfalse;
moveresult->type = 0;
moveresult->blocked = qfalse;
moveresult->blockentity = 0;
moveresult->traveltype = 0;
moveresult->flags = 0;
} //end of the function BotClearMoveResult
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed dist, speed;
avec3_t hordir;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//first walk straight to the reachability start
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
//
if (dist < BFIXED(10,0))
{
//walk straight to the reachability end
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
} //end if
//if going towards a crouch area
if (!(AAS_AreaPresenceType(reach->areanum) & PRESENCE_NORMAL))
{
//if pretty close to the reachable area
if (dist < BFIXED(20,0)) EA_Crouch(ms->client);
} //end if
//
dist = BotGapDistance(ms->origin, hordir, ms->entitynum);
//
if (ms->moveflags & MFL_WALK)
{
if (dist > BFIXED_0) speed = BFIXED(200,0) - (BFIXED(180,0) - BFIXED_1 * dist);
else speed = BFIXED(200,0);
EA_Walk(ms->client);
} //end if
else
{
if (dist >BFIXED_0) speed = BFIXED(400,0) - (BFIXED(360,0) - BFIXED(2,0) * dist);
else speed = BFIXED(400,0);
} //end else
//elemantary action move in direction
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Walk
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Walk(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir;
bfixed dist, speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if not on the ground and changed areas... don't walk back!!
//(doesn't seem to help)
/*
ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
if (ms->areanum == reach->areanum)
{
#ifdef DEBUG
botimport.Print(PRT_MESSAGE, "BotFinishTravel_Walk: already in reach area\n");
#endif //DEBUG
return result;
} //end if*/
//go straight to the reachability end
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist > BFIXED(100,0)) dist = BFIXED(100,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(3,0) * dist);
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_Walk
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Crouch(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed speed;
avec3_t hordir;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
speed = BFIXED(400,0);
//walk straight to reachability end
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
//elemantary actions
EA_Crouch(ms->client);
EA_Move(ms->client, hordir, speed);
//
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Crouch
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed dist, speed;
avec3_t hordir;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//walk straight to reachability start
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
//if pretty close to the barrier
if (dist < BFIXED(9,0))
{
EA_Jump(ms->client);
} //end if
else
{
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
EA_Move(ms->client, hordir, speed);
} //end else
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_BarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_BarrierJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed dist;
avec3_t hordir;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if near the top or going down
if (ms->velocity[2] < BFIXED(250,0))
{
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
//
EA_Move(ms->client, hordir, BFIXED(400,0));
VectorCopy(hordir, result.movedir);
} //end if
//
return result;
} //end of the function BotFinishTravel_BarrierJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Swim(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t dir;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//swim straight to reachability end
VectorSubtract(reach->start, ms->origin, tmp);
VectorNormalizeB2A(tmp,dir);
//
BotCheckBlocked(ms, dir, qtrue, &result);
//elementary actions
EA_Move(ms->client, dir, BFIXED(400,0));
//
VectorCopy(dir, result.movedir);
Vector2Angles(dir, result.ideal_viewangles);
result.flags |= MOVERESULT_SWIMVIEW;
//
return result;
} //end of the function BotTravel_Swim
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t bdir, tmp1;
avec3_t adir, hordir;
bfixed dist;
bot_moveresult_t result;
BotClearMoveResult(&result);
//swim straight to reachability end
VectorSubtract(reach->end, ms->origin, bdir);
VectorCopy(bdir, tmp1);
tmp1[2] = BFIXED_0;
bdir[2] += BFIXED(15,0) + crandom_b() * BFIXED(40,0);
//botimport.Print(PRT_MESSAGE, "BotTravel_WaterJump: dir[2] = %f\n", FIXED_TO_DOUBLE(dir[2]));
VectorNormalizeB2A(bdir,adir);
dist = VectorNormalizeB2A(tmp1,hordir);
//elemantary actions
//EA_Move(ms->client, adir, 400);
EA_MoveForward(ms->client);
//move up if close to the actual out of water jump spot
if (dist < BFIXED(40,0)) EA_MoveUp(ms->client);
//set the ideal view angles
Vector2Angles(adir, result.ideal_viewangles);
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
VectorCopy(adir, result.movedir);
//
return result;
} //end of the function BotTravel_WaterJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WaterJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t bdir;
avec3_t adir;
bvec3_t pnt;
bfixed dist;
bot_moveresult_t result;
//botimport.Print(PRT_MESSAGE, "BotFinishTravel_WaterJump\n");
BotClearMoveResult(&result);
//if waterjumping there's nothing to do
if (ms->moveflags & MFL_WATERJUMP) return result;
//if not touching any water anymore don't do anything
//otherwise the bot sometimes keeps jumping?
VectorCopy(ms->origin, pnt);
pnt[2] -= BFIXED(32,0); //extra for q2dm4 near red armor/mega health
if (!(AAS_PointContents(pnt) & (CONTENTS_LAVA|CONTENTS_SLIME|CONTENTS_WATER))) return result;
//swim straight to reachability end
VectorSubtract(reach->end, ms->origin, bdir);
bdir[0] += crandom_b() * BFIXED(10,0);
bdir[1] += crandom_b() * BFIXED(10,0);
bdir[2] += BFIXED(70,0) + crandom_b() * BFIXED(10,0);
dist = VectorNormalizeB2A(bdir,adir);
//elemantary actions
EA_Move(ms->client, adir, BFIXED(400,0));
//set the ideal view angles
Vector2Angles(adir, result.ideal_viewangles);
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
VectorCopy(adir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_WaterJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir, dir;
bfixed dist, speed, reachhordist;
bot_moveresult_t result;
BotClearMoveResult(&result);
//check if the bot is blocked by anything
VectorSubtract(reach->start, ms->origin, tmp);
VectorNormalizeB2A(tmp, dir);
BotCheckBlocked(ms, dir, qtrue, &result);
//if the reachability start and end are practially above each other
VectorSubtract(reach->end, reach->start, tmp);
tmp[2] = BFIXED_0;
reachhordist = FIXED_VEC3LEN(tmp);
//walk straight to the reachability start
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//if pretty close to the start focus on the reachability end
if (dist < BFIXED(48,0))
{
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//
if (reachhordist < BFIXED(20,0))
{
speed = BFIXED(100,0);
} //end if
else if (!AAS_HorizontalVelocityForJump(BFIXED_0, reach->start, reach->end, &speed))
{
speed = BFIXED(400,0);
} //end if
} //end if
else
{
if (reachhordist < BFIXED(20,0))
{
if (dist > BFIXED(64,0)) dist = BFIXED(64,0);
speed = BFIXED(400,0) - (BFIXED(256,0) - BFIXED(4,0) * dist);
} //end if
else
{
speed = BFIXED(400,0);
} //end else
} //end else
//
BotCheckBlocked(ms, hordir, qtrue, &result);
//elemantary action
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_WalkOffLedge
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotAirControl(bvec3_t origin, bvec3_t velocity, bvec3_t goal, avec3_t dir, bfixed *speed)
{
bvec3_t org, vel, tmp;
bfixed dist;
int i;
VectorCopy(origin, org);
FIXED_VEC3SCALE(velocity, BFIXED(0,1), vel);
for (i = 0; i < 50; i++)
{
vel[2] -= MAKE_BFIXED(sv_gravity->value * LFIXED(0,01));
//if going down and next position would be below the goal
if (vel[2] < BFIXED_0 && org[2] + vel[2] < goal[2])
{
FIXED_VEC3SCALE(vel, (goal[2] - org[2]) / vel[2], vel);
VectorAdd(org, vel, org);
VectorSubtract(goal, org, tmp);
dist = VectorNormalizeB2A(tmp,dir);
if (dist > BFIXED(32,0)) dist = BFIXED(32,0);
*speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(13,0) * dist);
return qtrue;
} //end if
else
{
VectorAdd(org, vel, org);
} //end else
} //end for
VectorSet(dir, AFIXED_0, AFIXED_0, AFIXED_0);
*speed = BFIXED(400,0);
return qfalse;
} //end of the function BotAirControl
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WalkOffLedge(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t hordir,av;
bvec3_t tmp , end, v;
avec3_t adir;
bvec3_t bdir;
bfixed dist, speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
VectorSubtract(reach->end, ms->origin, bdir);
VectorNormalizeB2A(bdir,adir);
BotCheckBlocked(ms, adir, qtrue, &result);
//
VectorSubtract(reach->end, ms->origin, v);
v[2] = BFIXED_0;
dist = VectorNormalizeB2A(v,av);
if (dist > BFIXED(16,0)) FIXED_VEC3MA_R(reach->end, BFIXED(16,0), av, end);
else VectorCopy(reach->end, end);
//
if (!BotAirControl(ms->origin, ms->velocity, end, hordir, &speed))
{
//go straight to the reachability end
VectorCopy(bdir, tmp);
tmp[2] = BFIXED_0;
//
dist = VectorNormalizeB2A(tmp,hordir);
speed = BFIXED(400,0);
} //end if
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_WalkOffLedge
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
/*
bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t hordir;
bfixed dist, gapdist, speed, horspeed, sv_jumpvel;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
sv_jumpvel = botlibglobals.sv_jumpvel->value;
//walk straight to the reachability start
hordir[0] = reach->start[0] - ms->origin[0];
hordir[1] = reach->start[1] - ms->origin[1];
hordir[2] = 0;
dist = VectorNormalize(hordir);
//
speed = 350;
//
gapdist = BotGapDistance(ms, hordir, ms->entitynum);
//if pretty close to the start focus on the reachability end
if (dist < 50 || (gapdist && gapdist < 50))
{
//NOTE: using max speed (400) works best
//if (AAS_HorizontalVelocityForJump(sv_jumpvel, ms->origin, reach->end, &horspeed))
//{
// speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
//} //end if
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
VectorNormalize(hordir);
//elemantary action jump
EA_Jump(ms->client);
//
ms->jumpreach = ms->lastreachnum;
speed = 600;
} //end if
else
{
if (AAS_HorizontalVelocityForJump(sv_jumpvel, reach->start, reach->end, &horspeed))
{
speed = horspeed * 400 / botlibglobals.sv_maxwalkvelocity->value;
} //end if
} //end else
//elemantary action
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Jump*/
/*
bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t hordir, dir1, dir2, mins, maxs, start, end;
bfixed dist1, dist2, speed;
bot_moveresult_t result;
bsp_trace_t trace;
BotClearMoveResult(&result);
//
hordir[0] = reach->start[0] - reach->end[0];
hordir[1] = reach->start[1] - reach->end[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
VectorCopy(reach->start, start);
start[2] += 1;
//minus back the bouding box size plus 16
FIXED_VEC3MA(reach->start, BFIXED(80,0), hordir, end);
//
AAS_PresenceTypeBoundingBox(PRESENCE_NORMAL, mins, maxs);
//check for solids
trace = AAS_Trace(start, mins, maxs, end, ms->entitynum, MASK_PLAYERSOLID);
if (trace.startsolid) VectorCopy(start, trace.endpos);
//check for a gap
for (dist1 = 0; dist1 < 80; dist1 += 10)
{
FIXED_VEC3MA(start, dist1+BFIXED(10,0), hordir, end);
end[2] += 1;
if (AAS_PointAreaNum(end) != ms->reachareanum) break;
} //end for
if (dist1 < 80) FIXED_VEC3MA(reach->start, dist1, hordir, trace.endpos);
// dist1 = BotGapDistance(start, hordir, ms->entitynum);
// if (dist1 && dist1 <= trace.fraction * 80) FIXED_VEC3MA(reach->start, dist1-BFIXED(20,0), hordir, trace.endpos);
//
VectorSubtract(ms->origin, reach->start, dir1);
dir1[2] = 0;
dist1 = VectorNormalize(dir1);
VectorSubtract(ms->origin, trace.endpos, dir2);
dir2[2] = 0;
dist2 = VectorNormalize(dir2);
//if just before the reachability start
if (FIXED_VEC3DOT(dir1, dir2) < -BFIXED(0,8) || dist2 < 5)
{
//botimport.Print(PRT_MESSAGE, "between jump start and run to point\n");
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//elemantary action jump
if (dist1 < 24) EA_Jump(ms->client);
else if (dist1 < 32) EA_DelayedJump(ms->client);
EA_Move(ms->client, hordir, 600);
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
//botimport.Print(PRT_MESSAGE, "going towards run to point\n");
hordir[0] = trace.endpos[0] - ms->origin[0];
hordir[1] = trace.endpos[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//
if (dist2 > 80) dist2 = 80;
speed = 400 - (400 - 5 * dist2);
EA_Move(ms->client, hordir, speed);
} //end else
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Jump*/
//*
bot_moveresult_t BotTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t hordir, dir1, dir2;
bvec3_t runstart,tmp, start, end;
bfixed dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
AAS_JumpReachRunStart(reach, runstart);
//*
tmp[0] = runstart[0] - reach->start[0];
tmp[1] = runstart[1] - reach->start[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//
VectorCopy(reach->start, start);
start[2] += BFIXED_1;
FIXED_VEC3MA_R(reach->start, BFIXED(80,0), hordir, runstart);
//check for a gap
for (dist1 = BFIXED_0; dist1 < BFIXED(80,0); dist1 += BFIXED(10,0))
{
FIXED_VEC3MA_R(start, dist1+BFIXED(10,0), hordir, end);
end[2] += BFIXED_1;
if (AAS_PointAreaNum(end) != ms->reachareanum) break;
} //end for
if (dist1 < BFIXED(80,0)) FIXED_VEC3MA_R(reach->start, dist1, hordir, runstart);
//
VectorSubtract(ms->origin, reach->start, tmp);
tmp[2] = BFIXED_0;
dist1 = VectorNormalizeB2A(tmp,dir1);
VectorSubtract(ms->origin, runstart, tmp);
tmp[2] = BFIXED_0;
dist2 = VectorNormalizeB2A(tmp,dir2);
//if just before the reachability start
if (FIXED_VEC3DOT(dir1, dir2) < -AFIXED(0,8) || dist2 < BFIXED(5,0))
{
// botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//elemantary action jump
if (dist1 < BFIXED(24,0)) EA_Jump(ms->client);
else if (dist1 < BFIXED(32,0)) EA_DelayedJump(ms->client);
EA_Move(ms->client, hordir, BFIXED(600,0));
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
// botimport.Print(PRT_MESSAGE, "going towards run start point\n");
tmp[0] = runstart[0] - ms->origin[0];
tmp[1] = runstart[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//
if (dist2 > BFIXED(80,0)) dist2 = BFIXED(80,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(5,0) * dist2);
EA_Move(ms->client, hordir, speed);
} //end else
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_Jump*/
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Jump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir, hordir2;
bfixed speed, dist;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if not jumped yet
if (!ms->jumpreach) return result;
//go straight to the reachability end
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
tmp[0] = reach->end[0] - reach->start[0];
tmp[1] = reach->end[1] - reach->start[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir2);
//
if (FIXED_VEC3DOT(hordir, hordir2) < -AFIXED(0,5) && dist < BFIXED(24,0)) return result;
//always use max speed when traveling through the air
speed = BFIXED(800,0);
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_Jump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Ladder(bot_movestate_t *ms, aas_reachability_t *reach)
{
//bfixed dist, speed;
avec3_t dir, viewdir;//, hordir;
bvec3_t tmp;
avec3_t origin = {AFIXED_0, AFIXED_0, AFIXED_0};
// avec3_t up = {AFIXED_0, AFIXED_0, AFIXED_1};
bot_moveresult_t result;
BotClearMoveResult(&result);
//
// if ((ms->moveflags & MFL_AGAINSTLADDER))
//NOTE: not a good idea for ladders starting in water
// || !(ms->moveflags & MFL_ONGROUND))
{
//botimport.Print(PRT_MESSAGE, "against ladder or not on ground\n");
VectorSubtract(reach->end, ms->origin, tmp);
VectorNormalizeB2A(tmp,dir);
//set the ideal view angles, facing the ladder up or down
viewdir[0] = dir[0];
viewdir[1] = dir[1];
viewdir[2] = AFIXED(3,0) * dir[2];
Vector2Angles(viewdir, result.ideal_viewangles);
//elemantary action
EA_Move(ms->client, origin, BFIXED_0);
EA_MoveForward(ms->client);
//set movement view flag so the AI can see the view is focussed
result.flags |= MOVERESULT_MOVEMENTVIEW;
} //end if
/* else
{
//botimport.Print(PRT_MESSAGE, "moving towards ladder\n");
VectorSubtract(reach->end, ms->origin, dir);
//make sure the horizontal movement is large anough
VectorCopy(dir, hordir);
hordir[2] = 0;
dist = VectorNormalize(hordir);
//
dir[0] = hordir[0];
dir[1] = hordir[1];
if (dir[2] > 0) dir[2] = 1;
else dir[2] = -1;
if (dist > 50) dist = 50;
speed = 400 - (200 - 4 * dist);
EA_Move(ms->client, dir, speed);
} //end else*/
//save the movement direction
VectorCopy(dir, result.movedir);
//
return result;
} //end of the function BotTravel_Ladder
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Teleport(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t hordir;
bfixed dist;
bvec3_t tmp;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if the bot is being teleported
if (ms->moveflags & MFL_TELEPORTED) return result;
//walk straight to center of the teleporter
VectorSubtract(reach->start, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
if (dist < BFIXED(30,0)) EA_Move(ms->client, hordir, BFIXED(200,0));
else EA_Move(ms->client, hordir, BFIXED(400,0));
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
VectorCopy(hordir, result.movedir);
return result;
} //end of the function BotTravel_Teleport
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t dir, dir1, dir2, hordir;
bvec3_t tmp, bottomcenter, bdir;
bfixed dist, dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if standing on the plat
if (BotOnMover(ms->origin, ms->entitynum, reach))
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot on elevator\n");
#endif //DEBUG_ELEVATOR
//if vertically not too far from the end point
if (FIXED_ABS(ms->origin[2] - reach->end[2]) < MAKE_BFIXED(sv_maxbarrier->value))
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot moving to end\n");
#endif //DEBUG_ELEVATOR
//move to the end point
VectorSubtract(reach->end, ms->origin, tmp);
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
if (!BotCheckBarrierJump(ms, hordir, BFIXED(100,0)))
{
EA_Move(ms->client, hordir, BFIXED(400,0));
} //end if
VectorCopy(hordir, result.movedir);
} //end else
//if not really close to the center of the elevator
else
{
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, tmp);
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist > BFIXED(10,0))
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot moving to center\n");
#endif //DEBUG_ELEVATOR
//move to the center of the plat
if (dist > BFIXED(100,0)) dist = BFIXED(100,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(4,0) * dist);
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
} //end if
} //end else
} //end if
else
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot not on elevator\n");
#endif //DEBUG_ELEVATOR
//if very near the reachability end
VectorSubtract(reach->end, ms->origin, bdir);
dist = FIXED_VEC3LEN(bdir);
if (dist < BFIXED(64,0))
{
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
//
if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
if (speed > BFIXED(5,0)) EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
//stop using this reachability
ms->reachability_time = GFIXED_0;
return result;
} //end if
//get direction and distance to reachability start
VectorSubtract(reach->start, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist1 = VectorNormalizeB2A(tmp, dir1);
//if the elevator isn't down
if (!MoverDown(reach))
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "elevator not down\n");
#endif //DEBUG_ELEVATOR
dist = dist1;
VectorCopy(dir1, dir);
//
BotCheckBlocked(ms, dir, qfalse, &result);
//
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
//
if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
if (speed > BFIXED(5,0)) EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
//this isn't a failure... just wait till the elevator comes down
result.type = RESULTTYPE_ELEVATORUP;
result.flags |= MOVERESULT_WAITING;
return result;
} //end if
//get direction and distance to elevator bottom center
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist2 = VectorNormalizeB2A(tmp,dir2);
//if very close to the reachability start or
//closer to the elevator center or
//between reachability start and elevator center
if (dist1 < BFIXED(20,0) || dist2 < dist1 || FIXED_VEC3DOT(dir1, dir2) < AFIXED_0)
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot moving to center\n");
#endif //DEBUG_ELEVATOR
dist = dist2;
VectorCopy(dir2, dir);
} //end if
else //closer to the reachability start
{
#ifdef DEBUG_ELEVATOR
botimport.Print(PRT_MESSAGE, "bot moving to start\n");
#endif //DEBUG_ELEVATOR
dist = dist1;
VectorCopy(dir1, dir);
} //end else
//
BotCheckBlocked(ms, dir, qfalse, &result);
//
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(6,0) * dist);
//
if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
} //end else
return result;
} //end of the function BotTravel_Elevator
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_Elevator(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t bottomcenter;
bvec3_t bdtmp,tdtmp;
avec3_t bottomdir, topdir;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, bdtmp);
//
VectorSubtract(reach->end, ms->origin, tdtmp);
//
if (FIXED_ABS(bdtmp[2]) < FIXED_ABS(tdtmp[2]))
{
VectorNormalizeB2A(bdtmp,bottomdir);
EA_Move(ms->client, bottomdir, BFIXED(300,0));
} //end if
else
{
VectorNormalizeB2A(tdtmp,topdir);
EA_Move(ms->client, topdir, BFIXED(300,0));
} //end else
return result;
} //end of the function BotFinishTravel_Elevator
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotFuncBobStartEnd(aas_reachability_t *reach, bvec3_t start, bvec3_t end, bvec3_t origin)
{
int spawnflags, modelnum;
bvec3_t mins, maxs, mid;
avec3_t angles = {AFIXED_0, AFIXED_0, AFIXED_0};
int num0, num1;
modelnum = reach->facenum & 0x0000FFFF;
if (!AAS_OriginOfMoverWithModelNum(modelnum, origin))
{
botimport.Print(PRT_MESSAGE, "BotFuncBobStartEnd: no entity with model %d\n", modelnum);
VectorSet(start, BFIXED_0, BFIXED_0, BFIXED_0);
VectorSet(end, BFIXED_0, BFIXED_0, BFIXED_0);
return;
} //end if
AAS_BSPModelMinsMaxsOrigin(modelnum, angles, mins, maxs, NULL);
VectorAdd(mins, maxs, mid);
FIXED_VEC3SCALE(mid, BFIXED(0,5), mid);
VectorCopy(mid, start);
VectorCopy(mid, end);
spawnflags = reach->facenum >> 16;
num0 = reach->edgenum >> 16;
if (num0 > 0x00007FFF) num0 |= 0xFFFF0000;
num1 = reach->edgenum & 0x0000FFFF;
if (num1 > 0x00007FFF) num1 |= 0xFFFF0000;
if (spawnflags & 1)
{
start[0] = MAKE_BFIXED(num0);
end[0] = MAKE_BFIXED(num1);
//
origin[0] += mid[0];
origin[1] = mid[1];
origin[2] = mid[2];
} //end if
else if (spawnflags & 2)
{
start[1] = MAKE_BFIXED(num0);
end[1] = MAKE_BFIXED(num1);
//
origin[0] = mid[0];
origin[1] += mid[1];
origin[2] = mid[2];
} //end else if
else
{
start[2] = MAKE_BFIXED(num0);
end[2] = MAKE_BFIXED(num1);
//
origin[0] = mid[0];
origin[1] = mid[1];
origin[2] += mid[2];
} //end else
} //end of the function BotFuncBobStartEnd
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t dir, dir1, dir2, hordir;
bvec3_t bottomcenter, bob_start, bob_end, bob_origin, tmp;
bfixed dist, dist1, dist2, speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//
BotFuncBobStartEnd(reach, bob_start, bob_end, bob_origin);
//if standing ontop of the func_bobbing
if (BotOnMover(ms->origin, ms->entitynum, reach))
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot on func_bobbing\n");
#endif
//if near end point of reachability
VectorSubtract(bob_origin, bob_end, tmp);
if (FIXED_VEC3LEN(tmp) < BFIXED(24,0))
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot moving to reachability end\n");
#endif
//move to the end point
VectorSubtract(reach->end, ms->origin, tmp);
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
if (!BotCheckBarrierJump(ms, hordir, BFIXED(100,0)))
{
EA_Move(ms->client, hordir, BFIXED(400,0));
} //end if
VectorCopy(hordir, result.movedir);
} //end else
//if not really close to the center of the elevator
else
{
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, tmp);
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist > BFIXED(10,0))
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n");
#endif
//move to the center of the plat
if (dist > BFIXED(100,0)) dist = BFIXED(100,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(4,0) * dist);
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
} //end if
} //end else
} //end if
else
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot not ontop of func_bobbing\n");
#endif
//if very near the reachability end
VectorSubtract(reach->end, ms->origin, tmp);
dist = FIXED_VEC3LEN(tmp);
if (dist < BFIXED(64,0))
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot moving to end\n");
#endif
VectorNormalizeB2A(tmp,dir);
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
//if swimming or no barrier jump
if ((ms->moveflags & MFL_SWIMMING) || !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
if (speed > BFIXED(5,0)) EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
//stop using this reachability
ms->reachability_time = GFIXED_0;
return result;
} //end if
//get direction and distance to reachability start
VectorSubtract(reach->start, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist1 = VectorNormalizeB2A(tmp,dir1);
//if func_bobbing is Not it's start position
VectorSubtract(bob_origin, bob_start, tmp);
if (FIXED_VEC3LEN(tmp) > BFIXED(16,0))
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "func_bobbing not at start\n");
#endif
dist = dist1;
VectorCopy(dir1, dir);
//
BotCheckBlocked(ms, dir, qfalse, &result);
//
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
//
if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
if (speed > BFIXED(5,0)) EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
//this isn't a failure... just wait till the func_bobbing arrives
result.type = RESULTTYPE_WAITFORFUNCBOBBING;
result.flags |= MOVERESULT_WAITING;
return result;
} //end if
//get direction and distance to func_bob bottom center
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist2 = VectorNormalizeB2A(tmp,dir2);
//if very close to the reachability start or
//closer to the elevator center or
//between reachability start and func_bobbing center
if (dist1 < BFIXED(20,0) || dist2 < dist1 || FIXED_VEC3DOT(dir1, dir2) < AFIXED_0)
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot moving to func_bobbing center\n");
#endif
dist = dist2;
VectorCopy(dir2, dir);
} //end if
else //closer to the reachability start
{
#ifdef DEBUG_FUNCBOB
botimport.Print(PRT_MESSAGE, "bot moving to reachability start\n");
#endif
dist = dist1;
VectorCopy(dir1, dir);
} //end else
//
BotCheckBlocked(ms, dir, qfalse, &result);
//
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(6,0) * dist);
//
if (!(ms->moveflags & MFL_SWIMMING) && !BotCheckBarrierJump(ms, dir, BFIXED(50,0)))
{
EA_Move(ms->client, dir, speed);
} //end if
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
} //end else
return result;
} //end of the function BotTravel_FuncBobbing
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_FuncBobbing(bot_movestate_t *ms, aas_reachability_t *reach)
{
avec3_t dir, hordir;
bvec3_t bob_origin, bob_start, bob_end, bottomcenter,tmp;
bot_moveresult_t result;
bfixed dist, speed;
BotClearMoveResult(&result);
//
BotFuncBobStartEnd(reach, bob_start, bob_end, bob_origin);
//
VectorSubtract(bob_origin, bob_end, tmp);
dist = FIXED_VEC3LEN(tmp);
//if the func_bobbing is near the end
if (dist < BFIXED(16,0))
{
VectorNormalizeB2A(tmp,dir);
VectorSubtract(reach->end, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist > BFIXED(60,0)) dist = BFIXED(60,0);
speed = BFIXED(360,0) - (BFIXED(360,0) - BFIXED(6,0) * dist);
//
if (speed > BFIXED(5,0)) EA_Move(ms->client, dir, speed);
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING) result.flags |= MOVERESULT_SWIMVIEW;
} //end if
else
{
MoverBottomCenter(reach, bottomcenter);
VectorSubtract(bottomcenter, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist > BFIXED(5,0))
{
//move to the center of the plat
if (dist > BFIXED(100,0)) dist = BFIXED(100,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(4,0) * dist);
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
} //end if
} //end else
return result;
} //end of the function BotFinishTravel_FuncBobbing
//===========================================================================
// 0 no valid grapple hook visible
// 1 the grapple hook is still flying
// 2 the grapple hooked into a wall
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int GrappleState(bot_movestate_t *ms, aas_reachability_t *reach)
{
int i;
aas_entityinfo_t entinfo;
//if the grapple hook is pulling
if (ms->moveflags & MFL_GRAPPLEPULL)
return 2;
//check for a visible grapple missile entity
//or visible grapple entity
for (i = AAS_NextEntity(0); i; i = AAS_NextEntity(i))
{
if (AAS_EntityType(i) == FIXED_TO_INT(entitytypemissile->value))
{
AAS_EntityInfo(i, &entinfo);
if (entinfo.weapon == FIXED_TO_INT(weapindex_grapple->value))
{
return 1;
} //end if
} //end if
} //end for
//no valid grapple at all
return 0;
} //end of the function GrappleState
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetGrapple(bot_movestate_t *ms)
{
aas_reachability_t reach;
AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
//if not using the grapple hook reachability anymore
if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_GRAPPLEHOOK)
{
if ((ms->moveflags & MFL_ACTIVEGRAPPLE) || FIXED_NOT_ZERO(ms->grapplevisible_time))
{
if (FIXED_NOT_ZERO(offhandgrapple->value))
EA_Command(ms->client, cmd_grappleoff->string);
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->grapplevisible_time = GFIXED_0;
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_MESSAGE, "reset grapple\n");
#endif //DEBUG_GRAPPLE
} //end if
} //end if
} //end of the function BotResetGrapple
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_Grapple(bot_movestate_t *ms, aas_reachability_t *reach)
{
bot_moveresult_t result;
bfixed dist, speed;
avec3_t dir;
bvec3_t tmp, org, viewdir;
int state, areanum;
bsp_trace_t trace;
#ifdef DEBUG_GRAPPLE
static int debugline;
if (!debugline) debugline = botimport.DebugLineCreate();
botimport.DebugLineShow(debugline, reach->start, reach->end, LINECOLOR_BLUE);
#endif //DEBUG_GRAPPLE
BotClearMoveResult(&result);
//
if (ms->moveflags & MFL_GRAPPLERESET)
{
if (FIXED_NOT_ZERO(offhandgrapple->value))
EA_Command(ms->client, cmd_grappleoff->string);
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
return result;
} //end if
//
if (!FIXED_TO_INT(offhandgrapple->value))
{
result.weapon = FIXED_TO_INT(weapindex_grapple->value);
result.flags |= MOVERESULT_MOVEMENTWEAPON;
} //end if
//
if (ms->moveflags & MFL_ACTIVEGRAPPLE)
{
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: active grapple\n");
#endif //DEBUG_GRAPPLE
//
state = GrappleState(ms, reach);
//
VectorSubtract(reach->end, ms->origin, tmp);
tmp[2] = BFIXED_0;
dist = FIXED_VEC3LEN(tmp);
//if very close to the grapple end or the grappled is hooked and
//the bot doesn't get any closer
if (state && dist < BFIXED(48,0))
{
if (ms->lastgrappledist - dist < BFIXED_1)
{
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_ERROR, "grapple normal end\n");
#endif //DEBUG_GRAPPLE
if (FIXED_NOT_ZERO(offhandgrapple->value))
EA_Command(ms->client, cmd_grappleoff->string);
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->moveflags |= MFL_GRAPPLERESET;
ms->reachability_time = GFIXED_0; //end the reachability
return result;
} //end if
} //end if
//if no valid grapple at all, or the grapple hooked and the bot
//isn't moving anymore
else if (!state || (state == 2 && dist > ms->lastgrappledist - BFIXED(2,0)))
{
if (ms->grapplevisible_time < AAS_Time() - GFIXED(0,4))
{
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_ERROR, "grapple not visible\n");
#endif //DEBUG_GRAPPLE
if (FIXED_NOT_ZERO(offhandgrapple->value))
EA_Command(ms->client, cmd_grappleoff->string);
ms->moveflags &= ~MFL_ACTIVEGRAPPLE;
ms->moveflags |= MFL_GRAPPLERESET;
ms->reachability_time = GFIXED_0; //end the reachability
return result;
} //end if
} //end if
else
{
ms->grapplevisible_time = AAS_Time();
} //end else
//
if (!FIXED_TO_INT(offhandgrapple->value))
{
EA_Attack(ms->client);
} //end if
//remember the current grapple distance
ms->lastgrappledist = dist;
} //end if
else
{
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: inactive grapple\n");
#endif //DEBUG_GRAPPLE
//
ms->grapplevisible_time = AAS_Time();
//
VectorSubtract(reach->start, ms->origin, tmp);
if (!(ms->moveflags & MFL_SWIMMING)) tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,dir);
VectorAdd(ms->origin, ms->viewoffset, org);
VectorSubtract(reach->end, org, viewdir);
//
Vector2Angles(viewdir, result.ideal_viewangles);
result.flags |= MOVERESULT_MOVEMENTVIEW;
//
if (dist < BFIXED(5,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < AFIXED(2,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < AFIXED(2,0))
{
#ifdef DEBUG_GRAPPLE
botimport.Print(PRT_MESSAGE, "BotTravel_Grapple: activating grapple\n");
#endif //DEBUG_GRAPPLE
//check if the grapple missile path is clear
VectorAdd(ms->origin, ms->viewoffset, org);
trace = AAS_Trace(org, NULL, NULL, reach->end, ms->entitynum, CONTENTS_SOLID);
VectorSubtract(reach->end, trace.endpos, tmp);
if (FIXED_VEC3LEN(tmp) > BFIXED(16,0))
{
result.failure = qtrue;
return result;
} //end if
//activate the grapple
if (FIXED_NOT_ZERO(offhandgrapple->value))
{
EA_Command(ms->client, cmd_grappleon->string);
} //end if
else
{
EA_Attack(ms->client);
} //end else
ms->moveflags |= MFL_ACTIVEGRAPPLE;
ms->lastgrappledist = BFIXED(999999,0);
} //end if
else
{
if (dist < BFIXED(70,0)) speed = BFIXED(300,0) - (BFIXED(300,0) - BFIXED(4,0) * dist);
else speed = BFIXED(400,0);
//
BotCheckBlocked(ms, dir, qtrue, &result);
//elemantary action move in direction
EA_Move(ms->client, dir, speed);
VectorCopy(dir, result.movedir);
} //end else
//if in another area before actually grappling
areanum = AAS_PointAreaNum(ms->origin);
if (areanum && areanum != ms->reachareanum) ms->reachability_time = GFIXED_0;
} //end else
return result;
} //end of the function BotTravel_Grapple
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_RocketJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir;
bfixed dist, speed;
bot_moveresult_t result;
//botimport.Print(PRT_MESSAGE, "BotTravel_RocketJump: bah\n");
BotClearMoveResult(&result);
//
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
//
dist = VectorNormalizeB2A(tmp,hordir);
//look in the movement direction
Vector2Angles(hordir, result.ideal_viewangles);
//look straight down
result.ideal_viewangles[PITCH] = AFIXED(90,0);
//
if (dist < BFIXED(5,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < AFIXED(5,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < AFIXED(5,0) )
{
//botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//elemantary action jump
EA_Jump(ms->client);
EA_Attack(ms->client);
EA_Move(ms->client, hordir, BFIXED(800,0));
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
if (dist > BFIXED(80,0)) dist = BFIXED(80,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(5,0) * dist);
EA_Move(ms->client, hordir, speed);
} //end else
//look in the movement direction
Vector2Angles(hordir, result.ideal_viewangles);
//look straight down
result.ideal_viewangles[PITCH] = AFIXED(90,0);
//set the view angles directly
EA_View(ms->client, result.ideal_viewangles);
//view is important for the movment
result.flags |= MOVERESULT_MOVEMENTVIEWSET;
//select the rocket launcher
EA_SelectWeapon(ms->client, FIXED_TO_INT(weapindex_rocketlauncher->value));
//weapon is used for movement
result.weapon = FIXED_TO_INT(weapindex_rocketlauncher->value);
result.flags |= MOVERESULT_MOVEMENTWEAPON;
//
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_RocketJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_BFGJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir;
bfixed dist, speed;
bot_moveresult_t result;
//botimport.Print(PRT_MESSAGE, "BotTravel_BFGJump: bah\n");
BotClearMoveResult(&result);
//
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
//
dist = VectorNormalizeB2A(tmp,hordir);
//
if (dist < BFIXED(5,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[0], ms->viewangles[0])) < AFIXED(5,0) &&
FIXED_ABS(AngleDiff(result.ideal_viewangles[1], ms->viewangles[1])) < AFIXED(5,0))
{
//botimport.Print(PRT_MESSAGE, "between jump start and run start point\n");
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
//elemantary action jump
EA_Jump(ms->client);
EA_Attack(ms->client);
EA_Move(ms->client, hordir, BFIXED(800,0));
//
ms->jumpreach = ms->lastreachnum;
} //end if
else
{
if (dist > BFIXED(80,0)) dist = BFIXED(80,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(5,0) * dist);
EA_Move(ms->client, hordir, speed);
} //end else
//look in the movement direction
Vector2Angles(hordir, result.ideal_viewangles);
//look straight down
result.ideal_viewangles[PITCH] = AFIXED(90,0);
//set the view angles directly
EA_View(ms->client, result.ideal_viewangles);
//view is important for the movment
result.flags |= MOVERESULT_MOVEMENTVIEWSET;
//select the rocket launcher
EA_SelectWeapon(ms->client, FIXED_TO_INT(weapindex_bfg10k->value));
//weapon is used for movement
result.weapon = FIXED_TO_INT(weapindex_bfg10k->value);
result.flags |= MOVERESULT_MOVEMENTWEAPON;
//
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_BFGJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_WeaponJump(bot_movestate_t *ms, aas_reachability_t *reach)
{
bvec3_t tmp;
avec3_t hordir;
bfixed speed;
bot_moveresult_t result;
BotClearMoveResult(&result);
//if not jumped yet
if (!ms->jumpreach) return result;
/*
//go straight to the reachability end
hordir[0] = reach->end[0] - ms->origin[0];
hordir[1] = reach->end[1] - ms->origin[1];
hordir[2] = 0;
VectorNormalize(hordir);
//always use max speed when traveling through the air
EA_Move(ms->client, hordir, 800);
VectorCopy(hordir, result.movedir);
*/
//
if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed))
{
//go straight to the reachability end
VectorSubtract(reach->end, ms->origin, tmp);
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
speed = BFIXED(400,0);
} //end if
//
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_WeaponJump
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed dist, speed;
bvec3_t tmp;
avec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult(&result);
//first walk straight to the reachability start
tmp[0] = reach->start[0] - ms->origin[0];
tmp[1] = reach->start[1] - ms->origin[1];
tmp[2] = BFIXED_0;
dist = VectorNormalizeB2A(tmp,hordir);
//
BotCheckBlocked(ms, hordir, qtrue, &result);
speed = BFIXED(400,0);
//elemantary action move in direction
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotTravel_JumpPad
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotFinishTravel_JumpPad(bot_movestate_t *ms, aas_reachability_t *reach)
{
bfixed speed;
bvec3_t tmp;
avec3_t hordir;
bot_moveresult_t result;
BotClearMoveResult(&result);
if (!BotAirControl(ms->origin, ms->velocity, reach->end, hordir, &speed))
{
tmp[0] = reach->end[0] - ms->origin[0];
tmp[1] = reach->end[1] - ms->origin[1];
tmp[2] = BFIXED_0;
VectorNormalizeB2A(tmp,hordir);
speed = BFIXED(400,0);
} //end if
BotCheckBlocked(ms, hordir, qtrue, &result);
//elemantary action move in direction
EA_Move(ms->client, hordir, speed);
VectorCopy(hordir, result.movedir);
//
return result;
} //end of the function BotFinishTravel_JumpPad
//===========================================================================
// time before the reachability times out
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotReachabilityTime(aas_reachability_t *reach)
{
switch(reach->traveltype & TRAVELTYPE_MASK)
{
case TRAVEL_WALK: return 5;
case TRAVEL_CROUCH: return 5;
case TRAVEL_BARRIERJUMP: return 5;
case TRAVEL_LADDER: return 6;
case TRAVEL_WALKOFFLEDGE: return 5;
case TRAVEL_JUMP: return 5;
case TRAVEL_SWIM: return 5;
case TRAVEL_WATERJUMP: return 5;
case TRAVEL_TELEPORT: return 5;
case TRAVEL_ELEVATOR: return 10;
case TRAVEL_GRAPPLEHOOK: return 8;
case TRAVEL_ROCKETJUMP: return 6;
case TRAVEL_BFGJUMP: return 6;
case TRAVEL_JUMPPAD: return 10;
case TRAVEL_FUNCBOB: return 10;
default:
{
botimport.Print(PRT_ERROR, "travel type %d not implemented yet\n", reach->traveltype);
return 8;
} //end case
} //end switch
} //end of the function BotReachabilityTime
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
bot_moveresult_t BotMoveInGoalArea(bot_movestate_t *ms, bot_goal_t *goal)
{
bot_moveresult_t result;
bvec3_t tmp;
avec3_t dir;
bfixed dist, speed;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "%s: moving straight to goal\n", ClientName(ms->entitynum-1));
//AAS_ClearShownDebugLines();
//AAS_DebugLine(ms->origin, goal->origin, LINECOLOR_RED);
#endif //DEBUG
BotClearMoveResult(&result);
//walk straight to the goal origin
tmp[0] = goal->origin[0] - ms->origin[0];
tmp[1] = goal->origin[1] - ms->origin[1];
if (ms->moveflags & MFL_SWIMMING)
{
tmp[2] = goal->origin[2] - ms->origin[2];
result.traveltype = TRAVEL_SWIM;
} //end if
else
{
tmp[2] = BFIXED_0;
result.traveltype = TRAVEL_WALK;
} //endif
//
dist = VectorNormalizeB2A(tmp,dir);
if (dist > BFIXED(100,0)) dist = BFIXED(100,0);
speed = BFIXED(400,0) - (BFIXED(400,0) - BFIXED(4,0) * dist);
if (speed < BFIXED(10,0)) speed = BFIXED_0;
//
BotCheckBlocked(ms, dir, qtrue, &result);
//elemantary action move in direction
EA_Move(ms->client, dir, speed);
VectorCopy(dir, result.movedir);
//
if (ms->moveflags & MFL_SWIMMING)
{
Vector2Angles(dir, result.ideal_viewangles);
result.flags |= MOVERESULT_SWIMVIEW;
} //end if
//if (!debugline) debugline = botimport.DebugLineCreate();
//botimport.DebugLineShow(debugline, ms->origin, goal->origin, LINECOLOR_BLUE);
//
ms->lastreachnum = 0;
ms->lastareanum = 0;
ms->lastgoalareanum = goal->areanum;
VectorCopy(ms->origin, ms->lastorigin);
//
return result;
} //end of the function BotMoveInGoalArea
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotMoveToGoal(bot_moveresult_t *result, int movestate, bot_goal_t *goal, int travelflags)
{
int reachnum, lastreachnum, foundjumppad, ent, resultflags;
aas_reachability_t reach, lastreach;
bot_movestate_t *ms;
//bvec3_t mins, maxs, up = {0, 0, 1};
//bsp_trace_t trace;
//static int debugline;
BotClearMoveResult(result);
//
ms = BotMoveStateFromHandle(movestate);
if (!ms) return;
//reset the grapple before testing if the bot has a valid goal
//because the bot could loose all it's goals when stuck to a wall
BotResetGrapple(ms);
//
if (!goal)
{
#ifdef DEBUG
botimport.Print(PRT_MESSAGE, "client %d: movetogoal -> no goal\n", ms->client);
#endif //DEBUG
result->failure = qtrue;
return;
} //end if
//botimport.Print(PRT_MESSAGE, "numavoidreach = %d\n", ms->numavoidreach);
//remove some of the move flags
ms->moveflags &= ~(MFL_SWIMMING|MFL_AGAINSTLADDER);
//set some of the move flags
//NOTE: the MFL_ONGROUND flag is also set in the higher AI
if (AAS_OnGround(ms->origin, ms->presencetype, ms->entitynum)) ms->moveflags |= MFL_ONGROUND;
//
if (ms->moveflags & MFL_ONGROUND)
{
int modeltype, modelnum;
ent = BotOnTopOfEntity(ms);
if (ent != -1)
{
modelnum = AAS_EntityModelindex(ent);
if (modelnum >= 0 && modelnum < MAX_MODELS)
{
modeltype = modeltypes[modelnum];
if (modeltype == MODELTYPE_FUNC_PLAT)
{
AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
//if the bot is Not using the elevator
if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR ||
//NOTE: the face number is the plat model number
(reach.facenum & 0x0000FFFF) != modelnum)
{
reachnum = AAS_NextModelReachability(0, modelnum);
if (reachnum)
{
//botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_plat\n", ms->client);
AAS_ReachabilityFromNum(reachnum, &reach);
ms->lastreachnum = reachnum;
ms->reachability_time = AAS_Time() + MAKE_GFIXED(BotReachabilityTime(&reach));
} //end if
else
{
if (bl_bot_developer)
{
botimport.Print(PRT_MESSAGE, "client %d: on func_plat without reachability\n", ms->client);
} //end if
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
} //end if
result->flags |= MOVERESULT_ONTOPOF_ELEVATOR;
} //end if
else if (modeltype == MODELTYPE_FUNC_BOB)
{
AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
//if the bot is Not using the func bobbing
if ((reach.traveltype & TRAVELTYPE_MASK) != TRAVEL_FUNCBOB ||
//NOTE: the face number is the func_bobbing model number
(reach.facenum & 0x0000FFFF) != modelnum)
{
reachnum = AAS_NextModelReachability(0, modelnum);
if (reachnum)
{
//botimport.Print(PRT_MESSAGE, "client %d: accidentally ended up on func_bobbing\n", ms->client);
AAS_ReachabilityFromNum(reachnum, &reach);
ms->lastreachnum = reachnum;
ms->reachability_time = AAS_Time() + MAKE_GFIXED(BotReachabilityTime(&reach));
} //end if
else
{
if (bl_bot_developer)
{
botimport.Print(PRT_MESSAGE, "client %d: on func_bobbing without reachability\n", ms->client);
} //end if
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
} //end if
result->flags |= MOVERESULT_ONTOPOF_FUNCBOB;
} //end if
else if (modeltype == MODELTYPE_FUNC_STATIC || modeltype == MODELTYPE_FUNC_DOOR)
{
// check if ontop of a door bridge ?
ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
// if not in a reachability area
if (!AAS_AreaReachability(ms->areanum))
{
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end if
} //end else if
else
{
result->blocked = qtrue;
result->blockentity = ent;
result->flags |= MOVERESULT_ONTOPOFOBSTACLE;
return;
} //end else
} //end if
} //end if
} //end if
//if swimming
if (AAS_Swimming(ms->origin)) ms->moveflags |= MFL_SWIMMING;
//if against a ladder
if (AAS_AgainstLadder(ms->origin)) ms->moveflags |= MFL_AGAINSTLADDER;
//if the bot is on the ground, swimming or against a ladder
if (ms->moveflags & (MFL_ONGROUND|MFL_SWIMMING|MFL_AGAINSTLADDER))
{
//botimport.Print(PRT_MESSAGE, "%s: onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
//
AAS_ReachabilityFromNum(ms->lastreachnum, &lastreach);
//reachability area the bot is in
//ms->areanum = BotReachabilityArea(ms->origin, ((lastreach.traveltype & TRAVELTYPE_MASK) != TRAVEL_ELEVATOR));
ms->areanum = BotFuzzyPointReachabilityArea(ms->origin);
//
if ( !ms->areanum )
{
result->failure = qtrue;
result->blocked = qtrue;
result->blockentity = 0;
result->type = RESULTTYPE_INSOLIDAREA;
return;
} //end if
//if the bot is in the goal area
if (ms->areanum == goal->areanum)
{
*result = BotMoveInGoalArea(ms, goal);
return;
} //end if
//assume we can use the reachability from the last frame
reachnum = ms->lastreachnum;
//if there is a last reachability
if (reachnum)
{
AAS_ReachabilityFromNum(reachnum, &reach);
//check if the reachability is still valid
if (!(AAS_TravelFlagForType(reach.traveltype) & travelflags))
{
reachnum = 0;
} //end if
//special grapple hook case
else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_GRAPPLEHOOK)
{
if (ms->reachability_time < AAS_Time() ||
(ms->moveflags & MFL_GRAPPLERESET))
{
reachnum = 0;
} //end if
} //end if
//special elevator case
else if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_ELEVATOR ||
(reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_FUNCBOB)
{
if ((result->flags & MOVERESULT_ONTOPOF_FUNCBOB) ||
(result->flags & MOVERESULT_ONTOPOF_FUNCBOB))
{
ms->reachability_time = AAS_Time() + GFIXED(5,0);
} //end if
//if the bot was going for an elevator and reached the reachability area
if (ms->areanum == reach.areanum ||
ms->reachability_time < AAS_Time())
{
reachnum = 0;
} //end if
} //end if
else
{
#ifdef DEBUG
if (bl_bot_developer)
{
if (ms->reachability_time < AAS_Time())
{
botimport.Print(PRT_MESSAGE, "client %d: reachability timeout in ", ms->client);
AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
botimport.Print(PRT_MESSAGE, "\n");
} //end if
/*
if (ms->lastareanum != ms->areanum)
{
botimport.Print(PRT_MESSAGE, "changed from area %d to %d\n", ms->lastareanum, ms->areanum);
} //end if*/
} //end if
#endif //DEBUG
//if the goal area changed or the reachability timed out
//or the area changed
if (ms->lastgoalareanum != goal->areanum ||
ms->reachability_time < AAS_Time() ||
ms->lastareanum != ms->areanum)
{
reachnum = 0;
//botimport.Print(PRT_MESSAGE, "area change or timeout\n");
} //end else if
} //end else
} //end if
resultflags = 0;
//if the bot needs a new reachability
if (!reachnum)
{
//if the area has no reachability links
if (!AAS_AreaReachability(ms->areanum))
{
#ifdef DEBUG
if (bl_bot_developer)
{
botimport.Print(PRT_MESSAGE, "area %d no reachability\n", ms->areanum);
} //end if
#endif //DEBUG
} //end if
//get a new reachability leading towards the goal
reachnum = BotGetReachabilityToGoal(ms->origin, ms->areanum,
ms->lastgoalareanum, ms->lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, travelflags,
ms->avoidspots, ms->numavoidspots, &resultflags);
//the area number the reachability starts in
ms->reachareanum = ms->areanum;
//reset some state variables
ms->jumpreach = 0; //for TRAVEL_JUMP
ms->moveflags &= ~MFL_GRAPPLERESET; //for TRAVEL_GRAPPLEHOOK
//if there is a reachability to the goal
if (reachnum)
{
AAS_ReachabilityFromNum(reachnum, &reach);
//set a timeout for this reachability
ms->reachability_time = AAS_Time() + MAKE_GFIXED(BotReachabilityTime(&reach));
//
#ifdef AVOIDREACH
//add the reachability to the reachabilities to avoid for a while
BotAddToAvoidReach(ms, reachnum, GFIXED(AVOIDREACH_TIME,0));
#endif //AVOIDREACH
} //end if
#ifdef DEBUG
else if (bl_bot_developer)
{
botimport.Print(PRT_MESSAGE, "goal not reachable\n");
Com_Memset(&reach, 0, sizeof(aas_reachability_t)); //make compiler happy
} //end else
if (bl_bot_developer)
{
//if still going for the same goal
if (ms->lastgoalareanum == goal->areanum)
{
if (ms->lastareanum == reach.areanum)
{
botimport.Print(PRT_MESSAGE, "same goal, going back to previous area\n");
} //end if
} //end if
} //end if
#endif //DEBUG
} //end else
//
ms->lastreachnum = reachnum;
ms->lastgoalareanum = goal->areanum;
ms->lastareanum = ms->areanum;
//if the bot has a reachability
if (reachnum)
{
//get the reachability from the number
AAS_ReachabilityFromNum(reachnum, &reach);
result->traveltype = reach.traveltype;
//
#ifdef DEBUG_AI_MOVE
AAS_ClearShownDebugLines();
AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
AAS_ShowReachability(&reach);
#endif //DEBUG_AI_MOVE
//
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "client %d: ", ms->client);
//AAS_PrintTravelType(reach.traveltype);
//botimport.Print(PRT_MESSAGE, "\n");
#endif //DEBUG
switch(reach.traveltype & TRAVELTYPE_MASK)
{
case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break;
case TRAVEL_CROUCH: *result = BotTravel_Crouch(ms, &reach); break;
case TRAVEL_BARRIERJUMP: *result = BotTravel_BarrierJump(ms, &reach); break;
case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break;
case TRAVEL_WALKOFFLEDGE: *result = BotTravel_WalkOffLedge(ms, &reach); break;
case TRAVEL_JUMP: *result = BotTravel_Jump(ms, &reach); break;
case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break;
case TRAVEL_WATERJUMP: *result = BotTravel_WaterJump(ms, &reach); break;
case TRAVEL_TELEPORT: *result = BotTravel_Teleport(ms, &reach); break;
case TRAVEL_ELEVATOR: *result = BotTravel_Elevator(ms, &reach); break;
case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break;
case TRAVEL_ROCKETJUMP: *result = BotTravel_RocketJump(ms, &reach); break;
case TRAVEL_BFGJUMP: *result = BotTravel_BFGJump(ms, &reach); break;
case TRAVEL_JUMPPAD: *result = BotTravel_JumpPad(ms, &reach); break;
case TRAVEL_FUNCBOB: *result = BotTravel_FuncBobbing(ms, &reach); break;
default:
{
botimport.Print(PRT_FATAL, "travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK));
break;
} //end case
} //end switch
result->traveltype = reach.traveltype;
result->flags |= resultflags;
} //end if
else
{
result->failure = qtrue;
result->flags |= resultflags;
Com_Memset(&reach, 0, sizeof(aas_reachability_t));
} //end else
#ifdef DEBUG
if (bl_bot_developer)
{
if (result->failure)
{
botimport.Print(PRT_MESSAGE, "client %d: movement failure in ", ms->client);
AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
botimport.Print(PRT_MESSAGE, "\n");
} //end if
} //end if
#endif //DEBUG
} //end if
else
{
int i, numareas, areas[16];
bvec3_t end;
//special handling of jump pads when the bot uses a jump pad without knowing it
foundjumppad = qfalse;
FIXED_VEC3MA(ms->origin, -BFIXED(2,0) * MAKE_BFIXED(ms->thinktime), ms->velocity, end);
numareas = AAS_TraceAreas(ms->origin, end, areas, NULL, 16);
for (i = numareas-1; i >= 0; i--)
{
if (AAS_AreaJumpPad(areas[i]))
{
//botimport.Print(PRT_MESSAGE, "client %d used a jumppad without knowing, area %d\n", ms->client, areas[i]);
foundjumppad = qtrue;
lastreachnum = BotGetReachabilityToGoal(end, areas[i],
ms->lastgoalareanum, ms->lastareanum,
ms->avoidreach, ms->avoidreachtimes, ms->avoidreachtries,
goal, travelflags, TFL_JUMPPAD, ms->avoidspots, ms->numavoidspots, NULL);
if (lastreachnum)
{
ms->lastreachnum = lastreachnum;
ms->lastareanum = areas[i];
//botimport.Print(PRT_MESSAGE, "found jumppad reachability\n");
break;
} //end if
else
{
for (lastreachnum = AAS_NextAreaReachability(areas[i], 0); lastreachnum;
lastreachnum = AAS_NextAreaReachability(areas[i], lastreachnum))
{
//get the reachability from the number
AAS_ReachabilityFromNum(lastreachnum, &reach);
if ((reach.traveltype & TRAVELTYPE_MASK) == TRAVEL_JUMPPAD)
{
ms->lastreachnum = lastreachnum;
ms->lastareanum = areas[i];
//botimport.Print(PRT_MESSAGE, "found jumppad reachability hard!!\n");
break;
} //end if
} //end for
if (lastreachnum) break;
} //end else
} //end if
} //end for
if (bl_bot_developer)
{
//if a jumppad is found with the trace but no reachability is found
if (foundjumppad && !ms->lastreachnum)
{
botimport.Print(PRT_MESSAGE, "client %d didn't find jumppad reachability\n", ms->client);
} //end if
} //end if
//
if (ms->lastreachnum)
{
//botimport.Print(PRT_MESSAGE, "%s: NOT onground, swimming or against ladder\n", ClientName(ms->entitynum-1));
AAS_ReachabilityFromNum(ms->lastreachnum, &reach);
result->traveltype = reach.traveltype;
#ifdef DEBUG
//botimport.Print(PRT_MESSAGE, "client %d finish: ", ms->client);
//AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
//botimport.Print(PRT_MESSAGE, "\n");
#endif //DEBUG
//
switch(reach.traveltype & TRAVELTYPE_MASK)
{
case TRAVEL_WALK: *result = BotTravel_Walk(ms, &reach); break;//BotFinishTravel_Walk(ms, &reach); break;
case TRAVEL_CROUCH: /*do nothing*/ break;
case TRAVEL_BARRIERJUMP: *result = BotFinishTravel_BarrierJump(ms, &reach); break;
case TRAVEL_LADDER: *result = BotTravel_Ladder(ms, &reach); break;
case TRAVEL_WALKOFFLEDGE: *result = BotFinishTravel_WalkOffLedge(ms, &reach); break;
case TRAVEL_JUMP: *result = BotFinishTravel_Jump(ms, &reach); break;
case TRAVEL_SWIM: *result = BotTravel_Swim(ms, &reach); break;
case TRAVEL_WATERJUMP: *result = BotFinishTravel_WaterJump(ms, &reach); break;
case TRAVEL_TELEPORT: /*do nothing*/ break;
case TRAVEL_ELEVATOR: *result = BotFinishTravel_Elevator(ms, &reach); break;
case TRAVEL_GRAPPLEHOOK: *result = BotTravel_Grapple(ms, &reach); break;
case TRAVEL_ROCKETJUMP:
case TRAVEL_BFGJUMP: *result = BotFinishTravel_WeaponJump(ms, &reach); break;
case TRAVEL_JUMPPAD: *result = BotFinishTravel_JumpPad(ms, &reach); break;
case TRAVEL_FUNCBOB: *result = BotFinishTravel_FuncBobbing(ms, &reach); break;
default:
{
botimport.Print(PRT_FATAL, "(last) travel type %d not implemented yet\n", (reach.traveltype & TRAVELTYPE_MASK));
break;
} //end case
} //end switch
result->traveltype = reach.traveltype;
#ifdef DEBUG
if (bl_bot_developer)
{
if (result->failure)
{
botimport.Print(PRT_MESSAGE, "client %d: movement failure in finish ", ms->client);
AAS_PrintTravelType(reach.traveltype & TRAVELTYPE_MASK);
botimport.Print(PRT_MESSAGE, "\n");
} //end if
} //end if
#endif //DEBUG
} //end if
} //end else
//FIXME: is it right to do this here?
if (result->blocked) ms->reachability_time -= GFIXED(10,0) * ms->thinktime;
//copy the last origin
VectorCopy(ms->origin, ms->lastorigin);
//return the movement result
return;
} //end of the function BotMoveToGoal
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetAvoidReach(int movestate)
{
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return;
Com_Memset(ms->avoidreach, 0, MAX_AVOIDREACH * sizeof(int));
Com_Memset(ms->avoidreachtimes, 0, MAX_AVOIDREACH * sizeof(bfixed));
Com_Memset(ms->avoidreachtries, 0, MAX_AVOIDREACH * sizeof(int));
} //end of the function BotResetAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetLastAvoidReach(int movestate)
{
int i, latest;
gfixed latesttime;
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return;
latesttime = GFIXED_0;
latest = 0;
for (i = 0; i < MAX_AVOIDREACH; i++)
{
if (ms->avoidreachtimes[i] > latesttime)
{
latesttime = ms->avoidreachtimes[i];
latest = i;
} //end if
} //end for
if (FIXED_NOT_ZERO(latesttime))
{
ms->avoidreachtimes[latest] = GFIXED_0;
if (ms->avoidreachtries[i] > 0) ms->avoidreachtries[latest]--;
} //end if
} //end of the function BotResetLastAvoidReach
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotResetMoveState(int movestate)
{
bot_movestate_t *ms;
ms = BotMoveStateFromHandle(movestate);
if (!ms) return;
Com_Memset(ms, 0, sizeof(bot_movestate_t));
} //end of the function BotResetMoveState
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
int BotSetupMoveAI(void)
{
BotSetBrushModelTypes();
sv_maxstep = LibVar("sv_step", "18");
sv_maxbarrier = LibVar("sv_maxbarrier", "32");
sv_gravity = LibVar("sv_gravity", "800");
weapindex_rocketlauncher = LibVar("weapindex_rocketlauncher", "5");
weapindex_bfg10k = LibVar("weapindex_bfg10k", "9");
weapindex_grapple = LibVar("weapindex_grapple", "10");
entitytypemissile = LibVar("entitytypemissile", "3");
offhandgrapple = LibVar("offhandgrapple", "0");
cmd_grappleon = LibVar("cmd_grappleon", "grappleon");
cmd_grappleoff = LibVar("cmd_grappleoff", "grappleoff");
return BLERR_NOERROR;
} //end of the function BotSetupMoveAI
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void BotShutdownMoveAI(void)
{
int i;
for (i = 1; i <= MAX_CLIENTS; i++)
{
if (botmovestates[i])
{
FreeMemory(botmovestates[i]);
botmovestates[i] = NULL;
} //end if
} //end for
} //end of the function BotShutdownMoveAI
| [
"jack.palevich@684fc592-8442-0410-8ea1-df6b371289ac"
]
| [
[
[
1,
3637
]
]
]
|
8fdb6e84f9d2a84f87de8d81b02f7c27ba682956 | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /Display/Effect.h | 4f4e1d64ffcd5ea0a5b1a189a5d043df2017d925 | []
| no_license | 15831944/bastionlandscape | e1acc932f6b5a452a3bd94471748b0436a96de5d | c8008384cf4e790400f9979b5818a5a3806bd1af | refs/heads/master | 2023-03-16T03:28:55.813938 | 2010-05-21T15:00:07 | 2010-05-21T15:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,025 | h | #ifndef __EFFECT_H__
#define __EFFECT_H__
#include "../Display/Display.h"
#include "../Display/EffectStateManager.h"
#include "../Core/CoreTypes.h"
#include "../Core/Util.h"
namespace ElixirEngine
{
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
#define EFFECT_RENDER_FLAGS (D3DXFX_DONOTSAVESTATE | D3DXFX_DONOTSAVESHADERSTATE | D3DXFX_DONOTSAVESAMPLERSTATE)
//#define EFFECT_RENDER_FLAGS (0)
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
struct DisplayMemoryBuffer
{
DisplayMemoryBuffer();
~DisplayMemoryBuffer();
inline bool Reserve(const UInt _uCapacity);
inline bool Copy(const VoidPtr _pSrc, const UInt _uSize);
inline bool CanAlloc(const UInt _uSize);
inline VoidPtr Alloc(const UInt _uSize);
inline void Clear();
BytePtr m_pBuffer;
UInt m_uCapacity;
UInt m_uSize;
};
typedef DisplayMemoryBuffer* DisplayMemoryBufferPtr;
typedef DisplayMemoryBuffer& DisplayMemoryBufferRef;
inline bool DisplayMemoryBuffer::Reserve(const UInt _uCapacity)
{
if (NULL != m_pBuffer)
{
delete[] m_pBuffer;
m_pBuffer = NULL;
}
m_pBuffer = new Byte[_uCapacity];
m_uCapacity = _uCapacity;
m_uSize = 0;
return (NULL != m_pBuffer);
}
inline bool DisplayMemoryBuffer::Copy(const VoidPtr _pSrc, const UInt _uSize)
{
const bool bResult = CanAlloc(_uSize);
if (false != bResult)
{
memcpy_s(m_pBuffer + m_uSize, m_uCapacity - m_uSize, _pSrc, _uSize);
m_uSize += _uSize;
}
return bResult;
}
inline bool DisplayMemoryBuffer::CanAlloc(const UInt _uSize)
{
const bool bResult = (m_uCapacity >= (m_uSize + _uSize));
if (false == bResult)
{
vsoutput(__FUNCTION__" : cannot alloc %u bytes\n", _uSize);
}
return bResult;
}
inline VoidPtr DisplayMemoryBuffer::Alloc(const UInt _uSize)
{
VoidPtr pResult = NULL;
const bool bResult = CanAlloc(_uSize);
if (false != bResult)
{
pResult = m_pBuffer + m_uSize;
m_uSize += _uSize;
}
return pResult;
}
inline void DisplayMemoryBuffer::Clear()
{
m_uSize = 0;
}
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayEffectInclude : public CoreObject, public ID3DXInclude
{
public:
DisplayEffectInclude();
virtual ~DisplayEffectInclude();
virtual bool Create(const boost::any& _rConfig);
virtual void Release();
HRESULT __stdcall Open(
D3DXINCLUDE_TYPE IncludeType,
LPCSTR pFileName,
LPCVOID pParentData,
LPCVOID *ppData,
UINT * pBytes
);
HRESULT __stdcall Close(
LPCVOID pData
);
protected:
CharPtrVec m_vBuffers;
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayEffect : public CoreObject
{
public:
struct CreateInfo
{
string m_strPath;
bool m_bIsText;
};
public:
DisplayEffect(DisplayRef _rDisplay);
virtual ~DisplayEffect();
virtual bool Create(const boost::any& _rConfig);
virtual void Update();
virtual void Release();
virtual void RenderRequest(DisplayMaterialPtr _pDisplayMaterial);
virtual void Render();
virtual EffectPtr GetEffect();
Handle GetHandleBySemanticKey(const Key& _uKey);
HandleMapRef GetHandles();
const string& GetNameBySemanticKey(const Key& _uKey);
Handle GetTechniqueByName(const char* _pszName);
void SetTechnique(Handle _hTechnique);
bool GetTechniqueDesc(Handle _hTechnique, D3DXTECHNIQUE_DESC* _pDesc);
protected:
bool GetParameters();
protected:
string m_strName;
map<Key, string> m_mSemantics;
DisplayRef m_rDisplay;
EffectPtr m_pEffect;
DisplayMaterialPtrVec m_vRenderList;
HandleMap m_mHandles;
Handle m_hCurrentTechnique;
private:
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayMaterial : public CoreObject
{
public:
struct CreateInfo
{
DisplayEffectPtr m_pEffect;
LuaObjectPtr m_pLuaObject;
};
typedef CreateInfo* CreateInfoPtr;
typedef CreateInfo& CreateInforef;
public:
DisplayMaterial(DisplayMaterialManagerRef _rMaterialManager);
virtual ~DisplayMaterial();
virtual bool Create(const boost::any& _rConfig);
virtual void Update();
virtual void Release();
virtual void RenderRequest(DisplayObjectPtr _pDisplayObject);
virtual void Render();
virtual void UseParams();
virtual DisplayEffectPtr GetEffect();
virtual DisplayMaterialManagerRef GetMaterialManager();
virtual UInt GetPassCount();
protected:
struct FATEntry
{
Handle m_hParam;
VoidPtr m_pData;
UInt m_uSize;
UInt m_uCount;
};
typedef FATEntry* FATEntryPtr;
typedef FATEntry& FATEntryRef;
protected:
bool CreateFromLuaConfig(CreateInfoPtr _pInfo);
FATEntryPtr GetOrCreateParamEntry(Handle _hData, FATEntryPtr _pFAT);
FATEntryPtr GetParamEntry(Handle _hData, FATEntryPtr _pFAT);
protected:
DisplayMaterialManagerRef m_rMaterialManager;
DisplayEffectPtr m_pEffect;
DisplayObjectPtrVec m_vRenderList;
DisplayEffectParamPtrVec m_vParams;
Handle m_hTechnique;
UInt m_uPassCount;
private:
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
class DisplayMaterialManager : public CoreObject
{
public:
// this enum enables the application to redefine effect parameters semantics
// that are internally used by various display classes.
enum ECommonParamSemantic
{
// common
ECommonParamSemantic_WORLDVIEWPROJ,
ECommonParamSemantic_WORLD,
ECommonParamSemantic_VIEW,
ECommonParamSemantic_WORLDVIEW,
ECommonParamSemantic_VIEWINV,
ECommonParamSemantic_VIEWPROJ,
ECommonParamSemantic_PROJ,
ECommonParamSemantic_WORLDINVTRANSPOSE,
ECommonParamSemantic_ENVIRONMENTTEX,
ECommonParamSemantic_NORMALTEX,
ECommonParamSemantic_DIFFUSETEX,
ECommonParamSemantic_CAMERAPOS,
ECommonParamSemantic_FRUSTUMCORNERS,
ECommonParamSemantic_DIFFUSECOLOR,
// render target texture
ECommonParamSemantic_RT2D00,
ECommonParamSemantic_RT2D01,
ECommonParamSemantic_RT2D02,
ECommonParamSemantic_RT2D03,
ECommonParamSemantic_RT2D04,
ECommonParamSemantic_RT2D05,
ECommonParamSemantic_RT2D06,
ECommonParamSemantic_RT2D07,
// original render target texture (rendered during normal process mode)
ECommonParamSemantic_ORT2D00,
ECommonParamSemantic_ORT2D01,
ECommonParamSemantic_ORT2D02,
ECommonParamSemantic_ORT2D03,
ECommonParamSemantic_ORT2D04,
ECommonParamSemantic_ORT2D05,
ECommonParamSemantic_ORT2D06,
ECommonParamSemantic_ORT2D07,
// standard texture
ECommonParamSemantic_TEX2D00,
ECommonParamSemantic_TEX2D01,
ECommonParamSemantic_TEX2D02,
ECommonParamSemantic_TEX2D03,
ECommonParamSemantic_TEX2D04,
ECommonParamSemantic_TEX2D05,
ECommonParamSemantic_TEX2D06,
ECommonParamSemantic_TEX2D07,
ECommonParamSemantic_COUNT // always last enum member
};
public:
DisplayMaterialManager(DisplayRef _rDisplay);
virtual ~DisplayMaterialManager();
virtual bool Create(const boost::any& _rConfig);
virtual void Update();
virtual void Release();
bool CreateMaterial(const Key& _uNameKey, LuaObjectRef _rLuaObject);
void UnloadMaterial(const string& _strName);
void UnloadMaterial(const Key& _uNameKey);
DisplayMaterialPtr GetMaterial(const string& _strName);
DisplayMaterialPtr GetMaterial(const Key& _strNameKey);
bool LoadEffect(const string& _strName, const string& _strPath);
void UnloadEffect(const string& _strName);
DisplayEffectPtr GetEffect(const string& _strName);
bool RegisterParamCreator(const Key& _uSemanticNameKey, CreateParamFunc _Func);
bool UnregisterParamCreator(const Key& _uSemanticNameKey);
DisplayEffectParamPtr CreateParam(const string& _strSemanticName, const boost::any& _rConfig);
DisplayEffectParamPtr CreateParam(const Key& _uSemanticNameKey, const boost::any& _rConfig);
void ReleaseParam(DisplayEffectParamPtr _pParam);
void UnloadAll();
DisplayRef GetDisplay();
DisplayMemoryBufferPtr GetParamsMemory();
void SetFloatBySemantic(const Key& _uSemanticKey, FloatPtr _pData);
FloatPtr GetFloatBySemantic(const Key& _uSemanticKey);
void SetVector2BySemantic(const Key& _uSemanticKey, Vector2* _pData);
Vector2* GetVector2BySemantic(const Key& _uSemanticKey);
void SetVector3BySemantic(const Key& _uSemanticKey, Vector3* _pData);
Vector3* GetVector3BySemantic(const Key& _uSemanticKey);
void SetVector4BySemantic(const Key& _uSemanticKey, Vector4* _pData);
Vector4* GetVector4BySemantic(const Key& _uSemanticKey);
void SetMatrixBySemantic(const Key& _uSemanticKey, MatrixPtr _pData);
MatrixPtr GetMatrixBySemantic(const Key& _uSemanticKey);
void SetStructBySemantic(const Key& _uSemanticKey, VoidPtr _pData, const UInt _uSize);
VoidPtr GetStructBySemantic(const Key& _uSemanticKey, UIntRef _uSize);
bool OverrideCommonParamSemantic(const ECommonParamSemantic _uCommonParam, const Key _uNewParamKey);
bool ResetCommonParamSemantic(const ECommonParamSemantic _uCommonParam);
void SetEffectIncludeBasePath(const string& _strPath);
const string& GetEffectIncludeBasePath();
DisplayEffectIncludePtr GetEffectIncludeInterface();
DisplayStateManagerPtr GetStateManagerInterface();
protected:
struct StructData
{
StructData();
VoidPtr m_pData;
UInt m_uSize;
};
typedef StructData* StructDataPtr;
typedef StructData& StructDataRef;
typedef map<Key, StructData> StructDataMap;
protected:
DisplayEffectPtrMap m_mEffects;
DisplayMaterialPtrMap m_mMaterials;
CreateParamFuncMap m_mParamCreators;
FloatPtrMap m_mFloatInfo;
Vector2PtrMap m_mVector2Info;
Vector3PtrMap m_mVector3Info;
Vector4PtrMap m_mVector4Info;
MatrixPtrMap m_mMatrixInfo;
StructDataMap m_mStructInfo;
KeyVec m_vCurrentParamKeys;
KeyVec m_vDefaultParamKeys;
DisplayMemoryBuffer m_oParamsBuffer;
DisplayRef m_rDisplay;
DisplayEffectIncludePtr m_pIncludeInterface;
string m_strIncludeBasePath;
private:
};
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
struct RenderObjectFunction
{
RenderObjectFunction(DisplayMaterialPtr _pMaterial)
: m_pMaterial(_pMaterial)
{
}
void operator() (DisplayObjectPtr _pDisplayObject)
{
DisplayPtr pDisplay = Display::GetInstance();
DisplayStateManagerPtr pStateManager = pDisplay->GetStateManagerInterface();
EffectPtr pEffect = m_pMaterial->GetEffect()->GetEffect();
UInt uPassCount;
pEffect->Begin(&uPassCount, EFFECT_RENDER_FLAGS);
_pDisplayObject->RenderBegin();
pDisplay->SetCurrentWorldMatrix(_pDisplayObject->GetWorldMatrix());
for (UInt uPass = 0 ; uPass < uPassCount ; ++uPass)
{
pDisplay->MRTRenderBeginPass(uPass);
pStateManager->BeginPass(uPass);
pEffect->BeginPass(uPass);
m_pMaterial->UseParams();
pEffect->CommitChanges();
_pDisplayObject->Render();
pEffect->EndPass();
pStateManager->EndPass();
pDisplay->MRTRenderEndPass();
}
_pDisplayObject->RenderEnd();
pEffect->End();
}
DisplayMaterialPtr m_pMaterial;
};
}
#endif // __EFFECT_H__
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
]
| [
[
[
1,
404
]
]
]
|
0cee78ec865aff8034566be735d12b7732127d66 | 7c50c958f5138e4f31b131794ca47a439b27533f | /vlfeat/currencyreader.cpp | 98bdafd29958697c9965e51fb6cf6bfe135b4483 | []
| no_license | choolwe1992/pp-mcreader | 5e3b007ef4900ef0bb917e69635509e6ac073ade | 8fa9153cbf16096496f03ad7eed6a40a14ce0a41 | refs/heads/master | 2020-05-15T14:03:31.367352 | 2010-03-16T06:51:26 | 2010-03-16T06:51:26 | 35,541,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,730 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
#include<string>
#include<iostream>
#include<sstream>
#include<fstream>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
extern "C" {
//#include "vl/generic.h"
#include "vl/sift.h"
}
#include "Image.h"
//#include "Exception.h"
const int COEFFICIENT_ARRAY_WIDTH = 9;
const int MAX_CORRESPONDENCES = 50;
const int MAXDESCRIPTORS = 3000;
const int threshold = 28000;
const double PI = 3.141592654;
Image I1 ;
Image I2 ;
struct descriptor
{
vl_sift_pix *d;
float x1;
float x2;
descriptor* matches[20];
int numMatches;
};
void convertToGrayscale(Image img, vl_sift_pix *gray );
static long imin(long a, long b) {return (a < b) ? a : b;}
int ssd( descriptor* d1, int size1, descriptor* d2, int size2 );
int sift( descriptor* d, float* pixels, Image I ); //returns the number of keypoints
vl_sift_pix* initializeImage( string name, Image& image )
{
ifstream ifs(name.c_str(), ios_base::in | ios_base::binary) ;
if(!ifs) {
cout << "Could not open file";
//throw Exception("Could not open a file") ;
}
ifs>>image;
vl_sift_pix* gray = new vl_sift_pix[image.getHeight()*image.getWidth()];
convertToGrayscale(image, gray );
return gray;
}
int main(int argc, char *argv[])
{
//for (int i=0; argv[1][i] != 0; i++)
//image1 += argv[1][i];
const int numTests = 10;
string command = "convert " + (string)argv[1] + " test.ppm";
system(command.c_str());
string image1 = "test.ppm";
vl_sift_pix* gray1 = initializeImage( image1, I1 );
string baseName = "libnn.ppm";
char buffer1[33]; //tens place
char buffer2[33]; //ones place
string testNames[numTests];
vl_sift_pix* gray[numTests];
Image testIms[numTests];
for(int i=0; i < numTests; i++ ) //Assumes that numTests < 100
{
if( i < 10 )
//itoa((int)0, buffer1,10);
sprintf(buffer1, "%d", 0);
else
//itoa(i/10, buffer1,10);
sprintf(buffer1, "%d", i/10);
//itoa(i%10, buffer2,10);
sprintf(buffer2, "%d", i%10);
baseName[3] = buffer1[0];
baseName[4] = buffer2[0];
testNames[i] = baseName;
gray[i] = initializeImage( baseName, testIms[i] );
convertToGrayscale(testIms[i], gray[i] );
}
descriptor* d1 = new descriptor[MAXDESCRIPTORS];
for( int k=0; k<MAXDESCRIPTORS; k++ ) //Allocate the descriptors for the first image
{
d1[k].x1 = 0;
d1[k].x2 = 0;
d1[k].d = new vl_sift_pix[128];
d1[k].numMatches = 0;
}
/////////
descriptor* dtests[numTests];
int counts[numTests];
int numMatch[numTests];
int count1 = 0;
count1 = sift( d1, gray1, I1); //sift and store the descriptors in d1, and return the # of descriptors
for ( int i=0; i < count1; i++ ) //Normalize the values
{
for ( int k=0; k < 128; k++ )
{
double x = 512.0 * d1[i].d[k];
x = (x < 255.0) ? x : 255.0 ;
d1[i].d[k] = x;
}
}
for( int i=0; i < numTests; i++ )
{
dtests[i] = new descriptor[MAXDESCRIPTORS];
for( int k=0; k<MAXDESCRIPTORS; k++ ) //Allocate the descriptors for the test images
{
dtests[i][k].x1 = 0;
dtests[i][k].x2 = 0;
dtests[i][k].d = new vl_sift_pix[128];
dtests[i][k].numMatches = 0;
}
counts[i] = sift( dtests[i], gray[i], testIms[i]); //sift and store the descriptors in d2, and return the # of descriptors
for ( int j=0; j < counts[i]; j++ ) //Normalize the values of the 2nd image
{
for ( int k=0; k < 128; k++ )
{
double x = 512.0 * dtests[i][j].d[k];
x = (x < 255.0) ? x : 255.0 ;
dtests[i][j].d[k] = x;
}
}
numMatch[i] = ssd( d1, count1, dtests[i], counts[i] ); //take the sum of squared differences
}
//Find the test image with the most matches
int largestMatch = numMatch[0];
int matchIndex = 0;
for( int i=1; i <numTests; i++ )
{
if( numMatch[i] > largestMatch )
{
largestMatch = numMatch[i];
matchIndex = i;
}
}
bool match = false;
if( (float)largestMatch/(float)counts[matchIndex] >= 0.075 )
match = true;
if(match)
{
switch(matchIndex)
{
case 0:
case 1:
cout<< 1;
return 1;
case 2:
case 3:
cout<< 5;
return 5;
case 4:
case 5:
cout<< 10;
return 10;
case 6:
case 7:
cout<< 20;
return 20;
case 8:
case 9:
cout<< 50;
return 50;
case 10:
case 11:
cout << 100;
return 100;
}
}
else
{
cout<< 0;
return 0;
}
/*ssd( d1, count1, dtests[matchIndex], counts[matchIndex] );
for ( int i=0; i<count1; i++ )
{
for ( int j=0; j< d1[i].numMatches; j++ )
{
int image1x = d1[i].x1;
int image1y = d1[i].x2;
int image2x = d1[i].matches[j]->x1;
int image2y = d1[i].matches[j]->x2;
unsigned char* pt = I1.getPixelPt( image1x, image1y);
pt[0] = 255;
pt[1] = 0;
pt[2] = 0;
unsigned char* pt2 = testIms[matchIndex].getPixelPt( image2x, image2y);
pt2[0] = 255;
pt2[1] = 0;
pt2[2] = 0;
}
}
string outFile = "testmatch.ppm";
ofstream ofile(outFile.c_str(), ios_base::out | ios_base::binary);
ofile<<I1;
ofile.close();
//testNames[matchIndex].resize(testNames[matchIndex].size()-4);
string outFile2 = "libmatch.ppm";
ofstream ofile2(outFile2.c_str(), ios_base::out | ios_base::binary);
ofile2<<testIms[matchIndex];
ofile2.close();*/
/////////////DEallocation///////////////////
for( int k=0; k<MAXDESCRIPTORS; k++ ) //DEallocate the descriptors for the first image
{
delete [] d1[k].d;
}
delete [] d1;
for(int i=0; i< numTests; i++)
{
for( int k=0; k<MAXDESCRIPTORS; k++ ) //DEallocate the descriptors for the second image
{
delete [] dtests[i][k].d;
}
delete [] dtests[i];
}
return 0;
}
void convertToGrayscale(Image img, vl_sift_pix *gray )
{
if( img.getDataSize() == img.getHeight()*img.getWidth() ) //already grayscale, since pixelsize = 1
for ( int i=0; i<img.getHeight()*img.getWidth(); i++ )
gray[i] = (float)*(img.getDataPt()+i);
else //converting rgb to grayscale
for ( int i=0; i < img.getHeight()*img.getWidth(); i++ )
gray[i] = (float)( 0.3 * *(img.getDataPt()+3*i) + 0.59 * *(img.getDataPt()+3*i+1) + 0.11 * *(img.getDataPt()+3*i+2) );
}
int sift( descriptor* d, float* pixels, Image I ) //returns the number of keypoints
{
VlSiftFilt *sift = vl_sift_new(I.getWidth(),I.getHeight(),-1,3,0);
vl_sift_process_first_octave(sift, pixels) ; //process over the first octave
int count = 0;
do
{
vl_sift_detect(sift);
const VlSiftKeypoint* key = vl_sift_get_keypoints(sift);
for(int i=0; i<sift->nkeys; i++)
{
double angles[4];
int numOrients = vl_sift_calc_keypoint_orientations(sift,angles,key+i);
for(int j=0;j<numOrients; j++)
{
vl_sift_calc_keypoint_descriptor(sift,(d[count].d),key+i,angles[j]); //calculate the descriptor
d[count].x1=(key+i)->x;
d[count].x2=(key+i)->y;
count++;
}
}
}while( vl_sift_process_next_octave(sift) != VL_ERR_EOF ); //iterate over the rest of the octaves
vl_sift_delete(sift);
return count;
}
int ssd( descriptor* d1, int size1, descriptor* d2, int size2 )
{
int totalMatches = 0;
for ( int i=0; i < size1; i++ )
{
d1[i].numMatches=0;
for ( int j=0; j < size2; j++ )
{
float sum = 0;
for ( int k=0; k < 128; k++ )
{
sum += (float)(d1[i].d[k] - d2[j].d[k]) * (float)(d1[i].d[k] - d2[j].d[k]); //square the differences
}
if ( sum < threshold )
{
d1[i].matches[d1[i].numMatches] = &d2[j];
d1[i].numMatches++;
totalMatches++;
break;
}
}
}
return totalMatches;
}
| [
"chippoc@12bb654a-2419-11df-acfb-edf9ec2220e5"
]
| [
[
[
1,
304
]
]
]
|
a812d4d212ba50cba370ae49ff4e5c862ba7f50a | 9420f67e448d4990326fd19841dd3266a96601c3 | / mcvr/mcvr/MersenneTwisterGenerator.cpp | c58421fc8560feeaaee008173ce060aa7a132d78 | []
| no_license | xrr/mcvr | 4d8d7880c2fd50e41352fae1b9ede0231cf970a2 | b8d3b3c46cfddee281e099945cee8d844cea4e23 | refs/heads/master | 2020-06-05T11:59:27.857504 | 2010-02-24T19:32:21 | 2010-02-24T19:32:21 | 32,275,830 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | #include "MersenneTwisterGenerator.h"
MersenneTwisterGenerator::MersenneTwisterGenerator(void) {
_pMTR = new MTRand();
}
MersenneTwisterGenerator::~MersenneTwisterGenerator(void)
{
delete _pMTR;
}
double MersenneTwisterGenerator::Next(void) {
return _pMTR->rand();
}
| [
"romain.rousseau@fa0ec5f0-0fe6-11df-8179-3f26cfb4ba5f"
]
| [
[
[
1,
14
]
]
]
|
a4f5ea97a93c71cdb1f03d55d4011c644bf62671 | d63c4c79d0bf83ae646d0ac023ee0528a0f4a879 | /cs240/a3/keyList.h | 52f2b70477f8dae2da7240df0f8ce33d814f1283 | []
| no_license | stratigoster/UW | 4dc31f08f7f1c9a958301105dcad481c39c5361f | 7a4bff4f1476607c43278c488f70d01077b1566b | refs/heads/master | 2021-07-07T04:52:01.543221 | 2011-08-15T05:08:48 | 2011-08-15T05:08:48 | 10,858,995 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 400 | h | // keyList.h: interface for the keyList class.
class keyList
{
public:
int compare(int index1, int index2);
void exchange(int index1, int index2);
int getNoOfExchanges();
int getNoOfComparisons();
int getNoOfKeys();
void printKeys();
void readKeys();
keyList();
virtual ~keyList();
private:
int NoOfExchanges;
int NoOfComparisons;
int * List;
int NoOfKeys;
};
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
1989537b183ca9be2286c18c4af27b330c230c72 | bef7d0477a5cac485b4b3921a718394d5c2cf700 | /nanobots/src/demo/EntityInfoRenderer.h | d718d5c02b436ff2cadaec480e378fac7d318248 | [
"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 | 1,267 | h | #ifndef __ENTITY_INFO_RENDERER_H
#define __ENTITY_INFO_RENDERER_H
#include <dingus/renderer/RenderableBuffer.h>
class CEntityInfoRenderer : public boost::noncopyable {
public:
CEntityInfoRenderer( CD3DIndexBuffer& ib );
~CEntityInfoRenderer();
void beginInfos() {
mBars.clear();
mBrackets.clear();
}
void addBar( const SVector3& pos, float dy, D3DCOLOR color, float fill, float size = 1.0f ) {
mBars.push_back( SBar() );
SBar& b = mBars.back();
b.pos = pos;
b.dy = dy;
b.color = color;
b.fill = fill;
b.size = size;
}
void addBracket( const SVector3& pos, float dy, D3DCOLOR color, float size = 2.0f ) {
mBrackets.push_back( SBracket() );
SBracket& b = mBrackets.back();
b.pos = pos;
b.dy = dy;
b.color = color;
b.size = size;
}
void endInfos() {
}
void render();
private:
CRenderableIndexedBuffer* mRenderable;
CD3DIndexBuffer* mIB;
CD3DVertexDecl* mVDecl;
// health bars
struct SBar {
SVector3 pos;
float dy;
D3DCOLOR color;
float fill;
float size;
};
std::vector<SBar> mBars;
// selection brackets
struct SBracket {
SVector3 pos;
float dy;
D3DCOLOR color;
float size;
};
std::vector<SBracket> mBrackets;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
79711d3d1f37dab8618199c28b45ce7fe46c5e4c | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/type_traits/is_function.hpp | a991d11ddf8a25672be7ed8f1e14c23505faff40 | [
"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 | 2,538 | hpp |
// Copyright 2000 John Maddock ([email protected])
// Copyright 2002 Aleksey Gurtovoy ([email protected])
//
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
//
// See http://www.boost.org/libs/type_traits for most recent version including documentation.
#ifndef BOOST_TT_IS_FUNCTION_HPP_INCLUDED
#define BOOST_TT_IS_FUNCTION_HPP_INCLUDED
#include <boost/type_traits/is_reference.hpp>
#include <boost/type_traits/detail/false_result.hpp>
#include <boost/config.hpp>
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_TT_TEST_MS_FUNC_SIGS)
# include <boost/type_traits/detail/is_function_ptr_helper.hpp>
#else
# include <boost/type_traits/detail/is_function_ptr_tester.hpp>
# include <boost/type_traits/detail/yes_no_type.hpp>
#endif
// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>
// is a type a function?
// Please note that this implementation is unnecessarily complex:
// we could just use !is_convertible<T*, const volatile void*>::value,
// except that some compilers erroneously allow conversions from
// function pointers to void*.
namespace boost {
namespace detail {
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) && !defined(BOOST_TT_TEST_MS_FUNC_SIGS)
template<bool is_ref = true>
struct is_function_chooser
: ::boost::type_traits::false_result
{
};
template <>
struct is_function_chooser<false>
{
template< typename T > struct result_
: ::boost::type_traits::is_function_ptr_helper<T*>
{
};
};
template <typename T>
struct is_function_impl
: is_function_chooser< ::boost::is_reference<T>::value >
::BOOST_NESTED_TEMPLATE result_<T>
{
};
#else
template <typename T>
struct is_function_impl
{
static T* t;
BOOST_STATIC_CONSTANT(
bool, value = sizeof(::boost::type_traits::is_function_ptr_tester(t))
== sizeof(::boost::type_traits::yes_type)
);
};
#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template <typename T>
struct is_function_impl<T&> : public false_type
{};
#endif
#endif
} // namespace detail
BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_function,T,::boost::detail::is_function_impl<T>::value)
} // namespace boost
#include <boost/type_traits/detail/bool_trait_undef.hpp>
#endif // BOOST_TT_IS_FUNCTION_HPP_INCLUDED
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
88
]
]
]
|
147f9fc1ccd3fa765dc4b16984ea7305663aaa52 | b8fe0ddfa6869de08ba9cd434e3cf11e57d59085 | /ouan-tests/OgreSceneLoader/Application.h | 08dd4a638a5d1847034725f960b3fd9cf5f41138 | []
| no_license | juanjmostazo/ouan-tests | c89933891ed4f6ad48f48d03df1f22ba0f3ff392 | eaa73fb482b264d555071f3726510ed73bef22ea | refs/heads/master | 2021-01-10T20:18:35.918470 | 2010-06-20T15:45:00 | 2010-06-20T15:45:00 | 38,101,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 868 | h | #ifndef __APPLICATION__H__
#define __APPLICATION__H__
#include "GeneralHeader.h"
using namespace Ogre;
class Application
: SimpleInputManager
{
public:
Application();
virtual ~Application();
void initialise();
void go();
virtual bool keyPressed( const OIS::KeyEvent& e );
virtual bool mouseMoved( const OIS::MouseEvent& e );
private:
Ogre::Root* m_root;
Ogre::RenderWindow* m_window;
Ogre::SceneManager* m_sceneManager;
Ogre::Camera* m_camera;
Ogre::Viewport* m_viewport;
CameraControllerFirstPerson* m_cameraControllerFirstPerson;
bool application_started;
bool m_exitRequested;
void defineResources();
void loadResources();
void createScene();
void updateLogic( const float elapsedSeconds );
void updateGraphics( const float elapsedSeconds );
void changeCamera(String camera);
};
#endif
| [
"ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde"
]
| [
[
[
1,
44
]
]
]
|
35367ce44c3d4f5a02e0845d63f240fb854d4215 | e2e49023f5a82922cb9b134e93ae926ed69675a1 | /tools/aoslcpp/include/aosl/event_signal_forward.hpp | 67500e42982c42b4130c2486cd8360d915aa41ae | []
| no_license | invy/mjklaim-freewindows | c93c867e93f0e2fe1d33f207306c0b9538ac61d6 | 30de8e3dfcde4e81a57e9059dfaf54c98cc1135b | refs/heads/master | 2021-01-10T10:21:51.579762 | 2011-12-12T18:56:43 | 2011-12-12T18:56:43 | 54,794,395 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,642 | hpp | // Copyright (C) 2005-2010 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema
// to C++ data binding compiler, in the Proprietary License mode.
// You should have received a proprietary license from Code Synthesis
// Tools CC prior to generating this code. See the license text for
// conditions.
//
#ifndef AOSLCPP_AOSL__EVENT_SIGNAL_FORWARD_HPP
#define AOSLCPP_AOSL__EVENT_SIGNAL_FORWARD_HPP
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/version.hxx>
#if (XSD_INT_VERSION != 3030000L)
#error XSD runtime version mismatch
#endif
#include <xsd/cxx/pre.hxx>
#ifndef XSD_USE_CHAR
#define XSD_USE_CHAR
#endif
#ifndef XSD_CXX_TREE_USE_CHAR
#define XSD_CXX_TREE_USE_CHAR
#endif
#include <xsd/cxx/xml/char-utf8.hxx>
#include <xsd/cxx/tree/exceptions.hxx>
#include <xsd/cxx/tree/elements.hxx>
#include <xsd/cxx/tree/types.hxx>
#include <xsd/cxx/xml/error-handler.hxx>
#include <xsd/cxx/xml/dom/auto-ptr.hxx>
#include <xsd/cxx/tree/parsing.hxx>
#include <xsd/cxx/tree/parsing/byte.hxx>
#include <xsd/cxx/tree/parsing/unsigned-byte.hxx>
#include <xsd/cxx/tree/parsing/short.hxx>
#include <xsd/cxx/tree/parsing/unsigned-short.hxx>
#include <xsd/cxx/tree/parsing/int.hxx>
#include <xsd/cxx/tree/parsing/unsigned-int.hxx>
#include <xsd/cxx/tree/parsing/long.hxx>
#include <xsd/cxx/tree/parsing/unsigned-long.hxx>
#include <xsd/cxx/tree/parsing/boolean.hxx>
#include <xsd/cxx/tree/parsing/float.hxx>
#include <xsd/cxx/tree/parsing/double.hxx>
#include <xsd/cxx/tree/parsing/decimal.hxx>
#include <xsd/cxx/xml/dom/serialization-header.hxx>
#include <xsd/cxx/tree/serialization.hxx>
#include <xsd/cxx/tree/serialization/byte.hxx>
#include <xsd/cxx/tree/serialization/unsigned-byte.hxx>
#include <xsd/cxx/tree/serialization/short.hxx>
#include <xsd/cxx/tree/serialization/unsigned-short.hxx>
#include <xsd/cxx/tree/serialization/int.hxx>
#include <xsd/cxx/tree/serialization/unsigned-int.hxx>
#include <xsd/cxx/tree/serialization/long.hxx>
#include <xsd/cxx/tree/serialization/unsigned-long.hxx>
#include <xsd/cxx/tree/serialization/boolean.hxx>
#include <xsd/cxx/tree/serialization/float.hxx>
#include <xsd/cxx/tree/serialization/double.hxx>
#include <xsd/cxx/tree/serialization/decimal.hxx>
#include <xsd/cxx/tree/std-ostream-operators.hxx>
/**
* @brief C++ namespace for the %http://www.w3.org/2001/XMLSchema
* schema namespace.
*/
namespace xml_schema
{
// anyType and anySimpleType.
//
/**
* @brief C++ type corresponding to the anyType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::type Type;
/**
* @brief C++ type corresponding to the anySimpleType XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::simple_type< Type > SimpleType;
/**
* @brief Alias for the anyType type.
*/
typedef ::xsd::cxx::tree::type Container;
// 8-bit
//
/**
* @brief C++ type corresponding to the byte XML Schema
* built-in type.
*/
typedef signed char Byte;
/**
* @brief C++ type corresponding to the unsignedByte XML Schema
* built-in type.
*/
typedef unsigned char UnsignedByte;
// 16-bit
//
/**
* @brief C++ type corresponding to the short XML Schema
* built-in type.
*/
typedef short Short;
/**
* @brief C++ type corresponding to the unsignedShort XML Schema
* built-in type.
*/
typedef unsigned short UnsignedShort;
// 32-bit
//
/**
* @brief C++ type corresponding to the int XML Schema
* built-in type.
*/
typedef int Int;
/**
* @brief C++ type corresponding to the unsignedInt XML Schema
* built-in type.
*/
typedef unsigned int UnsignedInt;
// 64-bit
//
/**
* @brief C++ type corresponding to the long XML Schema
* built-in type.
*/
typedef long long Long;
/**
* @brief C++ type corresponding to the unsignedLong XML Schema
* built-in type.
*/
typedef unsigned long long UnsignedLong;
// Supposed to be arbitrary-length integral types.
//
/**
* @brief C++ type corresponding to the integer XML Schema
* built-in type.
*/
typedef long long Integer;
/**
* @brief C++ type corresponding to the nonPositiveInteger XML Schema
* built-in type.
*/
typedef long long NonPositiveInteger;
/**
* @brief C++ type corresponding to the nonNegativeInteger XML Schema
* built-in type.
*/
typedef unsigned long long NonNegativeInteger;
/**
* @brief C++ type corresponding to the positiveInteger XML Schema
* built-in type.
*/
typedef unsigned long long PositiveInteger;
/**
* @brief C++ type corresponding to the negativeInteger XML Schema
* built-in type.
*/
typedef long long NegativeInteger;
// Boolean.
//
/**
* @brief C++ type corresponding to the boolean XML Schema
* built-in type.
*/
typedef bool Boolean;
// Floating-point types.
//
/**
* @brief C++ type corresponding to the float XML Schema
* built-in type.
*/
typedef float Float;
/**
* @brief C++ type corresponding to the double XML Schema
* built-in type.
*/
typedef double Double;
/**
* @brief C++ type corresponding to the decimal XML Schema
* built-in type.
*/
typedef double Decimal;
// String types.
//
/**
* @brief C++ type corresponding to the string XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::string< char, SimpleType > String;
/**
* @brief C++ type corresponding to the normalizedString XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::normalized_string< char, String > NormalizedString;
/**
* @brief C++ type corresponding to the token XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::token< char, NormalizedString > Token;
/**
* @brief C++ type corresponding to the Name XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::name< char, Token > Name;
/**
* @brief C++ type corresponding to the NMTOKEN XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtoken< char, Token > Nmtoken;
/**
* @brief C++ type corresponding to the NMTOKENS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::nmtokens< char, SimpleType, Nmtoken > Nmtokens;
/**
* @brief C++ type corresponding to the NCName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::ncname< char, Name > Ncname;
/**
* @brief C++ type corresponding to the language XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::language< char, Token > Language;
// ID/IDREF.
//
/**
* @brief C++ type corresponding to the ID XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::id< char, Ncname > Id;
/**
* @brief C++ type corresponding to the IDREF XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idref< char, Ncname, Type > Idref;
/**
* @brief C++ type corresponding to the IDREFS XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::idrefs< char, SimpleType, Idref > Idrefs;
// URI.
//
/**
* @brief C++ type corresponding to the anyURI XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::uri< char, SimpleType > Uri;
// Qualified name.
//
/**
* @brief C++ type corresponding to the QName XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::qname< char, SimpleType, Uri, Ncname > Qname;
// Binary.
//
/**
* @brief Binary buffer type.
*/
typedef ::xsd::cxx::tree::buffer< char > Buffer;
/**
* @brief C++ type corresponding to the base64Binary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::base64_binary< char, SimpleType > Base64Binary;
/**
* @brief C++ type corresponding to the hexBinary XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::hex_binary< char, SimpleType > HexBinary;
// Date/time.
//
/**
* @brief Time zone type.
*/
typedef ::xsd::cxx::tree::time_zone TimeZone;
/**
* @brief C++ type corresponding to the date XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date< char, SimpleType > Date;
/**
* @brief C++ type corresponding to the dateTime XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::date_time< char, SimpleType > DateTime;
/**
* @brief C++ type corresponding to the duration XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::duration< char, SimpleType > Duration;
/**
* @brief C++ type corresponding to the gDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gday< char, SimpleType > Gday;
/**
* @brief C++ type corresponding to the gMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth< char, SimpleType > Gmonth;
/**
* @brief C++ type corresponding to the gMonthDay XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gmonth_day< char, SimpleType > GmonthDay;
/**
* @brief C++ type corresponding to the gYear XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear< char, SimpleType > Gyear;
/**
* @brief C++ type corresponding to the gYearMonth XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::gyear_month< char, SimpleType > GyearMonth;
/**
* @brief C++ type corresponding to the time XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::time< char, SimpleType > Time;
// Entity.
//
/**
* @brief C++ type corresponding to the ENTITY XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entity< char, Ncname > Entity;
/**
* @brief C++ type corresponding to the ENTITIES XML Schema
* built-in type.
*/
typedef ::xsd::cxx::tree::entities< char, SimpleType, Entity > Entities;
// Namespace information and list stream. Used in
// serialization functions.
//
/**
* @brief Namespace serialization information.
*/
typedef ::xsd::cxx::xml::dom::namespace_info< char > NamespaceInfo;
/**
* @brief Namespace serialization information map.
*/
typedef ::xsd::cxx::xml::dom::namespace_infomap< char > NamespaceInfomap;
/**
* @brief List serialization stream.
*/
typedef ::xsd::cxx::tree::list_stream< char > ListStream;
/**
* @brief Serialization wrapper for the %double type.
*/
typedef ::xsd::cxx::tree::as_double< Double > AsDouble;
/**
* @brief Serialization wrapper for the %decimal type.
*/
typedef ::xsd::cxx::tree::as_decimal< Decimal > AsDecimal;
/**
* @brief Simple type facet.
*/
typedef ::xsd::cxx::tree::facet Facet;
// Flags and properties.
//
/**
* @brief Parsing and serialization flags.
*/
typedef ::xsd::cxx::tree::flags Flags;
/**
* @brief Parsing properties.
*/
typedef ::xsd::cxx::tree::properties< char > Properties;
// Parsing/serialization diagnostics.
//
/**
* @brief Error severity.
*/
typedef ::xsd::cxx::tree::severity Severity;
/**
* @brief Error condition.
*/
typedef ::xsd::cxx::tree::error< char > Error;
/**
* @brief List of %error conditions.
*/
typedef ::xsd::cxx::tree::diagnostics< char > Diagnostics;
// Exceptions.
//
/**
* @brief Root of the C++/Tree %exception hierarchy.
*/
typedef ::xsd::cxx::tree::exception< char > Exception;
/**
* @brief Exception indicating that the size argument exceeds
* the capacity argument.
*/
typedef ::xsd::cxx::tree::bounds< char > Bounds;
/**
* @brief Exception indicating that a duplicate ID value
* was encountered in the object model.
*/
typedef ::xsd::cxx::tree::duplicate_id< char > DuplicateId;
/**
* @brief Exception indicating a parsing failure.
*/
typedef ::xsd::cxx::tree::parsing< char > Parsing;
/**
* @brief Exception indicating that an expected element
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_element< char > ExpectedElement;
/**
* @brief Exception indicating that an unexpected element
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_element< char > UnexpectedElement;
/**
* @brief Exception indicating that an expected attribute
* was not encountered.
*/
typedef ::xsd::cxx::tree::expected_attribute< char > ExpectedAttribute;
/**
* @brief Exception indicating that an unexpected enumerator
* was encountered.
*/
typedef ::xsd::cxx::tree::unexpected_enumerator< char > UnexpectedEnumerator;
/**
* @brief Exception indicating that the text content was
* expected for an element.
*/
typedef ::xsd::cxx::tree::expected_text_content< char > ExpectedTextContent;
/**
* @brief Exception indicating that a prefix-namespace
* mapping was not provided.
*/
typedef ::xsd::cxx::tree::no_prefix_mapping< char > NoPrefixMapping;
/**
* @brief Exception indicating that the type information
* is not available for a type.
*/
typedef ::xsd::cxx::tree::no_type_info< char > NoTypeInfo;
/**
* @brief Exception indicating that the types are not
* related by inheritance.
*/
typedef ::xsd::cxx::tree::not_derived< char > NotDerived;
/**
* @brief Exception indicating a serialization failure.
*/
typedef ::xsd::cxx::tree::serialization< char > Serialization;
/**
* @brief Error handler callback interface.
*/
typedef ::xsd::cxx::xml::error_handler< char > ErrorHandler;
/**
* @brief DOM interaction.
*/
namespace dom
{
/**
* @brief Automatic pointer for DOMDocument.
*/
using ::xsd::cxx::xml::dom::auto_ptr;
#ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
#define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA
/**
* @brief DOM user data key for back pointers to tree nodes.
*/
const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node;
#endif
}
}
#include "aosl/event_signal_base_forward.hpp"
#include "aosl/signal_source_forward.hpp"
// Forward declarations.
//
namespace aosl
{
class Event_signal;
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
#endif // AOSLCPP_AOSL__EVENT_SIGNAL_FORWARD_HPP
| [
"klaim@localhost"
]
| [
[
[
1,
612
]
]
]
|
e67904c3e779cf90875555a15ae137a36605770c | a296df442777ae1e63188cbdf5bcd2ca0adedf3f | /cppProject/FirstTry/FirstTry/Tower.h | 409a1b3a1b6c825b5df92fbed9d3902135ba2407 | []
| no_license | piyushv94/jpcap-scanner | 39b4d710166c12a2fe695d9ec222da7b36787443 | 8fbf4214586e4f07f1b3ec4819f9a3c7451bd679 | refs/heads/master | 2021-01-10T06:15:32.064675 | 2011-11-26T20:23:55 | 2011-11-26T20:23:55 | 44,114,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | h | #ifndef _Tower
#define _Tower
#include "Item.h"
class Tower:public Item{
public:
ostream& print(ostream&) const ;
friend ostream& operator<<(ostream& ,Tower &);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
13
]
]
]
|
c3bd41742dab44b4b79ac92cfd7421476eabc21c | 5ed707de9f3de6044543886ea91bde39879bfae6 | /ASHockey/ASFIsOrb/Source/ASHockeyLineupQueryRqst.h | d332c3a73758c88de3072fbd3f32d611a9207983 | []
| no_license | grtvd/asifantasysports | 9e472632bedeec0f2d734aa798b7ff00148e7f19 | 76df32c77c76a76078152c77e582faa097f127a8 | refs/heads/master | 2020-03-19T02:25:23.901618 | 1999-12-31T16:00:00 | 2018-05-31T19:48:19 | 135,627,290 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | h | /* ASHockeyLineupQueryRqst.h */
/******************************************************************************/
/******************************************************************************/
#ifndef ASHockeyLineupQueryRqstH
#define ASHockeyLineupQueryRqstH
#include "ASFantasyLineupQueryRqst.h"
using namespace asfantasy;
namespace ashockey
{
/******************************************************************************/
class ASHockeyLineupQueryRqst : public LineupQueryRqst
{
protected:
virtual bool areChangesAllowed(TLeagueID leagueID) { return(true); }
virtual void fillPlayerIDArray(const TTeamPtr teamPtr,
std::vector<TPlayerIDVector>& playerIDArray);
virtual PlayerInfoPtr createNewLineupPlayer(const TProfPlayerPtr profPlayerPtr)
{ return(LineupPlayer::createFromProfPlayer(profPlayerPtr)); }
};
/******************************************************************************/
}; //namespace ashockey
#endif //ASHockeyLineupQueryRqstH
/******************************************************************************/
/******************************************************************************/
| [
"[email protected]"
]
| [
[
[
1,
34
]
]
]
|
f1e9cbe488fff0c5ab63c6fc33d00726896c1211 | 55196303f36aa20da255031a8f115b6af83e7d11 | /private/external/gameswf/gameswf/gameswf_function.cpp | bbd0b2fba4f7bf0465259530e2e19c7c91939b84 | []
| no_license | Heartbroken/bikini | 3f5447647d39587ffe15a7ae5badab3300d2a2ff | fe74f51a3a5d281c671d303632ff38be84d23dd7 | refs/heads/master | 2021-01-10T19:48:40.851837 | 2010-05-25T19:58:52 | 2010-05-25T19:58:52 | 37,190,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,979 | cpp | // gameswf_function.cpp -- Thatcher Ulrich <[email protected]> 2003
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// ActionScript function.
#include "gameswf/gameswf_function.h"
#include "gameswf/gameswf_log.h"
#include "gameswf/gameswf_character.h"
#include "gameswf/gameswf_sprite.h"
#include "gameswf/gameswf_as_classes/as_array.h"
namespace gameswf
{
// Invokes the function represented by a Function object.
// public call(thisObject:Object, [parameter1:Object]) : Object
void as_s_function_call(const fn_call& fn)
{
assert(fn.this_ptr);
if (fn.nargs > 0)
{
as_object* properties = fn.this_ptr;
if (properties->m_this_ptr != NULL)
{
as_object* func = properties->m_this_ptr.get_ptr();
if (func)
{
as_environment env(fn.get_player());
int nargs = 0;
if (fn.nargs > 1)
{
nargs = 1;
env.push(fn.arg(1));
}
*fn.result = call_method(func, &env, fn.arg(0).to_object(),
nargs, env.get_top_index());
}
}
}
}
as_s_function::as_s_function(player* player,
const action_buffer* ab, int start, const array<with_stack_entry>& with_stack) :
as_function(player),
m_with_stack(with_stack),
m_start_pc(start),
m_length(0),
m_is_function2(false),
m_local_register_count(0),
m_function2_flags(0)
{
// Flash stores a body(functions) of a class in _global,
// action_buffer is in movie_def, therefore when we load another _root
// action_buffer will be deleted and _global.MyClass will keep
// the pointer to the removed object(action_buffer).
// Therefore we have updated action_buffer* ==> action_buffer in as_s_function
assert(ab);
m_action_buffer = *ab;
m_this_ptr = this;
// any function MUST have prototype
builtin_member("prototype", new as_object(player));
builtin_member("call", as_s_function_call);
}
as_s_function::~as_s_function()
{
}
void as_s_function::operator()(const fn_call& fn)
// Dispatch.
{
assert(fn.env);
// Keep target alive during execution!
smart_ptr<as_object> target = m_target;
// try to use caller environment
// if the caller object has own environment then we use its environment
as_environment* env = fn.env;
if (fn.this_ptr)
{
if (fn.this_ptr->get_environment())
{
env = fn.this_ptr->get_environment();
}
}
// set 'this'
as_object* this_ptr = env->get_target();
if (fn.this_ptr)
{
this_ptr = fn.this_ptr;
if (this_ptr->m_this_ptr != NULL)
{
this_ptr = this_ptr->m_this_ptr.get_ptr();
}
}
// Function has been declared in moviclip ==> we should use its environment
// At the same time 'this_ptr' may refers to another object
// see testcase in .h file
if (m_target != NULL)
{
character* ch = cast_to<character>(m_target.get_ptr());
if (ch)
{
if (ch->is_alive())
{
env = m_target->get_environment();
}
}
}
// Set up local stack frame, for parameters and locals.
int local_stack_top = env->get_local_frame_top();
env->add_frame_barrier();
if (m_is_function2 == false)
{
// Conventional function.
// Push the arguments onto the local frame.
int args_to_pass = imin(fn.nargs, m_args.size());
for (int i = 0; i < args_to_pass; i++)
{
assert(m_args[i].m_register == 0);
env->add_local(m_args[i].m_name, fn.arg(i));
}
env->set_local("this", this_ptr);
// Put 'super' in a local var.
if (fn.this_ptr)
{
env->add_local("super", fn.this_ptr->get_proto());
}
}
else
{
// function2: most args go in registers; any others get pushed.
// Create local registers.
env->add_local_registers(m_local_register_count);
// Handle the explicit args.
int args_to_pass = imin(fn.nargs, m_args.size());
for (int i = 0; i < args_to_pass; i++)
{
if (m_args[i].m_register == 0)
{
// Conventional arg passing: create a local var.
env->add_local(m_args[i].m_name, fn.arg(i));
}
else
{
// Pass argument into a register.
int reg = m_args[i].m_register;
env->set_register(reg, fn.arg(i));
}
}
// Handle the implicit args.
int current_reg = 1;
if (m_function2_flags & 0x01)
{
// preload 'this' into a register.
IF_VERBOSE_ACTION(log_msg("-------------- preload this=0x%X to register %d\n",
this_ptr, current_reg));
env->set_register(current_reg, this_ptr);
current_reg++;
}
if (m_function2_flags & 0x02)
{
// Don't put 'this' into a local var.
}
else
{
// Put 'this' in a local var.
env->add_local("this", as_value(this_ptr));
}
// Init arguments array, if it's going to be needed.
smart_ptr<as_array> arg_array;
if ((m_function2_flags & 0x04) || ! (m_function2_flags & 0x08))
{
arg_array = new as_array(env->get_player());
as_value index_number;
for (int i = 0; i < fn.nargs; i++)
{
index_number.set_int(i);
arg_array->set_member(index_number.to_string(), fn.arg(i));
}
}
if (m_function2_flags & 0x04)
{
// preload 'arguments' into a register.
env->set_register(current_reg, arg_array.get_ptr());
current_reg++;
}
if (m_function2_flags & 0x08)
{
// Don't put 'arguments' in a local var.
}
else
{
// Put 'arguments' in a local var.
env->add_local("arguments", as_value(arg_array.get_ptr()));
}
if (m_function2_flags & 0x10)
{
// Put 'super' in a register.
IF_VERBOSE_ACTION(log_msg("-------------- preload super=0x%X to register %d\n",
fn.this_ptr->get_proto(), current_reg));
env->set_register(current_reg, fn.this_ptr->get_proto());
current_reg++;
}
if (m_function2_flags & 0x20)
{
// Don't put 'super' in a local var.
}
else
{
// Put 'super' in a local var.
env->add_local("super", fn.this_ptr->get_proto());
}
if (m_function2_flags & 0x40)
{
// Put '_root' in a register.
env->set_register(current_reg, env->get_root()->get_root_movie());
current_reg++;
}
if (m_function2_flags & 0x80)
{
// Put '_parent' in a register.
array<with_stack_entry> dummy;
as_value parent = env->get_variable("_parent", dummy);
IF_VERBOSE_ACTION(log_msg("-------------- preload _parent=0x%X to register %d\n", parent, current_reg));
env->set_register(current_reg, parent);
current_reg++;
}
if (m_function2_flags & 0x100)
{
// Put '_global' in a register.
IF_VERBOSE_ACTION(log_msg("-------------- preload _global=0x%X to register %d\n",
get_global(), current_reg));
env->set_register(current_reg, get_global());
current_reg++;
}
}
// keep stack size
int stack_size = env->m_stack.size();
// printf("***on entry*** %d\n", stack_size);
// Execute the actions.
m_action_buffer.execute(env, m_start_pc, m_length, fn.result, m_with_stack, m_is_function2);
// restore stack size
// it should not be but it happens
if (stack_size != env->m_stack.size())
{
// log_error("s_function: on entry stack size (%d) != on exit stack size (%d)\n",
// stack_size, env->m_stack.size());
env->m_stack.resize(stack_size);
}
// Clean up stack frame.
env->set_local_frame_top(local_stack_top);
if (m_is_function2)
{
// Clean up the local registers.
env->drop_local_registers(m_local_register_count);
}
}
as_c_function::as_c_function(player* player, as_c_function_ptr func) :
as_function(player),
m_func(func)
{
// any function MUST have prototype
builtin_member("prototype", new as_object(player));
}
void as_c_function::operator()(const fn_call& fn)
{
if (m_func)
{
(*m_func)(fn);
}
}
}
| [
"viktor.reutskyy@68c2588f-494f-0410-aecb-65da31d84587"
]
| [
[
[
1,
310
]
]
]
|
50df06d55a59fb95c9108a83977e52ac84718f7b | c7f1dcc066955e698ab5a42acf1ed50680bf4d0b | /include/pdl_commctrl.h | 6e366dce6f42e5a83db02d0921a5f9a85ec09a56 | []
| no_license | wjcsharp/pdl-titilima | 8618082d734e5c1d051b2fab5e975ab15e8bbdd8 | 2bb4f618b00d2d57b509a64d792eff7d1208d380 | refs/heads/master | 2020-04-20T16:20:11.236062 | 2010-11-25T10:17:01 | 2010-11-25T10:17:01 | 32,128,071 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 21,037 | h | /**
* \file pdl_commctrl.h
* \brief PDL 公共控件封装
* \details 对公共控件的功能封装:
* \li \c LComCtl 公共控件基类
* \li \c LDateTime 日期/时间控件类
* \li \c LHeader Header 控件类
* \li \c LHotKey 热键控件类
* \li \c LImageList 图像列表类
* \li \c LListView 列表视图类
* \li \c LMonthCal 日历控件类
* \li \c LProgressBar 进度条控件类
* \li \c LPropSheet 属性表控件类
* \li \c LPropSheetPage 属性页控件类
* \li \c LReBar ReBar 控件类
* \li \c LStatusBar 状态栏控件类
* \li \c LTabCtrl 标签控件类
* \li \c LToolBar 工具栏控件类
* \li \c LToolTip 工具提示控件类
* \li \c LTrackBar 滑动条控件类
* \li \c LTreeView 树形视图类
* \li \c LUpDown 微调控件类
*/
#pragma once
#include "pdl_window.h"
/**
* \class LComCtl
* \brief 公共控件基类
*/
class LComCtl : public LWnd
{
public:
LComCtl(__in HWND hWnd = NULL);
LComCtl& operator=(__in HWND hWnd);
public:
static BOOL PDLAPI Init(__in DWORD dwICC);
public:
BOOL GetUnicodeFormat(void);
DWORD GetVersion(void);
BOOL SetUnicodeFormat(__in BOOL bUnicode);
DWORD SetVersion(__in DWORD dwVersion);
};
/**
* \class LDateTime
* \brief 日期/时间控件类
*/
class LDateTime : public LComCtl
{
public:
LDateTime(__in HWND hWnd = NULL);
LDateTime& operator=(__in HWND hWnd);
public:
DWORD GetTime(__in LPSYSTEMTIME lpSysTime);
BOOL SetTime(__in DWORD dwFlag, __in LPSYSTEMTIME lpSysTime);
};
/**
* \class LHeader
* \brief Header 控件类
*/
class LHeader : public LComCtl
{
public:
LHeader(__in HWND hWnd = NULL);
LHeader& operator=(__in HWND hWnd);
operator HWND(void) const { return m_hWnd; }
public:
BOOL Create(__in HWND hParent, __in UINT uId, __in DWORD dwStyle);
int InsertItem(__in int index, __in const LPHDITEMA phdi);
int InsertItem(__in int index, __in const LPHDITEMW phdi);
int InsertItem(__in int index, __in PCSTR pszText, __in int cxy,
__in int fmt = HDF_LEFT);
int InsertItem(__in int index, __in PCWSTR pszText, __in int cxy,
__in int fmt = HDF_LEFT);
BOOL Layout(__in LPRECT prc, __out LPWINDOWPOS pwpos);
BOOL SetItem(__in int iIndex, __in LPHDITEM phdItem);
};
/**
* \class LHotKey
* \brief 热键控件类
*/
class LHotKey : public LComCtl
{
public:
LHotKey(__in HWND hWnd = NULL);
LHotKey& operator=(__in HWND hWnd);
public:
UINT GetHotKey(void);
void GetHotKey(__out PUINT fsModifiers, __out PUINT vk);
static UINT MakeHotKey(__in UINT fsModifiers, __in UINT vk);
static void ParseHotKey(__in UINT uHotKey, __out PUINT fsModifiers,
__out PUINT vk);
void SetHotKey(__in UINT uHotKey);
void SetHotKey(__in UINT fsModifiers, __in UINT vk);
};
/**
* \class LImageList
* \brief 图像列表类
*/
class LImageList
{
public:
LImageList(__in HIMAGELIST himl = NULL);
~LImageList(void);
LImageList& operator=(__in HIMAGELIST himl);
operator HIMAGELIST(void) const;
public:
int Add(__in HBITMAP hbmImage, __in HBITMAP hbmMask);
int AddIcon(__in HICON hIcon);
int AddMasked(__in HBITMAP hbmImage, __in COLORREF crMask);
BOOL BeginDrag(__in int iTrack, __in int dxHotspot, __in int dyHotspot);
BOOL Copy(__in HIMAGELIST himlSrc, __in int iDst, __in int iSrc,
__in UINT uFlags);
BOOL Create(__in int cx, __in int cy, __in UINT flags,
__in int cInitial, __in int cGrow);
BOOL Destroy(void);
BOOL DragEnter(__in HWND hwndLock, __in int x, __in int y);
BOOL DragLeave(__in HWND hwndLock);
BOOL DragMove(__in int x, __in int y);
static BOOL PDLAPI DragShowNolock(__in BOOL fShow);
BOOL Draw(__in int i, __in HDC hdcDst, __in int x,
__in int y, __in UINT fStyle);
BOOL DrawEx(int i, HDC hdcDst, int x, int y, int dx, int dy,
COLORREF rgbBk, COLORREF rgbFg, UINT fStyle);
BOOL DrawIndirect(IMAGELISTDRAWPARAMS *pimldp);
HIMAGELIST Duplicate(void);
static void PDLAPI EndDrag(void);
HICON ExtractIcon(int i);
COLORREF GetBkColor() const;
HIMAGELIST GetHandle(void) { return m_hImageList; }
HICON GetIcon(int i, UINT flags);
BOOL GetIconSize(int *cx, int *cy);
int GetImageCount(void) const;
BOOL GetImageInfo(int i, LPIMAGEINFO pImageInfo);
static HIMAGELIST GetShellImageList(__in BOOL bLarge);
static HIMAGELIST LoadFromFile(__in PCSTR lpszFileName, __in int cx,
__in COLORREF crMask);
static HIMAGELIST LoadFromFile(__in PCWSTR lpszFileName, __in int cx,
__in COLORREF crMask);
BOOL LoadImage(__in PCSTR lpbmp, __in int cx, __in COLORREF crMask,
__in UINT flags, __in int cGrow);
BOOL LoadImage(__in PCWSTR lpbmp, __in int cx, __in COLORREF crMask,
__in UINT flags, __in int cGrow);
BOOL Merge(HIMAGELIST himl1, int i1, HIMAGELIST himl2, int i2, int dx,
int dy);
BOOL Remove(__in int i);
BOOL RemoveAll(void);
int ReplaceIcon(__in int i, __in HICON hicon);
COLORREF SetBkColor(COLORREF clrBk);
BOOL SetDragCursorImage(int iDrag, int dxHotspot, int dyHotspot);
BOOL SetIconSize(int cx, int cy);
BOOL SetImageCount(UINT uNewCount);
BOOL SetOverlayImage(int iImage, int iOverlay);
protected:
/**
* 图像列表句柄
*/
HIMAGELIST m_hImageList;
};
/**
* \class LListView
* \brief 列表视图类
*/
class LListView : public LComCtl
{
public:
LListView& operator=(__in HWND hWnd);
public:
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT nID);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT nID);
HIMAGELIST CreateDragImage(__in int iItem, __out LPPOINT lpptUpLeft);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT nID);
BOOL DeleteAllItems(void);
BOOL DeleteColumn(__in int iCol);
BOOL DeleteItem(__in int nItem);
HWND EditLabel(__in int iItem);
BOOL GetCheckState(__in UINT iIndex);
BOOL GetColumn(__in int iCol, __out LPLVCOLUMNA pcol);
BOOL GetColumn(__in int iCol, __out LPLVCOLUMNW pcol);
int GetColumnWidth(__in int iCol);
HWND GetEditControl(void);
HWND GetHeader(void);
HIMAGELIST GetImageList(__in int iImageList);
BOOL GetItem(__inout LPLVITEMA pitem);
BOOL GetItem(__inout LPLVITEMW pitem);
int GetItemCount(void) const;
LPARAM GetItemData(__in int iItem);
BOOL GetItemRect(__in int iItem, __out LPRECT rc, __in int code);
UINT GetItemState(__in int iItem, __in UINT mask);
void GetItemText(__in int iItem, __in int iSubItem, __out PSTR pszText,
__in int cchTextMax);
void GetItemText(__in int iItem, __in int iSubItem, __out PWSTR pszText,
__in int cchTextMax);
int GetNextItem(__in int iStart, __in UINT flags);
UINT GetSelectedCount(void);
int GetSelectionMark(void);
int HitTest(__inout LPLVHITTESTINFO hi);
int HitTest(__in POINT pt, __out UINT* pFlags = NULL);
int InsertColumn(__in int iCol, __in PCSTR pszText, __in int cx,
__in int fmt = LVCFMT_LEFT);
int InsertColumn(__in int iCol, __in PCWSTR pszText, __in int cx,
__in int fmt = LVCFMT_LEFT);
int InsertColumn(__in int iCol, __in const LPLVCOLUMNA pcol);
int InsertColumn(__in int iCol, __in const LPLVCOLUMNW pcol);
int InsertItem(__in int iItem, __in PCSTR pszText,
__in int iImage = I_IMAGENONE, __in LPARAM lParam = 0);
int InsertItem(__in int iItem, __in PCWSTR pszText,
__in int iImage = I_IMAGENONE, __in LPARAM lParam = 0);
int InsertItem(__in const LPLVITEMA pitem);
int InsertItem(__in const LPLVITEMW pitem);
BOOL SetCallbackMask(__in UINT mask);
void SetCheckState(__in UINT iIndex, __in BOOL fCheck);
BOOL SetColumnWidth(__in int iCol, __in int cx);
void SetExtendedListViewStyle(__in DWORD dwExMask, __in DWORD dwExStyle);
HIMAGELIST SetImageList(__in HIMAGELIST hImageList, __in int iImageList);
BOOL SetItem(const LPLVITEMA pitem);
BOOL SetItem(const LPLVITEMW pitem);
BOOL SetItemData(__in int iItem, LPARAM lParam);
void SetItemState(__in int i, __in UINT state, __in UINT mask);
void SetItemText(__in int i, __in int iSubItem, __in PCSTR pszText);
void SetItemText(__in int i, __in int iSubItem, __in PCWSTR pszText);
int SetSelectionMark(__in int iIndex);
BOOL SortItems(__in PFNLVCOMPARE pfnCompare, __in LPARAM lParamSort);
BOOL Update(__in int iItem);
};
/**
* \class LMonthCal
* \brief 日历控件类
*/
class LMonthCal : public LComCtl
{
public:
LMonthCal(__in HWND hWnd = NULL);
LMonthCal& operator=(__in HWND hWnd);
public:
BOOL GetCurSel(__in LPSYSTEMTIME lpSysTime);
};
/**
* \class LProgressBar
* \brief 进度条控件类
*/
class LProgressBar : public LComCtl
{
public:
LProgressBar& operator=(__in HWND hWnd);
public:
int GetStep(void);
UINT GetPos(void);
int SetPos(__in int nPos);
void SetRange32(__in int nLower, __in int nUpper);
int SetStep(__in int nStepInc);
int StepIt(void);
};
/**
* \class LPropSheet
* \brief 属性表控件类
*/
class LPropSheet;
class LPropSheetPage : protected LDialog
{
friend class LPropSheet;
public:
LPropSheetPage(__in UINT idPage);
~LPropSheetPage(void);
public:
BOOL Create(__in DWORD dwFlags, __in PCSTR pszTitle, __in LPARAM lParam,
__in LPFNPSPCALLBACKA pfnCallback);
BOOL Create(__in DWORD dwFlags, __in PCWSTR pszTitle, __in LPARAM lParam,
__in LPFNPSPCALLBACKW pfnCallback);
protected:
LPropSheet* GetParentSheet(void);
private:
HPROPSHEETPAGE m_hPropPage;
LPropSheet* m_pParent;
};
/**
* \class LPropSheetPage
* \brief 属性页控件类
*/
typedef struct ThunkPS *PTHUNKPS;
#define PROPSHEET_CENTERWINDOW 0x00000001
class LPropSheet : public LComCtl
{
public:
LPropSheet(__in int nMaxCnt = 1);
~LPropSheet(void);
public:
BOOL AddPage(__in LPropSheetPage* page);
BOOL AddPage(__in HPROPSHEETPAGE hPage);
int DoModal(__in HWND hParent, __in PCSTR pszCaption);
int DoModal(__in HWND hParent, __in PCWSTR pszCaption);
DWORD SetFlags(__in DWORD dwNewFlags);
void SetWizButtons(__in DWORD dwFlags);
void ShowWizButtons(__in DWORD dwFlag, __in DWORD dwButton);
protected:
virtual void OnMessage(UINT uMsg, LPARAM lParam);
private:
void InitThunk(void);
static int CALLBACK StartProc(LPropSheet* pThis, UINT uMsg, LPARAM lParam);
protected:
DWORD m_dwFlags;
HPROPSHEETPAGE* m_hPages;
int m_nPageCnt;
int m_nMaxCnt;
private:
PTHUNKPS m_thunk;
};
/**
* \class LReBar
* \brief ReBar 控件类
*/
class LReBar : public LComCtl
{
public:
BOOL Create(__in DWORD dwStyle, __in HWND hWndParent, __in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in DWORD dwStyle,
__in HWND hWndParent, __in UINT nID);
static int SizeOfREBARBANDINFO(void);
BOOL InsertBand(__in UINT ulIndex, __in LPREBARBANDINFOA lpRbbi);
BOOL InsertBand(__in UINT ulIndex, __in LPREBARBANDINFOW lpRbbi);
BOOL SetBarInfo(__in LPREBARINFO lpRbi);
};
/**
* \class LStatusBar
* \brief 状态栏控件类
*/
class LStatusBar : public LComCtl
{
public:
BOOL Create(__in HWND hParent, __in PCSTR lpszWindowName,
__in DWORD dwStyle, __in UINT nID);
BOOL Create(__in HWND hParent, __in PCWSTR lpszWindowName,
__in DWORD dwStyle, __in UINT nID);
BOOL GetRect(__in int nPart, __out LPRECT lprc);
BOOL SetParts(__in int nParts, __in LPINT aWidths);
BOOL SetText(__in int nPart, __in PCSTR lpszText,
__in_opt int nType);
BOOL SetText(__in int nPart, __in PCWSTR lpszText,
__in_opt int nType);
};
/**
* \class LTabCtrl
* \brief 标签控件类
*/
class LTabCtrl : public LComCtl
{
public:
LTabCtrl(__in HWND hWnd = NULL);
LTabCtrl& operator=(__in HWND hWnd);
operator HWND(void) const { return m_hWnd; }
public:
void AdjustRect(__in BOOL fLarger, __inout LPRECT prc);
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT nID);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT nID);
BOOL DeleteAllItems(void);
BOOL DeleteItem(__in int iItem);
int GetCurSel(void);
BOOL GetItem(__in int iItem, __out LPTCITEMA pitem);
BOOL GetItem(__in int iItem, __out LPTCITEMW pitem);
int GetItemCount(void);
HWND GetToolTips(void);
int HitTest(__inout LPTCHITTESTINFO pinfo);
int InsertItem(__in int iItem, __in const LPTCITEMA pitem);
int InsertItem(__in int iItem, __in const LPTCITEMW pitem);
int InsertItem(__in int iItem, __in PCSTR lpszItem,
__in int nImage = I_IMAGENONE, __in LPARAM lParam = 0);
int InsertItem(__in int iItem, __in PCWSTR lpszItem,
__in int nImage = I_IMAGENONE, __in LPARAM lParam = 0);
int SetCurSel(__in int iItem);
HIMAGELIST SetImageList(__in HIMAGELIST himl);
BOOL SetItem(__in int iItem, __in LPTCITEMA pitem);
BOOL SetItem(__in int iItem, __in LPTCITEMW pitem);
};
/**
* \class LToolBar
* \brief 工具栏控件类
*/
#ifdef UNICODE
#define TbUnicode TRUE
#else // !UNICODE
#define TbUnicode FALSE
#endif // UNICODE
class LToolBar : public LComCtl
{
public:
LToolBar(__in HWND hWnd = NULL);
operator HWND(void) const { return m_hWnd; }
public:
BOOL Create(__in DWORD dwStyle, __in HWND hWndParent, __in UINT nID);
BOOL AddButtons(__in UINT uNumButtons, __in LPCTBBUTTON lpButtons,
__in BOOL bUnicode = TbUnicode);
int AddString(__in PCSTR lpString);
int AddString(__in PCWSTR lpString);
void AutoSize(void);
void ButtonStructSize(__in int cb);
BOOL EnableButton(__in int idButton, __in BOOL fEnable);
HIMAGELIST SetImageList(__in HIMAGELIST himl);
};
/**
* \class LToolTip
* \brief 工具提示控件类
*/
class LToolTip : public LComCtl
{
public:
LToolTip(__in HWND hWnd = NULL);
operator HWND(void) const { return m_hWnd; }
public:
BOOL Create(__in DWORD dwStyle, __in HWND hWndParent);
void Activate(__in BOOL fActivate = TRUE);
BOOL AddTool(__in LPTOOLINFOA pti);
BOOL AddTool(__in LPTOOLINFOW pti);
void DelTool(__in HWND hwnd, __in UINT uId);
void Pop(void);
void Popup(void);
void SetToolInfo(__in LPTOOLINFOA pti);
void SetToolInfo(__in LPTOOLINFOW pti);
};
/**
* \class LTrackBar
* \brief 滑动条控件类
*/
class LTrackBar : public LComCtl
{
public:
LTrackBar& operator=(__in HWND hWnd);
public:
void SetRange(__in int nMin, __in int nMax,
__in BOOL bRedraw = FALSE);
};
/**
* \class LTreeView
* \brief 树形视图类
*/
class LTreeView : public LComCtl
{
public:
LTreeView(__in HWND hWnd = NULL);
LTreeView& operator=(__in HWND hWnd);
operator HWND(void) const;
public:
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL Create(__in PCSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT id);
BOOL Create(__in PCWSTR lpWindowName, __in DWORD dwStyle,
__in int x, __in int y, __in int nWidth, __in int nHeight,
__in HWND hWndParent, __in UINT id);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in LPCRECT lpRect, __in HWND hWndParent,
__in UINT nID);
BOOL CreateEx(__in DWORD dwExStyle, __in PCSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT id);
BOOL CreateEx(__in DWORD dwExStyle, __in PCWSTR lpWindowName,
__in DWORD dwStyle, __in int X, __in int Y,
__in int nWidth, __in int nHeight, __in HWND hWndParent,
__in UINT id);
BOOL DeleteAllItems(void);
BOOL DeleteItem(__in HTREEITEM hItem);
HWND EditLabel(__in HTREEITEM hItem);
BOOL Expand(__in HTREEITEM hItem, __in UINT flag);
void ExpandAll(__in HTREEITEM hItem);
HTREEITEM GetDropHilight(void);
HWND GetEditControl(void);
BOOL GetItem(__inout LPTVITEMA pitem);
BOOL GetItem(__inout LPTVITEMW pitem);
BOOL GetItemRect(__in HTREEITEM hitem, __out LPRECT prc,
__in BOOL fItemRect);
UINT GetItemState(__in HTREEITEM hItem, __in UINT stateMask);
HTREEITEM GetNextItem(__in HTREEITEM hItem, __in UINT uFlag);
HTREEITEM GetSelection(void);
HTREEITEM HitTest(__inout LPTVHITTESTINFO lpht);
HTREEITEM InsertItem(__in HTREEITEM hParent, __in HTREEITEM hInsertAfter,
__in PCSTR lpszItem, __in int nImage = I_IMAGENONE,
__in int nSelImage = I_IMAGENONE, __in LPARAM lParam = 0);
HTREEITEM InsertItem(__in HTREEITEM hParent, __in HTREEITEM hInsertAfter,
__in PCWSTR lpszItem, __in int nImage = I_IMAGENONE,
__in int nSelImage = I_IMAGENONE, __in LPARAM lParam = 0);
HTREEITEM InsertItem(__in LPTVINSERTSTRUCTA lpis);
HTREEITEM InsertItem(__in LPTVINSERTSTRUCTW lpis);
BOOL SelectItem(__in HTREEITEM hItem);
HIMAGELIST SetImageList(__in HIMAGELIST himl, __in int iImage);
BOOL SetItem(__in LPTVITEMA pItem);
BOOL SetItem(__in LPTVITEMW pItem);
BOOL SortChildrenCB(__in LPTVSORTCB psort, BOOL fRecurse);
protected:
void SetChildState(__in HTREEITEM hParent, __in BOOL bHasChild);
};
/**
* \class LUpDown
* \brief 微调控件类
*/
class LUpDown : public LComCtl
{
public:
LUpDown(__in HWND hWnd = NULL);
LUpDown& operator=(__in HWND hWnd);
public:
HWND SetBuddy(__in HWND hwndBuddy);
short SetPos(__in short nPos);
int SetPos32(__in int nPos);
void SetRange(__in short nLower, __in short nUpper );
void SetRange32(__in int iLow, __in int iHigh);
};
| [
"titilima@89554c5a-91f9-11de-87e2-8d177609176d"
]
| [
[
[
1,
601
]
]
]
|
f9c2ba016fcc53bbcef9480c7d9c75012e66103e | 4c3c35e4fe1ff2567ef20f0b203fe101a4a2bf20 | /HW3/src/GzCommon.h | f0ea0d14da30bd3a217ed1c8175bcc86f7d9d70f | []
| no_license | kolebole/monopolocoso | 63c0986707728522650bd2704a5491d1da20ecf7 | a86c0814f5da2f05e7676b2e41f6858d87077e6a | refs/heads/master | 2021-01-19T15:04:09.283953 | 2011-03-27T23:21:53 | 2011-03-27T23:21:53 | 34,309,551 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,890 | h | #ifndef __GZ_COMMON_H_
#define __GZ_COMMON_H_
#include <vector>
using namespace std;
//Self decleration
const double PI = 3.141592;
//============================================================================
//Declarations in Assignment #1
//============================================================================
//Common data type------------------------------------------------------------
typedef int GzInt;
typedef bool GzBool;
typedef double GzReal;
typedef unsigned int GzFunctional;
typedef unsigned int GzPrimitiveType;
typedef unsigned int GzMatrixModeType;
//----------------------------------------------------------------------------
//Funtional constants---------------------------------------------------------
#define GZ_DEPTH_TEST 0x00000001
#define GZ_COLOR_BUFFER 0x00000002
#define GZ_DEPTH_BUFFER 0x00000004
//----------------------------------------------------------------------------
//Primitive types-------------------------------------------------------------
#define GZ_POINTS 0
//----------------------------------------------------------------------------
//3D coordinate data type-----------------------------------------------------
#define X 0
#define Y 1
#define Z 2
struct GzVertex:public vector<GzReal> {
GzVertex():vector<GzReal>(3, 0) {}
GzVertex(GzReal x, GzReal y, GzReal z):vector<GzReal>(3, 0) {
at(X)=x; at(Y)=y; at(Z)=z;
}
};
//----------------------------------------------------------------------------
//Color data type-------------------------------------------------------------
#define R 0
#define G 1
#define B 2
#define A 3
#include <iostream>
using namespace std;
struct GzColor:public vector<GzReal> {
GzColor():vector<GzReal>(4, 0) {at(A)=1;}
GzColor(GzReal r, GzReal g, GzReal b):vector<GzReal>(4, 0) {
at(R)=r; at(G)=g; at(B)=b; at(A)=1;
}
GzColor(GzReal r, GzReal g, GzReal b, GzReal a):vector<GzReal>(4, 0) {
at(R)=r; at(G)=g; at(B)=b; at(A)=a;
}
};
//----------------------------------------------------------------------------
//============================================================================
//End of Declarations in Assignment #1
//============================================================================
//============================================================================
//Declarations in Assignment #2
//============================================================================
//Primitive types-------------------------------------------------------------
#define GZ_TRIANGLES 1
//----------------------------------------------------------------------------
//============================================================================
//End of Declarations in Assignment #2
//============================================================================
#endif
| [
"chuminhtri@a7811d78-34aa-4512-2aaf-9c23cbf1bc95"
]
| [
[
[
1,
86
]
]
]
|
7a1291015a7e848ced74bc648f1b812944a8eaf4 | eb0b8f9d3bb244ad033c052041b8189e0c1ac461 | /iPhoneAugmentedVideo/Classes/NyARToolkitCPP-2.5.4/src/core/NyARRgbRaster.cpp | 63323ce28cd8b1770486d9c530ca5627f8be3ab8 | []
| no_license | nickthedude/iPhone-Stuff | 66bacc8eb89238b3f2852bb821348ecdad6fc590 | b85111dec18a4fbd98f81240f37bd5b5b8efe141 | refs/heads/master | 2021-01-01T17:16:30.540264 | 2010-12-14T17:07:19 | 2010-12-14T17:07:19 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,631 | cpp | /*
* PROJECT: NyARToolkitCPP
* --------------------------------------------------------------------------------
*
* The NyARToolkitCPP is C++ version NyARToolkit class library.
* Copyright (C)2008-2009 Ryo Iizuka
*
* 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/>.
*
* For further information please contact.
* http://nyatla.jp/nyatoolkit/
* <airmail(at)ebony.plala.or.jp> or <nyatla(at)nyatla.jp>
*
*/
#include "NyARRgbRaster.h"
#include "nyarcore.h"
#include "NyARRgbPixelReader_INT1D_X8R8G8B8_32.h"
#include "NyARRgbPixelReader_BYTE1D_B8G8R8X8_32.h"
#include "NyARRgbPixelReader_BYTE1D_R8G8B8_24.h"
#include <iostream>
using namespace std;
namespace NyARToolkitCPP
{
NyARRgbRaster::NyARRgbRaster(int i_width, int i_height,int i_raster_type,bool i_is_alloc)
:NyARRgbRaster_BasicClass(i_width,i_height,i_raster_type)
{
if(!initInstance(this->_size,i_raster_type,i_is_alloc)){
throw NyARException();
}
}
/**
*
* @param i_width
* @param i_height
* @param i_raster_type
* NyARBufferTypeに定義された定数値を指定してください。
* @throws NyARException
*/
NyARRgbRaster::NyARRgbRaster(int i_width, int i_height,int i_raster_type)
:NyARRgbRaster_BasicClass(i_width,i_height,i_raster_type)
{
if(!initInstance(this->_size,i_raster_type,true)){
throw NyARException();
}
}
NyARRgbRaster::~NyARRgbRaster()
{
NyAR_SAFE_DELETE(this->_reader);
if(this->_is_attached_buffer){
NyAR_SAFE_FREE(this->_buf);
}
}
bool NyARRgbRaster::initInstance(const TNyARIntSize& i_size,int i_raster_type,bool i_is_alloc)
{
switch(i_raster_type)
{
case NyARBufferType::INT1D_X8R8G8B8_32:
this->_buf=i_is_alloc?NyAR_MALLOC(sizeof(int)*i_size.w*i_size.h):NULL;
this->_reader=new NyARRgbPixelReader_INT1D_X8R8G8B8_32(&i_size,(int*)this->_buf);
break;
case NyARBufferType::BYTE1D_B8G8R8X8_32:
this->_buf=i_is_alloc?NyAR_MALLOC(sizeof(NyAR_BYTE_t)*i_size.w*i_size.h*4):NULL;
this->_reader=new NyARRgbPixelReader_BYTE1D_B8G8R8X8_32(&i_size,(NyAR_BYTE_t*)this->_buf);
break;
case NyARBufferType::BYTE1D_R8G8B8_24:
this->_buf=i_is_alloc?NyAR_MALLOC(sizeof(NyAR_BYTE_t)*i_size.w*i_size.h*3):NULL;
this->_reader=new NyARRgbPixelReader_BYTE1D_R8G8B8_24(&i_size,(NyAR_BYTE_t*)this->_buf);
break;
default:
return false;
}
this->_is_attached_buffer=i_is_alloc;
return true;
}
INyARRgbPixelReader& NyARRgbRaster::getRgbPixelReader()const
{
return *this->_reader;
}
void* NyARRgbRaster::getBuffer()const
{
return this->_buf;
}
bool NyARRgbRaster::hasBuffer()const
{
return this->_buf!=NULL;
}
void NyARRgbRaster::wrapBuffer(void* i_ref_buf)
{
NyAR_ASSERT(!this->_is_attached_buffer);//バッファがアタッチされていたら機能しない。
this->_buf=i_ref_buf;
//ピクセルリーダーの参照バッファを切り替える。
this->_reader->switchBuffer(i_ref_buf);
}
}
| [
"[email protected]"
]
| [
[
[
1,
118
]
]
]
|
21f301dea4eb3d9bcd8e3b9364f4b5754f1486d5 | 1bedffb06790d8e001e78e970fc290234550ed67 | /VotePlugin/Helpers.h | a0d5024c7e52c99d19fba01cb85cf2f061c2f28d | []
| no_license | mRB0/lazyslash | e14e2a7769b466555848548aee0d1d522da8ff9e | 52e06cf64cca5726b30d2f74b2c3392114f59dd9 | refs/heads/master | 2021-01-21T12:46:55.957672 | 2010-03-24T06:58:52 | 2010-03-24T06:58:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,912 | h | #pragma once
using namespace System;
namespace VotePlugin {
public ref class EntryFilenameComparer : public System::Collections::IComparer
{
public:
virtual int Compare(Object^ left, Object^ right)
{
return String::Compare( ((VotePlugin::Entry^)left)->filename, ((VotePlugin::Entry^)right)->filename );
}
};
public ref class EntryAuthorComparer : public System::Collections::IComparer
{
public:
virtual int Compare(Object^ left, Object^ right)
{
return String::Compare( ((VotePlugin::Entry^)left)->author, ((VotePlugin::Entry^)right)->author );
}
};
public ref class EntryTitleComparer : public System::Collections::IComparer
{
public:
virtual int Compare(Object^ left, Object^ right)
{
return String::Compare( ((VotePlugin::Entry^)left)->songtitle, ((VotePlugin::Entry^)right)->songtitle );
}
};
public ref class Helpers
{
public:
/*
* votes: In-order ArrayList^ of String^ items (voted filenames)
* entry_list: ArrayList^ of all Entry^ items
*
* Return: In-order ArrayList^ of voted-for Entry^ items
*/
static System::Collections::ArrayList^ votestrings_to_entries(System::Collections::ArrayList^ votes, System::Collections::ArrayList^ entry_list)
{
System::Collections::ArrayList^ vote_entries = gcnew System::Collections::ArrayList;
// for each String^ in votes,
// find an entry_list[...]->Entry with a matching filename,
// and stuff it into vote_entries
entry_list->Sort(gcnew EntryFilenameComparer);
for each(String^ vote in votes)
{
VotePlugin::Entry ve(L"", vote, L"");
int idx = entry_list->BinarySearch(%ve, gcnew EntryFilenameComparer);
if (idx < 0)
{
throw gcnew System::IndexOutOfRangeException(L"Entry not in entry_list");
}
vote_entries->Add(entry_list[idx]);
}
return vote_entries;
}
static int levenshtein(String^ s, String^ t)
{
s = s->ToLower();
t = t->ToLower();
// d is a table with m+1 rows and n+1 columns
array<int,2>^ d = gcnew array<int,2>(s->Length+1, t->Length+1);
int i, j;
for (i=0; i < s->Length+1; i++)
{
d[i, 0] = i; // deletion
}
for (j=0; j < t->Length+1; j++)
{
d[0, j] = j; // insertion
}
for (j=1; j < t->Length+1; j++)
{
for (i=1; i < s->Length+1; i++)
{
if (s[i-1] == t[j-1])
{
d[i, j] = d[i-1, j-1];
}
else
{
int del = d[i-1, j] + 1; // deletion
int ins = d[i, j-1] + 1; // insertion
int sub = d[i-1, j-1] + 1; // substitution
if (del < ins && del < sub)
{
d[i, j] = del;
}
else if (ins < sub)
{
d[i, j] = ins;
}
else
{
d[i, j] = sub;
}
}
}
}
return d[s->Length, t->Length];
}
};
}
| [
"[email protected]"
]
| [
[
[
1,
123
]
]
]
|
a3b56fe5e1ebfd16c32225797c6046207df81303 | 5bbdc0c6e34ce0f6273d6844840c1108895c083b | /NS2Torrent/stdafx.cpp | 5c7d312242b892e9b99f29135b85e0475f58c3a4 | []
| no_license | tsuckow/ns2torrent | 7e6622a8f99cdf2cc944d4f5e636818c754c3775 | c3ae6e257dc3647272846f5fd3c898337ed67480 | refs/heads/master | 2016-09-06T10:03:54.740731 | 2011-01-24T07:32:50 | 2011-01-24T07:32:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 300 | cpp | // stdafx.cpp : source file that includes just the standard includes
// TestLuaModule.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"tsuckow"
]
| [
[
[
1,
8
]
]
]
|
ebe0bc80e8bcda91f2652b8702325f1674375e96 | a130af41d59ddcd489281db39243befba692837c | /balancesimulator2.h | bee6259f30ed9dacfb5f48df88155dca5b4b8cc0 | []
| no_license | dragly/NeuralNetwork | 4066ae1ecb6eff8cd17f24c3d878a2cc6edfbff1 | 802abee9ae68bfd0449dec79333b18dbfb795099 | refs/heads/master | 2016-09-10T00:42:41.264609 | 2011-12-28T22:17:21 | 2011-12-28T22:17:21 | 3,016,437 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | h | #ifndef BALANCESIMULATOR2_H
#define BALANCESIMULATOR2_H
#include "physicssimulatorabstract.h"
class BalanceSimulator2 : public PhysicsSimulatorAbstract
{
Q_OBJECT
public:
BalanceSimulator2(QObject *parent);
double *parameters();
int advance(double *parameters);
void reset();
void refreshView();
private:
QGraphicsScene *simulatorScene;
QGraphicsItem *line;
QTimer *timer;
double lineAngularVelocity;
double rotation;
double position;
double velocity;
int counter;
int firstRun; //one run at each side
};
#endif // BALANCESIMULATOR2_H
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
20
],
[
23,
29
]
],
[
[
21,
22
]
]
]
|
da1b934d3e9190dcab2f33c6802818fa2a206f28 | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /common/test/tester.cpp | dfb354558ee34324b1dfe782332e9cc8611a73f5 | [
"MIT"
]
| permissive | ysei/Hayat | 74cc1e281ae6772b2a05bbeccfcf430215cb435b | b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0 | refs/heads/master | 2020-12-11T09:07:35.606061 | 2011-08-01T12:38:39 | 2011-08-01T12:38:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | /* -*- coding: sjis-dos; -*- */
#include <cppunit/ui/text/TestRunner.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
const char** HMD_LOADPATH = {
NULL
};
int main(int argc, char* argv[])
{
CppUnit::TextUi::TestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
CppUnit::Outputter* outputter =
new CppUnit::CompilerOutputter(&runner.result(),std::cout);
runner.setOutputter(outputter);
int result = runner.run() ? 0 : 1;
return result;
}
| [
"[email protected]"
]
| [
[
[
1,
23
]
]
]
|
e041126d4cabd71b8fb35cc930428b06f41c75b7 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/tlclasses/_CUnknownStruct1.h | 8c21c8b88c6a7edd3df5e1f54c3d757dca08dc08 | []
| no_license | drivehappy/tlapi | d10bb75f47773e381e3ba59206ff50889de7e66a | 56607a0243bd9d2f0d6fb853cddc4fce3e7e0eb9 | refs/heads/master | 2021-03-19T07:10:57.343889 | 2011-04-18T22:58:29 | 2011-04-18T22:58:29 | 32,191,364 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 246 | h | #pragma once
namespace TLAPI
{
#pragma pack(1)
// Size: Unknown
// Note: Tied to CAstarPathFinder & CUnknownStruct0
struct CUnknownStruct1
{
// Alternating 1s, 0s...
u8 unk0[800];
};
#pragma pack()
};
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
]
| [
[
[
1,
18
]
]
]
|
1711dfbbb6462db5c6e160ff20bb116519031739 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/weak_ptr.hpp | 472e5687fcfedbd2c3077fae11171c57fc88bcad | [
"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 | 4,523 | hpp | #ifndef BOOST_WEAK_PTR_HPP_INCLUDED
#define BOOST_WEAK_PTR_HPP_INCLUDED
//
// weak_ptr.hpp
//
// Copyright (c) 2001, 2002, 2003 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/smart_ptr/weak_ptr.htm for documentation.
//
#include <memory> // boost.TR1 include order fix
#include <boost/detail/shared_count.hpp>
#include <boost/shared_ptr.hpp>
#ifdef BOOST_MSVC // moved here to work around VC++ compiler crash
# pragma warning(push)
# pragma warning(disable:4284) // odd return type for operator->
#endif
namespace boost
{
template<class T> class weak_ptr
{
private:
// Borland 5.5.1 specific workarounds
typedef weak_ptr<T> this_type;
public:
typedef T element_type;
weak_ptr(): px(0), pn() // never throws in 1.30+
{
}
// generated copy constructor, assignment, destructor are fine
//
// The "obvious" converting constructor implementation:
//
// template<class Y>
// weak_ptr(weak_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws
// {
// }
//
// has a serious problem.
//
// r.px may already have been invalidated. The px(r.px)
// conversion may require access to *r.px (virtual inheritance).
//
// It is not possible to avoid spurious access violations since
// in multithreaded programs r.px may be invalidated at any point.
//
template<class Y>
weak_ptr(weak_ptr<Y> const & r): pn(r.pn) // never throws
{
px = r.lock().get();
}
template<class Y>
weak_ptr(shared_ptr<Y> const & r): px(r.px), pn(r.pn) // never throws
{
}
#if !defined(BOOST_MSVC) || (BOOST_MSVC >= 1300)
template<class Y>
weak_ptr & operator=(weak_ptr<Y> const & r) // never throws
{
px = r.lock().get();
pn = r.pn;
return *this;
}
template<class Y>
weak_ptr & operator=(shared_ptr<Y> const & r) // never throws
{
px = r.px;
pn = r.pn;
return *this;
}
#endif
shared_ptr<T> lock() const // never throws
{
#if defined(BOOST_HAS_THREADS)
// optimization: avoid throw overhead
if(expired())
{
return shared_ptr<element_type>();
}
try
{
return shared_ptr<element_type>(*this);
}
catch(bad_weak_ptr const &)
{
// Q: how can we get here?
// A: another thread may have invalidated r after the use_count test above.
return shared_ptr<element_type>();
}
#else
// optimization: avoid try/catch overhead when single threaded
return expired()? shared_ptr<element_type>(): shared_ptr<element_type>(*this);
#endif
}
long use_count() const // never throws
{
return pn.use_count();
}
bool expired() const // never throws
{
return pn.use_count() == 0;
}
void reset() // never throws in 1.30+
{
this_type().swap(*this);
}
void swap(this_type & other) // never throws
{
std::swap(px, other.px);
pn.swap(other.pn);
}
void _internal_assign(T * px2, boost::detail::shared_count const & pn2)
{
px = px2;
pn = pn2;
}
template<class Y> bool _internal_less(weak_ptr<Y> const & rhs) const
{
return pn < rhs.pn;
}
// Tasteless as this may seem, making all members public allows member templates
// to work in the absence of member template friends. (Matthew Langston)
#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
private:
template<class Y> friend class weak_ptr;
template<class Y> friend class shared_ptr;
#endif
T * px; // contained pointer
boost::detail::weak_count pn; // reference counter
}; // weak_ptr
template<class T, class U> inline bool operator<(weak_ptr<T> const & a, weak_ptr<U> const & b)
{
return a._internal_less(b);
}
template<class T> void swap(weak_ptr<T> & a, weak_ptr<T> & b)
{
a.swap(b);
}
// deprecated, provided for backward compatibility
template<class T> shared_ptr<T> make_shared(weak_ptr<T> const & r)
{
return r.lock();
}
} // namespace boost
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
#endif // #ifndef BOOST_WEAK_PTR_HPP_INCLUDED
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
194
]
]
]
|
34d6a311d4f77141d92cac5ecdbb3ed1a044e0f1 | 0841b965ef16edab738c260e2bb46dec5a44857d | /bitmaploader/source/bitmaploader.cpp | 4914bdd205678d2798063d7617717e23a8d19084 | []
| no_license | ant512/WoopsiExtras | b73e399ebb3bd7685587e7e8b6051d336989354a | 45ea469a22827b737a361b5a5f73cbeffe2974c3 | refs/heads/master | 2021-01-08T22:13:16.196976 | 2010-09-03T08:28:31 | 2010-09-03T08:28:31 | 242,157,454 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,367 | cpp | // Includes
#include "bitmaploader.h"
#include "amigascreen.h"
#include "amigawindow.h"
#include "superbitmap.h"
#include "bitmapio.h"
#include "bitmap.h"
void BitmapLoader::startup() {
// Call base startup method
Woopsi::startup();
// Create screen
AmigaScreen* screen = new AmigaScreen("BMP Loader Screen", Gadget::GADGET_DRAGGABLE, AmigaScreen::AMIGA_SCREEN_SHOW_DEPTH | AmigaScreen::AMIGA_SCREEN_SHOW_FLIP);
woopsiApplication->addGadget(screen);
// Add window
AmigaWindow* window = new AmigaWindow(0, 13, 256, 179, "BMP Loader Window", Gadget::GADGET_DRAGGABLE, AmigaWindow::AMIGA_WINDOW_SHOW_CLOSE | AmigaWindow::AMIGA_WINDOW_SHOW_DEPTH);
screen->addGadget(window);
// Get available area within window
Rect rect;
window->getClientRect(rect);
if (fatInitDefault()) {
// Create a superbitmap that we will use to draw to
SuperBitmap* superBitmap = new SuperBitmap(rect.x, rect.y, rect.width, rect.height, 256, 192, false);
window->addGadget(superBitmap);
// Load a 16-bit BMP in 555 format with a V3 DIB header
Bitmap* bitmap = BitmapIO::loadBMP("/logo16_v3.bmp");
// Draw the bitmap to the superbitmap
superBitmap->getGraphics()->drawBitmap(0, 0, bitmap->getWidth(), bitmap->getHeight(), bitmap, 0, 0);
// Delete the bitmap now we no longer need it
delete bitmap;
// Load a 16-bit BMP in 555 format with a V4 DIB header
bitmap = BitmapIO::loadBMP("/logo16_v4.bmp");
superBitmap->getGraphics()->drawBitmap(bitmap->getWidth(), 0, bitmap->getWidth(), bitmap->getHeight(), bitmap, 0, 0);
delete bitmap;
// Load a 24-bit BMP with a V3 DIB header
bitmap = BitmapIO::loadBMP("/logo24_v3.bmp");
superBitmap->getGraphics()->drawBitmap(bitmap->getWidth() * 2, 0, bitmap->getWidth(), bitmap->getHeight(), bitmap, 0, 0);
delete bitmap;
// Load a 24-bit BMP with a V4 DIB header
bitmap = BitmapIO::loadBMP("/logo24_v4.bmp");
superBitmap->getGraphics()->drawBitmap(bitmap->getWidth() * 3, 0, bitmap->getWidth(), bitmap->getHeight(), bitmap, 0, 0);
delete bitmap;
// Save the bitmap
BitmapIO::saveBMP("/bitmaploader.bmp", superBitmap->getBitmap());
}
// Ensure Woopsi can draw itself
enableDrawing();
// Draw GUI
redraw();
}
void BitmapLoader::shutdown() {
// Call base shutdown method
Woopsi::shutdown();
}
| [
"devnull@localhost"
]
| [
[
[
1,
71
]
]
]
|
2d53841c0cee681ae3a91217c78b400b1c4a80a7 | 110f8081090ba9591d295d617a55a674467d127e | /tests/Base64Test.cpp | f755379c8626175dc9fc277d69f84839bb2e9d7f | []
| no_license | rayfill/cpplib | 617bcf04368a2db70aea8b9418a45d7fd187d8c2 | bc37fbf0732141d0107dd93bcf5e0b31f0d078ca | refs/heads/master | 2021-01-25T03:49:26.965162 | 2011-07-17T15:19:11 | 2011-07-17T15:19:11 | 783,979 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,802 | cpp | #include <cppunit/extensions/HelperMacros.h>
#include <iostream>
#include <util/format/Base64.hpp>
#include <vector>
#include <algorithm>
class Base64Test : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE( Base64Test );
CPPUNIT_TEST(encodeTest);
CPPUNIT_TEST(encodeTest2);
CPPUNIT_TEST(decodeMapTest);
CPPUNIT_TEST(decodeTest);
CPPUNIT_TEST_SUITE_END();
public:
void decodeTest()
{
std::string base64encoded = "AAAAAAAAAAAAAA==";
std::vector<char> result = Base64::decode(base64encoded);
typedef std::vector<char>::size_type size_type;
CPPUNIT_ASSERT(result.size() == 10);
for (size_type i = 0; i < result.size(); ++i)
CPPUNIT_ASSERT(result[i] == 0);
/*
* 00000001 00000001 00000001
* 000000010000000100000001
* 000000 010000 000100 000001
* 0, 16, 4, 1
* 'A', 'A'+16, 'A'+4, 'A'+1
* 'A', 'Q', 'E', 'B'
*/
base64encoded = "AQEBAQEBAQEBAQ==";
result = Base64::decode(base64encoded);
CPPUNIT_ASSERT(result.size() == 10);
for (size_type i = 0; i < result.size(); ++i)
CPPUNIT_ASSERT(result[i] == 1);
base64encoded = "AQEBAQEBAQEBAQEB";
result = Base64::decode(base64encoded);
CPPUNIT_ASSERT(result.size() == 12);
for (size_type i = 0; i < result.size(); ++i)
CPPUNIT_ASSERT(result[i] == 1);
base64encoded = "";
result = Base64::decode(base64encoded);
CPPUNIT_ASSERT(result.size() == 0);
}
void decodeMapTest()
{
const char* reverseTable = Base64::getFromBase64Table();
CPPUNIT_ASSERT(reverseTable['A'] == 0);
CPPUNIT_ASSERT(reverseTable['B'] == 1);
CPPUNIT_ASSERT(reverseTable['C'] == 2);
CPPUNIT_ASSERT(reverseTable['D'] == 3);
CPPUNIT_ASSERT(reverseTable['E'] == 4);
CPPUNIT_ASSERT(reverseTable['F'] == 5);
CPPUNIT_ASSERT(reverseTable['G'] == 6);
CPPUNIT_ASSERT(reverseTable['H'] == 7);
CPPUNIT_ASSERT(reverseTable['I'] == 8);
CPPUNIT_ASSERT(reverseTable['J'] == 9);
CPPUNIT_ASSERT(reverseTable['K'] == 10);
CPPUNIT_ASSERT(reverseTable['L'] == 11);
CPPUNIT_ASSERT(reverseTable['M'] == 12);
CPPUNIT_ASSERT(reverseTable['N'] == 13);
CPPUNIT_ASSERT(reverseTable['O'] == 14);
CPPUNIT_ASSERT(reverseTable['P'] == 15);
CPPUNIT_ASSERT(reverseTable['Q'] == 16);
CPPUNIT_ASSERT(reverseTable['R'] == 17);
CPPUNIT_ASSERT(reverseTable['S'] == 18);
CPPUNIT_ASSERT(reverseTable['T'] == 19);
CPPUNIT_ASSERT(reverseTable['U'] == 20);
CPPUNIT_ASSERT(reverseTable['V'] == 21);
CPPUNIT_ASSERT(reverseTable['W'] == 22);
CPPUNIT_ASSERT(reverseTable['X'] == 23);
CPPUNIT_ASSERT(reverseTable['Y'] == 24);
CPPUNIT_ASSERT(reverseTable['Z'] == 25);
CPPUNIT_ASSERT(reverseTable['a'] == 26);
CPPUNIT_ASSERT(reverseTable['b'] == 27);
CPPUNIT_ASSERT(reverseTable['c'] == 28);
CPPUNIT_ASSERT(reverseTable['d'] == 29);
CPPUNIT_ASSERT(reverseTable['e'] == 30);
CPPUNIT_ASSERT(reverseTable['f'] == 31);
CPPUNIT_ASSERT(reverseTable['g'] == 32);
CPPUNIT_ASSERT(reverseTable['h'] == 33);
CPPUNIT_ASSERT(reverseTable['i'] == 34);
CPPUNIT_ASSERT(reverseTable['j'] == 35);
CPPUNIT_ASSERT(reverseTable['k'] == 36);
CPPUNIT_ASSERT(reverseTable['l'] == 37);
CPPUNIT_ASSERT(reverseTable['m'] == 38);
CPPUNIT_ASSERT(reverseTable['n'] == 39);
CPPUNIT_ASSERT(reverseTable['o'] == 40);
CPPUNIT_ASSERT(reverseTable['p'] == 41);
CPPUNIT_ASSERT(reverseTable['q'] == 42);
CPPUNIT_ASSERT(reverseTable['r'] == 43);
CPPUNIT_ASSERT(reverseTable['s'] == 44);
CPPUNIT_ASSERT(reverseTable['t'] == 45);
CPPUNIT_ASSERT(reverseTable['u'] == 46);
CPPUNIT_ASSERT(reverseTable['v'] == 47);
CPPUNIT_ASSERT(reverseTable['w'] == 48);
CPPUNIT_ASSERT(reverseTable['x'] == 49);
CPPUNIT_ASSERT(reverseTable['y'] == 50);
CPPUNIT_ASSERT(reverseTable['z'] == 51);
CPPUNIT_ASSERT(reverseTable['0'] == 52);
CPPUNIT_ASSERT(reverseTable['1'] == 53);
CPPUNIT_ASSERT(reverseTable['2'] == 54);
CPPUNIT_ASSERT(reverseTable['3'] == 55);
CPPUNIT_ASSERT(reverseTable['4'] == 56);
CPPUNIT_ASSERT(reverseTable['5'] == 57);
CPPUNIT_ASSERT(reverseTable['6'] == 58);
CPPUNIT_ASSERT(reverseTable['7'] == 59);
CPPUNIT_ASSERT(reverseTable['8'] == 60);
CPPUNIT_ASSERT(reverseTable['9'] == 61);
CPPUNIT_ASSERT(reverseTable['+'] == 62);
CPPUNIT_ASSERT(reverseTable['/'] == 63);
}
void encodeTest2()
{
std::string str = "U034059:okazaki1";
std::string encoded = "VTAzNDA1OTpva2F6YWtpMQ";
CPPUNIT_ASSERT_MESSAGE(
Base64::encode(std::vector<char>(str.begin(), str.end()), false),
Base64::encode(std::vector<char>(str.begin(), str.end()), false)
== encoded);
}
void encodeTest()
{
std::vector<char> data(10);
std::string base64encoded = Base64::encode(data);
CPPUNIT_ASSERT(base64encoded.size() == 16);
CPPUNIT_ASSERT_MESSAGE(base64encoded,
base64encoded == "AAAAAAAAAAAAAA==");
/*
* 00000001 00000001 00000001
* 000000010000000100000001
* 000000 010000 000100 000001
* 0, 16, 4, 1
* 'A', 'A'+16, 'A'+4, 'A'+1
* 'A', 'Q', 'E', 'B'
*/
std::fill(data.begin(), data.end(), 1);
base64encoded = Base64::encode(data);
CPPUNIT_ASSERT(base64encoded.size() == 16);
CPPUNIT_ASSERT_MESSAGE(base64encoded,
base64encoded == "AQEBAQEBAQEBAQ==");
data.resize(12);
std::fill(data.begin(), data.end(), 1);
base64encoded = Base64::encode(data);
CPPUNIT_ASSERT(base64encoded.size() == 16);
CPPUNIT_ASSERT_MESSAGE(base64encoded,
base64encoded == "AQEBAQEBAQEBAQEB");
base64encoded = Base64::encode(std::vector<char>());
CPPUNIT_ASSERT(base64encoded.size() == 0);
CPPUNIT_ASSERT_MESSAGE(base64encoded,
base64encoded == "");
}
};
CPPUNIT_TEST_SUITE_REGISTRATION( Base64Test );
| [
"alfeim@287b3242-7fab-264f-8401-8509467ab285"
]
| [
[
[
1,
180
]
]
]
|
6210bef5d52e1a4e9095fac76bd99df217461daa | b7c505dcef43c0675fd89d428e45f3c2850b124f | /Src/SimulatorQt/Util/qt/Win32/include/QtGui/qproxymodel.h | 5392d4e771516365e1a1d3b5e004953f74074278 | [
"BSD-2-Clause"
]
| permissive | pranet/bhuman2009fork | 14e473bd6e5d30af9f1745311d689723bfc5cfdb | 82c1bd4485ae24043aa720a3aa7cb3e605b1a329 | refs/heads/master | 2021-01-15T17:55:37.058289 | 2010-02-28T13:52:56 | 2010-02-28T13:52:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,493 | h | /****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QPROXYMODEL_H
#define QPROXYMODEL_H
#include <QtCore/qabstractitemmodel.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
#ifndef QT_NO_PROXYMODEL
class QProxyModelPrivate;
class Q_GUI_EXPORT QProxyModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit QProxyModel(QObject *parent = 0);
~QProxyModel();
virtual void setModel(QAbstractItemModel *model);
QAbstractItemModel *model() const;
// implementing model interface
QModelIndex index(int row, int column, const QModelIndex &parent) const;
QModelIndex parent(const QModelIndex &child) const;
int rowCount(const QModelIndex &parent) const;
int columnCount(const QModelIndex &parent) const;
bool hasChildren(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
bool setData(const QModelIndex &index, const QVariant &value, int role);
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value,
int role);
QStringList mimeTypes() const;
QMimeData *mimeData(const QModelIndexList &indexes) const;
bool dropMimeData(const QMimeData *data, Qt::DropAction action,
int row, int column, const QModelIndex &parent);
Qt::DropActions supportedDropActions() const;
bool insertRows(int row, int count, const QModelIndex &parent);
bool insertColumns(int column, int count, const QModelIndex &parent);
void fetchMore(const QModelIndex &parent);
Qt::ItemFlags flags(const QModelIndex &index) const;
void sort(int column, Qt::SortOrder order);
QModelIndexList match(const QModelIndex &start, int role, const QVariant &value,
int hits, Qt::MatchFlags flags) const;
QSize span(const QModelIndex &index) const;
bool submit();
void revert();
#ifdef Q_NO_USING_KEYWORD
inline QObject *parent() const { return QObject::parent(); }
#else
using QObject::parent;
#endif
protected:
QProxyModel(QProxyModelPrivate &, QObject *parent = 0);
QModelIndex setProxyModel(const QModelIndex &source_index) const;
QModelIndex setSourceModel(const QModelIndex &proxy_index) const;
void connectToModel(const QAbstractItemModel *model) const;
void disconnectFromModel(const QAbstractItemModel *model) const;
private:
Q_DECLARE_PRIVATE(QProxyModel)
Q_DISABLE_COPY(QProxyModel)
Q_PRIVATE_SLOT(d_func(), void _q_sourceDataChanged(const QModelIndex&,const QModelIndex&))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeInserted(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsInserted(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsAboutToBeRemoved(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceRowsRemoved(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeInserted(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsInserted(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsAboutToBeRemoved(const QModelIndex&,int,int))
Q_PRIVATE_SLOT(d_func(), void _q_sourceColumnsRemoved(const QModelIndex&,int,int))
};
#endif // QT_NO_PROXYMODEL
QT_END_NAMESPACE
QT_END_HEADER
#endif // QPROXYMODEL_H
| [
"alon@rogue.(none)"
]
| [
[
[
1,
142
]
]
]
|
031424b57711bdc1f46feed311da1086afac8aea | 1493997bb11718d3c18c6632b6dd010535f742f5 | /battleship/test/main.cpp | 75c81c30e0ffa5a6433f721e609e889d77291406 | []
| no_license | kovrov/scrap | cd0cf2c98a62d5af6e4206a2cab7bb8e4560b168 | b0f38d95dd4acd89c832188265dece4d91383bbb | refs/heads/master | 2021-01-20T12:21:34.742007 | 2010-01-12T19:53:23 | 2010-01-12T19:53:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp | #ifdef _DEBUG
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <iostream>
#include <vector>
#include <map>
#include <exception>
#include <stdlib.h>
#include <time.h>
#include "../game/logic.h"
#include "../game/ai.h"
#include "../game/board.h"
#include <boost/foreach.hpp>
#define foreach BOOST_FOREACH
void print_sea(logic::Game& game, logic::PLAYER_HANDLE player_id, board::Pos& last_shot, board::SHOT res)
{
int rows = 10;
int side = rows * 2 + 1;
std::vector<char> grid(rows * side, ' ');
foreach (const board::Shot& shot, game.GetPlayerShots(player_id))
grid[shot.y * side + shot.x * 2 + 1] = '.';
foreach (const board::Ship& ship, game.GetOpponentShips(player_id))
{
foreach (const board::ShipSegment& segment, ship.segments)
grid[segment.pos.y * side + segment.pos.x * 2 + 1] = segment.active ? ' ' : 'x';
}
grid[last_shot.y * side + last_shot.x * 2] = '[';
grid[last_shot.y * side + last_shot.x * 2 + 2] = ']';
const char* padding = (player_id == 0) ? " |" : "";
for (int i=0; i < rows; i++)
{
std::cout << padding;
for (int j = i * side; j < (i + 1) * side; j++)
std::cout << grid[j];
std::cout << '\n';
}
std::cout << padding
<< " PLAYER_" << player_id << ' '
<< res << ' '
<< last_shot.x << ',' << last_shot.y << "\n\n";
}
void run()
{
logic::PLAYER_HANDLE PLAYER1 = 0;
logic::PLAYER_HANDLE PLAYER2 = 1;
logic::Game game(PLAYER1, PLAYER2);
std::map<logic::PLAYER_HANDLE, ai::ComputerPlayer> players;
std::map<logic::PLAYER_HANDLE, int> shots_made;
while (true)
{
logic::STATE state = game.GetState();
if (state == logic::BATTLE_STARTED)
{
game.Setup(PLAYER1, ai::setup_ships(10, game.GetConfig()));
game.Setup(PLAYER2, ai::setup_ships(10, game.GetConfig()));
players[PLAYER1] = ai::ComputerPlayer(10, game.GetConfig());
players[PLAYER2] = ai::ComputerPlayer(10, game.GetConfig());
shots_made[PLAYER1] = shots_made[PLAYER2] = 0;
}
else if (state == logic::PLAYER_TURN)
{
logic::PLAYER_HANDLE current_player_id = game.GetCurrentPlayer();
ai::ComputerPlayer& current_player = players[current_player_id];
board::Pos shot = current_player.Shot();
board::SHOT res = game.Shoot(current_player_id, shot);
current_player.Track(shot, res);
shots_made[current_player_id] += 1;
print_sea(game, current_player_id, shot, res);
}
else if (state == logic::BATTLE_ENDED)
{
printf("# BATTLE ENDED\n");
printf("%d win, shots made: %d\n", game.GetCurrentPlayer(), shots_made[game.GetCurrentPlayer()]);
break;
}
else
{
throw std::exception(); // unknown state
}
}
}
int main(int argc, char* argv[])
{
srand((unsigned)time(NULL));
run();
#ifdef _DEBUG
_CrtDumpMemoryLeaks();
#endif
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
101
]
]
]
|
17ba2eab8cdb1defc3153a173b9018432cc6d744 | d6eba554d0c3db3b2252ad34ffce74669fa49c58 | /Source/States/GameStates/gamePlayState.cpp | 8ab3232b62effb321ea38ffeebeb70ba889f5c63 | []
| no_license | nbucciarelli/Polarity-Shift | e7246af9b8c3eb4aa0e6aaa41b17f0914f9d0b10 | 8b9c982f2938d7d1e5bd1eb8de0bdf10505ed017 | refs/heads/master | 2016-09-11T00:24:32.906933 | 2008-09-26T18:01:01 | 2008-09-26T18:01:01 | 3,408,115 | 1 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 13,871 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: “gamePlayState.cpp”
// Author: Scott Smallback (SS) / Jared Hamby (JH)
// Purpose: This is the code file for the game play state
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "gamePlayState.h"
#include "..\..\Wrappers\CSGD_DirectInput.h"
#include "..\..\EventSystem\eventManager.h"
#include "..\..\EventSystem\eventIDs.h"
#include "../../EventSystem/gameEvent.h"
#include "../../EventSystem/playHandler.h"
#include "../../Objects/objManager.h"
#include "..\..\Engines\CTileEngine.h"
#include "..\..\Engines\CAIEngine.h"
#include "..\..\game.h"
#include "levelChooseState.h"
#include "../../helpers/datatypes.h"
#include "../../wrappers/mouse.h"
#include "../../Objects/playerObj.h"
#include "../../Engines/CParticleEffectManager.h"
#include "..\..\Helpers\bitFont.h"
#include "../../engines/debugControl.h"
#include "CKeyState.h"
#include "..\GamePlayStates\CTallySheet.h"
#include "../../EventSystem\globalEvents.h"
#include "../../Wrappers/CSGD_FModManager.h"
#include "..\..\Helpers\CXBOXController.h"
gamePlayState::gamePlayState() : debugger(0) {timeMod = 2.0f;}
gamePlayState::~gamePlayState() {}
gamePlayState* gamePlayState::getInstance()
{
static gamePlayState playa;
return &playa;
}
void gamePlayState::enter(void)
{
timeMod = 2.0f;
//for (int i = 0 ; i < 4 ; ++i)
// m_bIsBuffered[i] = true;
m_cLeftRight = '0';
m_cRightTrigger = '0';
m_cLeftTrigger = '0';
m_fInvulnerableTime = 0.0f;
theMouse = mouse::getInstance();
OM = objManager::getInstance();
theInput = CSGD_DirectInput::GetInstance();
EM = eventManager::getInstance();
theFont = bitFont::getInstance();
Player1 = new CXBOXController(1);
TE = CTileEngine::GetInstance();
m_fLevelTime = 0;
m_fLevelScore = 100;
for (int i = 0 ; i < 4 ; ++i)
{
Tutorials[i] = false;
}
//string buff;
char buff[256] = {0};
sprintf_s(buff,256,"Resource/PS_Level%d.bmf",levelChooseState::getInstance()->GetPlayLevel());
if(levelChooseState::getInstance()->GetPlayLevel() == 1 ||
levelChooseState::getInstance()->GetPlayLevel() == 2 ||
levelChooseState::getInstance()->GetPlayLevel() == 3 ||
levelChooseState::getInstance()->GetPlayLevel() == 4 ||
levelChooseState::getInstance()->GetPlayLevel() == 5)
{
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetLevel15Music()))
{
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetLevel15Music(), true);
}
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetMenuMusic());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetLevel69Music());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetBossMusic());
}
else if(levelChooseState::getInstance()->GetPlayLevel() == 6 ||
levelChooseState::getInstance()->GetPlayLevel() == 7 ||
levelChooseState::getInstance()->GetPlayLevel() == 8 ||
levelChooseState::getInstance()->GetPlayLevel() == 9)
{
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetLevel69Music()))
{
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetLevel69Music(), true);
}
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetMenuMusic());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetLevel15Music());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetBossMusic());
}
else if(levelChooseState::getInstance()->GetPlayLevel() == 10)
{
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetBossMusic()))
{
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetBossMusic(), true);
}
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetMenuMusic());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetLevel15Music());
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetLevel69Music());
}
TE->LoadMap(string(buff));
m_nParticleImageID = CParticleEffectManager::GetInstance()->LoadEffect("Resource/PS_SmokeBottomRight.prt");
m_bTrapActive = false;
handler = new playHandler;
handler->initialize();
for(int c = BEGIN_PLAY_EVENTS; c < END_PLAY_EVENTS; c++)
EM->registerClient(c, this);
EM->sendEvent(EVENT_GAMELOADING);
AIE = new CAIEngine();
}
void gamePlayState::exit(void)
{
while(rendering)
Sleep(1);
delete Player1;
gameState::exit();
if(debugger)
{
debugger->shutdown();
delete debugger;
debugger = 0;
}
m_bTrapActive = false;
TE->ShutDown();
delete AIE;
OM->clear();
handler->shutdown();
delete handler;
theMouse->shutdown();
CParticleEffectManager::GetInstance()->Unload(m_nParticleImageID);
}
bool gamePlayState::input(float dt)
{
if (theInput->KeyPressed(DIK_ESCAPE) || theInput->KeyPressed(DIK_F10) || Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_START)
EM->sendEvent(EVENT_GAMEPAUSE);
if(entered)
{
if (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_LEFT)
m_cLeftRight = '1';
else if (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_RIGHT)
m_cLeftRight = '2';
else
m_cLeftRight = '0';
if(theInput->KeyDown(game::GetInstance()->GetKeys().m_nRunLeft) || m_cLeftRight == '1')
EM->sendEvent(EVENT_PLAYERGOLEFT);
else if(theInput->KeyDown(game::GetInstance()->GetKeys().m_nRunRight) || m_cLeftRight == '2')
EM->sendEvent(EVENT_PLAYERGORIGHT);
else if((theInput->KeyReleased(game::GetInstance()->GetKeys().m_nRunLeft)
|| theInput->KeyReleased(game::GetInstance()->GetKeys().m_nRunRight)) || m_cLeftRight == '0')
EM->sendEvent(EVENT_PLAYERSTOP);
if(theInput->KeyDown(game::GetInstance()->GetKeys().m_nJump) || (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_A) || (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_DPAD_UP)|| (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER)|| (Player1->GetState().Gamepad.wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER))
{
Tutorials[0] = true;
EM->sendEvent(EVENT_PLAYERJUMP);
}
if(theInput->KeyReleased(game::GetInstance()->GetKeys().m_nJump))
EM->sendEvent(EVENT_PLAYERJUMPSTOP);
}
/*if (Player1->GetState().Gamepad.bLeftTrigger)
m_cLeftTrigger = '1';
else
m_cLeftTrigger = '0';
if (Player1->GetState().Gamepad.bRightTrigger)
m_cRightTrigger = '1';
else
m_cRightTrigger = '0';*/
if(!Player1->GetState().Gamepad.bLeftTrigger && m_cLeftTrigger == '1')
m_cLeftTrigger = '2';
else if(Player1->GetState().Gamepad.bLeftTrigger)
m_cLeftTrigger = '1';
else
m_cLeftTrigger = '0';
if(!Player1->GetState().Gamepad.bRightTrigger && m_cRightTrigger == '1')
m_cRightTrigger = '2';
else if (Player1->GetState().Gamepad.bRightTrigger)
m_cRightTrigger = '1';
else
m_cRightTrigger = '0';
float pos = Player1->GetState().Gamepad.sThumbRX;
if(fabs(pos) > XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)
{
if(Player1->GetState().Gamepad.sThumbRX < 0)
{
float mod = Player1->GetState().Gamepad.sThumbRX/40.0f;
mouse::getInstance()->setPos(mouse::getInstance()->getPos()+vector3(mod*dt,0,0));
}
else
{
float mod = Player1->GetState().Gamepad.sThumbRX/40.0f;
mouse::getInstance()->setPos(mouse::getInstance()->getPos()+vector3(mod*dt,0,0));
}
}
pos = Player1->GetState().Gamepad.sThumbRY;
if(fabs(pos) > XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)
{
if(Player1->GetState().Gamepad.sThumbRY < 0)
{
float mod = Player1->GetState().Gamepad.sThumbRY/40.0f;
mouse::getInstance()->setPos(mouse::getInstance()->getPos()+vector3(0,-mod*dt,0));
}
else
{
float mod = Player1->GetState().Gamepad.sThumbRY/40.0f;
mouse::getInstance()->setPos(mouse::getInstance()->getPos()+vector3(0,-mod*dt,0));
}
}
if(theInput->MouseButtonPressedEx(0) || m_cLeftTrigger == '1')
{
Tutorials[1] = true;
EM->sendEvent(EVENT_PLAYERFIRE);
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetGunSound1()))
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetGunSound1());
}
if(theInput->MouseButtonPressedEx(1) || m_cRightTrigger == '1')
{
EM->sendEvent(EVENT_PLAYERFIRE2);
if(!CSGD_FModManager::GetInstance()->IsSoundPlaying(game::GetInstance()->GetGunSound2()))
CSGD_FModManager::GetInstance()->PlaySound(game::GetInstance()->GetGunSound2());
}
if(theInput->MouseButtonReleased(0) || m_cLeftTrigger == '2')
{
EM->sendEvent(EVENT_PLAYERCEASEFIRE, new int(EVENT_PLAYERFIRE));
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetGunSound1());
}
if(theInput->MouseButtonReleased(1) || m_cRightTrigger == '2')
{
EM->sendEvent(EVENT_PLAYERCEASEFIRE, new int(EVENT_PLAYERFIRE2));
CSGD_FModManager::GetInstance()->StopSound(game::GetInstance()->GetGunSound2());
}
if(theInput->KeyPressed(DIK_DELETE))
EM->sendEvent(EVENT_DEBUG_SWITCH);
if(theInput->KeyPressed(DIK_NUMPADPLUS))
timeMod+=.5f;
if(theInput->KeyPressed(DIK_NUMPADMINUS))
timeMod-=.5f;
// if (theInput->KeyPressed(DIK_P))
// {
// EM->sendGlobalEvent(GE_STATE_CHANGETO, new int(STATE_TALLYSHEET));
// CTallySheetState::getInstance()->Initialize(/*LevelNum*/1 ,100.0f, m_fLevelTime);
// }
if (theInput->CheckBufferedKeysEx())
{
m_qCheatCode.push(theInput->CheckBufferedKeysEx());
if (m_qCheatCode.size() > 5)
{
m_qCheatCode.pop();
}
}
return true;
}
void gamePlayState::update(float dt)
{
m_fLevelTime += dt;
if (m_bIsGodMode)
{
m_fInvulnerableTime += dt;
if (m_bIsGodMode && m_fInvulnerableTime >= 5.0f)
{
m_bIsGodMode = false;
}
}
dt*=timeMod;
if(entered)
{
AIE->update(dt);
OM->checkCollisions();
OM->update(dt);
theMouse->update(dt);
CParticleEffectManager::GetInstance()->Update(dt);
if(debugger)
debugger->update(dt/timeMod);
}
EM->processEvents();
if (m_qCheatCode.size() == 5)
{
if(m_qCheatCode.front() == 'u')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'd')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'i')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'e')
{
m_qCheatCode.pop();
if(m_qCheatCode.front() = 'd')
{
m_qCheatCode.pop();
SetGodMode(true);
}
}
}
}
}
}
if (m_qCheatCode.size() == 5)
{
if(m_qCheatCode.front() == 'l')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'e')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'v')
{
m_qCheatCode.pop();
if (m_qCheatCode.front() == 'e')
{
m_qCheatCode.pop();
if(m_qCheatCode.front() = 'l')
{
m_qCheatCode.pop();
for(int i = 0; i < 10; i++)
game::GetInstance()->SetLevelComplete(i);
}
}
}
}
}
}
}
void gamePlayState::render(void) const
{
if(!entered)
return;
OM->render();
if(TE)
TE->Render();
theMouse->render();
char buff[256] = {0};
sprintf_s(buff,256,"Level: %d",levelChooseState::getInstance()->GetPlayLevel());
theFont->drawText(buff, 200, 30, 0xffff0000, .5f);
sprintf_s(buff, 256, "Time: %.2f", m_fLevelTime);
theFont->drawText(buff, 1600, 30, 0xffff0000, .5f);
if(m_bTrapActive == true)
{
CParticleEffectManager::GetInstance()->Render(m_nParticleImageID,TE->GetTraps()[0].x,TE->GetTraps()[0].y);
}
if (game::GetInstance()->GetTutorialDone() == false)
{
if (Tutorials[0] == false && AIE->GetTrackPos()->x >= 100)
{
char buffertut[256] = {0};
sprintf_s(buffertut, 256, "Press %s to jump over the walls", CKeyState::getInstance()->SetKeyString(game::GetInstance()->GetKeys().m_nJump));
theFont->drawText(buffertut, 100, 700, 0xffff0000);
}
else if (Tutorials[1] == false && AIE->GetTrackPos()->x >= 250)
{
//char buffertut[256] = {0};
//sprintf_s(buffertut, 256, "Press %s to push the blocks onto each other", "Mouse 1");
theFont->drawText("Press Mouse 1 to push", 100, 700, 0xffff0000);
theFont->drawText("the blocks onto each other", 100, 750, 0xffff0000);
}
else if (Tutorials[2] == false && AIE->GetTrackPos()->x >= 600)
{
theFont->drawText("Run through the exit!", 100, 700, 0xffff0000);
}
}
if(debugger)
debugger->render();
}
void gamePlayState::HandleEvent(gameEvent* ev)
{
switch(ev->getEventID())
{
case EVENT_LEVELLOADED:
entered = true;
break;
case EVENT_LEVELFINISHED:
{
game* theGame = game::GetInstance();
theGame->SetTutorialDone(true);
m_fLevelScore = m_fLevelScore - (m_fLevelTime * 5);
if (m_fLevelScore <= 0.0f)
m_fLevelScore = 0.0f;
int currlevel = levelChooseState::getInstance()->GetPlayLevel();
if (m_fLevelScore > theGame->GetHighScore(currlevel))
theGame->SetHighScore(currlevel, m_fLevelScore);
theGame->SetLevelComplete(currlevel-1);
if(m_fLevelTime <= theGame->GetAchievementNumbers(currlevel-1))
theGame->SetAchievementUnlock(currlevel-1);
EM->sendGlobalEvent(GE_STATE_CHANGETO, new int(STATE_TALLYSHEET));
CTallySheetState::getInstance()->Initialize(currlevel,m_fLevelScore, m_fLevelTime);
entered = false;
}
break;
case EVENT_DEBUG_SWITCH:
if(!debugger)
{
debugger = new debugControl;
debugger->initialize();
}
else
{
debugger->shutdown();
delete debugger;
debugger = 0;
}
break;
}
} | [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
6
],
[
14,
15
],
[
17,
17
],
[
20,
22
],
[
27,
27
],
[
29,
29
],
[
32,
32
],
[
44,
44
],
[
58,
58
],
[
60,
62
],
[
69,
115
],
[
124,
124
],
[
142,
145
],
[
151,
152
],
[
177,
177
],
[
212,
216
],
[
218,
221
],
[
223,
231
],
[
233,
236
],
[
238,
239
],
[
241,
241
],
[
247,
248
],
[
252,
252
],
[
254,
256
],
[
259,
259
],
[
261,
262
],
[
265,
265
],
[
267,
268
],
[
273,
276
],
[
297,
298
],
[
310,
310
],
[
313,
313
],
[
330,
346
],
[
348,
353
],
[
355,
379
],
[
388,
389
],
[
392,
392
],
[
394,
400
],
[
402,
406
],
[
413,
413
],
[
420,
421
],
[
425,
425
],
[
442,
442
],
[
459,
461
],
[
463,
464
]
],
[
[
7,
13
],
[
16,
16
],
[
18,
19
],
[
23,
26
],
[
28,
28
],
[
30,
31
],
[
33,
43
],
[
45,
57
],
[
59,
59
],
[
63,
68
],
[
116,
123
],
[
125,
141
],
[
146,
150
],
[
153,
176
],
[
178,
211
],
[
217,
217
],
[
222,
222
],
[
232,
232
],
[
237,
237
],
[
240,
240
],
[
242,
246
],
[
249,
251
],
[
253,
253
],
[
257,
258
],
[
260,
260
],
[
263,
264
],
[
266,
266
],
[
269,
272
],
[
277,
296
],
[
299,
309
],
[
311,
312
],
[
314,
329
],
[
347,
347
],
[
354,
354
],
[
380,
387
],
[
390,
391
],
[
393,
393
],
[
401,
401
],
[
407,
412
],
[
414,
419
],
[
422,
424
],
[
426,
441
],
[
443,
458
],
[
462,
462
],
[
465,
480
]
]
]
|
58e64523a88a103436326c1b40c9d63e1e377fef | 7f72fc855742261daf566d90e5280e10ca8033cf | /branches/full-calibration/ground/src/plugins/uavobjects/telemetrysettings.cpp | 080c3d3c074a847b7a1677a23a34ee7017c5ee34 | []
| no_license | caichunyang2007/my_OpenPilot_mods | 8e91f061dc209a38c9049bf6a1c80dfccb26cce4 | 0ca472f4da7da7d5f53aa688f632b1f5c6102671 | refs/heads/master | 2023-06-06T03:17:37.587838 | 2011-02-28T10:25:56 | 2011-02-28T10:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,435 | cpp | /**
******************************************************************************
*
* @file telemetrysettings.cpp
* @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010.
* @see The GNU Public License (GPL) Version 3
* @addtogroup GCSPlugins GCS Plugins
* @{
* @addtogroup UAVObjectsPlugin UAVObjects Plugin
* @{
*
* @note Object definition file: telemetrysettings.xml.
* This is an automatically generated file.
* DO NOT modify manually.
*
* @brief The UAVUObjects GCS plugin
*****************************************************************************/
/*
* 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, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "telemetrysettings.h"
#include "uavobjectfield.h"
const QString TelemetrySettings::NAME = QString("TelemetrySettings");
/**
* Constructor
*/
TelemetrySettings::TelemetrySettings(): UAVDataObject(OBJID, ISSINGLEINST, ISSETTINGS, NAME)
{
// Create fields
QList<UAVObjectField*> fields;
QStringList SpeedElemNames;
SpeedElemNames.append("0");
QStringList SpeedEnumOptions;
SpeedEnumOptions.append("9600");
SpeedEnumOptions.append("38400");
SpeedEnumOptions.append("57600");
SpeedEnumOptions.append("115200");
fields.append( new UAVObjectField(QString("Speed"), QString(""), UAVObjectField::ENUM, SpeedElemNames, SpeedEnumOptions) );
// Initialize object
initializeFields(fields, (quint8*)&data, NUMBYTES);
// Set the default field values
setDefaultFieldValues();
}
/**
* Get the default metadata for this object
*/
UAVObject::Metadata TelemetrySettings::getDefaultMetadata()
{
UAVObject::Metadata metadata;
metadata.flightAccess = ACCESS_READWRITE;
metadata.gcsAccess = ACCESS_READWRITE;
metadata.gcsTelemetryAcked = 1;
metadata.gcsTelemetryUpdateMode = UAVObject::UPDATEMODE_ONCHANGE;
metadata.gcsTelemetryUpdatePeriod = 0;
metadata.flightTelemetryAcked = 1;
metadata.flightTelemetryUpdateMode = UAVObject::UPDATEMODE_ONCHANGE;
metadata.flightTelemetryUpdatePeriod = 0;
metadata.loggingUpdateMode = UAVObject::UPDATEMODE_NEVER;
metadata.loggingUpdatePeriod = 0;
return metadata;
}
/**
* Initialize object fields with the default values.
* If a default value is not specified the object fields
* will be initialized to zero.
*/
void TelemetrySettings::setDefaultFieldValues()
{
data.Speed = 2;
}
/**
* Get the object data fields
*/
TelemetrySettings::DataFields TelemetrySettings::getData()
{
QMutexLocker locker(mutex);
return data;
}
/**
* Set the object data fields
*/
void TelemetrySettings::setData(const DataFields& data)
{
QMutexLocker locker(mutex);
// Get metadata
Metadata mdata = getMetadata();
// Update object if the access mode permits
if ( mdata.gcsAccess == ACCESS_READWRITE )
{
this->data = data;
emit objectUpdatedAuto(this); // trigger object updated event
emit objectUpdated(this);
}
}
/**
* Create a clone of this object, a new instance ID must be specified.
* Do not use this function directly to create new instances, the
* UAVObjectManager should be used instead.
*/
UAVDataObject* TelemetrySettings::clone(quint32 instID)
{
TelemetrySettings* obj = new TelemetrySettings();
obj->initialize(instID, this->getMetaObject());
return obj;
}
/**
* Static function to retrieve an instance of the object.
*/
TelemetrySettings* TelemetrySettings::GetInstance(UAVObjectManager* objMngr, quint32 instID)
{
return dynamic_cast<TelemetrySettings*>(objMngr->getObject(TelemetrySettings::OBJID, instID));
}
| [
"jonathan@ebee16cc-31ac-478f-84a7-5cbb03baadba"
]
| [
[
[
1,
134
]
]
]
|
8b57d6f547b2570ce8cb5d43420afcf7a3ac655b | ce1b0d027c41f70bc4cfa13cb05f09bd4edaf6a2 | / edge2d --username [email protected]/EdgeBase/EdgeLogManager.cpp | 519b828ec0c4592e6707fa86beb247b4b9dc49f6 | []
| no_license | ratalaika/edge2d | 11189c41b166960d5d7d5dbcf9bfaf833a41c079 | 79470a0fa6e8f5ea255df1696da655145bbf83ff | refs/heads/master | 2021-01-10T04:59:22.495428 | 2010-02-19T13:45:03 | 2010-02-19T13:45:03 | 36,088,756 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,188 | cpp | /*
-----------------------------------------------------------------------------
This source file is part of EDGE
(A very object-oriented and plugin-based 2d game engine)
For the latest info, see http://edge2d.googlecode.com
Copyright (c) 2007-2008 The EDGE Team
Also see acknowledgements in Readme.html
This program 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 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
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.
-----------------------------------------------------------------------------
*/
#include "EdgeLogManager.h"
#include <algorithm>
#include <stdarg.h>
#ifdef _MSC_VER
#pragma warning( disable:4996 )
#endif
namespace Edge
{
LogManager::LogManager()
{
mCurrentLog = NULL;
setLogLevel( LL_INFORMATION );
}
LogManager::~LogManager()
{
destroyAllLogs();
}
void LogManager::addListener( LogListener *listener )
{
mLogListeners.push_back( listener );
}
void LogManager::removeListener( LogListener *listener )
{
mLogListeners.erase( std::find( mLogListeners.begin(),
mLogListeners.end(), listener ) );
}
Log *LogManager::createLog( const string &name, const string &file )
{
/// maybe here is a bug. If mLogs already has a log named name
/// the insert will failed, and LogManager doesnot maintain the log
Log *log = new Log( name, file );
mLogs[ name ] = log;
if( mCurrentLog == NULL )
{
mCurrentLog = log;
}
return log;
}
Log *LogManager::getLog( const string &name )
{
LogMap::iterator it = mLogs.find( name );
if( it != mLogs.end() )
{
return it->second;
}
return NULL;
}
Log *LogManager::getCurrentLog()
{
return mCurrentLog;
}
void LogManager::destroyLog( const string &name )
{
LogMap::iterator it = mLogs.find( name );
if( it != mLogs.end() )
{
delete it->second ;
mLogs.erase( it );
}
}
void LogManager::destroyLog( Log *log )
{
destroyLog( log->getName() );
}
void LogManager::destroyAllLogs()
{
for( LogMap::iterator it = mLogs.begin(); it != mLogs.end(); ++ it )
{
delete it->second;
}
mLogs.clear();
}
Log *LogManager::setCurrentLog( Log *log )
{
Log *prevLog = mCurrentLog;
mCurrentLog = log;
return prevLog;
}
void LogManager::logMessage( ELogLevel level, const string &msg )
{
if( mCurrentLog != NULL )
{
mCurrentLog->logMessage( level, msg );
}
}
void LogManager::logMessage( const string &logname, ELogLevel level, const string &msg )
{
Log *log = getLog( logname );
if( log != NULL )
{
log->logMessage( level, msg );
}
}
void LogManager::logMessageF( ELogLevel level, const char *format, ... )
{
char msg[512];
va_list list;
va_start( list, format );
vsprintf( msg, format, list );
va_end( list );
logMessage( level, msg );
}
void LogManager::logMessageF( const string &name, ELogLevel level, const char *format, ... )
{
char msg[512];
va_list list;
va_start( list, format );
vsprintf( msg, format, list );
va_end( list );
logMessage( name, level, msg );
}
//////////////////////////////////////////////////////////////////////////////////////////////////
bool LogManager::canLog( ELogLevel level )
{
return level <= mLogLevel;
}
void LogManager::_routeMessage( const string &logName, ELogLevel level, const string &msg )
{
for( size_t i = 0; i < mLogListeners.size(); ++ i )
{
mLogListeners.at( i )->log( logName, level, msg );
}
}
}
| [
"[email protected]@539dfdeb-0f3d-0410-9ace-d34ff1985647"
]
| [
[
[
1,
170
]
]
]
|
07d45c86461baea4737db79ce0e243aeb909c952 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/rational/rational_test.cpp | baead163324758e817f99277328b372ccefc8f39 | [
"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 | ISO-8859-1 | C++ | false | false | 21,127 | cpp | /*
* A test program for boost/rational.hpp.
* Change the typedef at the beginning of run_tests() to try out different
* integer types. (These tests are designed only for signed integer
* types. They should work for short, int and long.)
*
* (C) Copyright Stephen Silver, 2001. Permission to copy, use, modify, sell
* and distribute this software is granted provided this copyright notice
* appears in all copies. This software is provided "as is" without express or
* implied warranty, and with no claim as to its suitability for any purpose.
*
* Incorporated into the boost rational number library, and modified and
* extended, by Paul Moore, with permission.
*/
// Revision History
// 18 Oct 06 Various fixes for old compilers (Joaquín M López Muñoz)
// 27 Dec 05 Add testing for Boolean conversion operator (Daryle Walker)
// 24 Dec 05 Change code to use Boost.Test (Daryle Walker)
// 04 Mar 01 Patches for Intel C++ and GCC (David Abrahams)
#define BOOST_TEST_MAIN "Boost::Rational unit tests"
#include <boost/mpl/list.hpp>
#include <boost/operators.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/rational.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_case_template.hpp>
#include <iostream>
#include <istream>
#include <ostream>
#include <sstream>
// We can override this on the compile, as -DINT_TYPE=short or whatever.
// The default test is against rational<long>.
#ifndef INT_TYPE
#define INT_TYPE long
#endif
namespace {
// This is a trivial user-defined wrapper around the built in int type.
// It can be used as a test type for rational<>
class MyInt : boost::operators<MyInt>
{
int val;
public:
MyInt(int n = 0) : val(n) {}
friend MyInt operator+ (const MyInt&);
friend MyInt operator- (const MyInt&);
MyInt& operator+= (const MyInt& rhs) { val += rhs.val; return *this; }
MyInt& operator-= (const MyInt& rhs) { val -= rhs.val; return *this; }
MyInt& operator*= (const MyInt& rhs) { val *= rhs.val; return *this; }
MyInt& operator/= (const MyInt& rhs) { val /= rhs.val; return *this; }
MyInt& operator%= (const MyInt& rhs) { val %= rhs.val; return *this; }
MyInt& operator|= (const MyInt& rhs) { val |= rhs.val; return *this; }
MyInt& operator&= (const MyInt& rhs) { val &= rhs.val; return *this; }
MyInt& operator^= (const MyInt& rhs) { val ^= rhs.val; return *this; }
const MyInt& operator++() { ++val; return *this; }
const MyInt& operator--() { --val; return *this; }
bool operator< (const MyInt& rhs) const { return val < rhs.val; }
bool operator== (const MyInt& rhs) const { return val == rhs.val; }
bool operator! () const { return !val; }
friend std::istream& operator>>(std::istream&, MyInt&);
friend std::ostream& operator<<(std::ostream&, const MyInt&);
};
inline MyInt operator+(const MyInt& rhs) { return rhs; }
inline MyInt operator-(const MyInt& rhs) { return MyInt(-rhs.val); }
inline std::istream& operator>>(std::istream& is, MyInt& i) { is >> i.val; return is; }
inline std::ostream& operator<<(std::ostream& os, const MyInt& i) { os << i.val; return os; }
inline MyInt abs(MyInt rhs) { if (rhs < MyInt()) rhs = -rhs; return rhs; }
// This fixture replaces the check of rational's packing at the start of main.
class rational_size_check
{
typedef INT_TYPE int_type;
typedef ::boost::rational<int_type> rational_type;
public:
rational_size_check()
{
using ::std::cout;
char const * const int_name = BOOST_PP_STRINGIZE( INT_TYPE );
cout << "Running tests for boost::rational<" << int_name << ">\n\n";
cout << "Implementation issue: the minimal size for a rational\n"
<< "is twice the size of the underlying integer type.\n\n";
cout << "Checking to see if space is being wasted.\n"
<< "\tsizeof(" << int_name << ") == " << sizeof( int_type )
<< "\n";
cout << "\tsizeof(boost::rational<" << int_name << ">) == "
<< sizeof( rational_type ) << "\n\n";
cout << "Implementation has "
<< (
(sizeof( rational_type ) > 2u * sizeof( int_type ))
? "included padding bytes"
: "minimal size"
)
<< "\n\n";
}
};
// This fixture groups all the common settings.
class my_configuration
{
public:
template < typename T >
class hook
{
public:
typedef ::boost::rational<T> rational_type;
private:
struct parts { rational_type parts_[ 9 ]; };
static parts generate_rationals()
{
rational_type r1, r2( 0 ), r3( 1 ), r4( -3 ), r5( 7, 2 ),
r6( 5, 15 ), r7( 14, -21 ), r8( -4, 6 ),
r9( -14, -70 );
parts result;
result.parts_[0] = r1;
result.parts_[1] = r2;
result.parts_[2] = r3;
result.parts_[3] = r4;
result.parts_[4] = r5;
result.parts_[5] = r6;
result.parts_[6] = r7;
result.parts_[7] = r8;
result.parts_[8] = r9;
return result;
}
parts p_; // Order Dependency
public:
rational_type ( &r_ )[ 9 ]; // Order Dependency
hook() : p_( generate_rationals() ), r_( p_.parts_ ) {}
};
};
// Instead of controlling the integer type needed with a #define, use a list of
// all available types. Since the headers #included don't change because of the
// integer #define, only the built-in types and MyInt are available. (Any other
// arbitrary integer type introduced by the #define would get compiler errors
// because its header can't be #included.)
typedef ::boost::mpl::list<short, int, long> builtin_signed_test_types;
typedef ::boost::mpl::list<short, int, long, MyInt> all_signed_test_types;
// Without these explicit instantiations, MSVC++ 6.5/7.0 does not find
// some friend operators in certain contexts.
::boost::rational<short> dummy1;
::boost::rational<int> dummy2;
::boost::rational<long> dummy3;
::boost::rational<MyInt> dummy4;
// Should there be tests with unsigned integer types?
} // namespace
// Check if rational is the smallest size possible
BOOST_GLOBAL_FIXTURE( rational_size_check )
// The factoring function template suite
BOOST_AUTO_TEST_SUITE( factoring_suite )
// GCD tests
BOOST_AUTO_TEST_CASE_TEMPLATE( gcd_test, T, all_signed_test_types )
{
BOOST_CHECK_EQUAL( boost::gcd<T>( 1, -1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::gcd<T>( -1, 1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 1, 1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::gcd<T>( -1, -1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 0, 0), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 7, 0), static_cast<T>( 7) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 0, 9), static_cast<T>( 9) );
BOOST_CHECK_EQUAL( boost::gcd<T>( -7, 0), static_cast<T>( 7) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 0, -9), static_cast<T>( 9) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 42, 30), static_cast<T>( 6) );
BOOST_CHECK_EQUAL( boost::gcd<T>( 6, -9), static_cast<T>( 3) );
BOOST_CHECK_EQUAL( boost::gcd<T>(-10, -10), static_cast<T>(10) );
BOOST_CHECK_EQUAL( boost::gcd<T>(-25, -10), static_cast<T>( 5) );
}
// LCM tests
BOOST_AUTO_TEST_CASE_TEMPLATE( lcm_test, T, all_signed_test_types )
{
BOOST_CHECK_EQUAL( boost::lcm<T>( 1, -1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::lcm<T>( -1, 1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 1, 1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::lcm<T>( -1, -1), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 0, 0), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 6, 0), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 0, 7), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::lcm<T>( -5, 0), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 0, -4), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 18, 30), static_cast<T>(90) );
BOOST_CHECK_EQUAL( boost::lcm<T>( -6, 9), static_cast<T>(18) );
BOOST_CHECK_EQUAL( boost::lcm<T>(-10, -10), static_cast<T>(10) );
BOOST_CHECK_EQUAL( boost::lcm<T>( 25, -10), static_cast<T>(50) );
}
BOOST_AUTO_TEST_SUITE_END()
// The basic test suite
BOOST_FIXTURE_TEST_SUITE( basic_rational_suite, my_configuration )
// Initialization tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_initialization_test, T,
all_signed_test_types )
{
my_configuration::hook<T> h;
boost::rational<T> &r1 = h.r_[ 0 ], &r2 = h.r_[ 1 ], &r3 = h.r_[ 2 ],
&r4 = h.r_[ 3 ], &r5 = h.r_[ 4 ], &r6 = h.r_[ 5 ],
&r7 = h.r_[ 6 ], &r8 = h.r_[ 7 ], &r9 = h.r_[ 8 ];
BOOST_CHECK_EQUAL( r1.numerator(), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( r2.numerator(), static_cast<T>( 0) );
BOOST_CHECK_EQUAL( r3.numerator(), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( r4.numerator(), static_cast<T>(-3) );
BOOST_CHECK_EQUAL( r5.numerator(), static_cast<T>( 7) );
BOOST_CHECK_EQUAL( r6.numerator(), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( r7.numerator(), static_cast<T>(-2) );
BOOST_CHECK_EQUAL( r8.numerator(), static_cast<T>(-2) );
BOOST_CHECK_EQUAL( r9.numerator(), static_cast<T>( 1) );
BOOST_CHECK_EQUAL( r1.denominator(), static_cast<T>(1) );
BOOST_CHECK_EQUAL( r2.denominator(), static_cast<T>(1) );
BOOST_CHECK_EQUAL( r3.denominator(), static_cast<T>(1) );
BOOST_CHECK_EQUAL( r4.denominator(), static_cast<T>(1) );
BOOST_CHECK_EQUAL( r5.denominator(), static_cast<T>(2) );
BOOST_CHECK_EQUAL( r6.denominator(), static_cast<T>(3) );
BOOST_CHECK_EQUAL( r7.denominator(), static_cast<T>(3) );
BOOST_CHECK_EQUAL( r8.denominator(), static_cast<T>(3) );
BOOST_CHECK_EQUAL( r9.denominator(), static_cast<T>(5) );
}
// Assignment (non-operator) tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_assign_test, T, all_signed_test_types )
{
my_configuration::hook<T> h;
boost::rational<T> & r = h.r_[ 0 ];
r.assign( 6, 8 );
BOOST_CHECK_EQUAL( r.numerator(), static_cast<T>(3) );
BOOST_CHECK_EQUAL( r.denominator(), static_cast<T>(4) );
r.assign( 0, -7 );
BOOST_CHECK_EQUAL( r.numerator(), static_cast<T>(0) );
BOOST_CHECK_EQUAL( r.denominator(), static_cast<T>(1) );
}
// Comparison tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_comparison_test, T,
all_signed_test_types )
{
my_configuration::hook<T> h;
boost::rational<T> &r1 = h.r_[ 0 ], &r2 = h.r_[ 1 ], &r3 = h.r_[ 2 ],
&r4 = h.r_[ 3 ], &r5 = h.r_[ 4 ], &r6 = h.r_[ 5 ],
&r7 = h.r_[ 6 ], &r8 = h.r_[ 7 ], &r9 = h.r_[ 8 ];
BOOST_CHECK( r1 == r2 );
BOOST_CHECK( r2 != r3 );
BOOST_CHECK( r4 < r3 );
BOOST_CHECK( r4 <= r5 );
BOOST_CHECK( r1 <= r2 );
BOOST_CHECK( r5 > r6 );
BOOST_CHECK( r5 >= r6 );
BOOST_CHECK( r7 >= r8 );
BOOST_CHECK( !(r3 == r2) );
BOOST_CHECK( !(r1 != r2) );
BOOST_CHECK( !(r1 < r2) );
BOOST_CHECK( !(r5 < r6) );
BOOST_CHECK( !(r9 <= r2) );
BOOST_CHECK( !(r8 > r7) );
BOOST_CHECK( !(r8 > r2) );
BOOST_CHECK( !(r4 >= r6) );
BOOST_CHECK( r1 == static_cast<T>( 0) );
BOOST_CHECK( r2 != static_cast<T>(-1) );
BOOST_CHECK( r3 < static_cast<T>( 2) );
BOOST_CHECK( r4 <= static_cast<T>(-3) );
BOOST_CHECK( r5 > static_cast<T>( 3) );
BOOST_CHECK( r6 >= static_cast<T>( 0) );
BOOST_CHECK( static_cast<T>( 0) == r2 );
BOOST_CHECK( static_cast<T>( 0) != r7 );
BOOST_CHECK( static_cast<T>(-1) < r8 );
BOOST_CHECK( static_cast<T>(-2) <= r9 );
BOOST_CHECK( static_cast<T>( 1) > r1 );
BOOST_CHECK( static_cast<T>( 1) >= r3 );
}
// Increment & decrement tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_1step_test, T, all_signed_test_types )
{
my_configuration::hook<T> h;
boost::rational<T> &r1 = h.r_[ 0 ], &r2 = h.r_[ 1 ], &r3 = h.r_[ 2 ],
&r7 = h.r_[ 6 ], &r8 = h.r_[ 7 ];
BOOST_CHECK( r1++ == r2 );
BOOST_CHECK( r1 != r2 );
BOOST_CHECK( r1 == r3 );
BOOST_CHECK( --r1 == r2 );
BOOST_CHECK( r8-- == r7 );
BOOST_CHECK( r8 != r7 );
BOOST_CHECK( ++r8 == r7 );
}
// Absolute value tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_abs_test, T, all_signed_test_types )
{
typedef my_configuration::hook<T> hook_type;
typedef typename hook_type::rational_type rational_type;
hook_type h;
rational_type &r2 = h.r_[ 1 ], &r5 = h.r_[ 4 ], &r8 = h.r_[ 7 ];
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
// This is a nasty hack, required because some compilers do not implement
// "Koenig Lookup." Basically, if I call abs(r), the C++ standard says that
// the compiler should look for a definition of abs in the namespace which
// contains r's class (in this case boost)--among other places.
using boost::abs;
#endif
BOOST_CHECK_EQUAL( abs(r2), r2 );
BOOST_CHECK_EQUAL( abs(r5), r5 );
BOOST_CHECK_EQUAL( abs(r8), rational_type(2, 3) );
}
// Unary operator tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_unary_test, T, all_signed_test_types )
{
my_configuration::hook<T> h;
boost::rational<T> &r2 = h.r_[ 1 ], &r3 = h.r_[ 2 ],
&r4 = h.r_[ 3 ], &r5 = h.r_[ 4 ];
BOOST_CHECK_EQUAL( +r5, r5 );
BOOST_CHECK( -r3 != r3 );
BOOST_CHECK_EQUAL( -(-r3), r3 );
BOOST_CHECK_EQUAL( -r4, static_cast<T>(3) );
BOOST_CHECK( !r2 );
BOOST_CHECK( !!r3 );
BOOST_CHECK( ! static_cast<bool>(r2) );
BOOST_CHECK( r3 );
}
BOOST_AUTO_TEST_SUITE_END()
// The rational arithmetic operations suite
BOOST_AUTO_TEST_SUITE( rational_arithmetic_suite )
// Addition & subtraction tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_additive_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
BOOST_CHECK_EQUAL( rational_type( 1, 2) + rational_type(1, 2),
static_cast<T>(1) );
BOOST_CHECK_EQUAL( rational_type(11, 3) + rational_type(1, 2),
rational_type( 25, 6) );
BOOST_CHECK_EQUAL( rational_type(-8, 3) + rational_type(1, 5),
rational_type(-37, 15) );
BOOST_CHECK_EQUAL( rational_type(-7, 6) + rational_type(1, 7),
rational_type( 1, 7) - rational_type(7, 6) );
BOOST_CHECK_EQUAL( rational_type(13, 5) - rational_type(1, 2),
rational_type( 21, 10) );
BOOST_CHECK_EQUAL( rational_type(22, 3) + static_cast<T>(1),
rational_type( 25, 3) );
BOOST_CHECK_EQUAL( rational_type(12, 7) - static_cast<T>(2),
rational_type( -2, 7) );
BOOST_CHECK_EQUAL( static_cast<T>(3) + rational_type(4, 5),
rational_type( 19, 5) );
BOOST_CHECK_EQUAL( static_cast<T>(4) - rational_type(9, 2),
rational_type( -1, 2) );
rational_type r( 11 );
r -= rational_type( 20, 3 );
BOOST_CHECK_EQUAL( r, rational_type(13, 3) );
r += rational_type( 1, 2 );
BOOST_CHECK_EQUAL( r, rational_type(29, 6) );
r -= static_cast<T>( 5 );
BOOST_CHECK_EQUAL( r, rational_type( 1, -6) );
r += rational_type( 1, 5 );
BOOST_CHECK_EQUAL( r, rational_type( 1, 30) );
r += static_cast<T>( 2 );
BOOST_CHECK_EQUAL( r, rational_type(61, 30) );
}
// Assignment tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_assignment_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
rational_type r;
r = rational_type( 1, 10 );
BOOST_CHECK_EQUAL( r, rational_type( 1, 10) );
r = static_cast<T>( -9 );
BOOST_CHECK_EQUAL( r, rational_type(-9, 1) );
}
// Multiplication tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_multiplication_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
BOOST_CHECK_EQUAL( rational_type(1, 3) * rational_type(-3, 4),
rational_type(-1, 4) );
BOOST_CHECK_EQUAL( rational_type(2, 5) * static_cast<T>(7),
rational_type(14, 5) );
BOOST_CHECK_EQUAL( static_cast<T>(-2) * rational_type(1, 6),
rational_type(-1, 3) );
rational_type r = rational_type( 3, 7 );
r *= static_cast<T>( 14 );
BOOST_CHECK_EQUAL( r, static_cast<T>(6) );
r *= rational_type( 3, 8 );
BOOST_CHECK_EQUAL( r, rational_type(9, 4) );
}
// Division tests
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_division_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
BOOST_CHECK_EQUAL( rational_type(-1, 20) / rational_type(4, 5),
rational_type(-1, 16) );
BOOST_CHECK_EQUAL( rational_type( 5, 6) / static_cast<T>(7),
rational_type( 5, 42) );
BOOST_CHECK_EQUAL( static_cast<T>(8) / rational_type(2, 7),
static_cast<T>(28) );
rational_type r = rational_type( 4, 3 );
r /= rational_type( 5, 4 );
BOOST_CHECK_EQUAL( r, rational_type(16, 15) );
r /= static_cast<T>( 4 );
BOOST_CHECK_EQUAL( r, rational_type( 4, 15) );
BOOST_CHECK_EQUAL( rational_type(-1) / rational_type(-3),
rational_type(1, 3) );
}
// Tests for operations on self
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_self_operations_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
rational_type r = rational_type( 4, 3 );
r += r;
BOOST_CHECK_EQUAL( r, rational_type( 8, 3) );
r *= r;
BOOST_CHECK_EQUAL( r, rational_type(64, 9) );
r /= r;
BOOST_CHECK_EQUAL( r, rational_type( 1, 1) );
r -= r;
BOOST_CHECK_EQUAL( r, rational_type( 0, 1) );
}
BOOST_AUTO_TEST_SUITE_END()
// The non-basic rational operations suite
BOOST_AUTO_TEST_SUITE( rational_extras_suite )
// Output test
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_output_test, T, all_signed_test_types )
{
std::ostringstream oss;
oss << boost::rational<T>( 44, 14 );
BOOST_CHECK_EQUAL( oss.str(), "22/7" );
}
// Input test, failing
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_input_failing_test, T,
all_signed_test_types )
{
std::istringstream iss( "" );
boost::rational<T> r;
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "42" );
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "57A" );
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "20-20" );
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "1/" );
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "1/ 2" );
iss >> r;
BOOST_CHECK( !iss );
iss.clear();
iss.str( "1 /2" );
iss >> r;
BOOST_CHECK( !iss );
}
// Input test, passing
BOOST_AUTO_TEST_CASE_TEMPLATE( rational_input_passing_test, T,
all_signed_test_types )
{
typedef boost::rational<T> rational_type;
std::istringstream iss( "1/2 12" );
rational_type r;
int n = 0;
BOOST_CHECK( iss >> r >> n );
BOOST_CHECK_EQUAL( r, rational_type(1, 2) );
BOOST_CHECK_EQUAL( n, 12 );
iss.clear();
iss.str( "34/67" );
BOOST_CHECK( iss >> r );
BOOST_CHECK_EQUAL( r, rational_type(34, 67) );
iss.clear();
iss.str( "-3/-6" );
BOOST_CHECK( iss >> r );
BOOST_CHECK_EQUAL( r, rational_type(1, 2) );
}
// Conversion test
BOOST_AUTO_TEST_CASE( rational_cast_test )
{
// Note that these are not generic. The problem is that rational_cast<T>
// requires a conversion from IntType to T. However, for a user-defined
// IntType, it is not possible to define such a conversion except as an
// "operator T()". This causes problems with overloading resolution.
boost::rational<int> const half( 1, 2 );
BOOST_CHECK_CLOSE( boost::rational_cast<double>(half), 0.5, 0.01 );
BOOST_CHECK_EQUAL( boost::rational_cast<int>(half), 0 );
BOOST_CHECK_EQUAL( boost::rational_cast<MyInt>(half), MyInt() );
}
// Dice tests (a non-main test)
BOOST_AUTO_TEST_CASE_TEMPLATE( dice_roll_test, T, all_signed_test_types )
{
typedef boost::rational<T> rational_type;
// Determine the mean number of times a fair six-sided die
// must be thrown until each side has appeared at least once.
rational_type r = T( 0 );
for ( int i = 1 ; i <= 6 ; ++i )
{
r += rational_type( 1, i );
}
r *= static_cast<T>( 6 );
BOOST_CHECK_EQUAL( r, rational_type(147, 10) );
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
614
]
]
]
|
7b181e9a93467a99f2cc75451d5c05857a01727a | f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0 | /Depend/MyGUI/Tools/LayoutEditor/WidgetsWindow.h | c5aa35accb65e23a0a71c51cee957dc840699900 | []
| no_license | lxinhcn/starworld | 79ed06ca49d4064307ae73156574932d6185dbab | 86eb0fb8bd268994454b0cfe6419ffef3fc0fc80 | refs/heads/master | 2021-01-10T07:43:51.858394 | 2010-09-15T02:38:48 | 2010-09-15T02:38:48 | 47,859,019 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 889 | h | /*!
@file
@author Georgiy Evmenov
@date 09/2008
*/
#ifndef __WIDGETS_WINDOW_H__
#define __WIDGETS_WINDOW_H__
#include "BaseLayout/BaseLayout.h"
#include "EditorToolTip.h"
namespace tools
{
class WidgetsWindow :
public wraps::BaseLayout
{
public:
WidgetsWindow(MyGUI::Widget* _parent = nullptr);
virtual ~WidgetsWindow();
private:
void notifyToolTip(MyGUI::Widget* _sender, const MyGUI::ToolTipInfo& _info);
void notifySelectWidgetType(MyGUI::Widget* _sender);
void notifyChangeCreatorMode(bool _modeCreate);
void initialise();
private:
MyGUI::Tab* mTabSkins;
int mWidgetsButtonWidth;
int mWidgetsButtonHeight;
int mWidgetsButtonsInOneLine;
int mMaxLines;
std::string mSkinSheetName;
MyGUI::VectorWidgetPtr mWidgets;
EditorToolTip* mToolTip;
};
} // namespace tools
#endif // __WIDGETS_WINDOW_H__
| [
"albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c"
]
| [
[
[
1,
43
]
]
]
|
471cecb55a030ed7abb281a3c8a95dfa05495e66 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/python/test/indirect_traits_test.cpp | 9dd4030906bbdffb5c4ac0589528ec41527736ff | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,827 | cpp | // Copyright David Abrahams 2004. 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 <stdio.h>
#include <cassert>
#include <boost/python/detail/indirect_traits.hpp>
//#define print(expr) printf("%s ==> %s\n", #expr, expr)
// not all the compilers can handle an incomplete class type here.
struct X {};
int main()
{
using namespace boost::python::indirect_traits;
typedef void (X::*pmf)();
assert(is_reference_to_function<int (&)()>::value);
assert(!is_reference_to_function<int (*)()>::value);
assert(!is_reference_to_function<int&>::value);
assert(!is_reference_to_function<pmf>::value);
assert(!is_pointer_to_function<int (&)()>::value);
assert(is_pointer_to_function<int (*)()>::value);
assert(!is_pointer_to_function<int (*&)()>::value);
assert(!is_pointer_to_function<int (*const&)()>::value);
assert(!is_pointer_to_function<pmf>::value);
assert(!is_reference_to_function_pointer<int (&)()>::value);
assert(!is_reference_to_function_pointer<int (*)()>::value);
assert(!is_reference_to_function_pointer<int&>::value);
assert(is_reference_to_function_pointer<int (*&)()>::value);
assert(is_reference_to_function_pointer<int (*const&)()>::value);
assert(!is_reference_to_function_pointer<pmf>::value);
assert(is_reference_to_pointer<int*&>::value);
assert(is_reference_to_pointer<int* const&>::value);
assert(is_reference_to_pointer<int*volatile&>::value);
assert(is_reference_to_pointer<int*const volatile&>::value);
assert(is_reference_to_pointer<int const*&>::value);
assert(is_reference_to_pointer<int const* const&>::value);
assert(is_reference_to_pointer<int const*volatile&>::value);
assert(is_reference_to_pointer<int const*const volatile&>::value);
assert(!is_reference_to_pointer<pmf>::value);
assert(!is_reference_to_pointer<int const volatile>::value);
assert(!is_reference_to_pointer<int>::value);
assert(!is_reference_to_pointer<int*>::value);
assert(!is_reference_to_const<int*&>::value);
assert(is_reference_to_const<int* const&>::value);
assert(!is_reference_to_const<int*volatile&>::value);
assert(is_reference_to_const<int*const volatile&>::value);
assert(!is_reference_to_const<int const volatile>::value);
assert(!is_reference_to_const<int>::value);
assert(!is_reference_to_const<int*>::value);
assert(is_reference_to_non_const<int*&>::value);
assert(!is_reference_to_non_const<int* const&>::value);
assert(is_reference_to_non_const<int*volatile&>::value);
assert(!is_reference_to_non_const<int*const volatile&>::value);
assert(!is_reference_to_non_const<int const volatile>::value);
assert(!is_reference_to_non_const<int>::value);
assert(!is_reference_to_non_const<int*>::value);
assert(!is_reference_to_volatile<int*&>::value);
assert(!is_reference_to_volatile<int* const&>::value);
assert(is_reference_to_volatile<int*volatile&>::value);
assert(is_reference_to_volatile<int*const volatile&>::value);
assert(!is_reference_to_volatile<int const volatile>::value);
assert(!is_reference_to_volatile<int>::value);
assert(!is_reference_to_volatile<int*>::value);
assert(!is_reference_to_class<int>::value);
assert(!is_reference_to_class<int&>::value);
assert(!is_reference_to_class<int*>::value);
assert(!is_reference_to_class<X>::value);
assert(is_reference_to_class<X&>::value);
assert(is_reference_to_class<X const&>::value);
assert(is_reference_to_class<X volatile&>::value);
assert(is_reference_to_class<X const volatile&>::value);
assert(!is_pointer_to_class<int>::value);
assert(!is_pointer_to_class<int*>::value);
assert(!is_pointer_to_class<int&>::value);
assert(!is_pointer_to_class<X>::value);
assert(!is_pointer_to_class<X&>::value);
assert(is_pointer_to_class<X*>::value);
assert(is_pointer_to_class<X const*>::value);
assert(is_pointer_to_class<X volatile*>::value);
assert(is_pointer_to_class<X const volatile*>::value);
assert(is_reference_to_member_function_pointer<pmf&>::value);
assert(is_reference_to_member_function_pointer<pmf const&>::value);
assert(is_reference_to_member_function_pointer<pmf volatile&>::value);
assert(is_reference_to_member_function_pointer<pmf const volatile&>::value);
assert(!is_reference_to_member_function_pointer<pmf[2]>::value);
assert(!is_reference_to_member_function_pointer<pmf(&)[2]>::value);
assert(!is_reference_to_member_function_pointer<pmf>::value);
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
108
]
]
]
|
c4aa8e2d8fb09107d2d30df5a1ee7b413c6e8dff | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Metrics/AdvancedNormalizedCorrelation/itkAdvancedNormalizedCorrelationImageToImageMetric.h | 2bc17a72e67afcd5019d09b5a6ec7828a01e1ef5 | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,741 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php for
details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
======================================================================*/
#ifndef __itkAdvancedNormalizedCorrelationImageToImageMetric_h
#define __itkAdvancedNormalizedCorrelationImageToImageMetric_h
#include "itkAdvancedImageToImageMetric.h"
namespace itk
{
/** \class AdvancedNormalizedCorrelationImageToImageMetric
* \brief Computes normalized correlation between two images, based on AdvancedImageToImageMetric...
*
* This metric computes the correlation between pixels in the fixed image
* and pixels in the moving image. The spatial correspondance between
* fixed and moving image is established through a Transform. Pixel values are
* taken from the fixed image, their positions are mapped to the moving
* image and result in general in non-grid position on it. Values at these
* non-grid position of the moving image are interpolated using a user-selected
* Interpolator. The correlation is normalized by the autocorrelations of both
* the fixed and moving images.
*
* This implementation of the NormalizedCorrelation is based on the
* AdvancedImageToImageMetric, which means that:
* \li It uses the ImageSampler-framework
* \li It makes use of the compact support of B-splines, in case of B-spline transforms.
* \li Image derivatives are computed using either the B-spline interpolator's implementation
* or by nearest neighbor interpolation of a precomputed central difference image.
* \li A minimum number of samples that should map within the moving image (mask) can be specified.
*
* The normalized correlation NC is defined as:
*
* \f[
* \mathrm{NC} = \frac{\sum_x f(x) * m(x+u(x,p))}{\sqrt{ \sum_x f(x)^2 * \sum_x m(x+u(x,p))^2}}
* = \frac{\mathtt{sfm}}{\sqrt{\mathtt{sff} * \mathtt{smm}}}
* \f]
*
* where x a voxel in the fixed image f, m the moving image, u(x,p) the
* deformation of x depending on the transform parameters p. sfm, sff and smm
* is notation used in the source code. The derivative of NC to p equals:
*
* \f[
* \frac{\partial \mathrm{NC}}{\partial p} = \frac{\partial \mathrm{NC}}{\partial m} \frac{\partial m}{\partial x} \frac{\partial x}{\partial p} = \frac{\partial \mathrm{NC}}{\partial m} * \mathtt{gradient} * \mathtt{jacobian},
* \f]
*
* where gradient is the derivative of the moving image m to x, and where Jacobian is the
* derivative of the transformation to its parameters. gradient * Jacobian is called the differential.
* This yields for the derivative:
*
* \f[
* \frac{\partial \mathrm{NC}}{\partial p} = \frac{\sum_x[ f(x) * \mathtt{differential} ] - ( \mathtt{sfm} / \mathtt{smm} ) * \sum_x[ m(x+u(x,p)) * \mathtt{differential} ]}{\sqrt{\mathtt{sff} * \mathtt{smm}}}
* \f]
*
* This class has an option to subtract the sample mean from the sample values
* in the cross correlation formula. This typically results in narrower valleys
* in the cost fucntion NC. The default value is false. If SubtractMean is true,
* the NC is defined as:
*
* \f[
* \mathrm{NC} = \frac{\sum_x ( f(x) - \mathtt{Af} ) * ( m(x+u(x,p)) - \mathtt{Am})}{\sqrt{\sum_x (f(x) - \mathtt{Af})^2 * \sum_x (m(x+u(x,p)) - \mathtt{Am})^2}}
* = \frac{\mathtt{sfm} - \mathtt{sf} * \mathtt{sm} / N}{\sqrt{(\mathtt{sff} - \mathtt{sf} * \mathtt{sf} / N) * (\mathtt{smm} - \mathtt{sm} *\mathtt{sm} / N)}},
* \f]
*
* where Af and Am are the average of f and m, respectively.
*
*
* \ingroup RegistrationMetrics
* \ingroup Metrics
*/
template < class TFixedImage, class TMovingImage >
class AdvancedNormalizedCorrelationImageToImageMetric :
public AdvancedImageToImageMetric< TFixedImage, TMovingImage >
{
public:
/** Standard class typedefs. */
typedef AdvancedNormalizedCorrelationImageToImageMetric Self;
typedef AdvancedImageToImageMetric<
TFixedImage, TMovingImage > Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( AdvancedNormalizedCorrelationImageToImageMetric, AdvancedImageToImageMetric );
/** Typedefs from the superclass. */
typedef typename
Superclass::CoordinateRepresentationType CoordinateRepresentationType;
typedef typename Superclass::MovingImageType MovingImageType;
typedef typename Superclass::MovingImagePixelType MovingImagePixelType;
typedef typename Superclass::MovingImageConstPointer MovingImageConstPointer;
typedef typename Superclass::FixedImageType FixedImageType;
typedef typename Superclass::FixedImageConstPointer FixedImageConstPointer;
typedef typename Superclass::FixedImageRegionType FixedImageRegionType;
typedef typename Superclass::TransformType TransformType;
typedef typename Superclass::TransformPointer TransformPointer;
typedef typename Superclass::InputPointType InputPointType;
typedef typename Superclass::OutputPointType OutputPointType;
typedef typename Superclass::TransformParametersType TransformParametersType;
typedef typename Superclass::TransformJacobianType TransformJacobianType;
typedef typename Superclass::InterpolatorType InterpolatorType;
typedef typename Superclass::InterpolatorPointer InterpolatorPointer;
typedef typename Superclass::RealType RealType;
typedef typename Superclass::GradientPixelType GradientPixelType;
typedef typename Superclass::GradientImageType GradientImageType;
typedef typename Superclass::GradientImagePointer GradientImagePointer;
typedef typename Superclass::GradientImageFilterType GradientImageFilterType;
typedef typename Superclass::GradientImageFilterPointer GradientImageFilterPointer;
typedef typename Superclass::FixedImageMaskType FixedImageMaskType;
typedef typename Superclass::FixedImageMaskPointer FixedImageMaskPointer;
typedef typename Superclass::MovingImageMaskType MovingImageMaskType;
typedef typename Superclass::MovingImageMaskPointer MovingImageMaskPointer;
typedef typename Superclass::MeasureType MeasureType;
typedef typename Superclass::DerivativeType DerivativeType;
typedef typename Superclass::ParametersType ParametersType;
typedef typename Superclass::FixedImagePixelType FixedImagePixelType;
typedef typename Superclass::MovingImageRegionType MovingImageRegionType;
typedef typename Superclass::ImageSamplerType ImageSamplerType;
typedef typename Superclass::ImageSamplerPointer ImageSamplerPointer;
typedef typename Superclass::ImageSampleContainerType ImageSampleContainerType;
typedef typename
Superclass::ImageSampleContainerPointer ImageSampleContainerPointer;
typedef typename Superclass::FixedImageLimiterType FixedImageLimiterType;
typedef typename Superclass::MovingImageLimiterType MovingImageLimiterType;
typedef typename
Superclass::FixedImageLimiterOutputType FixedImageLimiterOutputType;
typedef typename
Superclass::MovingImageLimiterOutputType MovingImageLimiterOutputType;
typedef typename
Superclass::MovingImageDerivativeScalesType MovingImageDerivativeScalesType;
/** The fixed image dimension. */
itkStaticConstMacro( FixedImageDimension, unsigned int,
FixedImageType::ImageDimension );
/** The moving image dimension. */
itkStaticConstMacro( MovingImageDimension, unsigned int,
MovingImageType::ImageDimension );
/** Get the value for single valued optimizers. */
MeasureType GetValue( const TransformParametersType & parameters ) const;
/** Get the derivatives of the match measure. */
void GetDerivative( const TransformParametersType & parameters,
DerivativeType & Derivative ) const;
/** Get value and derivatives for multiple valued optimizers. */
void GetValueAndDerivative( const TransformParametersType & parameters,
MeasureType& Value, DerivativeType& Derivative ) const;
/** Set/Get SubtractMean boolean. If true, the sample mean is subtracted
* from the sample values in the cross-correlation formula and
* typically results in narrower valleys in the cost fucntion.
* Default value is false. */
itkSetMacro( SubtractMean, bool );
itkGetConstReferenceMacro( SubtractMean, bool );
itkBooleanMacro( SubtractMean );
protected:
AdvancedNormalizedCorrelationImageToImageMetric();
virtual ~AdvancedNormalizedCorrelationImageToImageMetric() {};
void PrintSelf( std::ostream& os, Indent indent ) const;
/** Protected Typedefs ******************/
/** Typedefs inherited from superclass */
typedef typename Superclass::FixedImageIndexType FixedImageIndexType;
typedef typename Superclass::FixedImageIndexValueType FixedImageIndexValueType;
typedef typename Superclass::MovingImageIndexType MovingImageIndexType;
typedef typename Superclass::FixedImagePointType FixedImagePointType;
typedef typename Superclass::MovingImagePointType MovingImagePointType;
typedef typename Superclass::MovingImageContinuousIndexType MovingImageContinuousIndexType;
typedef typename Superclass::BSplineInterpolatorType BSplineInterpolatorType;
typedef typename Superclass::CentralDifferenceGradientFilterType CentralDifferenceGradientFilterType;
typedef typename Superclass::MovingImageDerivativeType MovingImageDerivativeType;
typedef typename Superclass::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
/** Computes the innerproduct of transform Jacobian with moving image gradient.
* The results are stored in imageJacobian, which is supposed
* to have the right size (same length as Jacobian's number of columns). */
void EvaluateTransformJacobianInnerProduct(
const TransformJacobianType & jacobian,
const MovingImageDerivativeType & movingImageDerivative,
DerivativeType & imageJacobian) const;
/** Compute a pixel's contribution to the derivative terms;
* Called by GetValueAndDerivative(). */
void UpdateDerivativeTerms(
const RealType fixedImageValue,
const RealType movingImageValue,
const DerivativeType & imageJacobian,
const NonZeroJacobianIndicesType & nzji,
DerivativeType & derivativeF,
DerivativeType & derivativeM,
DerivativeType & differential ) const;
private:
AdvancedNormalizedCorrelationImageToImageMetric(const Self&); //purposely not implemented
void operator=(const Self&); //purposely not implemented
bool m_SubtractMean;
}; // end class AdvancedNormalizedCorrelationImageToImageMetric
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkAdvancedNormalizedCorrelationImageToImageMetric.txx"
#endif
#endif // end #ifndef __itkAdvancedNormalizedCorrelationImageToImageMetric_h
| [
"[email protected]"
]
| [
[
[
1,
227
]
]
]
|
76edc2c8beb874d052bec1fed384a30a001e351f | b50d915027e6fb2eb315264c3791727074d6a502 | /Libraries/pcl-1.2-bodyscanner/features/include/pcl/features/fpfh.h | 0cf88e2d9a8be9b2f29d4ff27374567f9d6b089a | [
"BSD-3-Clause"
]
| permissive | aybassiouny/BodyScanner | ff49df6de74fb9471eb1e323350e8d1345cf71de | 4eeb30466eb198ed520d218ddb90607734241474 | refs/heads/master | 2021-01-18T09:41:58.308546 | 2011-10-19T07:04:14 | 2011-10-19T07:04:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,546 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, 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 Willow Garage, Inc. 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.
*
* $Id: fpfh.h 2532 2011-09-20 20:39:18Z bouffa $
*
*/
#ifndef PCL_FPFH_H_
#define PCL_FPFH_H_
#include <pcl/features/feature.h>
#include <set>
namespace pcl
{
/** \brief @b FPFHEstimation estimates the <b>Fast Point Feature Histogram (FPFH)</b> descriptor for a given point
* cloud dataset containing points and normals.
*
* @note If you use this code in any academic work, please cite:
*
* <ul>
* <li> R.B. Rusu, N. Blodow, M. Beetz.
* Fast Point Feature Histograms (FPFH) for 3D Registration.
* In Proceedings of the IEEE International Conference on Robotics and Automation (ICRA),
* Kobe, Japan, May 12-17 2009.
* </li>
* <li> R.B. Rusu, A. Holzbach, N. Blodow, M. Beetz.
* Fast Geometric Point Labeling using Conditional Random Fields.
* In Proceedings of the 22nd IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS),
* St. Louis, MO, USA, October 11-15 2009.
* </li>
* </ul>
*
* @note The code is stateful as we do not expect this class to be multicore parallelized. Please look at
* \ref FPFHEstimationOMP for examples on parallel implementations of the FPFH (Fast Point Feature Histogram).
* \author Radu Bogdan Rusu
* \ingroup features
*/
template <typename PointInT, typename PointNT, typename PointOutT>
class FPFHEstimation : public FeatureFromNormals<PointInT, PointNT, PointOutT>
{
public:
using Feature<PointInT, PointOutT>::feature_name_;
using Feature<PointInT, PointOutT>::getClassName;
using Feature<PointInT, PointOutT>::indices_;
using Feature<PointInT, PointOutT>::k_;
using Feature<PointInT, PointOutT>::search_parameter_;
using Feature<PointInT, PointOutT>::input_;
using Feature<PointInT, PointOutT>::surface_;
using FeatureFromNormals<PointInT, PointNT, PointOutT>::normals_;
typedef typename Feature<PointInT, PointOutT>::PointCloudOut PointCloudOut;
/** \brief Empty constructor. */
FPFHEstimation () : nr_bins_f1_ (11), nr_bins_f2_ (11), nr_bins_f3_ (11), d_pi_ ((float)(1.0 / (2.0 * M_PI)))
{
feature_name_ = "FPFHEstimation";
};
/** \brief Compute the 4-tuple representation containing the three angles and one distance between two points
* represented by Cartesian coordinates and normals.
* \note For explanations about the features, please see the literature mentioned above (the order of the
* features might be different).
* \param cloud the dataset containing the XYZ Cartesian coordinates of the two points
* \param normals the dataset containing the surface normals (assuming normalized vectors) at each point in cloud
* \param p_idx the index of the first point (source)
* \param q_idx the index of the second point (target)
* \param f1 the first angular feature (angle between the projection of nq_idx and u)
* \param f2 the second angular feature (angle between nq_idx and v)
* \param f3 the third angular feature (angle between np_idx and |p_idx - q_idx|)
* \param f4 the distance feature (p_idx - q_idx)
*/
bool
computePairFeatures (const pcl::PointCloud<PointInT> &cloud, const pcl::PointCloud<PointNT> &normals,
int p_idx, int q_idx, float &f1, float &f2, float &f3, float &f4);
/** \brief Estimate the SPFH (Simple Point Feature Histograms) individual signatures of the three angular
* (f1, f2, f3) features for a given point based on its spatial neighborhood of 3D points with normals
* \param cloud the dataset containing the XYZ Cartesian coordinates of the two points
* \param normals the dataset containing the surface normals at each point in \a cloud
* \param p_idx the index of the query point (source)
* \param row the index of row in SPFH histograms (destination)
* \param indices the k-neighborhood point indices in the dataset
* \param hist_f1 the resultant SPFH histogram for feature f1
* \param hist_f2 the resultant SPFH histogram for feature f2
* \param hist_f3 the resultant SPFH histogram for feature f3
*/
void
computePointSPFHSignature (const pcl::PointCloud<PointInT> &cloud,
const pcl::PointCloud<PointNT> &normals, int p_idx, int row,
const std::vector<int> &indices,
Eigen::MatrixXf &hist_f1, Eigen::MatrixXf &hist_f2, Eigen::MatrixXf &hist_f3);
/** \brief Weight the SPFH (Simple Point Feature Histograms) individual histograms to create the final FPFH
* (Fast Point Feature Histogram) for a given point based on its 3D spatial neighborhood
* \param hist_f1 the histogram feature vector of \a f1 values over the given patch
* \param hist_f2 the histogram feature vector of \a f2 values over the given patch
* \param hist_f3 the histogram feature vector of \a f3 values over the given patch
* \param indices the point indices of p_idx's k-neighborhood in the point cloud
* \param dists the distances from p_idx to all its k-neighbors
* \param fpfh_histogram the resultant FPFH histogram representing the feature at the query point
*/
void
weightPointSPFHSignature (const Eigen::MatrixXf &hist_f1,
const Eigen::MatrixXf &hist_f2,
const Eigen::MatrixXf &hist_f3,
const std::vector<int> &indices,
const std::vector<float> &dists,
Eigen::VectorXf &fpfh_histogram);
/** \brief Set the number of subdivisions for each angular feature interval.
* \param nr_bins_f1 number of subdivisions for the first angular feature
* \param nr_bins_f2 number of subdivisions for the second angular feature
* \param nr_bins_f3 number of subdivisions for the third angular feature
*/
inline void
setNrSubdivisions (int nr_bins_f1, int nr_bins_f2, int nr_bins_f3)
{
nr_bins_f1_ = nr_bins_f1;
nr_bins_f2_ = nr_bins_f2;
nr_bins_f3_ = nr_bins_f3;
}
/** \brief Get the number of subdivisions for each angular feature interval. */
inline void
getNrSubdivisions (int &nr_bins_f1, int &nr_bins_f2, int &nr_bins_f3)
{
nr_bins_f1 = nr_bins_f1_;
nr_bins_f2 = nr_bins_f2_;
nr_bins_f3 = nr_bins_f3_;
}
protected:
/** \brief Estimate the Fast Point Feature Histograms (FPFH) descriptors at a set of points given by
* <setInputCloud (), setIndices ()> using the surface in setSearchSurface () and the spatial locator in
* setSearchMethod ()
* \param output the resultant point cloud model dataset that contains the FPFH feature estimates
*/
void
computeFeature (PointCloudOut &output);
/** \brief The number of subdivisions for each angular feature interval. */
int nr_bins_f1_, nr_bins_f2_, nr_bins_f3_;
/** \brief Placeholder for the f1 histogram. */
Eigen::MatrixXf hist_f1_;
/** \brief Placeholder for the f2 histogram. */
Eigen::MatrixXf hist_f2_;
/** \brief Placeholder for the f3 histogram. */
Eigen::MatrixXf hist_f3_;
private:
/** \brief Placeholder for a point's FPFH signature. */
Eigen::VectorXf fpfh_histogram_;
/** \brief Float constant = 1.0 / (2.0 * M_PI) */
float d_pi_;
};
}
#endif //#ifndef PCL_FPFH_H_
| [
"[email protected]"
]
| [
[
[
1,
195
]
]
]
|
f571ab2a3cefdbe0619e64bd5abf89e8707ad188 | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/WindowsCE/StringListDialog.hpp | 58de4846c0ecdf0a61741a771cee3fdaa83691fb | []
| no_license | danste/ars-framework | 5e7864630fd8dbf7f498f58cf6f9a62f8e1d95c6 | 90f99d43804d3892432acbe622b15ded6066ea5d | refs/heads/master | 2022-11-11T15:31:02.271791 | 2005-10-17T15:37:36 | 2005-10-17T15:37:36 | 263,623,421 | 0 | 0 | null | 2020-05-13T12:28:22 | 2020-05-13T12:28:21 | null | UTF-8 | C++ | false | false | 352 | hpp | #ifndef _STRING_LIST_DLG_H_
#define _STRING_LIST_DLG_H_
#include <Text.hpp>
#include <windows.h>
using ArsLexis::String;
bool FGetStringFromList(HWND hwnd, CharPtrList_t& strList, CharPtrList_t* labels, String& strOut);
bool FGetStringFromListRemoveDups(HWND hwnd, CharPtrList_t& strList, CharPtrList_t* labels, String& strOut);
#endif
| [
"kjk@10a9aba9-86da-0310-ac04-a2df2cc00fd9",
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
]
| [
[
[
1,
8
],
[
11,
12
]
],
[
[
9,
10
]
]
]
|
e7b4c2575a7538e2b32771ddef196f442598c532 | b2d46af9c6152323ce240374afc998c1574db71f | /cursovideojuegos/theflostiproject/3rdParty/boost/libs/iterator/example/projection_iterator_example.cpp | 7c85a83894a9805d1d4da3f1b2dc91b506cc2bad | []
| no_license | bugbit/cipsaoscar | 601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4 | 52aa8b4b67d48f59e46cb43527480f8b3552e96d | refs/heads/master | 2021-01-10T21:31:18.653163 | 2011-09-28T16:39:12 | 2011-09-28T16:39:12 | 33,032,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,069 | cpp | // (C) Copyright Jeremy Siek 2000.
// 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/config.hpp>
#include <list>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <string>
#include <boost/iterator/transform_iterator.hpp>
struct personnel_record {
personnel_record(std::string n, int id) : m_name(n), m_ID(id) { }
std::string m_name;
int m_ID;
};
struct select_name {
typedef personnel_record argument_type;
typedef std::string const& result_type;
const std::string& operator()(const personnel_record& r) const {
return r.m_name;
}
std::string& operator()(personnel_record& r) const {
return r.m_name;
}
};
struct select_ID {
typedef personnel_record argument_type;
typedef int& result_type;
const int& operator()(const personnel_record& r) const {
return r.m_ID;
}
int& operator()(personnel_record& r) const {
return r.m_ID;
}
};
int main(int, char*[])
{
std::list<personnel_record> personnel_list;
personnel_list.push_back(personnel_record("Barney", 13423));
personnel_list.push_back(personnel_record("Fred", 12343));
personnel_list.push_back(personnel_record("Wilma", 62454));
personnel_list.push_back(personnel_record("Betty", 20490));
// Example of using transform_iterator to print out the names in the
// personnel list using a projection.
boost::transform_iterator<
select_name
, std::list<personnel_record>::iterator
#ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
, std::string
#endif
>
personnel_first(personnel_list.begin()),
personnel_last(personnel_list.end());
std::copy(personnel_first, personnel_last,
std::ostream_iterator<std::string>(std::cout, "\n"));
std::cout << std::endl;
// Example of using transform_iterator with const_iterators to
// assign new ID numbers to the personnel.
boost::transform_iterator<
select_ID, std::list<personnel_record>::iterator
> ID_first(personnel_list.begin()),
ID_last(personnel_list.end());
int new_id = 0;
while (ID_first != ID_last) {
*ID_first = new_id++;
++ID_first;
}
boost::transform_iterator<
select_ID, std::list<personnel_record>::const_iterator, int const&
>
const_ID_first(personnel_list.begin()),
const_ID_last(personnel_list.end());
std::copy(const_ID_first, const_ID_last,
std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::cout << std::endl;
#ifndef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
// Example of using make_transform_iterator()
// to print out the names in the personnel list again.
std::copy(
boost::make_transform_iterator<select_name>(personnel_list.begin())
, boost::make_transform_iterator<select_name>(personnel_list.end())
, std::ostream_iterator<std::string>(std::cout, "\n"));
#endif
return 0;
}
| [
"ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a"
]
| [
[
[
1,
103
]
]
]
|
0f13ee738cfa60583be7aac62a543ae709f40c77 | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /code/ProcessHelper.cpp | 7f773b3d5d04f0958638f351b9dc5f77de33e69a | [
"BSD-3-Clause"
]
| permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,460 | cpp | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software 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 ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
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.
----------------------------------------------------------------------
*/
/// @file ProcessHelper.cpp
/** Implement shared utility functions for postprocessing steps */
#include "AssimpPCH.h"
#include "ProcessHelper.h"
#include <limits>
namespace Assimp {
// -------------------------------------------------------------------------------
void ConvertListToStrings(const std::string& in, std::list<std::string>& out)
{
const char* s = in.c_str();
while (*s) {
SkipSpacesAndLineEnd(&s);
if (*s == '\'') {
const char* base = ++s;
while (*s != '\'') {
++s;
if (*s == '\0') {
DefaultLogger::get()->error("ConvertListToString: String list is ill-formatted");
return;
}
}
out.push_back(std::string(base,(size_t)(s-base)));
++s;
}
else {
out.push_back(GetNextToken(s));
}
}
}
// -------------------------------------------------------------------------------
void FindAABBTransformed (const aiMesh* mesh, aiVector3D& min, aiVector3D& max,
const aiMatrix4x4& m)
{
min = aiVector3D (10e10f, 10e10f, 10e10f);
max = aiVector3D (-10e10f,-10e10f,-10e10f);
for (unsigned int i = 0;i < mesh->mNumVertices;++i)
{
const aiVector3D v = m * mesh->mVertices[i];
min = std::min(v,min);
max = std::max(v,max);
}
}
// -------------------------------------------------------------------------------
void FindMeshCenter (aiMesh* mesh, aiVector3D& out, aiVector3D& min, aiVector3D& max)
{
ArrayBounds(mesh->mVertices,mesh->mNumVertices, min,max);
out = min + (max-min)*0.5f;
}
// -------------------------------------------------------------------------------
void FindMeshCenterTransformed (aiMesh* mesh, aiVector3D& out, aiVector3D& min,
aiVector3D& max, const aiMatrix4x4& m)
{
FindAABBTransformed(mesh,min,max,m);
out = min + (max-min)*0.5f;
}
// -------------------------------------------------------------------------------
void FindMeshCenter (aiMesh* mesh, aiVector3D& out)
{
aiVector3D min,max;
FindMeshCenter(mesh,out,min,max);
}
// -------------------------------------------------------------------------------
void FindMeshCenterTransformed (aiMesh* mesh, aiVector3D& out,
const aiMatrix4x4& m)
{
aiVector3D min,max;
FindMeshCenterTransformed(mesh,out,min,max,m);
}
// -------------------------------------------------------------------------------
float ComputePositionEpsilon(const aiMesh* pMesh)
{
const float epsilon = 1e-4f;
// calculate the position bounds so we have a reliable epsilon to check position differences against
aiVector3D minVec, maxVec;
ArrayBounds(pMesh->mVertices,pMesh->mNumVertices,minVec,maxVec);
return (maxVec - minVec).Length() * epsilon;
}
// -------------------------------------------------------------------------------
float ComputePositionEpsilon(const aiMesh* const* pMeshes, size_t num)
{
const float epsilon = 1e-4f;
// calculate the position bounds so we have a reliable epsilon to check position differences against
aiVector3D minVec, maxVec, mi, ma;
MinMaxChooser<aiVector3D>()(minVec,maxVec);
for (size_t a = 0; a < num; ++a) {
const aiMesh* pMesh = pMeshes[a];
ArrayBounds(pMesh->mVertices,pMesh->mNumVertices,mi,ma);
minVec = std::min(minVec,mi);
maxVec = std::max(maxVec,ma);
}
return (maxVec - minVec).Length() * epsilon;
}
// -------------------------------------------------------------------------------
unsigned int GetMeshVFormatUnique(const aiMesh* pcMesh)
{
ai_assert(NULL != pcMesh);
// FIX: the hash may never be 0. Otherwise a comparison against
// nullptr could be successful
unsigned int iRet = 1;
// normals
if (pcMesh->HasNormals())iRet |= 0x2;
// tangents and bitangents
if (pcMesh->HasTangentsAndBitangents())iRet |= 0x4;
#ifdef BOOST_STATIC_ASSERT
BOOST_STATIC_ASSERT(8 >= AI_MAX_NUMBER_OF_COLOR_SETS);
BOOST_STATIC_ASSERT(8 >= AI_MAX_NUMBER_OF_TEXTURECOORDS);
#endif
// texture coordinates
unsigned int p = 0;
while (pcMesh->HasTextureCoords(p))
{
iRet |= (0x100 << p);
if (3 == pcMesh->mNumUVComponents[p])
iRet |= (0x10000 << p);
++p;
}
// vertex colors
p = 0;
while (pcMesh->HasVertexColors(p))iRet |= (0x1000000 << p++);
return iRet;
}
// -------------------------------------------------------------------------------
VertexWeightTable* ComputeVertexBoneWeightTable(const aiMesh* pMesh)
{
if (!pMesh || !pMesh->mNumVertices || !pMesh->mNumBones) {
return NULL;
}
VertexWeightTable* avPerVertexWeights = new VertexWeightTable[pMesh->mNumVertices];
for (unsigned int i = 0; i < pMesh->mNumBones;++i) {
aiBone* bone = pMesh->mBones[i];
for (unsigned int a = 0; a < bone->mNumWeights;++a) {
const aiVertexWeight& weight = bone->mWeights[a];
avPerVertexWeights[weight.mVertexId].push_back( std::pair<unsigned int,float>(i,weight.mWeight) );
}
}
return avPerVertexWeights;
}
// -------------------------------------------------------------------------------
const char* TextureTypeToString(aiTextureType in)
{
switch (in)
{
case aiTextureType_NONE:
return "n/a";
case aiTextureType_DIFFUSE:
return "Diffuse";
case aiTextureType_SPECULAR:
return "Specular";
case aiTextureType_AMBIENT:
return "Ambient";
case aiTextureType_EMISSIVE:
return "Emissive";
case aiTextureType_OPACITY:
return "Opacity";
case aiTextureType_NORMALS:
return "Normals";
case aiTextureType_HEIGHT:
return "Height";
case aiTextureType_SHININESS:
return "Shininess";
case aiTextureType_DISPLACEMENT:
return "Displacement";
case aiTextureType_LIGHTMAP:
return "Lightmap";
case aiTextureType_REFLECTION:
return "Reflection";
case aiTextureType_UNKNOWN:
return "Unknown";
default:
break;
}
ai_assert(false);
return "BUG";
}
// -------------------------------------------------------------------------------
const char* MappingTypeToString(aiTextureMapping in)
{
switch (in)
{
case aiTextureMapping_UV:
return "UV";
case aiTextureMapping_BOX:
return "Box";
case aiTextureMapping_SPHERE:
return "Sphere";
case aiTextureMapping_CYLINDER:
return "Cylinder";
case aiTextureMapping_PLANE:
return "Plane";
case aiTextureMapping_OTHER:
return "Other";
default:
break;
}
ai_assert(false);
return "BUG";
}
// -------------------------------------------------------------------------------
aiMesh* MakeSubmesh(const aiMesh *pMesh, const std::vector<unsigned int> &subMeshFaces, unsigned int subFlags)
{
aiMesh *oMesh = new aiMesh();
std::vector<unsigned int> vMap(pMesh->mNumVertices,UINT_MAX);
size_t numSubVerts = 0;
size_t numSubFaces = subMeshFaces.size();
for(unsigned int i=0;i<numSubFaces;i++) {
const aiFace &f = pMesh->mFaces[subMeshFaces[i]];
for(unsigned int j=0;j<f.mNumIndices;j++) {
if(vMap[f.mIndices[j]]==UINT_MAX) {
vMap[f.mIndices[j]] = numSubVerts++;
}
}
}
oMesh->mName = pMesh->mName;
oMesh->mMaterialIndex = pMesh->mMaterialIndex;
oMesh->mPrimitiveTypes = pMesh->mPrimitiveTypes;
// create all the arrays for this mesh if the old mesh contained them
oMesh->mNumFaces = subMeshFaces.size();
oMesh->mNumVertices = numSubVerts;
oMesh->mVertices = new aiVector3D[numSubVerts];
if( pMesh->HasNormals() ) {
oMesh->mNormals = new aiVector3D[numSubVerts];
}
if( pMesh->HasTangentsAndBitangents() ) {
oMesh->mTangents = new aiVector3D[numSubVerts];
oMesh->mBitangents = new aiVector3D[numSubVerts];
}
for( size_t a = 0; pMesh->HasTextureCoords( a) ; ++a ) {
oMesh->mTextureCoords[a] = new aiVector3D[numSubVerts];
oMesh->mNumUVComponents[a] = pMesh->mNumUVComponents[a];
}
for( size_t a = 0; pMesh->HasVertexColors( a); ++a ) {
oMesh->mColors[a] = new aiColor4D[numSubVerts];
}
// and copy over the data, generating faces with linear indices along the way
oMesh->mFaces = new aiFace[numSubFaces];
for(unsigned int a = 0; a < numSubFaces; ++a ) {
const aiFace& srcFace = pMesh->mFaces[subMeshFaces[a]];
aiFace& dstFace = oMesh->mFaces[a];
dstFace.mNumIndices = srcFace.mNumIndices;
dstFace.mIndices = new unsigned int[dstFace.mNumIndices];
// accumulate linearly all the vertices of the source face
for( size_t b = 0; b < dstFace.mNumIndices; ++b ) {
dstFace.mIndices[b] = vMap[srcFace.mIndices[b]];
}
}
for(unsigned int srcIndex = 0; srcIndex < pMesh->mNumVertices; ++srcIndex ) {
unsigned int nvi = vMap[srcIndex];
if(nvi==UINT_MAX) {
continue;
}
oMesh->mVertices[nvi] = pMesh->mVertices[srcIndex];
if( pMesh->HasNormals() ) {
oMesh->mNormals[nvi] = pMesh->mNormals[srcIndex];
}
if( pMesh->HasTangentsAndBitangents() ) {
oMesh->mTangents[nvi] = pMesh->mTangents[srcIndex];
oMesh->mBitangents[nvi] = pMesh->mBitangents[srcIndex];
}
for( size_t c = 0, cc = pMesh->GetNumUVChannels(); c < cc; ++c ) {
oMesh->mTextureCoords[c][nvi] = pMesh->mTextureCoords[c][srcIndex];
}
for( size_t c = 0, cc = pMesh->GetNumColorChannels(); c < cc; ++c ) {
oMesh->mColors[c][nvi] = pMesh->mColors[c][srcIndex];
}
}
if(~subFlags&AI_SUBMESH_FLAGS_SANS_BONES) {
std::vector<unsigned int> subBones(pMesh->mNumBones,0);
for(unsigned int a=0;a<pMesh->mNumBones;++a) {
const aiBone* bone = pMesh->mBones[a];
for(unsigned int b=0;b<bone->mNumWeights;b++) {
unsigned int v = vMap[bone->mWeights[b].mVertexId];
if(v!=UINT_MAX) {
subBones[a]++;
}
}
}
for(unsigned int a=0;a<pMesh->mNumBones;++a) {
if(subBones[a]>0) {
oMesh->mNumBones++;
}
}
if(oMesh->mNumBones) {
oMesh->mBones = new aiBone*[oMesh->mNumBones]();
unsigned int nbParanoia = oMesh->mNumBones;
oMesh->mNumBones = 0; //rewind
for(unsigned int a=0;a<pMesh->mNumBones;++a) {
if(subBones[a]==0) {
continue;
}
aiBone *newBone = new aiBone;
oMesh->mBones[oMesh->mNumBones++] = newBone;
const aiBone* bone = pMesh->mBones[a];
newBone->mName = bone->mName;
newBone->mOffsetMatrix = bone->mOffsetMatrix;
newBone->mWeights = new aiVertexWeight[subBones[a]];
for(unsigned int b=0;b<bone->mNumWeights;b++) {
const unsigned int v = vMap[bone->mWeights[b].mVertexId];
if(v!=UINT_MAX) {
aiVertexWeight w(v,bone->mWeights[b].mWeight);
newBone->mWeights[newBone->mNumWeights++] = w;
}
}
}
ai_assert(nbParanoia==oMesh->mNumBones);
(void)nbParanoia; // remove compiler warning on release build
}
}
return oMesh;
}
} // namespace Assimp
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
]
| [
[
[
1,
415
]
]
]
|
2b348d78a66e297359e877f30a0a672f24e305ae | 59cae771eaa097510750a011979e93bfed24696e | /Map.hpp | 5fdb6ef9665f79ed40260b1618abfb180b53ebad | []
| no_license | PhiBabin/LD21---Escape | 7121fa99b61e7027776dbc464618e705070200b7 | 861514ebc1b2f480961ef6f19728d788b45f138b | refs/heads/master | 2020-06-05T04:38:24.524584 | 2011-08-21T19:08:03 | 2011-08-21T19:08:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,962 | hpp | /**
Copyright (C) 2011 babin philippe
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 MAP_HPP_INCLUDED
#define MAP_HPP_INCLUDED
struct Type{
//! Propriétés
bool visible, solid, kill, princess,fall,touch;
//! La couleur correspondante
sf::Color colorPix;
//! Le rectangle visible du tileset
sf::IntRect zoneRect;
sf::Sprite tile;
};
class MapTile{
public:
MapTile();
MapTile(sf::RenderWindow *App,Player *playerOne);
void GenerateMap(int rate,int wmap,int hmap, int pmin, int pmax, int dmin, int dmax,int nbrTower);
void LoadMap();
void Draw();
vector<Type> & operator [] (int X);
unsigned char FindType(sf::Color Pix);
bool CollisionTile(float x,float y);
Type Tile(float x, float y);
vector<GameEntity*> * GetMapEntity();
bool CollisionGeneral(const sf::FloatRect playerRect);
~MapTile();
//! Public variable
int m_width, m_height;
sf::Vector2f m_spawnLocationOne;
vector <vector<Type> > m_tileSet;
private:
sf::RenderWindow *m_app;
sf::Texture m_ImgTypeTile;
sf::Sprite m_drawSprite;
vector <ImgAnim> m_motif;
vector <Type> m_typeList;
vector <GameEntity*> m_mapEntity;
Player *m_playerOne;
sf::RenderTexture m_map;
sf::RenderTexture m_background;
};
#endif // MAP_HPP_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
59
]
]
]
|
175c1873dc53e8502da52810d0b25739778860f7 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/CompilerSource/cfile_parse/cpmain.cpp | 7cdd23b8b079ce9255d278e6b2d49e33df485284 | []
| no_license | amorri40/Enigma-Game-Maker | 9d01f70ab8de42f7c80af9a0f8c7a66e412d19d6 | c6b701201b6037f2eb57c6938c184a5d4ba917cf | refs/heads/master | 2021-01-15T11:48:39.834788 | 2011-11-22T04:09:28 | 2011-11-22T04:09:28 | 1,855,342 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,282 | cpp | /********************************************************************************\
** **
** Copyright (C) 2008 Josh Ventura **
** **
** This file is a part of the ENIGMA Development Environment. **
** **
** **
** ENIGMA is free software: you can redistribute it and/or modify it under the **
** terms of the GNU General Public License as published by the Free Software **
** Foundation, version 3 of the license or any later version. **
** **
** This application and its source code is distributed AS-IS, WITHOUT ANY **
** WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS **
** FOR A PARTICULAR PURPOSE. See the GNU General Public License for more **
** details. **
** **
** You should have recieved a copy of the GNU General Public License along **
** with this code. If not, see <http://www.gnu.org/licenses/> **
** **
** ENIGMA is an environment designed to create games and other programs with a **
** high-level, fully compilable language. Developers of ENIGMA or anything **
** associated with ENIGMA are in no way responsible for its users or **
** applications created by its users, or damages caused by the environment **
** or programs made in the environment. **
** **
\********************************************************************************/
#include <map>
#include <string>
#include <iostream>
#include <cstdio>
#include <sys/time.h>
#include "../general/darray.h"
using namespace std;
#include "../externs/externs.h"
#include "expev_macros.h"
#include "value.h"
value evaluate_expression(string exp);
extern string rerr; extern int rerrpos;
void cparse_init();
extern string cferr;
#include "cfile_parse.h"
string file_contents(string file)
{
FILE *f = fopen(file.c_str(),"rb");
if (f==NULL) return "";
fseek(f,0,SEEK_END);
size_t sz = ftell(f);
char a[sz+1];
fseek(f,0,SEEK_SET);
sz = fread(a,1,sz,f);
fclose(f);
a[sz]=0;
return a;
}
void print_ext_data(externs *ext,int indent, int depth);
void print_scope_members(externs* gscope, int indent,int depth)
{
if (depth--)
for (extiter i=gscope->members.begin();i!=gscope->members.end();i++)
print_ext_data(i->second,indent,depth);
}
extern string strace(externs*);
void print_ext_data(externs *ext,int indent,int depth)
{
bool comma=0;
string indstr(indent,' ');
if (ext == NULL) {
cout << indstr << "error\n";
return;
}
cout << indstr << ext->name << ": ";
if (ext->is_function())
{
const int pcn = ext->parameter_count_min();
cout << "Function with " << pcn;
if (pcn != ext->parameter_count_max())
cout << " to " << ext->parameter_count_max();
cout << " parameters, returning ";
}
if (ext->type != NULL)
cout << ext->type->name << " ";
if (ext->ancestors.size)
{
cout << " derived from ";
string nc;
for (unsigned i = 0; i < ext->ancestors.size; i++) {
cout << nc << strace(ext->ancestors[i]);
nc = ", ";
}
cout << "; ";
}
if (ext->flags & EXTFLAG_TEMPLATE)
{
cout << "Template [" << ext->tempargs.size << "]<";
char comma = 0;
for (unsigned ii=0; ii < ext->tempargs.size; ii++)
{
if (comma != 0) cout << comma;
if (ext->tempargs[ii]->flags & EXTFLAG_TYPEDEF)
{
cout << "typename " << ext->tempargs[ii]->name;
if (ext->tempargs[ii]->type != NULL)
cout << "=" << ext->tempargs[ii]->type->name;
}
else
{
cout << ext->tempargs[ii]->name;
if (ext->tempargs[ii]->flags & EXTFLAG_VALUED)
cout << "=" << ext->tempargs[ii]->value_of;
}
comma = ',';
}
cout << "> ";
}
if (ext->flags & EXTFLAG_VALUED)
{
cout << " valued as " << ext->value_of;
comma = ',';
}
if (ext->flags & EXTFLAG_TYPENAME)
{
if (comma)
cout << ", serves as typename";
else
cout << " Serves as typename";
}
if (ext->flags & EXTFLAG_NAMESPACE) cout << " namespace";
if (ext->flags & EXTFLAG_STRUCT) cout << " : struct";
if (ext->flags & EXTFLAG_CLASS) cout << " : class";
if (ext->flags & EXTFLAG_TYPEDEF)
cout << " typedef'd as " << strace(ext->type) << " ";
else
if (!ext->members.empty())
{
cout << "\r\n" << indstr << "{\r\n";
print_scope_members(ext,indent+2,depth);
cout << indstr << "};\r\n";
}
else
if (ext->flags & (EXTFLAG_STRUCT | EXTFLAG_CLASS | EXTFLAG_NAMESPACE))
cout << " {}; ";
if (!ext->refstack.empty())
{
cout << "Dereference path: ";
for (rf_node *ii = ext->refstack.last; ii != NULL; ii = ii->prev)
if (ii->ref.symbol == '(') cout << "(params = " << ii->ref.count << ")";
else if (ii->ref.symbol == ')') cout << "</group>";
else if (ii->ref.symbol == '[') cout << "[]";
else cout << ii->ref.symbol;
}
cout << "\r\n";
}
#include "cparse_shared.h"
extern my_string fca(const char *fn);
int cfile_parse_main()
{
cparse_init();
my_string fc = fca("./ENIGMAsystem/SHELL/SHELLmain.cpp");
if (fc == NULL) cout << "FAILOOS.";
cout << fc;
time_t ts = clock();
int a = parse_cfile(fc);
time_t te = clock();
cout << "Parse time: " << ((te-ts) * 1000) / CLOCKS_PER_SEC << " milliseconds";
if (a != -1)
{
int line=0,pos=0;
for (int i=0; i<a; i++,pos++)
{
if (fc[i]=='\r')
i++;
if (fc[i]=='\n')
line++, pos=0;
}
printf("Line %d, position %d: %s\r\n",line+1,pos,cferr.c_str());
}
cout << "Macros:\r\n";
for (maciter i=macros.begin(); i!=macros.end();i++)
cout<<" "<<(string)i->second<<"\r\n";
print_scope_members(&global_scope, 0);
//system("pause");
return 0;
}
string fc(const char* fn);
char getch()
{
int c, first;
first = c = getchar();
while (c != '\n' && c != EOF)
c = getchar();
return first;
}
string getst()
{
string res;
int c, first;
first = c = getchar();
while (c != '\n' && c != EOF)
{
res += char(c);
c = getchar();
}
return res;
}
#include "cfile_parse.h"
#include "../general/implicit_stack.h"
void print_err_line_at(pt a)
{
int line=0,pos=0;
for (int i=0; i<(signed)a; i++,pos++)
{
if (i >= (signed)cfile.length()) {
line = -1, pos = a;
break;
}
if (cfile[i]=='\r')
i++;
if (cfile[i]=='\n')
line++, pos=0;
}
printf("%sLine %d, position %d: %s\r\n",cferr_get_file().c_str(),line+1,pos,cferr.c_str());
if (line >= 0)
{
const int margin = 100;
const pt
begin = (a < (margin/2))?0:a-(margin/2),
end = (a+pt(margin/2)>cfile.length())?cfile.length():a+(margin/2);
cout << "code snippet: " << cfile.substr(begin,end-begin).insert((a-begin<end)?a-begin:end,"<<>>") << endl;
}
cout << "Code snippet unavailable; possibly heavily buried in untraceable macros or instantiations." << endl;
cout << "------------------------------------------------\r\n\r\n";
}
void print_definition(string n)
{
maciter a = macros.find(n);
if (a != macros.end())
{
cout << " #define " << n;
if (a->second.argc != -1) {
cout << "("; for (int i=0; i<a->second.argc; i++)
cout << a->second.args[i] << (i+1<a->second.argc ? ", " : ")"); }
cout << " " << (string)a->second << endl;
}
else
{
extiter a;
string seg;
externs *isco = &global_scope;
for (pt i = 0; i<n.length();)
{
const pt is = i;
while (i<n.length() and n[i] != ':') i++;
seg = n.substr(is,i-is);
a = isco->members.find(seg);
if (i<n.length() and a != isco->members.end())
isco = a->second;
while (i<n.length() and n[i] == ':') i++;
}
if (a != isco->members.end())
print_ext_data(a->second, 2,1000);
else cout << "Not found: " << seg << endl;
}
}
int test_exp_eval()
{
while (1)
{
string p;
char ghere[2048];
value val;
cin.getline(ghere,2048);
p=ghere; int wret;
if (p=="x") return 0;
if (p=="c" or p=="cls") wret = system("cls");
else
{
val=evaluate_expression(p);
#if USETYPE_INT
if (val.type==RTYPE_INT)
cout<<val.real.i;
#endif
#if USETYPE_DOUBLE
if (val.type==RTYPE_DOUBLE)
cout<<val.real.d;
#endif
#if USETYPE_UINT
if (val.type==RTYPE_UINT)
cout<<val.real.u;
#endif
#if USETYPE_STRING
if (val.type==RTYPE_STRING)
cout << '"' << val.str << '"';
#endif
cout << endl;
if (rerr != "") cout <<"error at "<<rerrpos<<": "<<rerr << "\r\n\r\n";
}
}
}
int m_prog_loop_cfp()
{
my_string cftp = fca(0 ? "./ENIGMAsystem/SHELL/SHELLmain.cpp" : "./CompilerSource/cfile_parse/parsein.h");
#ifdef linux
timeval ts; gettimeofday(&ts,NULL);
#else
time_t ts = clock();
#endif
int a = parse_cfile(cftp);
int wret;
#ifdef linux
timeval te; gettimeofday(&te,NULL);
double tel = (te.tv_sec*1000.0 + te.tv_usec) - (ts.tv_sec*1000.0 + ts.tv_usec);
#else
time_t te = clock();
double tel = (((te-ts) * 1000.0) / CLOCKS_PER_SEC);
#endif
if (a != -1)
print_err_line_at(a);
else
cout << "No error.\r\nParse time: " << tel
<< " milliseconds\r\n++++++++++++++++++++++++++++++++++++++++++++++++\r\n\r\n";
cout << "Macros ("<<macros.size()<<") [+]\r\nVariables [+]\r\n";
cout << ">>";
char c = getch();
while (c != '\r' and c != '\n')
{
if (c == '+')
{
cout << "Macros ("<<macros.size()<<"):\r\n";
for (maciter i=macros.begin(); i!=macros.end();i++)
{
cout<<" "<<i->first;
if (i->second.argc != -1)
{
cout << "(";
for (int ii = 0; ii<i->second.argc; ii++)
cout << i->second.args[ii] << (ii<i->second.argc-1 ? ",":"");
cout << ")";
}
cout<<": "<<(string)i->second<<"\r\n";
}
cout<<"\r\nVariables:\r\n";
print_scope_members(&global_scope, 2);
}
if (c == 'c') wret = system("cls || clear");
if (c == 'd')
{
cout << "Define: ";
string n = getst();
print_definition(n);
}
if (c == 't')
{
cout << "Trace: ";
string n = getst();
extiter a = global_scope.members.find(n);
if (a != global_scope.members.end())
{
for (externs* i=a->second; i!=&global_scope; i=i->parent)
cout << i->name << "::";
}
else cout << "Not found: " << n << endl;
}
if (c == 'm')
{
string search_terms;
cout << "Search in Macros: ";
cin >> search_terms;
getch(); bool f = 0;
for (maciter i = macros.begin(); i != macros.end(); i++)
if (string(i->second).find(search_terms) != string::npos)
{ cout << "Found " << i->first << ". (N/Q)"; char a = getch(); f=1; if (a != 'N' and a != 'n') break; }
if (!f) cout << "Not found.";
}
if (c == 'e') print_err_line_at(a);
if (c == 'p') wret = system("PAUSE");
if (c == '>') cout << cfile << endl;
cout << ">>";
c = getch();
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
435
]
]
]
|
79978f943a6549ff811976d978ca18e030ea5b57 | 5d35825d03fbfe9885316ec7d757b7bcb8a6a975 | /inc/SearchFilter.h | ec5d440298d9cae31b0138e9ecbeb88b8bdeeddc | []
| no_license | jjzhang166/3D-Landscape-linux | ce887d290b72ebcc23386782dd30bdd198db93ef | 4f87eab887750e3dc5edcb524b9e1ad99977bd94 | refs/heads/master | 2023-03-15T05:24:40.303445 | 2010-03-25T00:23:43 | 2010-03-25T00:23:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 602 | h | #ifndef SEARCHFILTER_H
#define SEARCHFILTER_H
#include <QString>
#include <QList>
enum EFilterType
{
E_NAMEFILTER = 5000,
E_DISTANCEFILTER,
E_OPTIONSFILTER,
E_PRICESFILTER
};
//global filter, constructed from list of filters
struct TGlobalFilter
{
TGlobalFilter();
//name
QString name;
//services
QList<QString> services;
//distance
int centreX;
int centreZ;
int radius;
};
class SearchFilter
{
public:
SearchFilter(QString name);
QString name;
EFilterType type;
};
#endif //SEARCHFILTER_H
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
db32206f3ae2af3d1263a8b3f008176afbee10bd | 11dfb7197905169a3f0544eeaf507fe108d50f7e | /WiscScanAdaptiveOptics/Logger.cpp | dada901dfb09bc03ad222b5b11a60044d97bba8f | []
| no_license | rahulbhadani/adaptive-optics | 67791a49ecbb085ac8effdc44e5177b0357b0fa7 | e2b296664b7674e87a5a68ec7b794144b37ae74d | refs/heads/master | 2020-04-28T00:08:24.585833 | 2011-08-09T22:28:11 | 2011-08-09T22:28:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | cpp |
#include "StdAfx.h"
#include "Logger.h"
#include <iostream>
#include <fstream>
using namespace std;
Logger *Logger::pInstance = 0; // initialize pointer
/**
* Return the single instance of the class.
*
* @return The single instance of Logger.
*/
Logger *Logger::Instance ()
{
if (pInstance == 0) // is it the first call?
{
pInstance = new Logger; // create sole instance
}
return pInstance; // address of sole instance
}
/**
* Write to the log file.
*
* @param fileName The file name of source file. (__FILE__).
* @param lineNumber The location of the log call. (__LINE__).
* @param buffer The data (string stream) to be appended to the log file.
*/
void Logger::log( string fileName, int lineNumber, string buffer )
{
fstream file;
file.open(LOG_FILE, ios::out|ios::app);
file << fileName << ":" << lineNumber << " " << buffer << endl;
file.close();
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
41
],
[
43,
43
]
],
[
[
42,
42
]
]
]
|
ae1061852e15954f72d49456d84302333748e5d8 | 741b36f4ddf392c4459d777930bc55b966c2111a | /incubator/deeppurple/lwplugins/lwwrapper/Panel/ControlString.cpp | bc07808e3ac244f0798b8909ac96792a9d73078d | []
| 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 | 1,360 | cpp | #include "StdAfx.h"
#include "controlstring.h"
ControlString::ControlString(void) :
Width(50),
IsReadOnly(false)
{
}
ControlString::~ControlString(void)
{
}
bool ControlString::RegisterWithPanel(LWPanelID pan)
{
LWPanControlDesc Locdesc;
Locdesc.type=LWT_STRING;
Locdesc.string.width=Width;
if (this->IsReadOnly)
ThisControl=Lightwave3D::panf->addControl (pan, "InfoControl", &Locdesc, const_cast<char *>(Name.c_str()));
else
ThisControl=Lightwave3D::panf->addControl (pan, "EditControl", &Locdesc, const_cast<char *>(Name.c_str()));
return true;
}
bool ControlString::GetValue (string &LName)
{
LWValue locsval = { LWT_STRING };
char sBuffer[1000];
locsval.str.buf=sBuffer;
locsval.str.bufLen=1000;
ThisControl->get(ThisControl, CTL_VALUE, &locsval);
LName=sBuffer;
return true;
}
bool ControlString::SetValue (string &newString)
{
LWValue locsval = { LWT_STRING };
locsval.str.buf=const_cast<char *>(newString.c_str());
locsval.str.bufLen=static_cast<int>( newString.length() );
ThisControl->set(ThisControl, CTL_VALUE, &locsval);
return true;
}
void ControlString::Initialize(const char *name, Panel *SetOwner, int width, bool isreadonly)
{
this->Width=width;
this->IsReadOnly=isreadonly;
Control::Initialize(name,SetOwner);
} | [
"deeppurple@dac1304f-7ce9-0310-a59f-f2d444f72a61"
]
| [
[
[
1,
51
]
]
]
|
51861ad4c52c96a38d79b9da7137357632ea91b7 | c5ecda551cefa7aaa54b787850b55a2d8fd12387 | /src/UILayer/Wizard.h | 478e2a9266091eff8578d9536fd31eeab3bc54f3 | []
| no_license | firespeed79/easymule | b2520bfc44977c4e0643064bbc7211c0ce30cf66 | 3f890fa7ed2526c782cfcfabb5aac08c1e70e033 | refs/heads/master | 2021-05-28T20:52:15.983758 | 2007-12-05T09:41:56 | 2007-12-05T09:41:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | h | #pragma once
#include "PShtWiz1.h"
class CConnectionWizardDlg : public CDlgPageWizard
{
DECLARE_DYNAMIC(CConnectionWizardDlg)
public:
//CConnectionWizardDlg(CWnd* pParent = NULL); // standard constructor
CConnectionWizardDlg(LPCTSTR pszCaption = NULL, LPCTSTR pszHeaderTitle = NULL, LPCTSTR pszHeaderSubTitle = NULL);
virtual ~CConnectionWizardDlg();
enum { IDD = IDD_WIZARD };
void Localize();
protected:
HICON m_icnWnd;
CListCtrl m_provider;
int m_iOS;
int m_iTotalDownload;
int m_iConnectionType;
void SetCustomItemsActivation();
virtual BOOL OnInitDialog();
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedApply();
afx_msg void OnBnClickedCancel();
afx_msg void OnBnClickedWizRadioOsNtxp();
afx_msg void OnBnClickedWizRadioUs98me();
afx_msg void OnBnClickedWizLowdownloadRadio();
afx_msg void OnBnClickedWizMediumdownloadRadio();
afx_msg void OnBnClickedWizHighdownloadRadio();
afx_msg void OnBnClickedWizResetButton();
afx_msg void OnNMClickProviders(NMHDR *pNMHDR, LRESULT *pResult);
virtual LRESULT OnWizardNext();
};
| [
"LanceFong@4a627187-453b-0410-a94d-992500ef832d"
]
| [
[
[
1,
41
]
]
]
|
6e40a05dc6662e29e1eb5ac62c09d9b43e9c19fa | d76a67033e3abf492ff2f22d38fb80de804c4269 | /src/box2d/RevoluteJoint.h | 8f473446a740dec3d917e8494f8cfe17ec712f6c | [
"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,567 | h | /*
* LOVE: Totally Awesome 2D Gaming.
* Website: http://love.sourceforge.net
* Licence: ZLIB/libpng
* Copyright (c) 2006-2008 LOVE Development Team
*
* @author Anders Ruud
* @date 2008-08-12
*/
#ifndef LOVE_BOX2D_REVOLUTE_JOINT_H
#define LOVE_BOX2D_REVOLUTE_JOINT_H
// Module
#include "Joint.h"
namespace love_box2d
{
/**
* A RevoluteJoint allows two bodies relative rotation
* around a single point.
**/
class RevoluteJoint : public Joint
{
private:
// The Box2D revolute joint object.
b2RevoluteJoint * joint;
public:
/**
* Creates a new RevoluteJoint connecting body1 and body2.
**/
RevoluteJoint(boost::shared_ptr<Body> body1, boost::shared_ptr<Body> body2, b2RevoluteJointDef * def);
virtual ~RevoluteJoint();
/**
* Get the current joint angle in degrees.
**/
float getAngle() const;
/**
* Get the current joint angle speed in degrees per second.
**/
float getSpeed() const;
/**
* Enable/disable the joint motor.
**/
void setMotorEnabled(bool motor);
/**
* Checks whether the motor is enabled.
**/
bool isMotorEnabled() const;
/**
* Set the maximum motor torque, usually in N-m.
**/
void setMaxMotorTorque(float torque);
/**
* Gets the maximum motor torque, usually in N-m.
**/
float getMaxMotorTorque() const;
/**
* Sets the motor speed in degrees per second.
**/
void setMotorSpeed(float speed);
/**
* Gets the motor speed in degrees per second.
**/
float getMotorSpeed() const;
/**
* Get the current motor torque, usually in N-m.
**/
float getMotorTorque() const;
/**
* Enable/disable the joint limit.
**/
void setLimitsEnabled(bool limit);
/**
* Checks whether limits are enabled.
**/
bool isLimitsEnabled() const;
/**
* Sets the upper limit in degrees.
**/
void setUpperLimit(float limit);
/**
* Sets the lower limit in degrees.
**/
void setLowerLimit(float limit);
/**
* Sets the limits in degrees.
**/
void setLimits(float lower, float upper);
/**
* Gets the lower limit in degrees.
**/
float getLowerLimit() const;
/**
* Gets the upper limit in degrees.
**/
float getUpperLimit() const;
/**
* Gets the limits in degrees.
* @returns The lower limit.
* @returns The upper limit.
**/
int getLimits(lua_State * L);
};
typedef boost::shared_ptr<RevoluteJoint> pRevoluteJoint;
} // love_box2d
#endif // LOVE_BOX2D_REVOLUTE_JOINT_H
| [
"m4rvin2005@8b5f54a0-8722-11de-9e21-49812d2d8162"
]
| [
[
[
1,
131
]
]
]
|
11a32f6eb5691301242ff4b4c1d9795131006e9c | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /demo/demo_ui/UIApp.cpp | a281a805e1a24ed0c0fecfde41618bfe38a90178 | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | cpp | /*!
* \file UIApp.cpp
* \date 27-7-2009 15:38:19
*
*
* \author zjhlogo ([email protected])
*/
#include "UIApp.h"
#include "../common/AppHelper.h"
#include "UITestWindow.h"
#include <OECore/IOECore.h>
#include <OECore/IOEResMgr.h>
#include <OECore/IOETextureMgr.h>
#include <OECore/IOERenderSystem.h>
#include <libOEMsg/OEMsgList.h>
#include <OEUI/IOEUIRenderSystem.h>
IMPLEMENT_OEAPP(CUIApp);
CUIApp::CUIApp()
{
Init();
}
CUIApp::~CUIApp()
{
Destroy();
}
void CUIApp::Init()
{
m_pModel = NULL;
}
void CUIApp::Destroy()
{
// TODO:
}
bool CUIApp::UserDataInit()
{
m_pModel = g_pOEResMgr->CreateModel(TS("casual03.xml"));
if (!m_pModel) return false;
IOENode* pRootNode = g_pOECore->GetRootNode();
pRootNode->AttachObject(m_pModel);
IOENode* pLightNode = pRootNode->GetChildNode(TS("Light"));
pLightNode->SetPosition(CVector3(0.0f, 0.0f, -300.0f));
CUITestWindow* pTestWindow = new CUITestWindow(g_pOEUIRenderSystem->GetScreen());
if (!pTestWindow) return false;
ResetCameraPosRot(m_pModel);
return true;
}
void CUIApp::UserDataTerm()
{
SAFE_RELEASE(m_pModel);
}
void CUIApp::Update(float fDetailTime)
{
// TODO:
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
67
]
]
]
|
dd39e7041de36ba8bb75498a7643be277b6f6b89 | 011359e589f99ae5fe8271962d447165e9ff7768 | /src/burner/win32/run.cpp | 1ae561a1a4de16a472b25be337d0d8e1a74852fa | []
| no_license | PS3emulators/fba-next-slim | 4c753375fd68863c53830bb367c61737393f9777 | d082dea48c378bddd5e2a686fe8c19beb06db8e1 | refs/heads/master | 2021-01-17T23:05:29.479865 | 2011-12-01T18:16:02 | 2011-12-01T18:16:02 | 2,899,840 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,073 | cpp | // Run module
#include "burner.h"
#include "maphkeys.h"
#include "vid_directx_support.h"
int bRunPause = 0;
int bAltPause = 0;
int autoFrameSkip = 0;
int nAppVirtualFps = 6000; // App fps * 100
bool bShowFPS = false;
static unsigned int nDoFPS = 0;
TCHAR fpsString[16];
static unsigned int nNormalLast = 0; // Last value of timeGetTime()
static int nNormalFrac = 0; // Extra fraction we did
bool bAppDoStep = 0;
bool bAppDoFast = 0;
unsigned int nFastSpeed = 2;
static inline int GetInput(bool bCopy)
{
static int i = 0;
InputMake(bCopy); // get input
// FBA Combo - extra players input hack
if (bInputSwap && !kNetGame && bCopy) {
BurnDrvInputSwap();
}
// Update Input dialog ever 3 frames
if (i++ == 0) {
InpdUpdate();
}
if (i >= 3) {
i = 0;
}
// Update Input Set dialog
InpsUpdate();
return 0;
}
static inline void DisplayFPS()
{
static time_t fpsTimer;
static unsigned int nPreviousFrames;
float burnFps = (float)nBurnFPS / 100;
time_t tempTime = clock();
double fps = (double)(nFramesEmulated - nPreviousFrames) * CLOCKS_PER_SEC / (tempTime - fpsTimer);
_sntprintf(fpsString, sizearray(fpsString), _T("%2.2lf/%2.2lf"), fps, burnFps);
VidSNewShortMsg(fpsString, 0xDFDFFF, 480, 0);
fpsTimer = tempTime;
nPreviousFrames = nFramesEmulated;
// display fps on window title
scrnTitle();
}
// With or without sound, run one frame.
// If bDraw is true, it's the last frame before we are up to date, and so we should draw the screen
static int RunFrame(int bDraw, int bPause)
{
static int bPrevPause = 0;
static int bPrevDraw = 0;
if (bPrevDraw && !bPause) {
VidPaint(0); // paint the screen (no need to validate)
}
if (!bDrvOkay && !nShowEffect) {
return 1;
}
if (bPause) {
GetInput(false); // Update burner inputs, but not game inputs
if (bPause != bPrevPause) {
VidPaint(2); // Redraw the screen (to ensure mode indicators are updated)
}
} else {
nFramesEmulated++;
nCurrentFrame++;
if (kNetGame) {
GetInput(true); // Update inputs
if (KailleraGetInput()) { // Synchronize input with Kaillera
return 0;
}
// FBA Combo - extra players input hack
if (bInputSwap) {
BurnDrvInputSwap();
}
} else {
if (nReplayStatus == 2) {
GetInput(false); // Update burner inputs, but not game inputs
if (ReplayInput()) { // Read input from file
setPauseMode(true); // Auto pause after replay
menuSync(MENUT_FILE);
InputSetCooperativeLevel(false, false);
}
} else {
GetInput(true); // Update inputs
}
}
if (nReplayStatus == 1) {
RecordInput(); // Write input to file
}
if (bDraw) {
nFramesRendered++;
if (VidFrame()) { // Do one frame
audio.blank();
}
} else { // frame skipping
pBurnDraw = NULL; // Make sure no image is drawn
if (bDrvOkay || !nShowEffect) {
BurnDrvFrame();
}
}
if (bShowFPS) {
if (nDoFPS < nFramesRendered) {
DisplayFPS();
nDoFPS = nFramesRendered + 30;
}
}
}
if (nAviStatus) {
if (AviRecordFrame(bDraw)) {
AviStop();
}
}
bPrevPause = bPause;
bPrevDraw = bDraw;
return 0;
}
// Callback used when DSound needs more sound
static int RunGetNextSound(int bDraw)
{
if (pAudNextSound == NULL) {
return 1;
}
if (bRunPause) {
if (bAppDoStep) {
RunFrame(bDraw, 0);
AudWriteSlience();
} else {
RunFrame(bDraw, 1);
}
bAppDoStep = 0; // done one step
return 0;
}
if (bAppDoFast) { // do more frames
for (unsigned int i = 0; i < nFastSpeed; i++) {
RunFrame(0, 0);
}
}
// Render frame with sound
pBurnSoundOut = pAudNextSound;
RunFrame(bDraw, 0);
// Log wave file
waveLogWrite();
if (bAppDoStep) {
AudWriteSlience();
}
bAppDoStep = 0; // done one step
return 0;
}
int RunIdle()
{
if (audio.bAudPlaying) {
// Run with sound
audio.check();
return 0;
}
// Run without sound
int nTime = timeGetTime() - nNormalLast;
int nCount = (nTime * nAppVirtualFps - nNormalFrac) / 100000;
if (nCount <= 0) { // No need to do anything for a bit
Sleep(2);
return 0;
}
nNormalFrac += nCount * 100000;
nNormalLast += nNormalFrac / nAppVirtualFps;
nNormalFrac %= nAppVirtualFps;
if (bAppDoFast){ // Temporarily increase virtual fps
nCount += nFastSpeed * 10;
}
if (nCount > 100) { // Limit frame skipping
nCount = 100;
}
if (bRunPause) {
if (bAppDoStep) { // Step one frame
nCount = 10;
} else {
RunFrame(1, 1); // Paused
return 0;
}
}
bAppDoStep = 0;
for (int i = nCount / 10; i > 0; i--) { // Mid-frames
RunFrame(autoFrameSkip, 0);
}
RunFrame(1, 0); // End-frame
return 0;
}
int RunReset()
{
// Reset the speed throttling code
nNormalLast = 0;
nNormalFrac = 0;
// Reset FPS display
nDoFPS = 0;
if (!audio.bAudPlaying) {
// run without sound
nNormalLast = timeGetTime();
}
return 0;
}
int RunInit()
{
// Try to run with sound
audio.set(RunGetNextSound);
audio.play();
RunReset();
return 0;
}
int RunExit()
{
nNormalLast = 0;
// Stop sound if it was playing
audio.stop();
return 0;
}
static int RunKeyMsg(const MSG& Msg)
{
if (Msg.message == WM_SYSKEYDOWN || Msg.message == WM_KEYDOWN) {
return MHkeysDownHandle(Msg);
} else {
if (Msg.message == WM_SYSKEYUP || Msg.message == WM_KEYUP) {
return MHkeysUpHandle(Msg);
}
}
return 0;
}
// The main message loop
int RunMessageLoop()
{
int bRestartVideo;
MSG Msg;
do {
bRestartVideo = 0;
// Remove pending initialisation messages from the queue
while (PeekMessage(&Msg, NULL, WM_APP + 0, WM_APP + 0, PM_NOREMOVE)) {
if (Msg.message != WM_QUIT) {
PeekMessage(&Msg, NULL, WM_APP + 0, WM_APP + 0, PM_REMOVE);
}
}
RunInit();
ShowWindow(hScrnWnd, nAppShowCmd); // Show the screen window
nAppShowCmd = SW_NORMAL;
SetForegroundWindow(hScrnWnd);
GameInpCheckLeftAlt();
GameInpCheckMouse(); // Hide the cursor
while (1) {
if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) {
// A message is waiting to be processed
if (Msg.message == WM_QUIT) { // Quit program
break;
}
if (Msg.message == (WM_APP + 0)) { // Restart video
bRestartVideo = 1;
break;
}
// process key message
if (RunKeyMsg(Msg)) {
continue;
}
// Check for messages for dialogs etc.
if (!AppMessage(&Msg)) {
continue;
}
// if (TranslateAccelerator(hScrnWnd, hAccel, &Msg)) {
// continue;
// }
TranslateMessage(&Msg);
DispatchMessage(&Msg);
} else {
// No messages are waiting
SplashDestroy(0);
RunIdle();
}
}
RunExit();
mediaExit();
if (bRestartVideo) {
mediaInit();
}
} while (bRestartVideo);
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
348
]
]
]
|
ead59c2dd31a89b354c5df40dbd2396ef8220747 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/serialization/test/test_utf8_codecvt.cpp | fa4f9cc57694cd581d09a8af5727acb19b20a6ae | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,967 | cpp | /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// test_utf8_codecvt.cpp
// (C) Copyright 2002-4 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <locale>
#include <vector>
#include <string>
#include <cstddef> // size_t
#include <cwchar>
#include <boost/config.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::size_t;
using ::wcslen;
using ::w_int;
} // namespace std
#endif
// Note: copied from boost/iostreams/char_traits.hpp
//
// Dinkumware that comes with QNX Momentics 6.3.0, 4.0.2, incorrectly defines
// the EOF and WEOF macros to not std:: qualify the wint_t type (and so does
// Sun C++ 5.8 + STLport 4). Fix by placing the def in this scope.
// NOTE: Use BOOST_WORKAROUND?
#if (defined(__QNX__) && defined(BOOST_DINKUMWARE_STDLIB)) \
|| defined(__SUNPRO_CC)
using ::std::wint_t;
#endif
#include "test_tools.hpp"
#include <boost/archive/iterators/istream_iterator.hpp>
#include <boost/archive/iterators/ostream_iterator.hpp>
#include <boost/archive/add_facet.hpp>
#include <boost/archive/detail/utf8_codecvt_facet.hpp>
template<std::size_t s>
struct test_data
{
static unsigned char utf8_encoding[];
static wchar_t wchar_encoding[];
};
template<>
unsigned char test_data<2>::utf8_encoding[] = {
0x01,
0x7f,
0xc2, 0x80,
0xdf, 0xbf,
0xe0, 0xa0, 0x80,
0xe7, 0xbf, 0xbf
};
template<>
wchar_t test_data<2>::wchar_encoding[] = {
0x0001,
0x007f,
0x0080,
0x07ff,
0x0800,
0x7fff
};
template<>
unsigned char test_data<4>::utf8_encoding[] = {
0x01,
0x7f,
0xc2, 0x80,
0xdf, 0xbf,
0xe0, 0xa0, 0x80,
0xef, 0xbf, 0xbf,
0xf0, 0x90, 0x80, 0x80,
0xf4, 0x8f, 0xbf, 0xbf,
0xf7, 0xbf, 0xbf, 0xbf,
0xf8, 0x88, 0x80, 0x80, 0x80,
0xfb, 0xbf, 0xbf, 0xbf, 0xbf,
0xfc, 0x84, 0x80, 0x80, 0x80, 0x80,
0xfd, 0xbf, 0xbf, 0xbf, 0xbf, 0xbf
};
template<>
wchar_t test_data<4>::wchar_encoding[] = {
0x00000001,
0x0000007f,
0x00000080,
0x000007ff,
0x00000800,
0x0000ffff,
0x00010000,
0x0010ffff,
0x001fffff,
0x00200000,
0x03ffffff,
0x04000000,
0x7fffffff
};
int
test_main(int /* argc */, char * /* argv */[]) {
std::locale old_loc;
std::locale * utf8_locale
= boost::archive::add_facet(
old_loc,
new boost::archive::detail::utf8_codecvt_facet
);
typedef char utf8_t;
typedef test_data<sizeof(wchar_t)> td;
// Send our test UTF-8 data to file
{
std::ofstream ofs;
ofs.open("test.dat", std::ios::binary);
std::copy(
td::utf8_encoding,
#if ! defined(__BORLANDC__)
// borland 5.60 complains about this
td::utf8_encoding + sizeof(td::utf8_encoding) / sizeof(unsigned char),
#else
// so use this instead
td::utf8_encoding + 12,
#endif
boost::archive::iterators::ostream_iterator<utf8_t>(ofs)
);
}
// Read the test data back in, converting to UCS-4 on the way in
std::vector<wchar_t> from_file;
{
std::wifstream ifs;
ifs.imbue(*utf8_locale);
ifs.open("test.dat");
wchar_t item = 0;
// note can't use normal vector from iterator constructor because
// dinkumware doesn't have it.
for(;;){
item = ifs.get();
if(item == WEOF)
break;
//ifs >> item;
//if(ifs.eof())
// break;
from_file.push_back(item);
}
}
// compare the data read back in with the orginal
#if ! defined(__BORLANDC__)
// borland 5.60 complains about this
BOOST_CHECK(from_file.size() == sizeof(td::wchar_encoding)/sizeof(wchar_t));
#else
// so use this instead
BOOST_CHECK(from_file.size() == 6);
#endif
BOOST_CHECK(std::equal(from_file.begin(), from_file.end(), td::wchar_encoding));
// Send the UCS4_data back out, converting to UTF-8
{
std::wofstream ofs;
ofs.imbue(*utf8_locale);
ofs.open("test2.dat");
std::copy(
from_file.begin(),
from_file.end(),
boost::archive::iterators::ostream_iterator<wchar_t>(ofs)
);
}
// Make sure that both files are the same
{
typedef boost::archive::iterators::istream_iterator<utf8_t> is_iter;
is_iter end_iter;
std::ifstream ifs1("test.dat");
is_iter it1(ifs1);
std::vector<utf8_t> data1;
std::copy(it1, end_iter, std::back_inserter(data1));
std::ifstream ifs2("test2.dat");
is_iter it2(ifs2);
std::vector<utf8_t> data2;
std::copy(it2, end_iter, std::back_inserter(data2));
BOOST_CHECK(data1 == data2);
}
// some libraries have trouble that only shows up with longer strings
wchar_t * test3_data = L"\
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\
<!DOCTYPE boost_serialization>\
<boost_serialization signature=\"serialization::archive\" version=\"3\">\
<a class_id=\"0\" tracking_level=\"0\">\
<b>1</b>\
<f>96953204</f>\
<g>177129195</g>\
<l>1</l>\
<m>5627</m>\
<n>23010</n>\
<o>7419</o>\
<p>16212</p>\
<q>4086</q>\
<r>2749</r>\
<c>-33</c>\
<s>124</s>\
<t>28</t>\
<u>32225</u>\
<v>17543</v>\
<w>0.84431422</w>\
<x>1.0170664757130923</x>\
<y>tjbx</y>\
<z>cuwjentqpkejp</z>\
</a>\
</boost_serialization>\
";
// Send the UCS4_data back out, converting to UTF-8
std::size_t l = std::wcslen(test3_data);
{
std::wofstream ofs;
ofs.imbue(*utf8_locale);
ofs.open("test3.dat");
std::copy(
test3_data,
test3_data + l,
boost::archive::iterators::ostream_iterator<wchar_t>(ofs)
);
}
// Make sure that both files are the same
{
std::wifstream ifs;
ifs.imbue(*utf8_locale);
ifs.open("test3.dat");
BOOST_CHECK(
std::equal(
test3_data,
test3_data + l,
boost::archive::iterators::istream_iterator<wchar_t>(ifs)
)
);
}
delete utf8_locale;
return EXIT_SUCCESS;
}
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
258
]
]
]
|
1501c7b67f267851bfea6eb89d1951b9523b05cc | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/26042005/vfs/pcx/VFSPlugin_PCX.cpp | 38519d9f8cb8e3d1fbb4294e9525e5b7e1278b69 | []
| 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 | 5,323 | cpp | #include <VFSPlugin_PCX.h>
/** PCX File Format plugin Constructor
*
* Sets the default file extension for this format
*/
VFSPlugin_PCX::VFSPlugin_PCX()
{
m_type = "pcx;";
m_offset = 0;
m_fileinfo = NULL;
}
/** PCX File Format plugin Deconstructor */
VFSPlugin_PCX::~VFSPlugin_PCX(){}
/** Retrieves the type of file the plugin handles
*
* @returns The plugin identifier string
*/
char * VFSPlugin_PCX::Type(void)
{
return m_type;
}
/** Takes a bytestream and converts it into a structured format
*
* @param buffer A Bytestream containing the file contents
* @param length The length of the bytestream
*
* @returns A FileInfo structure containing the files contents
*
* Operation:
* -# Calls VFSPlugin_PCX::ReadPCXHeader()
* -# Calls VFSPlugin_PCX::ReadPCXImage()
* -# Calls VFSPlugin_PCX::ReadPCXPalette()
* -# Calls VFSPlugin_PCX::DecodeImage()
* -# Returns FileInfo structure
*/
FileInfo * VFSPlugin_PCX::Read(unsigned char *buffer, unsigned int length)
{
m_buffer = buffer;
m_length = length;
m_fileinfo = new ImageFileInfo();
m_fileinfo->filelength = m_length;
m_offset = 0;
if(ReadPCXHeader() == false){
delete m_fileinfo;
return NULL;
}
ReadPCXImage();
ReadPCXPalette();
DecodeImage();
return m_fileinfo;
}
/** Writes data to a bytestream
*
* @param data A FileInfo structure containing the data to write to the bytestream
* @param length The length of the resulting bytestream
*
* @returns A Bytestream containing the contents of the file
*/
char * VFSPlugin_PCX::Write(FileInfo *data, unsigned int &length)
{
// Not Implemented
return NULL;
}
/** Reads the PCX Header
*
* @returns boolean true or false, depending on whether the file is Version 5 and 8bit colour
*
* Operation:
* -# Copies the first 128 bytes into the header structure
* -# extracts the width/height/bit depth information from the header
*/
bool VFSPlugin_PCX::ReadPCXHeader(void)
{
memcpy(&header,&m_buffer[m_offset],headerlength);
m_offset+=headerlength;
m_length -= headerlength;
m_fileinfo->width = header.maxx+1;
m_fileinfo->height = header.maxy+1;
m_fileinfo->bpp = header.BitsPerPixel;
if(header.Version == 5 && header.BitsPerPixel == 8) return true;
return false;
}
/** Reads the Palette Data
*
* Operation:
* -# If the PCX Version is 5 and bitdepth is 8bit, file is ok to read
* -# Allocate a buffer for the palette data and copy it from the bytestream
*/
void VFSPlugin_PCX::ReadPCXPalette(void)
{
m_fileinfo->palette = new unsigned char[palettelength];
memset(m_fileinfo->palette,0,palettelength);
memcpy(m_fileinfo->palette,&m_buffer[m_offset],palettelength);
m_offset+=palettelength;
m_length -= palettelength;
}
/** Reads the Image data
*
* Operation:
* -# Calculate the number of bytes the image is stored in
* -# Create a buffer that size
* -# Copy that many bytes from the bytestream into the buffer
*/
void VFSPlugin_PCX::ReadPCXImage(void)
{
int read = m_length - palettelength;
raw_image = new char[read];
memcpy(raw_image,&m_buffer[m_offset],read);
m_offset+=read;
m_length -= read;
}
/** Decodes the raw image data into the final image
*
* The pcx format compresses the data to the raw image is a compressed version
*
* Operation:
* -# Calculate the number of pixels in the image
* -# Allocate a decodebuffer, the size of the decompressed image
* -# Loop for the number of pixels in the decompressed image
* -# Decode the pixel, copy the number of expanded pixels to the decodebuffer
* -# Once decoded delete the raw image buffer
* -# Assign the buffer into the FileInfo structure
*
* Decoding:
* This is a very simple process, you take a byte,
* compare it against an ID byte, which will tell
* you whether its a data byte or an ID byte, the
* value of an ID byte is 192 (0xC0), if and'ing the byte
* against the databyte produces 192, this is an ID byte.
*
* You then extract from the byte the number of
* pixels the next byte will decompress to, to
* do this "and" the binary "not" of 0xC0, which
* is 0x3F to the databyte.
*
* 0xC0 = 1100 0000
* 0x3F = 0011 1111
*
* This will produce a value which is the number
* of pixels to apply the next byte to. Once
* you have this value, you set the number of
* pixels and read the next byte, once read,
* you copy that byte into that many pixels,
* then continue until you've read the
* correct number of pixels. Easy
*
* @todo Perhaps I should implement this encoding as a VFSFilter?
*/
void VFSPlugin_PCX::DecodeImage(void)
{
int pcxlocation = 0,pixels = 0;
int numberpixels = (header.maxx+1) * (header.maxy+1);
char databyte = 0;
char *decodebuffer = new char[numberpixels];
char *buffer = raw_image;
while (pcxlocation < numberpixels)
{
databyte = *buffer++;
pixels = 1;
if((databyte & 0xC0) == 0xC0)
{
pixels = (databyte & 0x3F);
databyte = *buffer++;
}
memset(decodebuffer+pcxlocation,databyte,pixels);
pcxlocation += pixels;
}
if(raw_image) delete[] raw_image;
m_fileinfo->data = (unsigned char *)decodebuffer;
decodebuffer = NULL;
}
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
199
]
]
]
|
d41e57c057f97dfe473193443267d50aac2a75d5 | 05869e5d7a32845b306353bdf45d2eab70d5eddc | /soft/application/CoolSimulator/CoolSimulatorDlg.cpp | c96bb3753026df0690d8a967ea90cacb181c2eac | []
| no_license | shenfahsu/sc-fix | beb9dc8034f2a8fd9feb384155fa01d52f3a4b6a | ccc96bfaa3c18f68c38036cf68d3cb34ca5b40cd | refs/heads/master | 2020-07-14T16:13:47.424654 | 2011-07-22T16:46:45 | 2011-07-22T16:46:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 19,382 | cpp | // CoolSimulatorDlg.cpp : implementation file
//
#include "stdafx.h"
#include "CoolSimulator.h"
#include "CoolSimulatorDlg.h"
#include "Screen.h"
#include "TraceModule.h" // Trace Module
extern "C"
{
//#include "mmi_data_types.h"
//#include "MMI_features.h"
#include "GlobalConstants.h" /* KEY_INVALID */
#include "frameworkstruct.h"
#include "taskinit.h"
#include "lcd_sw_inc.h" // Get LCD_WIDTH,LCD_HEIGHT
extern void InitApplication();
extern void lcd_screen_init();
extern void UI_update(void);
#ifdef TOUCH_PANEL_SUPPORT
extern void mmi_pen_simulator_button_down_hdlr(S16 x, S16 y);
extern void mmi_pen_simulator_button_move_hdlr(S16 x, S16 y);
extern void mmi_pen_simulator_button_up_hdlr(S16 x, S16 y);
#endif
HWND g_hSimWnd ;
}
extern "C" void UpdateScreenFun(unsigned int *simulator_buffer, BITMAPINFO *lpbitmap_info)
{
((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_Phone.Screen().UpdateScreen((long*)simulator_buffer,(long*)lpbitmap_info);
}
extern "C" void UpdateLayerFun(int nLayer, unsigned int *simulator_buffer, BITMAPINFO *lpbitmap_info)
{
((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_LayerDlg.UpdateScreen(nLayer,simulator_buffer,lpbitmap_info);
}
#ifdef __MMI_BLACKBERRY_QWERTY__
static const int SimKeyPadMap[] = {
KEY_0,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_LSK, //10
KEY_RSK,
KEY_CSK,
KEY_UP_ARROW,
KEY_DOWN_ARROW,
KEY_LEFT_ARROW, //15
KEY_RIGHT_ARROW,
KEY_SEND,
KEY_END,
KEY_CLEAR,
KEY_STAR,
KEY_POUND,
KEY_VOL_UP,
KEY_VOL_DOWN,
KEY_CAMERA,
KEY_ENTER,
KEY_MSN,
KEY_DOLLAR,
KEY_SYM,
KEY_WAP,
KEY_IP,
KEY_EXTRA_1,
KEY_EXTRA_2,
#ifdef __SENDKEY2_SUPPORT__
KEY_SEND1,
KEY_SEND2,
KEY_SEND3,
KEY_SEND4,
#endif
KEY_BACKSPACE1,
KEY_SMS,
KEY_CLOG,
KEY_B,
KEY_G,
KEY_H,
KEY_I,//also with '-'
KEY_J,
KEY_K,//ALSO WITH '_'
KEY_L, //ALSO WITH '\'
KEY_M,
KEY_N,
KEY_O,//ALSO WITH '+'
KEY_P,//ALSO WITH '='
KEY_T,//also with '!'
KEY_U,
KEY_V,
KEY_Y,
KEY_COMMA,
KEY_FULLSTOP,
KEY_SHIFT1,
KEY_SHIFT_INPUTM,
KEY_SPACE1,
KEY_AND,
KEY_INTEGRR,
KEY_CTRL1,
KEY_NEWLINE,
KEY_QQ,
KEY_QF,
KEY_TV,
MAX_KEYS
};
#else
static const int SimKeyPadMap[] =
{
KEY_0,
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_LSK, //10
KEY_RSK, //11
KEY_UP_ARROW, //12
KEY_DOWN_ARROW, //13
KEY_LEFT_ARROW, //14
KEY_RIGHT_ARROW, //15
KEY_SEND, //16
KEY_END, //17
KEY_CLEAR, //18
KEY_STAR, //19
KEY_POUND, //20
KEY_VOL_UP, //21
KEY_VOL_DOWN, //22
KEY_INVALID, //23
KEY_QUICK_ACS, //24
KEY_ENTER, //25
KEY_EXTRA_1, //26
KEY_EXTRA_2, //27
KEY_INVALID, //28
KEY_INVALID, //29
KEY_BACKSPACE1,
KEY_SMS,
KEY_CLOG,
KEY_A, //33
KEY_H,
KEY_I,//also with '-'
KEY_J,
KEY_K,//ALSO WITH '_'
KEY_L, //ALSO WITH '\'
KEY_M, //39
KEY_O,//ALSO WITH '+'
KEY_P,//ALSO WITH '='
KEY_Q,//also with '!'
KEY_S,
KEY_U,
KEY_W,//also with ' " '
KEY_Y,
KEY_Z,
KEY_COMMA, //48
KEY_FULLSTOP,
KEY_SHIFT1,
KEY_SHIFT_INPUTM,
KEY_SPACE1,
KEY_AND,
KEY_INTEGRR,
KEY_CTRL1,
KEY_NEWLINE,
};
#endif
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__ ;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
//{{AFX_DATA(CAboutDlg)
enum { IDD = IDD_ABOUTBOX };
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAboutDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
//{{AFX_MSG(CAboutDlg)
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
//{{AFX_DATA_INIT(CAboutDlg)
//}}AFX_DATA_INIT
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAboutDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
//{{AFX_MSG_MAP(CAboutDlg)
// No message handlers
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCoolSimulatorDlg dialog
CCoolSimulatorDlg::CCoolSimulatorDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCoolSimulatorDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CCoolSimulatorDlg)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_bMouseDown = FALSE;
m_bLayerShow = FALSE;
}
void CCoolSimulatorDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCoolSimulatorDlg)
DDX_Control(pDX, IDC_COOLPHONECTRL, m_Phone);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCoolSimulatorDlg, CDialog)
//{{AFX_MSG_MAP(CCoolSimulatorDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_COMMAND(ID_FILE_Exit, OnFILEExit)
ON_COMMAND(IDM_FILE_NETWORK_SIMULATOR, OnFileNetworkSimulator)
ON_COMMAND(IDM_FILE_SAVE_WINDOW_POS, OnFileSaveWindowPos)
ON_COMMAND(IDM_TOOL_LOAD_SKIN, OnToolLoadSkin)
ON_COMMAND(IDM_TOOL_INFOMONITOR, OnToolInfoMonitor)
ON_WM_TIMER()
ON_COMMAND(IDM_TOOLS_EXT_KEYPAD, OnToolsExtKeypad)
ON_COMMAND(IDM_TOOLS_LAYER_WATCH, OnToolsLayerWatch)
ON_UPDATE_COMMAND_UI(IDM_TOOLS_LAYER_WATCH, OnUpdateToolsLayerWatch)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCoolSimulatorDlg message handlers
BOOL CCoolSimulatorDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
CString strAboutMenu;
strAboutMenu.LoadString(IDS_ABOUTBOX);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
//
m_LayerDlg.Create(IDD_LAYER_DLG,this);
m_LayerDlg.ShowWindow(SW_HIDE);
m_LayerDlg.SetScreenSize(CSize(LCD_WIDTH,LCD_HEIGHT));
// Add Trace Module
CTraceModule::DebugWindowAlloc(this->m_hWnd);
// Get module file name
TCHAR szFileName[_MAX_PATH] = {0};
TCHAR szDir[_MAX_PATH] = {0};
TCHAR szDriver[_MAX_PATH] = {0};
GetModuleFileName(NULL, szFileName, _MAX_PATH);
_tsplitpath(szFileName, szDriver, szDir, NULL, NULL);
//获得模拟器Skin配置列表
CString str = CString(_T("PhoneSkins\\PhoneList.ini"));
// str.LoadString(IDS_STRING_PHONE_LIST);
CString strExeDir = CString(szDriver) + szDir+str;
this->m_Phone.LoadSkinProfile(strExeDir);
g_hSimWnd = this->m_hWnd;
InitApplication();
lcd_screen_init();
// 设置Layer Watch对话框的初始位置
CRect rect;
GetWindowRect(&rect);
m_LayerDlg.SetWindowPos(NULL,rect.right,rect.top,0,0,SWP_NOSIZE);
return TRUE; // return TRUE unless you set the focus to a control
}
void CCoolSimulatorDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CCoolSimulatorDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CCoolSimulatorDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
BEGIN_EVENTSINK_MAP(CCoolSimulatorDlg, CDialog)
//{{AFX_EVENTSINK_MAP(CCoolSimulatorDlg)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 1 /* ChangeSize */, OnChangeSizeCoolphonectrl, VTS_I4 VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 8 /* SIMKeyDown */, OnSIMKeyDownCoolphonectrl, VTS_BSTR VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 7 /* SIMKeyUp */, OnSIMKeyUpCoolphonectrl, VTS_BSTR VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 3 /* PenDown */, OnPenDownCoolphonectrl, VTS_I4 VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 4 /* PenUp */, OnPenUpCoolphonectrl, VTS_I4 VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 5 /* PenMove */, OnPenMoveCoolphonectrl, VTS_I4 VTS_I4 VTS_I4)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, 6 /* UpdateSkin */, OnUpdateSkinCoolphonectrl, VTS_NONE)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, -602 /* KeyDown */, OnKeyDownCoolphonectrl, VTS_PI2 VTS_I2)
ON_EVENT(CCoolSimulatorDlg, IDC_COOLPHONECTRL, -604 /* KeyUp */, OnKeyUpCoolphonectrl, VTS_PI2 VTS_I2)
//}}AFX_EVENTSINK_MAP
END_EVENTSINK_MAP()
void CCoolSimulatorDlg::OnChangeSizeCoolphonectrl(long nWidth, long nHeight)
{
// TODO: Add your control notification handler code here
CRect rect1,rect2;
this->GetWindowRect(rect1);
this->GetClientRect(rect2);
this->MoveWindow(100,100, rect1.Width(), rect1.Height());
this->m_Phone.MoveWindow(0,0,nWidth,nHeight);
this->SetWindowPos(NULL,0,0,nWidth+(rect1.Width()-rect2.Width()),nHeight+(rect1.Height()-rect2.Height()),SWP_NOMOVE);
GetDlgItem(IDC_STATIC_COORDINATE)->MoveWindow(nWidth-56,1,55,20);
}
/*****************************************************************************
* FUNCTION
* writeKeyMsgOnCondition
* DESCRIPTION
* If message queue is not too crowed, write key message. Also onsider key up pairing.
*
* PARAMETERS
* void
* RETURNS
* wrote to queue or not
*
* GLOBALS AFFECTED
* void
*****************************************************************************/
BOOL writeKeyMsgOnCondition(MYQUEUE *Message)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
BOOL toSend = TRUE;
U8 num;
static BOOL waitKeyUpMsg = TRUE;
/* for debugging */
static int keyNumSkipped = 0;
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
/* check sending critera */
if ((num = OslNumOfQMsgs() < (MAX_PRT_NODES - (MAX_PRT_NODES/4.0))) ||
((waitKeyUpMsg == TRUE) && ((Message->oslMsgId == WM_KEYUP) || (Message->oslMsgId == WM_LBUTTONUP))))
{
toSend = TRUE;
}
else
{
toSend = FALSE;
}
/* send the msg */
if (toSend == TRUE)
{
if ((Message->oslMsgId != WM_KEYUP) && (Message->oslMsgId != WM_LBUTTONUP))
waitKeyUpMsg = TRUE;
else
waitKeyUpMsg = FALSE;
OslMsgSendExtQueue(Message);
return TRUE;
}
else
{
keyNumSkipped ++;
return FALSE;
}
}
void CCoolSimulatorDlg::OnSIMKeyDownCoolphonectrl(LPCTSTR lpszKeyName, long nKeyCode)
{
// TODO: Add your control notification handler code here
UINT i;
void *tempKeyBrdMsg;
static MYQUEUE Message;
KEYBRD_MESSAGE *KeyBrdMsg;
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
i = SimKeyPadMap[nKeyCode];
if(i >= MAX_KEYS) i = KEY_INVALID;
if(i != KEY_INVALID)
{
MessageBeep(0xFFFFFFFF);
Message.oslSrcId = 0xFFFF;
Message.oslDestId = MOD_PRT;
Message.oslMsgId = WM_LBUTTONDOWN;
/* OslFreeDataPtr(Message.oslDataPtr); */
tempKeyBrdMsg=OslConstructDataPtr(sizeof(KEYBRD_MESSAGE));
KeyBrdMsg =(KEYBRD_MESSAGE *)tempKeyBrdMsg;
/* KeyBrdMsg = (KEYBRD_MESSAGE *)OslConstructDataPtr(sizeof(KEYBRD_MESSAGE)); */
KeyBrdMsg->nKeyCode = i;
Message.oslDataPtr = KeyBrdMsg;
if (writeKeyMsgOnCondition(&Message) != TRUE)
{
OslFreeDataPtr(tempKeyBrdMsg);
}
}
}
void CCoolSimulatorDlg::OnSIMKeyUpCoolphonectrl(LPCTSTR lpszKeyName, long nKeyCode)
{
// TODO: Add your control notification handler code here
int i;
void *tempKeyBrdMsg;
static MYQUEUE Message;
KEYBRD_MESSAGE *KeyBrdMsg;
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
i = SimKeyPadMap[nKeyCode];
if(i >= MAX_KEYS) i = KEY_INVALID;
/* MessageBeep(0xFFFFFFFF); */
if(i != KEY_INVALID)
{
{
Message.oslSrcId = 0xFFFF;
Message.oslDestId=MOD_PRT;
Message.oslMsgId =WM_LBUTTONUP;
/* OslFreeDataPtr(Message.oslDataPtr); */
tempKeyBrdMsg = OslConstructDataPtr(sizeof(KEYBRD_MESSAGE));
KeyBrdMsg = (KEYBRD_MESSAGE *)tempKeyBrdMsg;
/* KeyBrdMsg = (KEYBRD_MESSAGE *)OslConstructDataPtr(sizeof(KEYBRD_MESSAGE)); */
KeyBrdMsg->nKeyCode = i;
Message.oslDataPtr=KeyBrdMsg;
if (writeKeyMsgOnCondition(&Message) != TRUE)
OslFreeDataPtr(tempKeyBrdMsg);
}
}
}
void CCoolSimulatorDlg::OnPenDownCoolphonectrl(long xPos, long yPos)
{
// TODO: Add your control notification handler code here
#ifdef TOUCH_PANEL_SUPPORT
mmi_pen_simulator_button_down_hdlr((S16)xPos, (S16)yPos);
#endif
m_bMouseDown = TRUE;
}
void CCoolSimulatorDlg::OnPenMoveCoolphonectrl(long xPos, long yPos, long nFlag)
{
// TODO: Add your control notification handler code here
if (m_bMouseDown)
{
#ifdef TOUCH_PANEL_SUPPORT
mmi_pen_simulator_button_move_hdlr((S16)xPos, (S16)yPos);
#endif
}
CString str;
str.Format(_T("%ld,%ld"),xPos,yPos);
SetDlgItemText(IDC_STATIC_COORDINATE,str);
}
void CCoolSimulatorDlg::OnPenUpCoolphonectrl(long xPos, long yPos)
{
// TODO: Add your control notification handler code here
if(m_bMouseDown)
{
#ifdef TOUCH_PANEL_SUPPORT
mmi_pen_simulator_button_up_hdlr((S16)xPos, (S16)yPos);
#endif
m_bMouseDown = FALSE;
}
}
void CCoolSimulatorDlg::OnUpdateSkinCoolphonectrl()
{
// TODO: Add your control notification handler code here
UI_update();
}
void CCoolSimulatorDlg::OnKeyDownCoolphonectrl(short FAR* KeyCode, short Shift)
{
// TODO: Add your control notification handler code here
}
void CCoolSimulatorDlg::OnKeyUpCoolphonectrl(short FAR* KeyCode, short Shift)
{
// TODO: Add your control notification handler code here
}
void CCoolSimulatorDlg::OnFILEExit()
{
// TODO: Add your command handler code here
SendMessage(WM_CLOSE);
}
void CCoolSimulatorDlg::OnFileNetworkSimulator()
{
// TODO: Add your command handler code here
if (m_SimulatorStart.IsInit())
{
m_SimulatorStart.ShowSimulator();
}
else
{
//InitPCSimulatorBootup();
CRect rect;
GetWindowRect(&rect);
m_SimulatorStart.InitSimulator(rect.right,rect.top);
m_SimulatorStart.SetReadQueueHandler((NWRECEIVEQ)OslReceiveMsgExtQ);
m_SimulatorStart.SetWriteQueueHandler((NWWRITEQ)OslMsgSendExtQueue);
m_SimulatorStart.SetReadQueueHandle((oslMsgqid_handle)task_info_g1[MOD_PST].task_ext_qid);
m_SimulatorStart.SetWriteQueueHandle((oslMsgqid_handle)task_info_g1[MOD_PRT].task_ext_qid);
m_SimulatorStart.Bootup();
}
SetForegroundWindow();
}
void CCoolSimulatorDlg::OnFileSaveWindowPos()
{
// TODO: Add your command handler code here
}
void CCoolSimulatorDlg::OnToolLoadSkin()
{
// TODO: Add your command handler code here
m_Phone.ShowSkinSetupDlg();
}
void CCoolSimulatorDlg::OnToolInfoMonitor()
{
// TODO: Add your command handler code here
}
void CCoolSimulatorDlg::OnTimer(UINT nIDEvent)
{
// TODO: Add your message handler code here and/or call default
oslTimerid timerid;
timerid = (oslTimerid)nIDEvent;
timerid->tmr_callback(timerid->tmr_callback_arg);
CDialog::OnTimer(nIDEvent);
}
bool isShutDownSystem = true;
/*****************************************************************************
* FUNCTION
* KillWindowObject
* DESCRIPTION
* Distroy the window
*
* PARAMETERS
* nil
* RETURNS
* void
* GLOBALS AFFECTED
* nil
*****************************************************************************/
extern "C"{
void KillWindowObject(void)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
// ((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_SimulatorStart.SetReadQueueHandler(NULL);
// ((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_SimulatorStart.SetWriteQueueHandler(NULL);
// ((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_SimulatorStart.SetReadQueueHandle(NULL);
// ((CCoolSimulatorDlg*)(AfxGetApp()->m_pMainWnd))->m_SimulatorStart.SetWriteQueueHandle(NULL);
if(isShutDownSystem == true)
{
isShutDownSystem = false;
SendMessage(AfxGetApp()->m_pMainWnd->m_hWnd, WM_CLOSE, 0, 0);
}
} /* end of KillWindowObject */
}
void CCoolSimulatorDlg::OnOK()
{
// TODO: Add extra validation here
//CDialog::OnOK();
}
void CCoolSimulatorDlg::OnToolsExtKeypad()
{
// TODO: Add your command handler code here
CRect rect;
GetWindowRect(&rect);
this->m_Phone.ShowExtendKeyboardEx(rect.right,rect.top+300,TRUE);
}
void CCoolSimulatorDlg::OnToolsLayerWatch()
{
// TODO: Add your command handler code here
m_bLayerShow = m_bLayerShow?FALSE:TRUE;
m_LayerDlg.ShowWindow(m_bLayerShow?SW_SHOW:SW_HIDE);
}
void CCoolSimulatorDlg::OnUpdateToolsLayerWatch(CCmdUI* pCmdUI)
{
// TODO: Add your command update UI handler code here
pCmdUI->SetCheck(m_bLayerShow?1:0);
}
| [
"windyin@2490691b-6763-96f4-2dba-14a298306784"
]
| [
[
[
1,
724
]
]
]
|
b6a4d3734c99c7ecb85a447e1d12463092e082db | e4bad8b090b8f2fd1ea44b681e3ac41981f50220 | /trunk/gui/abeetlesgui/release/moc_LabeledLCD.cpp | 323d76b3ab3e320361a09c381a0c3585f6c35a2c | []
| 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 | 2,469 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'LabeledLCD.h'
**
** Created: Sat 4. Aug 15:21:57 2007
** by: The Qt Meta Object Compiler version 59 (Qt 4.3.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../LabeledLCD.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'LabeledLCD.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 59
#error "This file was generated using the moc from 4.3.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
static const uint qt_meta_data_LabeledLCD[] = {
// content:
1, // revision
0, // classname
0, 0, // classinfo
2, 10, // methods
0, 0, // properties
0, 0, // enums/sets
// signals: signature, parameters, type, tag, flags
21, 12, 11, 11, 0x05,
// slots: signature, parameters, type, tag, flags
39, 12, 11, 11, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_LabeledLCD[] = {
"LabeledLCD\0\0newValue\0valueChanged(int)\0"
"setValue(int)\0"
};
const QMetaObject LabeledLCD::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_LabeledLCD,
qt_meta_data_LabeledLCD, 0 }
};
const QMetaObject *LabeledLCD::metaObject() const
{
return &staticMetaObject;
}
void *LabeledLCD::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_LabeledLCD))
return static_cast<void*>(const_cast< LabeledLCD*>(this));
return QWidget::qt_metacast(_clname);
}
int LabeledLCD::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: setValue((*reinterpret_cast< int(*)>(_a[1]))); break;
}
_id -= 2;
}
return _id;
}
// SIGNAL 0
void LabeledLCD::valueChanged(int _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
| [
"ibart@60a5a0de-1a2f-0410-942a-f28f22aea592"
]
| [
[
[
1,
81
]
]
]
|
f56dbb3d94647222de8ca1c985055cde0269d3eb | 5bd189ea897b10ece778fbf9c7a0891bf76ef371 | /BasicEngine/BasicEngine/Utility/Singleton.h | a206681c82d2c7a2296f9ff867f3f03f1d5161c6 | []
| no_license | boriel/masterullgrupo | c323bdf91f5e1e62c4c44a739daaedf095029710 | 81b3d81e831eb4d55ede181f875f57c715aa18e3 | refs/heads/master | 2021-01-02T08:19:54.413488 | 2011-12-14T22:42:23 | 2011-12-14T22:42:23 | 32,330,054 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 451 | h | /*
Clase Singleton.h:
El singleton es uno de los patrones de diseño más simples y extendidos. Se utiliza para garantizar
que una clase sólo tenga una instancia y para proporcionar un acceso gloabal a ella.
Este Singleton corresponde a Meyers
*/
#ifndef Singleton_H
#define Singleton_H
template <typename T> class cSingleton
{
public:
static T& Get()
{
static T lInstance;
return lInstance;
}
};
#endif | [
"yormanh@f2da8aa9-0175-0678-5dcd-d323193514b7"
]
| [
[
[
1,
24
]
]
]
|
79afb1251519915ab2e357709388a895e27c5535 | 3449de09f841146a804930f2a51ccafbc4afa804 | /C++/jet/jet.cpp | 54be5c8c62a1d67a339109e828349b03e084b0a3 | []
| no_license | davies/daviescode | 0c244f4aebee1eb909ec3de0e4e77db3a5bbacee | bb00ee0cfe5b7d5388485c59211ebc9ba2d6ecbd | refs/heads/master | 2020-06-04T23:32:27.360979 | 2007-08-19T06:31:49 | 2007-08-19T06:31:49 | 32,641,672 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,870 | cpp | #include "stdafx.h"
#include "jet.h"
#include <math.h>
/*
function J = jet(m)
%JET Variant of HSV.
% JET(M), a variant of HSV(M), is an M-by-3 matrix containing
% the default colormap used by CONTOUR, SURF and PCOLOR.
% The colors begin with dark blue, range through shades of
% blue, cyan, green, yellow and red, and end with dark red.
% JET, with no arguments, is the same length as the current colormap.
% Use COLORMAP(JET).
%
% See also HSV, HOT, PINK, FLAG, COLORMAP, RGBPLOT.
% Copyright 1984-2002 The MathWorks, Inc.
% $Revision: 5.7 $ $Date: 2002/04/01 21:01:50 $
if nargin < 1
m = size(get(gcf,'colormap'),1);
end
n = ceil(m/4);
u = [(1:1:n)/n ones(1,n-1) (n:-1:1)/n]';
g = ceil(n/2) - (mod(m,4)==1) + (1:length(u))';
r = g + n;
b = g - n;
g(g>m) = [];
r(r>m) = [];
b(b<1) = [];
J = zeros(m,3);
J(r,1) = u(1:length(r));
J(g,2) = u(1:length(g));
J(b,3) = u(end-length(b)+1:end);
*/
double** jet(int m)
{
int i=0;
//n = ceil(m/4);
int n = ceil(m/4.0);
//u = [(1:1:n)/n ones(1,n-1) (n:-1:1)/n]';
int u_len = n*3-1;
double* u = new double[u_len];
for(i=0;i<n;i++){
u[u_len-i-1] = u[i] = double(i+1)/n;
u[n+i] = 1;
}
//J = zeros(m,3);
double** J = new double*[m];
for(i=0;i<m;i++){
J[i] = new double[3];
for(int j=0;j<3;j++){
J[i][j] = 0;
}
}
//g = ceil(n/2) - (mod(m,4)==1) + (1:length(u))';
//g(g>m) = [];
//J(r,1) = u(1:length(r));
int t = ceil(n/2.0) - (m % 4 == 1);
int g_len = m-t;
for(i=0;i<g_len;i++){
J[t+i][1] = u[i];
}
//r = g + n;
//r(r>m) = [];
//J(g,2) = u(1:length(g));
int r_len = m-t-n;
for(i=0;i<r_len;i++){
J[t+i+n][0] = u[i];
}
//b = g - n;
//b(b<1) = [];
//J(b,3) = u(end-length(b)+1:end);
int b_start = n-t;
for(i=b_start;i<u_len;i++){
J[t+i-n][2] = u[i];
}
delete[] u;
return J;
} | [
"davies.liu@32811f3b-991a-0410-9d68-c977761b5317"
]
| [
[
[
1,
80
]
]
]
|
8c2d4454951c1a0ce8dfcb87fdacd30eeacd4234 | b999131a99dbbe85b256ed64700fc8651f69eb98 | /VNE_SOURCE/vne_engine/PhysObject.h | 648a2ff7a58891d9050c6a84b5a9b66fdffb1c1f | []
| no_license | liukan12/vne | 71ba2a63ade36b638107f2800ae6d9a3b3b56d52 | e896cc57af75c72ee5b52530ee9d9d1e7cfe73be | refs/heads/master | 2020-12-24T20:15:21.148998 | 2008-08-01T05:55:10 | 2008-08-01T05:55:10 | 56,172,273 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,774 | h | // a physical object must time-step itself carefully
// keep track of centroid, inertia, and actual
// vertex locations
#ifndef PHYSOBJECT
#define PHYSOBJECT
#include "Object.h"
#include <valarray>
struct ObjParams {
valarray<double> InitPosition;
valarray<double> InitVelocity;
vector<string> input;
};
class PhysObject : public Object
{
protected:
static double step; // default timestep
double massTotal;
valarray<double> Inertia;
valarray<double> Centroid;
valarray<double> Velocity;
valarray<double> AngVel;
valarray<double> Rotation;
valarray<double> Quarternion;
valarray<double> MassDistribution;
valarray<double> ForceDistributionX;
valarray<double> ForceDistributionY;
valarray<double> ForceDistributionZ;
valarray<double> TorqueDistributionX;
valarray<double> TorqueDistributionY;
valarray<double> TorqueDistributionZ;
valarray<double> RotVelX; // rotational velocity of points
valarray<double> RotVelY;
valarray<double> RotVelZ;
valarray<double> NetTorque; // sum of torques at each vertex
valarray<double> NetForce; // sum of forces at each vertex
valarray<double> CurVertX;
valarray<double> CurVertY;
valarray<double> CurVertZ;
valarray<double> LocVertX;
valarray<double> LocVertY;
valarray<double> LocVertZ;
valarray<double> RefVertX; // current vertices of triangle faces w.r.t. local coordinate system
valarray<double> RefVertY; // current vertices of triangle faces w.r.t. local coordinate system
valarray<double> RefVertZ; // current vertices of triangle faces w.r.t. local coordinate system
valarray<double> MyTemp; // this object's temporary numVerts-sized array
valarray<int> VertControlPts; // holds indices of min/max x,y,z vertices
valarray<double> CurNormX; // normals at vertices
valarray<double> CurNormY; // normals at vertices
valarray<double> CurNormZ; // normals at vertices
valarray<int> CurIdx; // indices into Verts & Norms
vector<PhysObject*> CollisionCandidates; // guys whose bounding sphere intersects my bounding sphere
int numFaces;
int numVerts;
double maxVertSpace;
double boundingSphereRad;
double timeStep;
void ComputeMaxVertexSpacing();
void ComputeBoundSphereRad();
virtual void ComputeInertia();
virtual void ComputeTorqueDistribution();
virtual void ComputeRotationMatrix();
virtual void ComputeRotationMatrix( const valarray<double> &ref, const valarray<double> &newdir );
virtual void ComputeRotationalVelocity();
virtual void ComputeCentroid();
virtual void ComputeNetTorque();
virtual void ComputeNetForce();
virtual void UpdateRotation();
virtual void UpdateTotals();
virtual void UpdateAngVel(double dt);
virtual void EulerTimeStep(double dt);
virtual void ProcessCollisions();
// helper function for general-purpose collision handling
double GetMinInterObjVertDist( PhysObject* obj1, PhysObject* obj2 );
double FindCollideTimeAndAdjust( PhysObject* obj1, PhysObject* obj2);
void ApplyCollisionImpulse( PhysObject* obj1, PhysObject* obj2 );
virtual void ProcessTriDataFiles( const vector<string> filenames );
virtual void SyncDrawObj();
public:
// constructors
PhysObject();
PhysObject(const PhysObject &);
PhysObject(const vector<string> &filenames);
~PhysObject();
virtual void UpdateSelf() {};
virtual void InitFromFile(const vector<string> &filenames);
virtual PhysObject* GetSpawnedObject() { return NULL; }
virtual bool IsSpawning() { return false; }
int GetNumVerts() { return numVerts; }
int GetNumFaces() { return numFaces; }
virtual void TimeStep( double dt = step ) {}
virtual void GetMinMaxVert( );
virtual void GetMinMaxVert( double* xmin, double* xmax, double* ymin,
double* ymax, double* zmin, double* zmax);
virtual void AddForceAllVerts( const valarray<double> &Force );
virtual void AddForceAllVerts( double fx, double fy, double fz );
virtual void AddForceAt( int vertIdx, const valarray<double> &Force );
virtual void AddForceAt( int vertIdx, double fx, double fy, double fz );
virtual void SetVelocity( double vx, double vy, double vz );
virtual void TranslateTo(double dx, double dy, double dz);
virtual void Scale( double sx, double sy, double sz );
virtual void TranslateBy(double dx, double dy, double dz);
virtual void AccelerateBy(double dx, double dy, double dz);
virtual bool CheckAndHandleCollision(PhysObject* otherObj);
virtual void ClearForce();
virtual bool isStatic() { return false; }
double GetMaxVertexSpacing() { return maxVertSpace; }
double GetBoundSphereRad() { return boundingSphereRad; }
double GetTimeStep() { return timeStep; }
valarray<double> GetCentroid() { return Centroid; }
};
#endif | [
"karasevpa@60124b6e-824b-0410-a204-ab2e215a433f"
]
| [
[
[
1,
129
]
]
]
|
af3fb2919bafad6243c32c90a260a113a0549e28 | 0d4bf5cb124a04e755b850a844bf2dd57d5186df | /DS1307RTC/DS1307RTC.h | 47d0455b839c45c1576b06850786814e98283cd2 | []
| no_license | smarslang/arduino-revisitato | 0cfbf99aedc42d56b85b365e5fc39f31754f84d3 | b03e11152a9a4f6cc18e1bad46e8f5b8ab7357ba | refs/heads/master | 2020-12-27T23:54:25.133157 | 2011-08-07T17:23:12 | 2011-08-07T17:23:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,767 | h | /*
* DS1307RTC.h - library for DS1307 RTC
* This library is intended to be uses with Arduino Time.h library functions
*/
#ifndef DS1307RTC_h_
#define DS1307RTC_h_
#include <WProgram.h>
#include <Time.h>
#define RTC DS1307RTC::instance
// library interface description
class DS1307RTC {
public:
enum SquareWaveRate {
SQW_1HZ = 0x00,
SQW_4096HZ = 0x01,
SQW_8192HZ = 0x02,
SQW_32768HZ = 0x03
};
static DS1307RTC instance;
/*
* Initializes the clock object instance. The <code>DS1307RTC</code> object has to be initialized before
* it can be used properly. If not initialized, the proper function is not guaranteed. The initialization
* goes through four steps:
* <ol>
* <li>
* <b>Power Management</b> - If the specified <code>pin</code> is greater than <code>-1</code>
* power management is enabled.
* The power management function assumes that the specified <code>pin</code> is
* connect to VCC of the DS1307, hence can control the power to the DS1307. Turning off the power will
* send the DS1307 into low power mode and draw it's power from the backup battery. Power will only
* be turned on when data is read from or written to the DS1307.
* <li>
* <b>DS1307 Status</b> - The method will read the <code>second</code> register to see if the DS1307 is started
* or not.
* <li>
* <b>Turn of Squae Wave Generator</b> - The method will turn of the wave generation by calling
* <code>stopSquareWave</code>.
* <li>
* <b>24-hour Mode</b> - The method will make sure that the chip is in 24-hour mode, rather than in
* AM/PM.
* <ol>
*
* @param[in] pin the Arduino I/O pin that controls the VCC of the clock chip. If <code>-1</code>
* is passed it is interpreted as no I/O pin connected to the VCC of the DS1307 and
* power management is turned off.
* @param[in] initWire if <code>true</code> is passed, <code>Wire.begin()</code> is called to initialized
* the I2C bus; otherwise, it is assumed that the I2C bus was initialized externally.
*
* @return <code>true</code> if the clock was properly initialized;<code>false</code> otherwise.
* @see <a href="http://arduino.cc/en/Reference/Wire">Arduino Wire Library</a>
*/
bool initialize(int8_t pin = -1, bool withWire = false);
/**
* Start the clock by setting the CH bit (bit seven) of the seconds register).
*
* @return <code>true</code> if the clock could be started;<code>false</code> otherwise.
*/
bool start();
/**
* Stops the clock by clearing the CH bit (bit seven) in the seconds register.
*
* @return <code>true</code> if the clock could be started;<code>false</code> otherwise.
*/
bool stop();
/**
* Returns <code> true </code> if the clock is running or <code>false</code>
* if the clock has been halted.
*
* @return <code>true</true> if the clock is running;<code>false</code> otherwise.
*/
bool isRunning();
//
// High level time related functions
//
bool readTime();
time_t getTime();
bool setTime(time_t t);
bool readTimeZone();
int8_t getTimeZone();
bool setTimeZone(int8_t tz);
int writeUserMemory(byte *buffer, int offset, int len);
int readUserMemory(byte *buffer, int offset, int len);
byte readControlRegister();
bool startSquareWave(SquareWaveRate rate);
bool stopSquareWave(bool out);
/**
* Reads <code>len</code> bytes from the clock's registers starting at <code>offset</code>.
*
* @param[out] buffer The buffer that will hold the content of the registers. The buffer
* has to be at least <code>len</code> bytes long.
* @param[in] offset The offset of the first register. The value has to be between 0x00 and
* and 0x3f.
* @param[in] len The number of bytes read from the clock's register if <code>offset + len</code>
* is smaller than 0x40;
*
* @return the number of bytes read from the clock's register, which is either <code>len</code>
* if <code>offset + len < 0x40</code> or <code>0x40 - offset<code> if
* <code>offset + len > 0x3f</code>.
*/
int readBytes(byte *buffer, int offset, int len);
/**
* Writes <code>len</code> bytes from the buffer to the clock's registers starting at
* <code>offset</code>.
*
* @param[in] buffer The buffer that will holds the content to be written to the registers.
* The buffer has to be at least <code>len</code> bytes long.
* @param[in] offset The offset of the first register. The value has to be between 0x00 and
* and 0x3f.
* @param[in] len The number of bytes to be written to the clock's register if
* <code>offset + len</code> is smaller than 0x40;
*
* @return the number of bytes written to the clock's register, which is either <code>len</code>
* if <code>offset + len < 0x40</code> or <code>0x40 - offset<code> if
* <code>offset + len > 0x3f</code>.
*/
int writeBytes(const byte *buffer, int offset, int len);
private:
DS1307RTC();
uint8_t dec2bcd(uint8_t num);
uint8_t bcd2dec(uint8_t num);
// static DS1307RTC instance = RTC();
bool running;
bool squareWave;
int8_t powerMgmtPin;
time_t _lastTime;
unsigned long _lastMillis;
int8_t _timezone;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
159
]
]
]
|
b8cc7d62f5cc84edc446a29f4f552a4003ad5ac9 | fb99c5ca73adb5857a462a98329d5c8753a9cb13 | /open/fluid/drawing.cc | 993df11a01d1ea7f7680633a395dc3f866379bce | []
| no_license | luqui/soylent | f82ff00cdf76b426c2c3580e9c432bcb48715358 | 94bbe25a1b93a30e94e2ab072f792bb273da3b06 | refs/heads/master | 2021-01-22T03:44:15.546888 | 2009-06-24T20:08:55 | 2009-06-24T20:08:55 | 113,045 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,341 | cc | #include "drawing.h"
#include "FluidGrid.h"
#include "util.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <cmath>
static float TIMING = 0;
static float TIMING1 = 0;
static float TIMING2 = 0;
static float TIMING3 = 0;
static float TIMING4 = 0;
static float TIMING5 = 0;
static float TIMING6 = 0;
void scale_color(float density, float alpha) {
float d = 20*density;
if (d < 0) {
glColor4f(-TIMING1*d, -TIMING2*d, -TIMING3*d, alpha);
}
else {
glColor4f(TIMING4*d, TIMING5*d, TIMING6*d, alpha);
}
}
void set_color_at(const GPUFluid* field, int x, int y) {
scale_color(field->get_density_direct(x,y));
}
void draw_rect(vec ll, vec ur) {
glBegin(GL_QUADS);
glTexCoord2f(0,1); glVertex2f(ll.x,ll.y);
glTexCoord2f(1,1); glVertex2f(ur.x,ll.y);
glTexCoord2f(1,0); glVertex2f(ur.x,ur.y);
glTexCoord2f(0,0); glVertex2f(ll.x,ur.y);
glEnd();
}
void init_color() {
TIMING = randrange(-10000,10000);
}
void draw_board(const GPUFluid* field, int w, int h) {
g_pFlo->SetInkColor(g_rInkRGB);
if (!b['p'] || b['.'])
{
b['.'] = false;
// cycle ink color
if (b['c'] && (TIMING1 > 100))
{
TIMING1 = 0;
static int sColor = 0;
sColor = (sColor + 1) % 7;
g_rInkRGB[0] = 0.15f * (sColor & 0x1) +
0.05f * ((sColor & 0x2) / 2);
g_rInkRGB[1] = 0.15f * ((sColor & 0x2) / 2) +
0.05f * ((sColor & 0x4) / 4);
g_rInkRGB[2] = 0.15f * ((sColor & 0x4) / 4) +
0.05f * (sColor & 0x1);
if (sColor > 699) sColor = 0;
}
// set parameters that may have changed
g_pFlo->SetViscosity(g_rViscosity);
g_pFlo->EnablePressureClear(b['C']);
g_pFlo->SetNumPoissonSteps(g_iNumPoissonSteps);
g_pFlo->SetInkColor(g_rInkRGB);
g_pFlo->SetInkLongevity(g_rInkLongevity);
g_pFlo->SetTimeStep(g_rTimestep);
g_pFlo->SetGridScale(g_rGridScale);
g_pFlo->SetVorticityConfinementScale(g_rVCScale);
if (g_displayMode == Flo::DISPLAY_VORTICITY || b['v'])
g_pFlo->EnableVorticityComputation(true);
else
g_pFlo->EnableVorticityComputation(false);
}
if (b['D'])
{
// Display the fluid.
if (b['0'])
g_pFlo->Display(g_displayMode, b['b'], b['m'], b['o'], b['w']);
else
glClear(GL_COLOR_BUFFER_BIT);
if (g_vectorDisplayMode != Flo::VECTOR_DISPLAY_NONE)
g_pFlo->DisplayVectorField(g_vectorDisplayMode, g_iLineWidth,
g_iPointSize, g_rVectorScale);
}
/*float norm;
TIMING1 = sin(TIMING/(M_PI+1))+1;
TIMING2 = sin(TIMING/(2*M_PI))+1;
TIMING3 = sin(TIMING/(exp(float(2))))+1;
norm = sqrt(TIMING1*TIMING1 + TIMING2*TIMING2 + TIMING3*TIMING3)/3;
TIMING1 /= norm; TIMING2 /= norm; TIMING3 /= norm;
TIMING4 = sin(TIMING/8)+1;
TIMING5 = sin(TIMING/sqrt(float(10)))+1;
TIMING6 = sin(TIMING/sqrt(float(11)))+1;
norm = sqrt(TIMING4*TIMING4 + TIMING5*TIMING5 + TIMING6*TIMING6)/3;
TIMING4 /= norm; TIMING5 /= norm; TIMING6 /= norm;
float colordist = (TIMING1-TIMING4)*(TIMING1-TIMING4)
+ (TIMING2-TIMING5)*(TIMING2-TIMING5)
+ (TIMING3-TIMING6)*(TIMING3-TIMING6);
if (colordist < MIN_COLOR_NORM) {
const float offs = 1/MAX_COLOR_CHANGE_RATE;
const float mul = (1/COLOR_CHANGE_RATE - offs) / MIN_COLOR_NORM;
TIMING += 1/(mul*colordist + offs)*DT;
}
else {
TIMING += COLOR_CHANGE_RATE*DT;
}
glBegin(GL_QUADS);
for (int i = 0; i < w-1; i++) {
for (int j = 0; j < h-1; j++) {
set_color_at(field,i,j);
glVertex2f(i,j);
set_color_at(field,i+1,j);
glVertex2f(i+1,j);
set_color_at(field,i+1,j+1);
glVertex2f(i+1,j+1);
set_color_at(field,i,j+1);
glVertex2f(i,j+1);
}
}
glEnd();
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glColor4f(0,0,0,0.25);
glBegin(GL_QUADS);
glVertex2f(0,0);
glVertex2f(W,0);
glVertex2f(W,CLAMPH);
glVertex2f(0,CLAMPH);
glVertex2f(0,H-CLAMPH);
glVertex2f(W,H-CLAMPH);
glVertex2f(W,H);
glVertex2f(0,H);
glVertex2f(0,CLAMPH);
glVertex2f(CLAMPW,CLAMPH);
glVertex2f(CLAMPW,H-CLAMPH);
glVertex2f(0,H-CLAMPH);
glVertex2f(W-CLAMPW,CLAMPH);
glVertex2f(W,CLAMPH);
glVertex2f(W,H-CLAMPH);
glVertex2f(W-CLAMPW,H-CLAMPH);
glEnd();
glDisable(GL_BLEND);*/
}
| [
"luqui@94b1653a-ed48-0410-b77d-b6a479af8a11"
]
| [
[
[
1,
159
]
]
]
|
dcaecfbe25c51b635e9ce9051a0fce6af1e9e78d | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/sound/soundcore.h | a7e37db95496ac877bacad8a4c31492c5569c328 | []
| no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,179 | h | /*!
@file
@brief サウンドコア
*/
#ifndef maid2_sound_soundcore_h
#define maid2_sound_soundcore_h
#include"../config/define.h"
#include"../auxiliary/globalpointer.h"
#include"../auxiliary/thread.h"
#include"../auxiliary/timer.h"
#include"core/idevice.h"
#include"soundmessagebase.h"
#include"isoundobject.h"
#include"pcmreader/ipcmreader.h"
#include<map>
namespace Maid {
class SoundCore
: public GlobalPointer<SoundCore>
{
public:
SoundCore();
virtual ~SoundCore();
struct INITIALIZEPARAM
{
Sound::SPDEVICE pDevice;
bool IsBackGround; // スレッドを作って別途処理する。
unt32 ProcesserMask;
INITIALIZEPARAM()
:IsBackGround(true)
,ProcesserMask(1)
{
}
};
void Initialize( const INITIALIZEPARAM& param );
void Finalize();
void Update();
SPSOUNDOBJECTINFO CreateObjectInfo();
SPPCMREADER CreatePCMReader( const void* pData, size_t Size ) const;
void PostMessage( const SPSOUNDOBJECTINFO& pInfo, const SPSOUNDMESSAGE& pMess );
private: // スレッド間をまたがないメンバ
void RegisterObject( const SPSOUNDOBJECTINFO& pInfo, const SPSOUNDOBJECT& pObj, const String& ShreadID );
void DeleteObject( const SPSOUNDOBJECTINFO& pInfo );
SPSOUNDOBJECT GetObject( const SPSOUNDOBJECTINFO& pInfo );
Sound::SPBUFFER GetSharedBuffer( const String& ShreadID );
struct DATA
{
SPSOUNDOBJECTINFO pInfo;
SPSOUNDOBJECT pObject;
String ShreadID;
};
typedef std::map<unt,DATA> OBJECTLIST;
OBJECTLIST m_ObjectList;
Timer m_Timer;
private: // スレッド間をまたぐメンバ
ThreadMutex m_MessageMutex;
SOUNDMESSAGEQUE m_MessageQue;
unt m_CreateCount;
ThreadMutex m_ObjectMutex;
private:
unt ThreadFunction(volatile ThreadController::BRIGEDATA& brige);
void ExecuteMessage( const SoundMessage::Base& Mess );
INITIALIZEPARAM m_Param;
ThreadController m_AccessThread;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
94
]
]
]
|
d99c3b35a01eac5cec63e844d0f3f7a5a8471cf6 | a51ac532423cf58c35682415c81aee8e8ae706ce | /CameraAPI/Image.h | ec3a299395738394cebf5fbd4c73319b878ac61e | []
| no_license | anderslindmark/PickNPlace | b9a89fb2a6df839b2b010b35a0c873af436a1ab9 | 00ca4f6ce2ecfeddfea7db5cb7ae8e9d0023a5e1 | refs/heads/master | 2020-12-24T16:59:20.515351 | 2008-05-25T01:32:31 | 2008-05-25T01:32:31 | 34,914,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,126 | h | #ifndef __IMAGE_H__
#define __IMAGE_H__
namespace camera
{
typedef unsigned char ImageBuffer;
class Image
{
public:
///
/// \brief The different pixel format used
///
static enum Format
{
FORMAT_Y8, ///< 8 bit gray scale
FORMAT_RGB32, ///< 32 bit color (8 bit red, 8 bit green, 8 bit blue, 8 bit not used)
FORMAT_RGB24, ///< 24 bit color (8 bit red, 8 bit green, 8 bit blue)
FORMAT_RGB16, ///< 16 bit color (5 bit red, 6 bit green, 5 bit blue)
FORMAT_RGB15, ///< 16 bit color (5 bit red, 5 bit green, 5 bit blue)
FORMAT_UNKNOWN = 1000 ///< Custom pixel format
};
///
/// \brief Return the length (in bytes) used for each pixel with the specified pixel format
/// \param format The pixel format
///
static int formatBytesPerPixel(Format format);
///
/// Create a new image with the specified width, height and format
/// \param width The with of the image in pixels
/// \param width The height of the image in pixels
/// \param format The pixel format of the image
///
Image(int width, int height, Format format);
///
/// Create a new image with the specified width, height and with custom pixel format (Format::FORMAT_UNKNOWN)
/// \param width The with of the image in pixels
/// \param width The height of the image in pixels
/// \param bytesPerPixel The length (in bytes) of each pixel
///
Image(int width, int height, int bytesPerPixel);
///
/// \brief The destructor. Deallocates the memory used by the image
///
~Image();
///
/// \brief Reallocate the image to a new size but keep the current pixel format.
///
void reallocate(int width, int height);
///
/// \brief Reallocate the image to a new size and pixel format.
///
void reallocate(int width, int height, Format format);
///
/// \brief Reallocate the image to a new size. Sets the format to FORMAT_UNKNOWN (Custom pixel format).
///
void reallocate(int width, int height, int bytesPerPixel);
///
/// \brief Returns a pointer to the memory containing the image data.
///
ImageBuffer *getBufferAddress() const;
///
/// \brief Returns the size (in bytes) of the image buffer returned by getBufferAddress.
///
int getBufferSize() const;
///
/// \brief Returns the format of the image.
///
Format getFormat() const;
///
/// \brief Returns the width of the image in pixels.
///
int getWidth() const;
///
/// \brief Returns the height of the image in pixels.
///
int getHeight() const;
///
/// \brief Returns the number of bytes each pixel needs. This depends on the pixel format.
///
int getBytesPerPixel() const;
///
/// \brief Custom user data that can be attached to the image.
///
void *userData;
private:
int m_width;
int m_height;
int m_bytesPerPixel;
Format m_format;
int m_bufferSize;
ImageBuffer *m_buffer;
};
} // namespace camera
#endif
| [
"kers@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7"
]
| [
[
[
1,
114
]
]
]
|
f4afcdad4c62b371d041163622cfc0089da3e35d | 19b8f2132768c8c52238180e15815cbd4243b41d | /ENVIADOS Fase I EDA/142 Mouse Clicks/main.cpp | ff16b22c90788a33459ba4f628fcad1a4cd5e1ef | []
| no_license | Greatfox/Programas-EDA | 604ae99e2576ecfae8a0a2965834d1206f41fb02 | 73d5d5961e041c27aadea0314f066e21e6d87807 | refs/heads/master | 2016-09-03T02:23:10.221535 | 2011-12-16T04:44:39 | 2011-12-16T04:44:39 | 2,279,239 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,033 | cpp | #include <iostream>
#include <vector>
using namespace std;
char idR = 'A';
int idI = 1;
struct R
{
int x, y, x2, y2;
char id;
R(int x, int y, int x2, int y2) :
x(x), y(y), x2(x2), y2(y2)
{
id = idR++;
}
};
struct I
{
int x, y;
int id;
I(int x, int y) :
x(x), y(y)
{
id = idI++;
}
};
int main(int argc, char **argv)
{
char C;
int x, y, x2, y2;
vector<R> VR;
vector<I> VI;
vector<bool> IN;
bool flag = 1;
while (cin >> C)
{
if (C == '#')
{
return 0;
}
switch (C)
{
case 'R':
cin >> x >> y >> x2 >> y2;
VR.push_back(R(x, y, x2, y2));
break;
case 'I':
cin >> x >> y;
VI.push_back(I(x, y));
break;
case 'M':
cin >> x >> y;
if (flag)
{
IN.resize(VI.size(), 1);
for (int i = 0; i < VI.size(); ++i)
{
for (int j = 0; j < VR.size(); ++j)
{
if (VI[i].x >= VR[j].x && VI[i].x <= VR[j].x2 &&
VI[i].y >= VR[j].y && VI[i].y <= VR[j].y2)
{
IN[i] = 0;
break;
}
}
}
flag = 0;
}
//With Regions
char r = ' ';
//cout << "lee" << endl;
for (int i = 0; i < VR.size(); ++i)
{
if (VR[i].id > r || r == ' ')
{
if (VR[i].x <= x && VR[i].x2 >= x && VR[i].y <= y
&& VR[i].y2 >= y)
{
r = VR[i].id;
}
}
}
if (r == ' ')
{
//With Icons
vector<int> ic;
int d, mind = 9999999;
for (int i = 0; i < VI.size(); ++i)
{
if (IN[i])
{
d = (x - VI[i].x) * (x - VI[i].x) + (y - VI[i].y) * (y
- VI[i].y);
if (d == mind)
{
ic.push_back(VI[i].id);
}
if (d < mind)
{
ic.clear();
ic.push_back(VI[i].id);
mind = d;
}
}
}
for (int i = 0; i < ic.size(); ++i)
{
cout.width(3);
cout << ic[i];
}
}
else
{
cout << r;
}
cout << endl;
break;
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
136
]
]
]
|
d24d044b789694ec08f3ea7819d87850a491ffea | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/dom/deprecated/NodeVector.cpp | da0f35235bbd0841c72c55467fe35a410af7654e | [
"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 | 3,467 | cpp | /*
* Copyright 1999-2002,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: NodeVector.cpp,v 1.5 2004/09/08 13:55:44 peiyongz Exp $
*/
//
// file: NodeVector.cpp
// Implementation of class NodeVector.
// (Use of STL vector, or equivalent, would have been nice,
// but is not available. 'NodeImpl *' is the only type
// kept in Vectors in this DOM implementation, so this is
// a hardwired implementation for that type.
//
#include "NodeVector.hpp"
#include <xercesc/framework/MemoryManager.hpp>
#include <assert.h>
XERCES_CPP_NAMESPACE_BEGIN
NodeVector::NodeVector(MemoryManager* const manager)
: fMemoryManager(manager)
{
init(10);
};
NodeVector::NodeVector(unsigned int size,
MemoryManager* const manager)
: fMemoryManager(manager)
{
init(size);
};
void NodeVector::init(unsigned int size) {
assert(size > 0);
data = (NodeImpl**) fMemoryManager->allocate(size * sizeof(NodeImpl*));//new NodeImpl *[size];
assert(data != 0);
allocatedSize = size;
nextFreeSlot = 0;
};
NodeVector::~NodeVector() {
fMemoryManager->deallocate(data);//delete [] data;
};
void NodeVector::addElement(NodeImpl *elem) {
checkSpace();
data[nextFreeSlot] = elem;
++nextFreeSlot;
};
void NodeVector::checkSpace() {
if (nextFreeSlot == allocatedSize) {
unsigned int grow = allocatedSize/2;
if (grow < 50) grow = 50;
unsigned int newAllocatedSize = allocatedSize + grow;
NodeImpl **newData = (NodeImpl**) fMemoryManager->allocate
(
newAllocatedSize * sizeof(NodeImpl*)
);//new NodeImpl *[newAllocatedSize];
assert(newData != 0);
for (unsigned int i=0; i<allocatedSize; i++) {
newData[i] = data[i];
};
fMemoryManager->deallocate(data);//delete [] data;
allocatedSize = newAllocatedSize;
data = newData;
};
};
NodeImpl *NodeVector::elementAt(unsigned int index) {
if (index >= nextFreeSlot)
return 0;
return data[index];
};
NodeImpl *NodeVector::lastElement() {
if (nextFreeSlot == 0)
return 0;
return data[nextFreeSlot-1];
};
void NodeVector::insertElementAt(NodeImpl *elem, unsigned int index) {
unsigned int i;
assert(index <= nextFreeSlot);
checkSpace();
for (i=nextFreeSlot; i>index; --i) {
data[i] = data[i-1];
}
data[index] = elem;
++nextFreeSlot;
};
void NodeVector::removeElementAt(unsigned int index) {
assert(index < nextFreeSlot);
for (unsigned int i=index; i<nextFreeSlot-1; ++i) {
data[i] = data[i+1];
}
--nextFreeSlot;
};
void NodeVector::reset() {
nextFreeSlot = 0;
};
void NodeVector::setElementAt(NodeImpl *elem, unsigned int index) {
assert(index < nextFreeSlot);
data[index] = elem;
};
unsigned int NodeVector::size() {
return nextFreeSlot;
};
XERCES_CPP_NAMESPACE_END
| [
"[email protected]"
]
| [
[
[
1,
144
]
]
]
|
b4a911c04b5ba0783768d5c33efc30f3091fa407 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /SMDK/Include/DebugLib.h | 71d6a244e0907ccc0826b4e65d9b8d39e7a28fa7 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,209 | h | // DebugLib.h: interface for the DebugFile class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_DEBUGLIB_H__6780B3E2_46E4_43F1_AB44_10E816489653__INCLUDED_)
#define AFX_DEBUGLIB_H__6780B3E2_46E4_43F1_AB44_10E816489653__INCLUDED_
//#if _MSC_VER > 1000
//#pragma once
//#endif // _MSC_VER > 1000
#include <stdio.h>
#ifdef __DEBUGLIB_CPP
#define DllImportExport __declspec(dllexport)
#elif !defined(SCDIF)
#define DllImportExport __declspec(dllimport)
#else
#define DllImportExport
#endif
//=========================================================================
#define MAX_DEBUG_LEVEL 9
const int DEBUGARRAYLEN = 250;
DllImportExport HANDLE dbgfile();
DllImportExport char *dbgfilename();
DllImportExport bool dbgtestfileopen();
DllImportExport void dbglock();
DllImportExport void dbgunlock();
DllImportExport void dbgtime(int Opt);
DllImportExport void dbgpln(char * fmt, ...);
DllImportExport void dbgp(char * fmt, ...);
DllImportExport void dbgnln();
DllImportExport bool dbgfileopen(LPCTSTR Fn);
DllImportExport void dbgfileclose(void);
DllImportExport void dbgfiletrunc(long size=0);
DllImportExport void dbgfileflush(bool On);
DllImportExport void dbgindent(int chg, LPCTSTR where=NULL);
DllImportExport int dbgindentcnt();
//DllImportExport void Dbg_Entry();
//DllImportExport void Dbg_Exit();
DllImportExport LPCTSTR DbgFltString(double V, int eSig=3, int fSig=6, int RqdLen=0);
#define DBGATON 1
#define DBGATLEN 80
#define DBGATLISTLEN 256
DllImportExport void dbgMemoryState(LPCTSTR Where);
DllImportExport void dbgTimeStamp(LPCTSTR Where);
#define DBG_NEW(s)
//=========================================================================
class DllImportExport CStopWatch
{
protected:
LARGE_INTEGER Freq;
bool bRunning;
DWORD dwLaps;
double dCurrent;
double dAccum;
double dLapTime;
public:
double Time() { if (Freq.QuadPart==0) return 0; LARGE_INTEGER Tmp; QueryPerformanceCounter(&Tmp); return ((double)(Tmp.QuadPart))/Freq.QuadPart; }
void Start() { double Tm=Time(); dLapTime=-Tm; dCurrent -= Tm; dwLaps++; bRunning=1; };
void Stop() { double Tm=Time(); dLapTime+=Tm; dCurrent += Tm; bRunning=0; };
double Secs() { return dCurrent + (bRunning ? Time() : 0.0); };
double LapTime() { return bRunning ? dLapTime+Time() : dLapTime; };
void ReStart() { dAccum=0.0; Start(); };
double Lap() { double d1=Secs(); double d2=d1-dAccum; dAccum=d1; dwLaps++; return d2; };
void Clear() { dCurrent=dAccum=dLapTime=0.0; dwLaps=0; bRunning=0; };
DWORD Laps() { return dwLaps; };
bool Running() { return bRunning; };
static LPCTSTR MinSecDesc(double Seconds, CString & s);
static LPCTSTR MinSecHunDesc(double Seconds, CString & s);
static LPCTSTR HourMinSecHunDesc(double Seconds, CString & s);
static LPCTSTR DayHourMinSecHunDesc(double Seconds, CString & s);
LPCTSTR MinSecDesc(CString & s) { return MinSecDesc(Secs(), s); };
LPCTSTR MinSecHunDesc(CString & s) { return MinSecHunDesc(Secs(), s); };
LPCTSTR HourMinSecHunDesc(CString & s) { return HourMinSecHunDesc(Secs(), s); };
LPCTSTR DayHourMinSecHunDesc(CString & s) { return DayHourMinSecHunDesc(Secs(), s); };
CStopWatch() { QueryPerformanceFrequency(&Freq); Clear(); }
CStopWatch(bool DoStart) { QueryPerformanceFrequency(&Freq); Clear(); if (DoStart) Start(); }
};
//=========================================================================
class DllImportExport CStopWatchLap
{
protected:
CStopWatch & m_rSW;
public:
CStopWatchLap(CStopWatch & SW):
m_rSW(SW)
{
m_rSW.Start();
};
~CStopWatchLap()
{
m_rSW.Stop();
}
};
// ==========================================================================
class CGlblStopWatchList;
class DllImportExport CGlblStopWatch : public CStopWatch
{
friend class CGlblStopWatchList;
public:
enum eShowWhat { eShowDbg=1, eShowAccess=2, eShowTotal=4};
CGlblStopWatch(CGlblStopWatchList & List, LPCTSTR Group, LPCTSTR Name, int Order=0, int Show=(eShowDbg|eShowAccess));
~CGlblStopWatch();
LPCTSTR Group() { return m_sGroup; };
LPCTSTR Name() { return m_sName; };
LPCTSTR FullName() { return m_sFullName; };
int Show() { return m_iShow; };
double Time();
double TotalTime();
double TimeFrac();
double TotalTimeFrac();
protected:
CGlblStopWatchList &m_List;
CString m_sGroup;
CString m_sName;
CString m_sFullName;
int m_iOrder;
int m_iShow;
double m_dTimeMem;
};
class DllImportExport CGlblStopWatchList : public CArray<CGlblStopWatch*, CGlblStopWatch*>
{
public:
CGlblStopWatchList();
bool GroupIndices(LPCTSTR Group, int &First, int &Last);
void Start();
void Stop();
double StepTime() { return m_dStepTime; };
double Time(int i);
double TotalTime(int i);
double TimeFrac(int i);
double TotalTimeFrac(int i);
protected:
double m_dStepTime;
CStopWatch m_swStep;
};
extern DllImportExport CGlblStopWatchList gs_swFlwSolve;
extern DllImportExport CGlblStopWatchList gs_swExecute;
//===========================================================================
extern DllImportExport double GetProcessorTime();
// ==========================================================================
#undef DllImportExport
// ==========================================================================
#endif // !defined(AFX_DEBUGFILE_H__6780B3E2_46E4_43F1_AB44_10E816489653__INCLUDED_)
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
41
],
[
43,
171
],
[
176,
182
]
],
[
[
42,
42
],
[
172,
175
]
]
]
|
51ac4d5106a7aedb57b41ab6af5f4b096c14035c | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /InformationProviders/InfoProvider.h | d5aeb66787500a73699c3a8db5679b7c3aeab95b | []
| 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 | 5,574 | 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
// *
// */
#ifndef _IInfoProvider_h_
#define _IInfoProvider_h_
#include "IConfigurable.h"
class IInfoProvider:public IConfigurable
{
public:
enum ServiceEnum
{
SRV_First,
SRV_ArtistBio,
SRV_ArtistImage, // *
SRV_AlbumReview,
SRV_AlbumImage, // *
SRV_TrackLyrics,
SRV_TrackTablatures,
SRV_ArtistSimilar, // **
SRV_AlbumSimilar, // **
SRV_TrackSimilar, // **
SRV_TrackSyncedLyrics, //Track Synced Lyrics
SRV_TrackReview, //Track Story - Review
SRV_TrackInfo, //Track Length, Year, Price
SRV_AlbumInfo, //Track List, Year, Price etc
SRV_Last
};
struct Request
{
Request():service(SRV_First),title(NULL),album(NULL),artist(NULL){}
Request(ServiceEnum srv):service(srv),title(NULL),album(NULL),artist(NULL){}
ServiceEnum service;
LPCTSTR title;
LPCTSTR album;
LPCTSTR artist;
BOOL IsValid() const
{
switch (service)
{
case SRV_ArtistBio:
case SRV_ArtistImage:
case SRV_ArtistSimilar:
return artist != NULL && artist[0] != NULL;
case SRV_AlbumReview:
case SRV_AlbumImage:
case SRV_AlbumSimilar:
case SRV_AlbumInfo:
return artist != NULL && artist[0] != NULL && album != NULL && album[0] != NULL;
case SRV_TrackLyrics:
case SRV_TrackTablatures:
case SRV_TrackSimilar:
case SRV_TrackSyncedLyrics:
case SRV_TrackReview:
case SRV_TrackInfo:
return artist != NULL && artist[0] != NULL && title != NULL && title[0] != NULL;
}
return FALSE;
}
};
struct Result
{
Result():service(SRV_First),main(NULL),additionalInfo(NULL) {}
ServiceEnum service;
LPCTSTR main;
LPCTSTR additionalInfo;
BOOL IsValid() const
{
return service > SRV_First && service < SRV_Last && main != NULL;
}
};
// *: Result is a path to a temp file
// **: Result is a string '|' separated list
// All Artist have 1 param (Artist)
// All Album have 2 param (Artist, Album)
// All Track have 2 param (Artist, Title)
//enum ResultTypeEnum
//{
// //RES_Type,
// RES_Main,
// RES_AdditionalInfo,
// RES_Last
//};
public:
virtual ~IInfoProvider() {}
//--------------------------------------------------------
//INFO: Clones (Duplicate the current item)
//COMMENTS: Retains all the configuration;
virtual IInfoProvider* Clone() const = 0;
//--------------------------------------------------------
//INFO: Initializes a request
//PARAMS:
// params: Fill the appropriate structure with the required
// info for the
//RETURNS: TRUE if the request is valid
// FALSE if the request is not valid
//COMMENTS: This function must not take long. (eg. must not get data from internet)
// Call NextResult to get the first result
//USAGE: Request the info needed. Build the params using the InfoProviderHelper class
//virtual BOOL OpenRequest(LPCTSTR requestString) = 0;
virtual BOOL OpenRequest(const Request& request) = 0;
//--------------------------------------------------------
//INFO: Retrieves next or the first result.
//RETURNS: TRUE if there a result has been retrieved successfully
// FALSE if there are no more results
//USAGE: if returns true the call GetResult to get the data.
// You may call NextResult again until you get false
virtual BOOL GetNextResult(Result& result) = 0;
virtual const Request& GetRequest() = 0;
virtual BOOL AddResult(const Result& result) = 0;
virtual BOOL DeleteResult() = 0;
//--------------------------------------------------------
//INFO: Capabilities Function
//PARAMS:
// type: One of the types that is supported by the provider
//RETURNS: TRUE if you can request the specified type
// FALSE if this type is not supported for requests
virtual BOOL CanHandle(ServiceEnum service) const = 0;
enum ModuleInfo
{
IPI_ModuleFileName, //Self Calculated
IPI_UniqueID, //Unique for this provider. All capitals. Version Independent
IPI_Name,
IPI_Author,
IPI_VersionStr,
IPI_VersionNum,
IPI_Description,
IPI_HomePage,
IPI_Email,
IPI_UpdateURL,
IPI_XInfo,
IPI_Last
};
//--------------------------------------------------------
//Returns Information about the provider
virtual LPCTSTR GetModuleInfo(ModuleInfo mi) const = 0;
//--------------------------------------------------------
virtual void SetInternetHandle(LPVOID hInternet) = 0;
virtual LPVOID GetInternetHandle() const = 0;
//--------------------------------------------------------
//=== IConfigurable
virtual void UpdateConfiguration() {}
};
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
174
]
]
]
|
fca4b95967581c6cfdb6cdbb94620a6ea22b7798 | faacd0003e0c749daea18398b064e16363ea8340 | /lyxlib/scrolllabel.h | 56bd5d025c1498e2b891f8cd0e30fb1d17f808fa | []
| no_license | yjfcool/lyxcar | 355f7a4df7e4f19fea733d2cd4fee968ffdf65af | 750be6c984de694d7c60b5a515c4eb02c3e8c723 | refs/heads/master | 2016-09-10T10:18:56.638922 | 2009-09-29T06:03:19 | 2009-09-29T06:03:19 | 42,575,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,566 | h | /*
* Copyright (C) 2008 Pavlov Denis
*
* Comments unavailable.
*
* 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 any later version.
*
*/
#ifndef __SCROLLLABEL_H__
#define __SCROLLLABEL_H__
#include <QPainter>
#include <QTimer>
#include "control.h"
//! \brief ALyxScrollLabel implements scrolling text.
/*!
Scrolled text has some important parametes such as:
<ul>
<li>text</li>
<li>speed</li>
<li>step width</li>
<li>scroll start delay</li>
<li>edge blend size</li>
<li>fixed width</li>
</ul>
The maximum <b>speed</b> of scrolling is 999 that means the delay between steps
is 1ms. The <b>speed</b> of 0 means one step in a second.
<b>Step</b> width is defined in pixels.
Scroll start <b>delay</b> in <i>ms</i> means when startScroll() slot is executed the label
does not scroll for delay time and than begins to scroll.
<b>Edge blend size</b> is a width of edge gradients on the left and right edges
of a label. When there is room for label text edge blends aren't displayed.
If the fixed width is set:
<ul>
<li>width of a label isn't calculated to fit it's text (no autosizing)</li>
<li>label's text is scrolling when there is no room for text in it.</li>
</ul>
*/
class ALyxScrollLabel : public ALyxControl {
Q_OBJECT
public:
//! \brief Constructs new label object with parent.
ALyxScrollLabel(QWidget *parent = 0, QString text = "");
~ALyxScrollLabel();
//! \brief Set text of a label
void setText(QString text);
//! \brief Return text of a label
QString text() { return m_text; }
//! \brief Set speed of label scrolling animation
void setSpeed(int speed) { m_speed = speed; scrollTimer->setInterval(1000-m_speed); }
//! \brief Get speed of label scrolling animation
int speed() { return m_speed; }
//! \brief Set scroll step in pixels
void setStep(int step) { m_step = step; }
//! \brief Get scroll step in pixels
int step() { return m_step; }
//! \brief Set scroll delay
void setDelay(int delay) { m_delay = delay; delayTimer->setInterval(m_delay); }
//! \brief Get scroll delay
int delay() { return m_delay; }
//! \brief Set scrollable flag
void setScrollable(bool s) { m_scrollable = s; }
//! \brief Get scrollable flag
bool isScrollable() { return m_scrollable; }
//! \brief Set label text color
void setTextColor(QColor color) { m_textColor = color; }
//! \brief Set edge blend size
void setBlendSize(int length);
//! \brief Derived from ALyxControl
void setFixedWidth(int w);
//! \brief Derived from ALyxControl
void setFixedSize(int w, int h);
//! \brief Derived from ALyxControl
void setFixedSize(QSize size);
// //! \brief Sets font of a label
// void setFont(QFont font) { ALyxControl::setFont(font); update(); }
private:
QString m_text;
int m_delay;
int m_speed;
int m_step;
bool m_scrollable;
bool m_noRoom;
int m_scrollPosition;
QColor m_textColor;
int m_blendSize;
QTimer *scrollTimer;
QTimer *delayTimer;
bool isNoRoom() { return m_noRoom; }
protected:
void paintEvent(QPaintEvent *e);
private slots:
void scrollStep();
public slots:
//! \brief Starts the scroll animation loop.
void startScroll();
//! \brief Starts the scroll animation loop immediatly ignoring delay.
void startScrollImmediate();
//! \brief Stops the scroll animation loop.
void stopScroll();
signals:
};
#endif
| [
"futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9"
]
| [
[
[
1,
129
]
]
]
|
620d289e42391333b3d096339c15e8d6459a3249 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/GSD3DLib/GSD3DBaseClass.cpp | 935585e1aca7e159c160dc3314b272fd4547735a | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,527 | cpp | #include "stdafx.h"
#include "GSMacro.h"
#include "GSD3DBaseClass.h"
#include <DXUT.h>
#include <math.h>
#include <algorithm>
GSDXBase::GSDXBase()
{
m_pDevice = NULL;
m_pDeviceContext = NULL;
m_pSwapChain = NULL;
}
GSDXBase::GSDXBase(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, IDXGISwapChain* pSwapChain)
{
m_pDevice = pDevice;
m_pDeviceContext = pContext;
m_pSwapChain = pSwapChain;
SAFE_ADDREF(m_pDevice);
SAFE_ADDREF(m_pDeviceContext);
SAFE_ADDREF(m_pSwapChain);
}
GSDXBase::~GSDXBase()
{
SAFE_RELEASE(m_pDevice);
SAFE_RELEASE(m_pDeviceContext);
SAFE_RELEASE(m_pSwapChain);
}
ID3D11Device* GSDXBase::GetD3DDevice()
{
return m_pDevice;
}
ID3D11DeviceContext* GSDXBase::GetDeviceContext()
{
return m_pDeviceContext;
}
IDXGISwapChain* GSDXBase::GetSwapChain()
{
return m_pSwapChain;
}
HRESULT GSDXBase::CreateD3DDevice(HWND hwnd, UINT bufW, UINT bufH)
{
SAFE_RELEASE(m_pDevice);
SAFE_RELEASE(m_pDeviceContext);
SAFE_RELEASE(m_pSwapChain);
if (hwnd == NULL || bufW <= 0 || bufH <= 0)
return E_FAIL;
HRESULT hr = S_OK;
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory( &sd, sizeof( sd ) );
sd.BufferCount = 1;
sd.BufferDesc.Width = bufW;
sd.BufferDesc.Height = bufH;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hwnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
D3D_FEATURE_LEVEL FeatureLevelsRequested[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1,
};
UINT numLevelsRequested = 6;
D3D_FEATURE_LEVEL FeatureLevelsSupported;
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
if( FAILED (hr = D3D11CreateDeviceAndSwapChain( NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
createDeviceFlags,
FeatureLevelsRequested,
numLevelsRequested,
D3D11_SDK_VERSION,
&sd,
&m_pSwapChain,
&m_pDevice,
&FeatureLevelsSupported,
&m_pDeviceContext )))
{
return hr;
}
ID3D11RenderTargetView* pRTView = NULL;
ID3D11DepthStencilView* pDSView = NULL;
initRenderTargetState(pRTView);
initDepthStencilState(pDSView);
initViewPort();
m_pDeviceContext->OMSetRenderTargets(1, &pRTView, pDSView);
SAFE_RELEASE(pRTView);
SAFE_RELEASE(pDSView);
return S_OK;
}
HRESULT GSDXBase::initViewPort()
{
if (m_pDevice == NULL || m_pSwapChain == NULL || m_pDeviceContext == NULL)
return E_FAIL;
HRESULT hr = S_OK;
ID3D11Texture2D* pBuffer = NULL;
hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBuffer );
if( FAILED( hr ) )
return hr;
D3D11_TEXTURE2D_DESC desc;
pBuffer->GetDesc(&desc);
D3D11_VIEWPORT vp;
vp.Width = desc.Width;
vp.Height = desc.Height;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
m_pDeviceContext->RSSetViewports( 1, &vp );
SAFE_RELEASE(pBuffer);
return S_OK;
}
HRESULT GSDXBase::initRenderTargetState(ID3D11RenderTargetView*& pOutRTView)
{
if (m_pDevice == NULL || m_pSwapChain == NULL || m_pDeviceContext == NULL)
return E_FAIL;
HRESULT hr = S_OK;
ID3D11Texture2D* pBuffer = NULL;
hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBuffer );
if( FAILED( hr ) )
return hr;
ID3D11RenderTargetView* pRTView = NULL;
hr = m_pDevice->CreateRenderTargetView( pBuffer, NULL, &pRTView );
SAFE_RELEASE(pBuffer);
if( FAILED( hr ) )
return hr;
pOutRTView = pRTView;
return S_OK;
}
HRESULT GSDXBase::initDepthStencilState(ID3D11DepthStencilView*& pDSView)
{
if (m_pDevice == NULL || m_pSwapChain == NULL || m_pDeviceContext == NULL)
return E_FAIL;
HRESULT hr = S_OK;
ID3D11Texture2D* pBuffer = NULL;
hr = m_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBuffer );
if( FAILED( hr ) )
return hr;
D3D11_TEXTURE2D_DESC desc;
pBuffer->GetDesc(&desc);
SAFE_RELEASE(pBuffer);
ID3D11Texture2D* pDepthStencil = NULL;
D3D11_TEXTURE2D_DESC descDepth;
descDepth.Width = desc.Width;
descDepth.Height = desc.Height;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D32_FLOAT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = m_pDevice->CreateTexture2D( &descDepth, NULL, &pDepthStencil );
if (FAILED(hr))
return E_FAIL;
D3D11_DEPTH_STENCIL_DESC dsDesc;
// Depth test parameters
dsDesc.DepthEnable = true;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS;
// Stencil test parameters
dsDesc.StencilEnable = true;
dsDesc.StencilReadMask = 0xFF;
dsDesc.StencilWriteMask = 0xFF;
// Stencil operations if pixel is front-facing
dsDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
dsDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Stencil operations if pixel is back-facing
dsDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
dsDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
dsDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
// Create depth stencil state
ID3D11DepthStencilState * pDSState = NULL;
hr = m_pDevice->CreateDepthStencilState(&dsDesc, &pDSState);
if (FAILED(hr))
return E_FAIL;
// Bind depth stencil state
m_pDeviceContext->OMSetDepthStencilState(pDSState, 1);
SAFE_RELEASE(pDSState);
/*D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
descDSV.Format = DXGI_FORMAT_D32_FLOAT;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
*/
// Create the depth stencil view
ID3D11DepthStencilView* pDSV = NULL;
hr = m_pDevice->CreateDepthStencilView( pDepthStencil, // Depth stencil texture
NULL, // Depth stencil desc
&pDSV ); // [out] Depth stencil view
if (FAILED(hr))
return E_FAIL;
SAFE_RELEASE(pDepthStencil);
pDSView = pDSV;
return S_OK;
}
GS3DObj::GS3DObj()
{
D3DXCreateMatrixStack(0, &m_pMatrixStack);
m_pMatrixStack->LoadIdentity();
}
GS3DObj::~GS3DObj()
{
if (m_pMatrixStack != NULL)
{
m_pMatrixStack->Release();
m_pMatrixStack = NULL;
}
}
D3DXMATRIX GS3DObj::GetTransform()
{
return *m_pMatrixStack->GetTop();
}
HRESULT GS3DObj::SetTransform(const D3DXMATRIX* mat)
{
return m_pMatrixStack->LoadMatrix(mat);
}
HRESULT GS3DObj::Translate(D3DXVECTOR3& t)
{
m_pMatrixStack->Translate(t.x, t.y, t.z);
return S_OK;
}
HRESULT GS3DObj::RotateAxis(CONST D3DXVECTOR3 * pV, FLOAT angle)
{
m_pMatrixStack->RotateAxis(pV, angle);
return S_OK;
}
HRESULT GS3DObj::Scale(D3DXVECTOR3& s)
{
m_pMatrixStack->Scale(s.x, s.y, s.z);
return S_OK;
}
HRESULT GS3DObj::ResetTransform()
{
m_pMatrixStack->LoadIdentity();
return S_OK;
}
HRESULT GS3DObj::PushMatrix()
{
m_pMatrixStack->Push();
return S_OK;
}
HRESULT GS3DObj::PopMatrix()
{
m_pMatrixStack->Pop();
return S_OK;
}
HRESULT GS3DObj::SetPosition(D3DXVECTOR3 pos)
{
D3DXMATRIX mat = GetTransform();
mat.m[3][0] = pos.x;
mat.m[3][1] = pos.y;
mat.m[3][2] = pos.z;
m_pMatrixStack->LoadMatrix(&mat);
return S_OK;
}
D3DXVECTOR3 GS3DObj::GetPosition()
{
D3DXMATRIX mat = GetTransform();
D3DXVECTOR3 ret(0,0,0);
ret.x = mat.m[3][0];
ret.y = mat.m[3][1];
ret.z = mat.m[3][2];
return ret;
}
//////////Texture Base////////////
GSTexture2D::GSTexture2D(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, IDXGISwapChain* pSwapChain) : GSDXBase(pDevice, pContext, pSwapChain)
{
m_pTexture = NULL;
m_pRenderTargetView = NULL;
m_pShaderResourceView = NULL;
}
GSTexture2D::~GSTexture2D()
{
SAFE_RELEASE(m_pTexture);
SAFE_RELEASE(m_pRenderTargetView);
SAFE_RELEASE(m_pShaderResourceView);
}
ID3D11Texture2D* GSTexture2D::GetTexture()
{
return m_pTexture;
}
HRESULT GSTexture2D::SetTexture(ID3D11Texture2D* pTexture)
{
SAFE_RELEASE(m_pTexture);
m_pTexture = pTexture;
SAFE_ADDREF(pTexture);
return S_OK;
}
HRESULT GSTexture2D::Create(UINT texW, UINT texH, UINT MipLevels, D3D11_USAGE Usage,
DXGI_FORMAT format, UINT BindFlags, UINT CPUAccessFlags , UINT MiscFlags)
{
if (m_pDevice == NULL)
return E_FAIL;
SAFE_RELEASE(m_pTexture);
HRESULT hr = S_OK;
CD3D11_TEXTURE2D_DESC desc;
desc.Width = texW;
desc.Height = texH;
desc.MipLevels = desc.ArraySize = MipLevels;
desc.Format = format;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Usage = Usage;
desc.BindFlags = BindFlags;
desc.CPUAccessFlags = CPUAccessFlags;
desc.MiscFlags = MiscFlags;
ID3D11Texture2D *pTexture = NULL;
hr = m_pDevice->CreateTexture2D( &desc, NULL, &m_pTexture );
return hr;
}
HRESULT GSTexture2D::CreateRenderTargetView()
{
if (m_pDevice == NULL || m_pTexture == NULL)
{
return E_FAIL;
}
SAFE_RELEASE(m_pRenderTargetView);
HRESULT hr = S_OK;
hr = m_pDevice->CreateRenderTargetView(m_pTexture, NULL, &m_pRenderTargetView );
return hr;
}
HRESULT GSTexture2D::CreateShaderResourceView()
{
if (m_pDevice == NULL || m_pTexture == NULL)
{
return E_FAIL;
}
SAFE_RELEASE(m_pShaderResourceView);
HRESULT hr = S_OK;
hr = m_pDevice->CreateShaderResourceView(m_pTexture, NULL, &m_pShaderResourceView );
return hr;
}
HRESULT GSTexture2D::GetRenderTargetView(ID3D11RenderTargetView*& pRenderTargetView)
{
if (m_pTexture == NULL)
return E_FAIL;
SAFE_RELEASE(pRenderTargetView);
if (m_pRenderTargetView == NULL)
{
if (FAILED(CreateRenderTargetView()))
{
return E_FAIL;
}
}
pRenderTargetView = m_pRenderTargetView;
return S_OK;
}
HRESULT GSTexture2D::GetShaderResourceView(ID3D11ShaderResourceView*& pShaderResourceView)
{
if (m_pTexture == NULL)
return E_FAIL;
SAFE_RELEASE(pShaderResourceView);
if (m_pShaderResourceView == NULL)
{
if (FAILED(CreateShaderResourceView()))
{
return E_FAIL;
}
}
pShaderResourceView = m_pShaderResourceView;
return S_OK;
}
GSRenderBase::GSRenderBase()
{
m_pCBEffectSetting = NULL;
m_pCBParam = NULL;
}
GSRenderBase::~GSRenderBase()
{
for (int i =0; i < m_pBackupRenderTarget.size(); i++)
{
SAFE_RELEASE(m_pBackupRenderTarget.at(i));
}
m_pBackupRenderTarget.clear();
m_pCBEffectSetting = NULL;
m_pCBParam = NULL;
}
HRESULT GSRenderBase::RenderMesh(IGSMeshBase* pMesh, ID3D11DeviceContext* pDeviceContext, IGSEffectBase* pGSEffect, UINT idxTech)
{
if (pMesh == NULL || pGSEffect == NULL || pDeviceContext == NULL || m_pCBEffectSetting == NULL)
{
return E_FAIL;
}
HRESULT hr = S_OK;
float ClearColor[4] = { 0.25f, 0.25f, 0.25f, 0.55f };
ID3D11RenderTargetView* pRTView = NULL;
ID3D11DepthStencilView* pDSView = NULL;
pDeviceContext->OMGetRenderTargets(1, &pRTView, &pDSView);
if (pRTView == NULL || pDSView == NULL)
return E_FAIL;
pDeviceContext->ClearRenderTargetView( pRTView, ClearColor );
pDeviceContext->ClearDepthStencilView( pDSView, D3D11_CLEAR_DEPTH, 1.0, 0 );
SAFE_RELEASE(pRTView);
SAFE_RELEASE(pDSView);
ID3D11Buffer* pVertexBuffer = pMesh->GetVertexBuffer();
ID3D11Buffer* pIndexBuffer = pMesh->GetIndexBuffer();
if (pVertexBuffer == NULL || pIndexBuffer == NULL)
return E_FAIL;
ID3DX11Effect* pEffect = pGSEffect->GetEffect();
if (pEffect == NULL)
{
return E_FAIL;
}
D3DX11_TECHNIQUE_DESC tDesc;
ID3DX11EffectPass* pPass = NULL;
ID3DX11EffectTechnique* pTechnique = pEffect->GetTechniqueByIndex(0);
if (pTechnique == NULL)
return E_FAIL;
pTechnique->GetDesc(&tDesc);
D3D11_BUFFER_DESC indexDesc;
pIndexBuffer->GetDesc(&indexDesc);
UINT indexCount = indexDesc.ByteWidth / sizeof(UINT);
UINT stride = pMesh->GetVertexStride();
UINT offset = 0;
ID3D11InputLayout* pLayout = NULL;
pMesh->GetVertexLayout(pEffect, pLayout);
pDeviceContext->IASetInputLayout(pLayout);
pDeviceContext->IASetPrimitiveTopology(pMesh->GetPrimitiveTopology());
pDeviceContext->IASetVertexBuffers( 0, 1, &pVertexBuffer, &stride, &offset );
pDeviceContext->IASetIndexBuffer(pIndexBuffer, DXGI_FORMAT_R32_UINT, 0);
m_pCBEffectSetting(pEffect, m_pCBParam);
for (int iPass = 0; iPass < tDesc.Passes; iPass++)
{
pPass = pTechnique->GetPassByIndex(iPass);
pPass->Apply(0, pDeviceContext);
pDeviceContext->DrawIndexed( indexCount, 0, 0);
}
//need to set the shader resource to NULL, or we will get a warning
ID3D11ShaderResourceView *const pSRV[1] = {NULL};
pDeviceContext->PSSetShaderResources(0, 1, pSRV);
return S_OK;
}
HRESULT GSRenderBase::SetRenderTarget(ID3D11DeviceContext* pDeviceContext, ID3D11RenderTargetView* pRenderTarget)
{
if (pDeviceContext == NULL || pRenderTarget == NULL)
return E_FAIL;
HRESULT hr = S_OK;
ID3D11RenderTargetView* pBackup = NULL;
ID3D11DepthStencilView* pDepthView = NULL;
pDeviceContext->OMGetRenderTargets(1, &pBackup, &pDepthView);
m_pBackupRenderTarget.push_back(pBackup);
SAFE_ADDREF(pBackup);
pDeviceContext->OMSetRenderTargets(1, &pRenderTarget, pDepthView);
SAFE_RELEASE(pBackup);
SAFE_RELEASE(pDepthView);
return S_OK;
}
HRESULT GSRenderBase::ResetRenderTarget(ID3D11DeviceContext* pDeviceContext)
{
if (pDeviceContext == NULL)
return E_FAIL;
if (m_pBackupRenderTarget.size() <= 0)
return E_FAIL;
ID3D11RenderTargetView* pCurrRT = NULL;
ID3D11DepthStencilView* pCurrDepth = NULL;
pDeviceContext->OMGetRenderTargets(1, &pCurrRT, &pCurrDepth);
ID3D11RenderTargetView* pBackupRenderTarget = m_pBackupRenderTarget[ m_pBackupRenderTarget.size()-1];
m_pBackupRenderTarget.pop_back();
pDeviceContext->OMSetRenderTargets(1, &pBackupRenderTarget, pCurrDepth);
SAFE_RELEASE(pBackupRenderTarget);
SAFE_RELEASE(pCurrRT);
SAFE_RELEASE(pCurrDepth);
return S_OK;
}
HRESULT GSRenderBase::SetCBEffectSetting(CBEffectSetting pfunc, void* self)
{
m_pCBEffectSetting = pfunc;
m_pCBParam = self;
return S_OK;
}
HRESULT GSRenderBase::ClearCBEffectSetting()
{
m_pCBEffectSetting = NULL;
m_pCBParam = NULL;
return S_OK;
} | [
"ndhumuscle@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
533
]
]
]
|
cf92655eb7afae173428e2bd0707288448c6c9bf | 3ef49f2a62aaef8fd370468c68904e95ee5466aa | /Visible.cpp | a6c45614b76a085ed17e61b12c9d709c52f49a97 | []
| no_license | xf0e/pixelcity | 6f42f6204b52882da391467c21d92fa2c6f01e1a | 959796a68a0727d73e327cc8de5471daacecd0b7 | refs/heads/master | 2020-03-08T23:19:34.771087 | 2009-05-23T23:17:44 | 2009-05-23T23:17:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,169 | cpp | /*-----------------------------------------------------------------------------
Visible.cpp
2009 Shamus Young
-------------------------------------------------------------------------------
This module runs the visibility grid, a 2-dimensional array that aids in
culling objects during rendering.
There are many ways this could be refined or sped up, although tests indicate
it's not a huge drain on performance.
-----------------------------------------------------------------------------*/
#ifdef WINDOWS
#include <windows.h>
#endif
#include <math.h>
#include <string.h>
#include "glTypes.h"
#include "Camera.h"
#include "Macro.h"
#include "Math.h"
#include "Visible.h"
#include "World.h"
#include "Win.h"
static bool vis_grid[GRID_SIZE][GRID_SIZE];
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool Visible (GLvector pos)
{
return vis_grid[WORLD_TO_GRID(pos.x)][WORLD_TO_GRID(pos.z)];
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool Visible (int x, int z)
{
return vis_grid[x][z];
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void VisibleUpdate (void)
{
GLvector angle;
GLvector position;
int x, y, grid_x, grid_z;
int left, right, front, back;
float angle_to;
float angle_diff;
float target_x, target_z;
//Clear the visibility table
memset (vis_grid, 0, sizeof (vis_grid));
//Calculate which cell the camera is in
angle = CameraAngle ();
position = CameraPosition ();
grid_x = WORLD_TO_GRID(position.x);
grid_z = WORLD_TO_GRID(position.z);
//Cells directly adjactent to the camera might technically fall out of the fov,
//but still have a few objects poking into screenspace when looking up or down.
//Rather than obsess over sorting those objects properly, it's more efficient to
//just mark them visible.
left = right = front = back = 3;
//Looking north, can't see south.
if (angle.y < 45.0f || angle.y > 315.0f)
front = 0;
//Looking south, can't see north
if (angle.y > 135.0f && angle.y < 225.0f)
back = 0;
//Looking east, can't see west
if (angle.y > 45.0f && angle.y < 135.0f)
left = 0;
//Looking west, can't see east
if (angle.y > 225.0f && angle.y < 315.0f)
right = 0;
//Now mark the block around us the might be visible
for (x = grid_x - left; x <= grid_x + right; x++) {
if (x < 0 || x >= GRID_SIZE) //just in case the camera leaves the world map
continue;
for (y = grid_z - back; y <= grid_z + front; y++) {
if (y < 0 || y >= GRID_SIZE) //just in case the camera leaves the world map
continue;
vis_grid[x][y] = true;
}
}
//Doesn't matter where we are facing, objects in current cell are always visible
vis_grid[grid_x][grid_z] = true;
//Here, we look at the angle from the current camera position to the cell
//on the grid, and how much that angle deviates from the current view angle.
for (x = 0; x < GRID_SIZE; x++) {
for (y = 0; y < GRID_SIZE; y++) {
//if we marked it visible earlier, skip all this math
if (vis_grid[x][y])
continue;
//if the camera is to the left of this cell, use the left edge
if (grid_x < x)
target_x = (float)x * GRID_RESOLUTION;
else
target_x = (float)(x + 1) * GRID_RESOLUTION;
if (grid_z < y)
target_z = (float)y * GRID_RESOLUTION;
else
target_z = (float)(y + 1) * GRID_RESOLUTION;
angle_to = 180 - MathAngle (target_x, target_z, position.x, position.z);
//Store how many degrees the cell is to the
angle_diff = (float)fabs (MathAngleDifference (angle.y, angle_to));
vis_grid[x][y] = angle_diff < 45;
}
}
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
16
],
[
18,
18
],
[
21,
21
],
[
23,
24
],
[
31,
74
],
[
76,
135
]
],
[
[
17,
17
],
[
19,
20
],
[
22,
22
],
[
25,
30
],
[
75,
75
]
]
]
|
3322480810edd7d3a79eb6c6e65100f0170f81b5 | 25426133cf6405c5cebf4b51c48ff3dce2629ea9 | /gmScript/Interpreter.h | e3784ea2e86694d6656e0f509ca87f79a90e440c | []
| no_license | tolhc1234/openglengine | 456fd5a099b30544af1e338fab289402d2b81341 | 6ed525f9a74235605157e68728e36b8b5291b096 | refs/heads/master | 2021-01-10T02:38:58.457222 | 2010-01-12T20:28:21 | 2010-01-12T20:28:21 | 50,214,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | #ifndef INTERPRETER_H
#define INTERPRETER_H
#include "dataTypes.h"
#include "func.h"
#include "functions/debug.h"
//#include "../GUI/simpleGUI.h"
//extern gui* consoleWindow;
//extern textbox* consoleText;
//extern button* consoleButton;
class Interpreter
{
public:
//vector<GMSvar)v....
void init();
int execute(const char* script);
//onder: functies die checken of het een var is,functie of anders.. etc
bool handleVar(const char* script);
bool findVarName(char* name);
//bool handeFunc
//bool oop??
}extern interpreter;
void executeConsoleScript();
#endif | [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
80bb75965c34b71627ec080c3447fd83ab9144c9 | c2153dcfa8bcf5b6d7f187e5a337b904ad9f91ac | /src/Engine/Resource/IResource.h | b3549d977b9237f188628616cc6028515bf13d1a | []
| no_license | ptrefall/smn6200fluidmechanics | 841541a26023f72aa53d214fe4787ed7f5db88e1 | 77e5f919982116a6cdee59f58ca929313dfbb3f7 | refs/heads/master | 2020-08-09T17:03:59.726027 | 2011-01-13T22:39:03 | 2011-01-13T22:39:03 | 32,448,422 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | h | #pragma once
namespace Engine
{
class CoreMgr;
class IResource
{
public:
IResource(CoreMgr *coreMgr, const CL_String &fileName) {}
virtual ~IResource() {}
virtual CL_String getResType() const = 0;
virtual int getInt(const CL_String &id) { return -1; }
virtual bool getBool(const CL_String &id) { return false; }
virtual CL_String getString(const CL_String &id) { return CL_String(); }
virtual CL_DataBuffer *getBuffer() const { return 0; }
};
}
| [
"[email protected]@c628178a-a759-096a-d0f3-7c7507b30227"
]
| [
[
[
1,
22
]
]
]
|
0f88bb2f186c3983738e8f6480d2bbc4f3caa1be | 1c80a726376d6134744d82eec3129456b0ab0cbf | /Project/C++/POJ/2765/2765.cpp | ed90315f2e93b556ad5140c5d172327954e00b38 | []
| no_license | dabaopku/project_pku | 338a8971586b6c4cdc52bf82cdd301d398ad909f | b97f3f15cdc3f85a9407e6bf35587116b5129334 | refs/heads/master | 2021-01-19T11:35:53.500533 | 2010-09-01T03:42:40 | 2010-09-01T03:42:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | cpp | #include "iostream"
#include "stdio.h"
using namespace std;
void swap(int &x,int &y)
{
int temp=x;
x=y;
y=temp;
}
int main()
{
int x,y;
cin>>x>>y;
if(x>y)
swap(x,y);
while(x!=y){
y=y/2;
if(x>y) swap(x,y);
}
cout<<x<<endl;
} | [
"[email protected]@592586dc-1302-11df-8689-7786f20063ad"
]
| [
[
[
1,
21
]
]
]
|
54c14c844f6be3bfddb930766ee782f0a9f90fb2 | 2a3952c00a7835e6cb61b9cb371ce4fb6e78dc83 | /BasicOgreFramework/PhysxSDK/Samples/SampleD6Joint/src/SampleD6Joint.cpp | e4bcbdbd2a6cc3f1e30617e752f409d39430e255 | []
| no_license | mgq812/simengines-g2-code | 5908d397ef2186e1988b1d14fa8b73f4674f96ea | 699cb29145742c1768857945dc59ef283810d511 | refs/heads/master | 2016-09-01T22:57:54.845817 | 2010-01-11T19:26:51 | 2010-01-11T19:26:51 | 32,267,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,593 | cpp | // ===============================================================================
//
// AGEIA PhysX SDK Sample Program
//
// Title: Six Degree of Freedom Joints
// Description: This sample program shows how to use the D6 joints. For example it
// is possible to use this joint to switch from one type of joint to
// another without recreating the joint.
//
// Originally written by: Bob Schade (10-15-04)
//
// ===============================================================================
#include "SampleD6Joint.h"
#include "GLFontRenderer.h"
#include "Timing.h"
#include "Utilities.h"
#include "SamplesVRDSettings.h"
// Physics SDK globals
NxPhysicsSDK* gPhysicsSDK = NULL;
NxScene* gScene = NULL;
//NxVec3 gDefaultGravity(0,-9.8,0);
NxVec3 gDefaultGravity(0,0,0);
DebugRenderer gDebugRenderer;
// Time globals
NxReal gTime;
NxReal gLastTime;
// Display globals
int gMainHandle;
int mx = 0;
int my = 0;
// Camera globals
NxVec3 gCameraPos(0,5,-8);
NxVec3 gCameraForward(0,0,1);
NxVec3 gCameraRight(-1,0,0);
const NxReal gCameraSpeed = 0.02;
// HUD globals
char gDisplayString[512] = "";
NxD6JointMotion gJointMotion[6] =
{
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LOCKED
};
char* gJointMotionString[3] = {"Locked","Limited","Free"};
// Force globals
NxVec3 gForceVec(0,0,0);
NxReal gForceStrength = 1000;
bool bForceMode = true;
// Limit globals
NxReal gLinearLimit = 1.0f;
NxReal gSwing1Limit = NxPiF32 / 180.0f * 30.0f;
NxReal gSwing2Limit = NxPiF32 / 180.0f * 70.0f;
NxReal gTwistLowLimit = NxPiF32 / 180.0f * -90.0f;
NxReal gTwistHighLimit = NxPiF32 / 180.0f * 45.0f;
// Keyboard globals
#define MAX_KEYS 256
bool gKeys[MAX_KEYS];
// Simulation globals
bool bPause = false;
bool bShadows = true;
bool bDebugWireframeMode = false;
// Actor globals
NxActor* groundPlane = NULL;
NxActor* capsule1 = NULL;
NxActor* capsule2 = NULL;
// Joint globals
NxD6Joint* d6Joint = NULL;
NxD6Joint* d6JointUpper = NULL;
// Focus actor
NxActor* gSelectedActor = NULL;
// Upper Joint mode
int bUpperJointLocked = true;
void toggle(NxD6JointMotion &motion)
{
switch(motion) {
case NX_D6JOINT_MOTION_LOCKED : motion = NX_D6JOINT_MOTION_LIMITED; break;
case NX_D6JOINT_MOTION_LIMITED : motion = NX_D6JOINT_MOTION_FREE; break;
case NX_D6JOINT_MOTION_FREE : motion = NX_D6JOINT_MOTION_LOCKED; break;
}
}
void PrintControls()
{
printf("\n Flight Controls:\n ----------------\n w = forward, s = back\n a = strafe left, d = strafe right\n q = up, z = down\n");
printf("\n Force Controls:\n ---------------\n i = +z, k = -z\n j = +x, l = -x\n u = +y, m = -y\n");
printf("\n Miscellaneous:\n --------------\n 1-6 = toggle DOF\n p = Pause\n r = Select Next Actor\n f = Toggle Force Mode\n t = Toggle Upper Joint Mode\n b = Toggle Debug Wireframe Mode\n x = Toggle Shadows\n Q = Reset Scene\n");
}
void DisplayText()
{
float y = 0.95f;
int len = strlen(gDisplayString);
len = (len < 256)?len:255;
int start = 0;
char textBuffer[256];
for(int i=0;i<len;i++)
{
if(gDisplayString[i] == '\n' || i == len-1)
{
int offset = i;
if(i == len-1) offset= i+1;
memcpy(textBuffer, gDisplayString+start, offset-start);
textBuffer[offset-start]=0;
GLFontRenderer::print(0.01, y, 0.03f, textBuffer);
y -= 0.035f;
start = offset+1;
}
}
}
void RefreshDisplayString()
{
sprintf(gDisplayString, "CONFIGURABLE JOINT subject to %s:\nROTATION 1, 2, 3\n Axis: %s Normal: %s Binormal: %s\nTRANSLATION 4, 5, 6\n Axis: %s Normal: %s Binormal: %s",
bForceMode ? "force" : "torque",
gJointMotionString[gJointMotion[3]],
gJointMotionString[gJointMotion[4]],
gJointMotionString[gJointMotion[5]],
gJointMotionString[gJointMotion[0]],
gJointMotionString[gJointMotion[1]],
gJointMotionString[gJointMotion[2]]);
}
// Configurable joint - roll joint
void ReconfigureD6Joint()
{
NxActor* a0 = capsule1;
NxActor* a1 = capsule2;
NxD6JointDesc d6Desc;
d6Joint->saveToDesc(d6Desc);
// reset actor 1
/*
NxMat33 orient;
orient.id();
a1->raiseBodyFlag(NX_BF_KINEMATIC);
a1->setGlobalOrientation(orient);
a1->setGlobalPosition(NxVec3(0,3,0));
a1->clearBodyFlag(NX_BF_KINEMATIC);
*/
// set the DOF
d6Desc.xMotion = gJointMotion[0];
d6Desc.yMotion = gJointMotion[1];
d6Desc.zMotion = gJointMotion[2];
d6Desc.twistMotion = gJointMotion[3];
d6Desc.swing1Motion = gJointMotion[4];
d6Desc.swing2Motion = gJointMotion[5];
d6Joint->loadFromDesc(d6Desc);
// reconfig upper joint
d6JointUpper->saveToDesc(d6Desc);
if (bUpperJointLocked) {
d6Desc.twistMotion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED;
}
else {
d6Desc.twistMotion = NX_D6JOINT_MOTION_FREE;
d6Desc.swing1Motion = NX_D6JOINT_MOTION_FREE;
d6Desc.swing2Motion = NX_D6JOINT_MOTION_FREE;
}
d6JointUpper->loadFromDesc(d6Desc);
}
NxVec3 ApplyForceToActor(NxActor* actor, const NxVec3& forceDir, const NxReal forceStrength, bool forceMode)
{
NxVec3 forceVec = forceStrength*forceDir;
if (forceMode)
actor->addForce(forceVec);
else
actor->addTorque(forceVec);
return forceVec;
}
void SelectNextActor()
{
NxU32 nbActors = gScene->getNbActors();
NxActor** actors = gScene->getActors();
for(NxU32 i = 0; i < nbActors; i++)
{
if (actors[i] == gSelectedActor)
{
gSelectedActor = actors[(i+1)%nbActors];
if (gSelectedActor == groundPlane) // skip the ground plane
{
gSelectedActor = actors[(i+2)%nbActors];
}
break;
}
}
}
void ProcessKeys()
{
// Process keys
for (int i = 0; i < MAX_KEYS; i++)
{
if (!gKeys[i]) { continue; }
switch (i)
{
// Camera controls
case 'w':{ gCameraPos += gCameraForward*gCameraSpeed; break; }
case 's':{ gCameraPos -= gCameraForward*gCameraSpeed; break; }
case 'a':{ gCameraPos -= gCameraRight*gCameraSpeed; break; }
case 'd':{ gCameraPos += gCameraRight*gCameraSpeed; break; }
case 'z':{ gCameraPos -= NxVec3(0,1,0)*gCameraSpeed; break; }
case 'q':{ gCameraPos += NxVec3(0,1,0)*gCameraSpeed; break; }
// Force controls
case 'i': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(0,0,1),gForceStrength,bForceMode); break; }
case 'k': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(0,0,-1),gForceStrength,bForceMode); break; }
case 'j': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(+1,0,0),gForceStrength,bForceMode); break; }
case 'l': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(-1,0,0),gForceStrength,bForceMode); break; }
case 'u': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(0,+1,0),gForceStrength,bForceMode); break; }
case 'm': {gForceVec = ApplyForceToActor(gSelectedActor,NxVec3(0,-1,0),gForceStrength,bForceMode); break; }
}
}
}
void SetupCamera()
{
// Setup camera
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0f, (float)glutGet(GLUT_WINDOW_WIDTH)/(float)glutGet(GLUT_WINDOW_HEIGHT), 1.0f, 10000.0f);
gluLookAt(gCameraPos.x,gCameraPos.y,gCameraPos.z,gCameraPos.x + gCameraForward.x, gCameraPos.y + gCameraForward.y, gCameraPos.z + gCameraForward.z, 0.0f, 1.0f, 0.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void RenderActors(bool shadows)
{
// Render all the actors in the scene
int nbActors = gScene->getNbActors();
NxActor** actors = gScene->getActors();
while (nbActors--)
{
NxActor* actor = *actors++;
DrawActor(actor, gSelectedActor);
// Handle shadows
if (shadows)
{
DrawActorShadow(actor);
}
}
}
void DrawForce(NxActor* actor, NxVec3& forceVec, const NxVec3& color)
{
// draw only if the force is large enough
NxReal force = forceVec.magnitude();
if (force < 0.1f) return;
forceVec = 3*forceVec/force;
NxVec3 pos = actor->getCMassGlobalPosition();
DrawArrow(pos, pos + forceVec, color);
}
void RenderCallback()
{
if (gScene && !bPause)
RunPhysics();
// Clear buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
ProcessKeys();
SetupCamera();
RenderActors(bShadows);
if (bForceMode)
DrawForce(gSelectedActor, gForceVec, NxVec3(1,1,0));
else
DrawForce(gSelectedActor, gForceVec, NxVec3(0,1,1));
gForceVec = NxVec3(0,0,0);
// Show debug wireframes
if (bDebugWireframeMode)
{
glDisable(GL_LIGHTING);
gDebugRenderer.renderData(*gScene->getDebugRenderable());
glEnable(GL_LIGHTING);
}
DisplayText();
glutSwapBuffers();
}
void ReshapeCallback(int width, int height)
{
glViewport(0, 0, width, height);
}
void IdleCallback()
{
glutPostRedisplay();
}
void KeyboardCallback(unsigned char key, int x, int y)
{
gKeys[key] = true;
switch (key)
{
case 'r': { SelectNextActor(); break; }
case 27 : { exit(0); break; }
case 'p': { bPause = !bPause; UpdateTime(); break; }
case 'x': { bShadows = !bShadows; break; }
case 'b': { bDebugWireframeMode = !bDebugWireframeMode; break; }
case 'f': { bForceMode = !bForceMode; RefreshDisplayString(); break; }
case 't': { bUpperJointLocked = !bUpperJointLocked; ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '1': { toggle(gJointMotion[3]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '2': { toggle(gJointMotion[4]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '3': { toggle(gJointMotion[5]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '4': { toggle(gJointMotion[0]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '5': { toggle(gJointMotion[1]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case '6': { toggle(gJointMotion[2]); ReconfigureD6Joint(); RefreshDisplayString(); break; }
case 'Q': { ResetNx(); break; }
default: { break; }
}
}
void KeyboardUpCallback(unsigned char key, int x, int y)
{
gKeys[key] = false;
}
//void SpecialCallback(int key, int x, int y)
//{
// gKeys[key] = true;
//
// switch (key)
// {
// // Reset PhysX
// case GLUT_KEY_F10: ResetNx(); return;
// }
//}
void MouseCallback(int button, int state, int x, int y)
{
mx = x;
my = y;
}
void MotionCallback(int x, int y)
{
int dx = mx - x;
int dy = my - y;
gCameraForward.normalize();
gCameraRight.cross(gCameraForward,NxVec3(0,1,0));
NxQuat qx(NxPiF32 * dx * 20 / 180.0f, NxVec3(0,1,0));
qx.rotate(gCameraForward);
NxQuat qy(NxPiF32 * dy * 20 / 180.0f, gCameraRight);
qy.rotate(gCameraForward);
mx = x;
my = y;
}
void ExitCallback()
{
if (gPhysicsSDK)
{
if (gScene) gPhysicsSDK->releaseScene(*gScene);
gPhysicsSDK->release();
}
}
void InitGlut(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitWindowSize(512, 512);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
gMainHandle = glutCreateWindow("SampleD6Joint");
glutSetWindow(gMainHandle);
glutDisplayFunc(RenderCallback);
glutReshapeFunc(ReshapeCallback);
glutIdleFunc(IdleCallback);
glutKeyboardFunc(KeyboardCallback);
glutKeyboardUpFunc(KeyboardUpCallback);
glutMouseFunc(MouseCallback);
glutMotionFunc(MotionCallback);
MotionCallback(0,0);
atexit(ExitCallback);
// Setup default render states
glClearColor(0.52f, 0.60f, 0.71f, 1.0f);
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_CULL_FACE);
// Setup lighting
glEnable(GL_LIGHTING);
float AmbientColor[] = { 0.0f, 0.1f, 0.2f, 0.0f }; glLightfv(GL_LIGHT0, GL_AMBIENT, AmbientColor);
float DiffuseColor[] = { 0.2f, 0.2f, 0.2f, 0.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, DiffuseColor);
float SpecularColor[] = { 0.5f, 0.5f, 0.5f, 0.0f }; glLightfv(GL_LIGHT0, GL_SPECULAR, SpecularColor);
float Position[] = { 100.0f, 100.0f, -400.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_POSITION, Position);
glEnable(GL_LIGHT0);
}
/*
enum NxD6JointLockFlags
{
NX_D6JOINT_LOCK_X = 1<<0,
NX_D6JOINT_LOCK_Y = 1<<1,
NX_D6JOINT_LOCK_Z = 1<<2,
NX_D6JOINT_LOCK_LINEAR = 7,
NX_D6JOINT_LOCK_TWIST = 1<<3,
NX_D6JOINT_LOCK_SWING1 = 1<<4,
NX_D6JOINT_LOCK_SWING2 = 1<<5,
NX_D6JOINT_LOCK_ANGULAR = 7<<3,
};
enum NxD6JointLimitFlags
{
NX_D6JOINT_LIMIT_TWIST = 1<<0,
NX_D6JOINT_LIMIT_SWING = 1<<1,
NX_D6JOINT_LIMIT_LINEAR = 1<<2
};
enum NxD6JointDriveType
{
NX_D6JOINT_DRIVE_POSITION = 1<<0,
NX_D6JOINT_DRIVE_VELOCITY = 1<<1,
NX_D6JOINT_DRIVE_SLERP = 1<<2
};
///////////////////////////////////////////////////////////
enum NxD6JointMotion
{
NX_D6JOINT_MOTION_LOCKED,
NX_D6JOINT_MOTION_LIMITED,
NX_D6JOINT_MOTION_FREE
};
*/
NxD6Joint* CreateD6Joint(NxActor* a0, NxActor* a1, const NxVec3& globalAnchor, const NxVec3& globalAxis)
{
NxD6JointDesc d6Desc;
d6Desc.actor[0] = a0;
d6Desc.actor[1] = a1;
d6Desc.setGlobalAnchor(globalAnchor);
d6Desc.setGlobalAxis(globalAxis);
d6Desc.twistMotion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.swing1Motion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.swing2Motion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.xMotion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.yMotion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.zMotion = NX_D6JOINT_MOTION_LOCKED;
d6Desc.linearLimit.value = gLinearLimit;
d6Desc.swing1Limit.value = gSwing1Limit;
d6Desc.swing2Limit.value = gSwing2Limit;
d6Desc.twistLimit.low.value = gTwistLowLimit;
d6Desc.twistLimit.high.value = gTwistHighLimit;
// drive test
/*
d6Desc.drivePosition.x = 0.5f;
d6Desc.xDrive.spring = 1000.0f;
d6Desc.xDrive.damping = 1.0f;
d6Desc.xDrive.driveType.raiseFlagMask(NX_D6JOINT_DRIVE_POSITION);
d6Desc.driveLinearVelocity.z = 0.5f;
d6Desc.zDrive.forceLimit = 1000.0f;
d6Desc.zDrive.driveType.raiseFlagMask(NX_D6JOINT_DRIVE_VELOCITY);
d6Desc.swingDrive.driveType.raiseFlagMask(NX_D6JOINT_DRIVE_POSITION);
d6Desc.swingDrive.spring = 100.0f;
d6Desc.swingDrive.damping = 1.0f;
d6Desc.driveOrientation.fromAngleAxis(-40.0f, NxVec3(0,1,1));
d6Desc.swingDrive.driveType.raiseFlagMask(NX_D6JOINT_DRIVE_VELOCITY);
d6Desc.swingDrive.forceLimit = 1000.0f;
d6Desc.driveAngularVelocity.y = 10.0f;
*/
// d6Desc.projectionMode = NX_JPM_NONE;
d6Desc.projectionMode = NX_JPM_POINT_MINDIST;
// d6Desc.jointFlags |= NX_JF_COLLISION_ENABLED;
NxJoint* d6Joint = gScene->createJoint(d6Desc);
return (NxD6Joint*)d6Joint->is(NX_JOINT_D6);
}
bool InitNx()
{
// Initialize PhysicsSDK
NxPhysicsSDKDesc desc;
NxSDKCreateError errorCode = NXCE_NO_ERROR;
gPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, NULL, NULL, desc, &errorCode);
if(gPhysicsSDK == NULL)
{
printf("\nSDK create error (%d - %s).\nUnable to initialize the PhysX SDK, exiting the sample.\n\n", errorCode, getNxSDKCreateError(errorCode));
return false;
}
#if SAMPLES_USE_VRD
// The settings for the VRD host and port are found in SampleCommonCode/SamplesVRDSettings.h
if (gPhysicsSDK->getFoundationSDK().getRemoteDebugger() && !gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->isConnected())
gPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect(SAMPLES_VRD_HOST, SAMPLES_VRD_PORT, SAMPLES_VRD_EVENTMASK);
#endif
// Set the physics parameters
gPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.005f);
// Set the debug visualization parameters
gPhysicsSDK->setParameter(NX_VISUALIZATION_SCALE, 1);
gPhysicsSDK->setParameter(NX_VISUALIZE_COLLISION_SHAPES, 1);
gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1);
gPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1);
// Create the scene
NxSceneDesc sceneDesc;
sceneDesc.gravity = gDefaultGravity;
gScene = gPhysicsSDK->createScene(sceneDesc);
if(gScene == NULL)
{
printf("\nError: Unable to create a PhysX scene, exiting the sample.\n\n");
return false;
}
NxMaterial * defaultMaterial = gScene->getMaterialFromIndex(0);
defaultMaterial->setRestitution(0.0f);
defaultMaterial->setStaticFriction(0.5f);
defaultMaterial->setDynamicFriction(0.5f);
// Create the objects in the scene
groundPlane = CreateGroundPlane();
capsule1 = CreateCapsule(NxVec3(0,5,0), 1, 0.5, 10);
// capsule1->raiseBodyFlag(NX_BF_KINEMATIC);
capsule2 = CreateCapsule(NxVec3(0,3,0), 1, 0.5, 10);
capsule2->setLinearDamping(0.5);
NxVec3 globalAnchor = NxVec3(0,5,0);
NxVec3 globalAnchorUpper = NxVec3(0,7,0);
NxVec3 globalAxis = NxVec3(0,-1,0);
// upper joint
d6JointUpper = CreateD6Joint(NULL, capsule1, globalAnchorUpper, globalAxis);
// lower test joint
d6Joint = CreateD6Joint(capsule1, capsule2, globalAnchor, globalAxis);
gSelectedActor = capsule2;
UpdateTime();
RefreshDisplayString();
#if defined(_XBOX) || defined(__CELLOS_LV2__)
glutRemapButtonExt(8, 'f', true); //shift+Left shoulder to toggle force mode
glutRemapButtonExt(9, 'Q', true); //shift+Right shoulder to reset
glutRemapButtonExt(4, 'w', true); //Shift+Up to forward
glutRemapButtonExt(5, 's', true); //Shift+Down to back
glutRemapButtonExt(6, 'a', true); //Shift+Left to left
glutRemapButtonExt(7, 'd', true); //Shift+Right to right
glutRemapButtonExt(4, 'k', false); //Up to force forward
glutRemapButtonExt(5, 'i', false); //Down to force backward
glutRemapButtonExt(6, 'l', false); //Left to force left
glutRemapButtonExt(7, 'j', false); //Right to force right
glutRemapButtonExt(8, 'u', false); //Left shoulder to force up
glutRemapButtonExt(9, 'm', false); //Right shoulder to force down
glutRemapButtonExt(0, 'r', false); //A/X to select next actor
glutRemapButtonExt(0, 't', true); //Shift+A/X to toggle joint lock
glutRemapButtonExt(1, '1', false); //B/O to toggle joint motion 1
glutRemapButtonExt(1, '2', true); //Shift+B/O to toggle joint motion 2
glutRemapButtonExt(2, '3', false); //X/S to toggle joint motion 3
glutRemapButtonExt(2, '4', true); //Shift+X/S to toggle joint motion 4
glutRemapButtonExt(3, '5', false); //Y/T to toggle joint motion 5
glutRemapButtonExt(3, '6', true); //Shift+Y/T to toggle joint motion 6
#endif
return true;
}
void ReleaseNx()
{
if(gPhysicsSDK != NULL)
{
if(gScene != NULL) gPhysicsSDK->releaseScene(*gScene);
gScene = NULL;
NxReleasePhysicsSDK(gPhysicsSDK);
gPhysicsSDK = NULL;
}
}
void ResetNx()
{
ReleaseNx();
if (!InitNx()) exit(0);
}
NxReal UpdateTime()
{
NxReal deltaTime;
gTime = timeGetTime()*0.001f; // Get current time in seconds
deltaTime = gTime - gLastTime;
gLastTime = gTime;
return deltaTime;
}
void RunPhysics()
{
// Update the time step
NxReal deltaTime = UpdateTime();
// Run collision and dynamics for delta time since the last frame
gScene->simulate(deltaTime);
gScene->flushStream();
gScene->fetchResults(NX_RIGID_BODY_FINISHED, true);
}
int main(int argc, char** argv)
{
PrintControls();
InitGlut(argc, argv);
// Initialize physics scene and start the application main loop if scene was created
if (InitNx())
glutMainLoop();
ReleaseNx();
return 0;
}
| [
"erucarno@789472dc-e1c3-11de-81d3-db62269da9c1"
]
| [
[
[
1,
669
]
]
]
|
3ebce85a83eddcb892fc4ca88707d727e59d0bd3 | a01b67b20207e2d31404262146763d3839ee833d | /trunk/Projet/trunk/Data/monofinfile.cpp | 553bd88e5e6172461442ab6227fa9cb60b6ad9ce | []
| no_license | BackupTheBerlios/qtfin-svn | 49b59747b6753c72a035bf1e2e95601f91f5992c | ee18d9eb4f80a57a9121ba32dade96971196a3a2 | refs/heads/master | 2016-09-05T09:42:14.189410 | 2010-09-21T17:34:43 | 2010-09-21T17:34:43 | 40,801,620 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,033 | cpp | #include "profil.h"
#include "surface.h"
#include "layer.h"
#include "monofinfile.h"
#include <iostream>
namespace Data{
MonofinFile::MonofinFile(ConfigFile * link) {
_monofinProfil = new Profil(link);
_monofinSurface = new Surface();
}
MonofinFile::~MonofinFile(){
delete _monofinProfil;
delete _monofinSurface;
}
/***********
* Setters *
***********/
/**********
* Layers *
**********/
/**
* insert a layer at the given rank (displace if necessary other layers), if the rank is outside the current number of layer it will be placed at the last rank
*@param rank an integer, where we want to insert the new Layer, a negative rank will insert the layer at the begining, a bigger rank than that exist actually will place the layer at the end
*@param length a float, the (between 0 and 1) between the length of the layer and the length of the fin
*@param height a float, the (between 0 and 1) between the height if the layer and the height of the fin
*/
void MonofinFile::addLayer(int rank, float length, float height){
_monofinProfil->addLayer(rank,new Layer(length,height));
}
/**
* a setter on the length of the layer at the given rank
*@param rank an integer, the rank of the layer to modify, if it's an incorrect rank, nothing will be done
*@param length a float, the new length
*/
void MonofinFile::setLayerLength(int rank, float length){
_monofinProfil->setLayerLength(rank, length);
}
/**
* a setter on the heigth of the layer at the given rank
*@param height a float, the new heigtht
*/
void MonofinFile::setLayerHeight(int rank, float height){
_monofinProfil->setLayerHeight(rank, height);
}
/**
* destroy the layer at the given rank, if no there are no layer at this rank, nothing will be done
*@param rank an integer, the rank of the layer we want to remove
*/
void MonofinFile::removeLayer(int rank){
_monofinProfil->remLayer(rank);
}
/***********
* Surface *
***********/
/**
* add a segment to the segment table
*@param intersectionPointKey1 an integer, the key of the point representing the first edge of the segment, must be a valid key, otherwise the segment will not be created
*@param intersectionPointKey2 an integer, the key of the point representing the second edge of the segment, must be a valid key, otherwise the segment will not be created
*@param controlPointKey an integer, the, must be a valid key or MONOFIN_SURFACE_NO_CONTROL_POINT, otherwise the segment will not be created
*@return an integer, the key of the created segment or MONOFIN_SURFACE_NOT_CREATED_SEGMENT if an error occured.
*/
int MonofinFile::addSegment(int intersectionPointKey1, int intersectionPointKey2, int controlPointKey){
return _monofinSurface->addSegment(intersectionPointKey1,intersectionPointKey2,controlPointKey);
}
/**
* add a point to the control point table
*@param x a float, x-axis coordinate
*@param y a float, y-axis coordinate
*@return an integer, the key of the created control point, or MONOFIN_SURFACE_NOT_CREATED_POINT
*/
int MonofinFile::addControlPoint(float x, float y){
return _monofinSurface->addControlPoint(x,y);
}
/**
* add a point to the intersection point table
*@param x a float, x-axis coordinate
*@param y a float, y-axis coordinate
*@return an integer, the key of the created intersection point, or MONOFIN_SURFACE_NOT_CREATED_POINT
*/
int MonofinFile::addIntersectionPoint(float x, float y){
return _monofinSurface->addIntersectionPoint(x,y);
}
/**
* subdivide a segment by the right
*@param segmentKey an integer, the segment to subdivide, must be a valid segment key otherwise, the function will have no effect
*@param intersectionPointKey, the intersection point that will subdivide the original segment into two segments, must be a valid key otherwise the function will have no effect
*@return an integer, the key of the created segment or MONOFIN_SURFACE_NOT_CREATED_SEGMENT if a key is not valid or an error occured
*/
int MonofinFile::subdivideSegment(int segmentKey, int intersectionPointKey){
return _monofinSurface->subdivideSegment(segmentKey,intersectionPointKey);
}
/**
* remove the control point which key is given
*@param controlPointKey an integer, the key of the control point to remove, must be a valid key otherwise nothing will be done
*/
void MonofinFile::removeControlPoint(int controlPointKey){
_monofinSurface->removeControlPoint(controlPointKey);
}
/**
* remove the intersection point which key is given and merge the two segments using this point
*@param intersectionPointKey an integer, the key of the intersection point to remove, must be a valid key otherwise nothing will be done
*@return an integer, the key of the erased segement, or MONOFIN_SURFACE_NO_SEGMENT_ERASED if the key weren't valid or an error occured
*/
int MonofinFile::removeIntersectionPoint(int intersectionPointKey){
return _monofinSurface->removeIntersectionPoint(intersectionPointKey);
}
/**
* set new coordinates for the intersection point which key is given
*@param intersectionPointKey an integer, the key of the intersection point to modify
*@param x a float, the new x-axis coordinate of the point
*@param y a float, the new y-axis coordinate of the point
*/
void MonofinFile::setIntersectionPoint(int intersectionPointKey, float x, float y){
_monofinSurface->setIntersectionPoint(intersectionPointKey,x,y);
}
/**
* set new coordinates for the control point which key is given
*@param intersectionPointKey an integer, the key of the control point to modify
*@param x a float, the new x-axis coordinate of the point
*@param y a float, the new y-axis coordinate of the point
*/
void MonofinFile::setControlPoint(int controlPointKey, float x, float y){
_monofinSurface->setControlPoint(controlPointKey,x,y);
}
/**
* set an existing control point to an existing segment, if keys are incorrect nothing will be done
*@param segmentKey an integer, the key of the segment we want to add a control point
*@param controlPointKey an integer, the key of the control point to add
*/
void MonofinFile::addControlPointToSegment(int segmentKey, int controlPointKey){
_monofinSurface->addControlPointToSegment(segmentKey,controlPointKey);
}
/**
* clear all the surface's structure(delete everything), undo/redo works on it
*/
void MonofinFile::clearSurface(){
_monofinSurface->clearSurface();
}
/***********
* Getters *
***********/
/**********
* Layers *
**********/
/**
* a getter on the length of the ranked layer
*@param rank an integer, the rank of the layer we want the length
*@return a float, the length of the layer, MONOFIN_PROFIL_BAD_RANK if rank don't exist
*/
float MonofinFile::getLayerLength(int rank){
return _monofinProfil->getLayerLength(rank);
}
/**
* a getter on the height of the ranked layer
*@param rank an integer, the rank of the layer we want the height
*@return a float, the height of the layer, MONOFIN_PROFIL_BAD_RANK if rank don't exist
*/
float MonofinFile::getLayerHeight(int rank){
return _monofinProfil->getLayerHeight(rank);
}
/**
* a getter on the number of layer we have
*@return an integer, the number of layer created
*/
int MonofinFile::getHowManyLayers(){
return _monofinProfil->getHowManyLayers();
}
/***********
* Surface *
***********/
/**
* get the coordinates of the intersection point which key is given
*@param intersectionPointKey an integer, the key of the point we want the coordinates
*@param x a float, return the x-axis coordinate
*@param y a float, return the y-axis coordinate
*/
void MonofinFile::getIntersectionPoint(int intersectionPointKey, float &x, float &y){
_monofinSurface->getIntersectionPoint(intersectionPointKey,x,y);
}
/**
* get the coordinates of the control point which key is given
*@param controlPointKey an integer, the key of the point we want the coordinates
*@param x a float, return the x-axis coordinate
*@param y a float, return the y-axis coordinate
*/
void MonofinFile::getControlPoint(int controlPointKey, float &x, float &y){
_monofinSurface->getControlPoint(controlPointKey,x,y);
}
/**
* get all the informations over a segment
*@param segmentKey an integer, the key of the segment we want informations over
*@param intersectionPointKey1 an integer, return the key of the first intersection point of the segment
*@param intersectionPointKey2 an integer, return the key of the second intersection point of the segment
*@param controlPointKey an integer, return the key of the control point (bezier curve), may return MONOFIN_SURFACE_NO_SEGMENT_ERASED if the point don't exist
*/
void MonofinFile::getSegment(int segmentKey, int &intersectionPointKey1, int &intersectionPointKey2, int &controlPointKey){
_monofinSurface->getSegment(segmentKey,intersectionPointKey1,intersectionPointKey2,controlPointKey);
}
/**
* a function called at the initialisation of the structure to linkthe profil and the configfile (which also manage layers)
*@param toLink a pointer to ConfigFile, the address of the current ConfigFile
*/
/*void MonofinFile::linkProfilWithConfigFile(ConfigFile * toLink){
_monofinProfil->link(toLink);
}*/
void MonofinFile::startHistory(Modification t){
_monofinSurface->startHistory(t);
_monofinProfil->startHistory(t);
}
QList<HistoryHolder<Modification> *> MonofinFile::retrieveHistory(Modification t){
return _monofinSurface->retrieveHistory(t)+_monofinProfil->retrieveHistory(t);;
}
void MonofinFile::undo(QList<HistoryHolder<Modification> *> history){
_monofinSurface->undo(history);
_monofinProfil->undo(history);
}
QList<int> MonofinFile::getAllSegmentKeys(){
return _monofinSurface->getAllSegmentKeys();
}
QList<int> MonofinFile::getAllIntersectionPointKeys(){
return _monofinSurface->getAllIntersectionPointKeys();
}
QList<int> MonofinFile::getAllControlPointKeys(){
return _monofinSurface->getAllControlPointKeys();
}
/**
* return all IntersectionPoint only linked to one segment
*@return QList<int>, key's list
*/
QList<int> MonofinFile::getExtremityPoint(){
return _monofinSurface->getExtremityPoint();
}
QList<int> MonofinFile::getSegmentKeysLinkedToPoint(int pointKey){
return _monofinSurface->getSegmentKeysLinkedToPoint(pointKey);
}
void MonofinFile::accept(SaveVisitor *sv){
_monofinProfil->accept(sv);
_monofinSurface->accept(sv);
}
void MonofinFile::accept(LoadVisitor *lv){
_monofinProfil->accept(lv);
_monofinSurface->accept(lv);
}
float MonofinFile::getLayerMaxLength(){
return _monofinProfil->getMaxLength();
}
float MonofinFile::getLayerMaxHeight(){
return _monofinProfil->getMaxHeight();
}
void MonofinFile::clearProfil(){
_monofinProfil->clearProfil();
}
}// namespace Data
| [
"sorontyls@314bda93-af5c-0410-b653-d297496769b1",
"kryptos@314bda93-af5c-0410-b653-d297496769b1"
]
| [
[
[
1,
3
],
[
5,
298
]
],
[
[
4,
4
],
[
299,
299
]
]
]
|
0f622a288ec9d5ff212917fa7cb6151cddb5ff5e | dd296e4ce663222db78a3aa7230cabe4b6620747 | /Programs/SearchAnimBones/main.cpp | 5f963b5dd7b7b2e6078335c837168bf8ff4a5974 | []
| no_license | vienis/mcbuddiapfel | 42213684b253d7a0dae8b785c58a13853d6c9efd | e4d5c6b91d2f9f3b2d0de011cca3298a4e266d89 | refs/heads/master | 2021-01-10T02:13:50.149299 | 2011-01-22T13:56:56 | 2011-01-22T13:56:56 | 36,045,662 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,755 | cpp | /*
* main.cpp
*
* Created on: 22.10.2009
* Author: Bastian
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
using namespace std;
typedef float Vec3D[3];
typedef unsigned short uint16;
typedef short int16;
typedef unsigned int uint32;
typedef int int32;
struct ModelHeader {
char id[4];
char version[4];
uint32 nameLength;
uint32 nameOfs;
uint32 Flags;
uint32 nGlobalSequences;
uint32 ofsGlobalSequences;
uint32 nAnimations;
uint32 ofsAnimations;
uint32 nAnimationLookup;
uint32 ofsAnimationLookup;
uint32 nBones;
uint32 ofsBones;
uint32 nKeyBoneLookup;
uint32 ofsKeyBoneLookup;
uint32 nVertices;
uint32 ofsVertices;
uint32 nViews;
uint32 nColors;
uint32 ofsColors;
uint32 nTextures;
uint32 ofsTextures;
uint32 nTransparency; // H
uint32 ofsTransparency;
uint32 nTexAnims; // J
uint32 ofsTexAnims;
uint32 nTexReplace;
uint32 ofsTexReplace;
uint32 nRenderFlags;
uint32 ofsRenderFlags;
uint32 nBoneLookupTable;
uint32 ofsBoneLookupTable;
uint32 nTexLookup;
uint32 ofsTexLookup;
uint32 nTexUnitLookup; // L
uint32 ofsTexUnitLookup;
uint32 nTransparencyLookup; // M
uint32 ofsTransparencyLookup;
uint32 nTexAnimLookup;
uint32 ofsTexAnimLookup;
//not sure about these :/
Vec3D VertexBoxMin;//?
Vec3D VertexBoxMax;//?
float VertexBoxRadius;
Vec3D BoundingBoxMin;//?
Vec3D BoundingBoxMax;//?
float BoundingBoxRadius;
uint32 nBoundingTriangles;
uint32 ofsBoundingTriangles;
uint32 nBoundingVertices;
uint32 ofsBoundingVertices;
uint32 nBoundingNormals;
uint32 ofsBoundingNormals;
uint32 nAttachments; // O
uint32 ofsAttachments;
uint32 nAttachLookup; // P
uint32 ofsAttachLookup;
uint32 nEvents; // SoundEvents
uint32 ofsEvents;
uint32 nLights; // R
uint32 ofsLights;
uint32 nCameras; // S
uint32 ofsCameras;
uint32 nCameraLookup;
uint32 ofsCameraLookup;
uint32 nRibbonEmitters; // U
uint32 ofsRibbonEmitters;
uint32 nParticleEmitters; // V
uint32 ofsParticleEmitters;
};
struct AnimationBlock {
int16 type; // interpolation type (0=none, 1=linear, 2=hermite, 3=Bezier)
int16 seq; // global sequence id or -1
uint32 nTimes;
uint32 ofsTimes;
uint32 nKeys;
uint32 ofsKeys;
};
struct AnimSub{
uint32 nOfs;
uint32 ofsOfs;
};
struct ModelBoneDef {
int32 KeyBoneID;
uint32 flags;
int16 parent; // parent bone index
uint16 unk[3];
AnimationBlock translation;
AnimationBlock rotation;
AnimationBlock scaling;
Vec3D pivot;
};
int main(int argc, char **argv) {
FILE* Input;
int FileSize;
char*f;
Input=fopen(argv[1],"rb+");
if(Input==NULL)
{
printf(" ERROR: Could not load file\n");
return 0;
}
fseek(Input,0,SEEK_END);
FileSize=ftell(Input);
fseek(Input,0,SEEK_SET);
f=new char[FileSize];
fread(f,FileSize,1,Input);
fclose(Input);
string fullname=argv[1];
fullname = fullname.substr(0, fullname.length() - 3 );
fullname.append(".txt");
filebuf fb;
fb.open(fullname.c_str(),ios::out);
ostream stream(&fb);
int ani=atoi(argv[2]);
ModelHeader *h=(ModelHeader *)f;
ModelBoneDef *b=(ModelBoneDef *)(f+h->ofsBones);
for(int i=0;i<h->nBones;i++){
AnimSub*tr=(AnimSub*)(f+b[i].translation.ofsTimes);
if(tr[ani].nOfs!=0){
stream<<"Bone: "<<i<<" is used within Anim "<<ani<<"\n";
continue;
}
AnimSub*sc=(AnimSub*)(f+b[i].scaling.ofsTimes);
if(sc[ani].nOfs!=0){
stream<<"Bone: "<<i<<" is used within Anim "<<ani<<"\n";
continue;
}
AnimSub*ro=(AnimSub*)(f+b[i].rotation.ofsTimes);
if(ro[ani].nOfs!=0){
stream<<"Bone: "<<i<<" is used within Anim "<<ani<<"\n";
continue;
}
}
fb.close();
return 0;
}
| [
"[email protected]@af0300bf-f729-58c1-2b4a-178d59e24212"
]
| [
[
[
1,
174
]
]
]
|
31f6a1aa58f850b9bbf6b9ed8acde9b6356142b2 | 6581dacb25182f7f5d7afb39975dc622914defc7 | /easyMule/easyMule/src/WorkLayer/ServerSocket.cpp | 139cde1a3abc1d2ccd4a660798b191ebbaf31a96 | []
| no_license | dice2019/alexlabonline | caeccad28bf803afb9f30b9e3cc663bb2909cc4f | 4c433839965ed0cff99dad82f0ba1757366be671 | refs/heads/master | 2021-01-16T19:37:24.002905 | 2011-09-21T15:20:16 | 2011-09-21T15:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,809 | cpp | /*
* $Id: ServerSocket.cpp 9297 2008-12-24 09:55:04Z dgkang $
*
* this file is part of eMule
* Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "stdafx.h"
//#include "emule.h"
#include "ServerSocket.h"
#include "SearchList.h"
#include "DownloadQueue.h"
#include "Statistics.h"
#include "ClientList.h"
#include "Server.h"
#include "ServerList.h"
#include "Sockets.h"
#include "OtherFunctions.h"
#include "Opcodes.h"
#include "Preferences.h"
#include "SafeFile.h"
#include "PartFile.h"
#include "Packets.h"
#include "UpDownClient.h"
//#include "emuleDlg.h"
#include "ServerWnd.h"
//#include "SearchDlg.h"
#include "IPFilter.h"
#include "Log.h"
#include "GlobalVariable.h"
#include "UIMessage.h"
#include "Ed2kUpDownClient.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#pragma pack(1)
struct LoginAnswer_Struct {
uint32 clientid;
};
#pragma pack()
CServerSocket::CServerSocket(CServerConnect* in_serverconnect)
{
serverconnect = in_serverconnect;
connectionstate = CS_NOTCONNECTED;
cur_server = NULL;
m_bIsDeleting = false;
m_dwLastTransmission = 0;
m_bStartNewMessageLog = true;
}
CServerSocket::~CServerSocket()
{
delete cur_server;
}
BOOL CServerSocket::OnHostNameResolved(const SOCKADDR_IN *pSockAddr)
{
// If we are connecting to a dynIP-server by DN, we will get this callback after the
// DNS query finished.
//
if (cur_server->HasDynIP())
{
// Update the IP of this dynIP-server
//
cur_server->SetIP(pSockAddr->sin_addr.S_un.S_addr);
CServer* pServer = CGlobalVariable::serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort());
if (pServer) {
pServer->SetIP(pSockAddr->sin_addr.S_un.S_addr);
// If we already have entries in the server list (dynIP-servers without a DN)
// with the same IP as this dynIP-server, remove the duplicates.
CGlobalVariable::serverlist->RemoveDuplicatesByIP(pServer);
}
DEBUG_ONLY( DebugLog(_T("Resolved DN for server '%s': IP=%s"), cur_server->GetAddress(), ipstr(cur_server->GetIP())) );
// As this is a dynIP-server, we need to check the IP against the IP-filter
// and eventually disconnect and delete that server.
//
// Comment UI
/*if (thePrefs.GetFilterServerByIP() && CGlobalVariable::ipfilter->IsFiltered(cur_server->GetIP())) {
if (thePrefs.GetLogFilteredIPs())
AddDebugLogLine(false, _T("Filtered server \"%s\" (IP=%s) - IP filter (%s)"), pServer ? pServer->GetAddress() : cur_server->GetAddress(), ipstr(cur_server->GetIP()), CGlobalVariable::ipfilter->GetLastHit());
if (pServer)
theApp.emuledlg->serverwnd->serverlistctrl.RemoveServer(pServer);
m_bIsDeleting = true;
SetConnectionState(CS_ERROR);
serverconnect->DestroySocket(this);
return FALSE; // Do *NOT* connect to this server
}*/
}
return TRUE; // Connect to this server
}
void CServerSocket::OnConnect(int nErrorCode)
{
CAsyncSocketEx::OnConnect(nErrorCode);
switch (nErrorCode)
{
case 0:
SetConnectionState(CS_WAITFORLOGIN);
break;
case WSAEADDRNOTAVAIL:
case WSAECONNREFUSED:
//case WSAENETUNREACH: // let this error default to 'fatal error' as it does not increase the server's failed count
case WSAETIMEDOUT:
case WSAEADDRINUSE:
if (thePrefs.GetVerbose())
DebugLogError(_T("Failed to connect to server %s; %s"), cur_server->GetAddress(), GetFullErrorMessage(nErrorCode));
m_bIsDeleting = true;
SetConnectionState(CS_SERVERDEAD);
serverconnect->DestroySocket(this);
return;
case WSAECONNABORTED:
if (m_bProxyConnectFailed)
{
if (thePrefs.GetVerbose())
DebugLogError(_T("Failed to connect to server %s; %s"), cur_server->GetAddress(), GetFullErrorMessage(nErrorCode));
m_bProxyConnectFailed = false;
m_bIsDeleting = true;
SetConnectionState(CS_SERVERDEAD);
serverconnect->DestroySocket(this);
return;
}
/* fall through */
default:
if (thePrefs.GetVerbose())
DebugLogError(_T("Failed to connect to server %s; %s"), cur_server->GetAddress(), GetFullErrorMessage(nErrorCode));
m_bIsDeleting = true;
SetConnectionState(CS_FATALERROR);
serverconnect->DestroySocket(this);
return;
}
}
void CServerSocket::OnReceive(int nErrorCode){
if (connectionstate != CS_CONNECTED && !this->serverconnect->IsConnecting()){
serverconnect->DestroySocket(this);
return;
}
CEMSocket::OnReceive(nErrorCode);
m_dwLastTransmission = GetTickCount();
}
bool CServerSocket::ProcessPacket(const BYTE* packet, uint32 size, uint8 opcode)
{
try
{
switch (opcode)
{
case OP_SERVERMESSAGE:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_ServerMessage\n"));
CServer* pServer = cur_server ? CGlobalVariable::serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort()) : NULL;
CSafeMemFile data(packet, size);
CString strMessages(data.ReadString(pServer ? pServer->GetUnicodeSupport() : false));
if (thePrefs.GetDebugServerTCPLevel() > 0){
UINT uAddData = (UINT)(data.GetLength() - data.GetPosition());
if (uAddData > 0){
Debug(_T("*** NOTE: OP_ServerMessage: ***AddData: %u bytes\n"), uAddData);
DebugHexDump(packet + data.GetPosition(), uAddData);
}
}
// 16.40 servers do not send separate OP_SERVERMESSAGE packets for each line;
// instead of this they are sending all text lines with one OP_SERVERMESSAGE packet.
int iPos = 0;
CString message = strMessages.Tokenize(_T("\r\n"), iPos);
while (!message.IsEmpty())
{
bool bOutputMessage = true;
if (_tcsnicmp(message, _T("server version"), 14) == 0){
CString strVer = message.Mid(14);
strVer.Trim();
strVer = strVer.Left(64); // truncate string to avoid misuse by servers in showing ads
if (pServer){
UINT nVerMaj, nVerMin;
if (_stscanf(strVer, _T("%u.%u"), &nVerMaj, &nVerMin) == 2)
strVer.Format(_T("%u.%02u"), nVerMaj, nVerMin);
pServer->SetVersion(strVer);
// Comment UI
/*theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
theApp.emuledlg->serverwnd->UpdateMyInfo();*/
UINotify(WM_SERVER_REFRESH, 1, (LPARAM)pServer, pServer);
}
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("%s\n"), message);
}
else if (_tcsncmp(message, _T("ERROR"), 5) == 0){
LogError(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"),
GetResString(IDS_ERROR),
pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER),
cur_server ? cur_server->GetAddress() : _T(""),
cur_server ? cur_server->GetPort() : 0, message.Mid(5).Trim(_T(" :")));
bOutputMessage = false;
}
else if (_tcsncmp(message, _T("WARNING"), 7) == 0){
LogWarning(LOG_STATUSBAR, _T("%s %s (%s:%u) - %s"),
GetResString(IDS_WARNING),
pServer ? pServer->GetListName() : GetResString(IDS_PW_SERVER),
cur_server ? cur_server->GetAddress() : _T(""),
cur_server ? cur_server->GetPort() : 0, message.Mid(7).Trim(_T(" :")));
bOutputMessage = false;
}
if (message.Find(_T("[emDynIP: ")) != -1 && message.Find(_T("]")) != -1 && message.Find(_T("[emDynIP: ")) < message.Find(_T("]"))){
CString dynip = message.Mid(message.Find(_T("[emDynIP: ")) + 10, message.Find(_T("]")) - (message.Find(_T("[emDynIP: ")) + 10));
dynip.Trim();
if (dynip.GetLength() && dynip.GetLength() < 51){
// Verify that we really received a DN.
if (pServer && inet_addr(CStringA(dynip)) == INADDR_NONE){
// Update the dynIP of this server, but do not reset it's IP
// which we just determined during connecting.
CString strOldDynIP = pServer->GetDynIP();
pServer->SetDynIP(dynip);
// If a dynIP-server changed its address or, if this is the
// first time we get the dynIP-address for a server which we
// already have as non-dynIP in our list, we need to remove
// an already available server with the same 'dynIP:port'.
if (strOldDynIP.CompareNoCase(pServer->GetDynIP()) != 0)
CGlobalVariable::serverlist->RemoveDuplicatesByAddress(pServer);
if (cur_server)
cur_server->SetDynIP(dynip);
// Comment UI
/*theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
theApp.emuledlg->serverwnd->UpdateMyInfo();*/
UINotify(WM_SERVER_REFRESH, 1, (LPARAM)pServer, pServer);
}
}
}
// Comment UI
/*if (bOutputMessage) {
if (m_bStartNewMessageLog) {
m_bStartNewMessageLog = false;
theApp.emuledlg->AddServerMessageLine(LOG_INFO, _T(""));
CString strMsg;
if (IsObfusicating())
strMsg.Format(_T("%s: ") + GetResString(IDS_CONNECTEDTOOBFUSCATED) + _T(" (%s:%u)"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetObfuscationPortTCP());
else
strMsg.Format(_T("%s: ") + GetResString(IDS_CONNECTEDTO) + _T(" (%s:%u)"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetPort());
theApp.emuledlg->AddServerMessageLine(LOG_SUCCESS, strMsg);
}
theApp.emuledlg->AddServerMessageLine(LOG_INFO, message);
}*/
message = strMessages.Tokenize(_T("\r\n"), iPos);
}
break;
}
case OP_IDCHANGE:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_IDChange\n"));
if (size < sizeof(LoginAnswer_Struct)){
throw GetResString(IDS_ERR_BADSERVERREPLY);
}
LoginAnswer_Struct* la = (LoginAnswer_Struct*)packet;
// save TCP flags in 'cur_server'
CServer* pServer = NULL;
ASSERT( cur_server );
if (cur_server){
if (size >= sizeof(LoginAnswer_Struct)+4){
DWORD dwFlags = *((uint32*)(packet + sizeof(LoginAnswer_Struct)));
if (thePrefs.GetDebugServerTCPLevel() > 0){
CString strInfo;
strInfo.AppendFormat(_T(" TCP Flags=0x%08x"), dwFlags);
const DWORD dwKnownBits = SRV_TCPFLG_COMPRESSION | SRV_TCPFLG_NEWTAGS | SRV_TCPFLG_UNICODE | SRV_TCPFLG_RELATEDSEARCH | SRV_TCPFLG_TYPETAGINTEGER | SRV_TCPFLG_LARGEFILES | SRV_TCPFLG_TCPOBFUSCATION;
if (dwFlags & ~dwKnownBits)
strInfo.AppendFormat(_T(" ***UnkBits=0x%08x"), dwFlags & ~dwKnownBits);
if (dwFlags & SRV_TCPFLG_COMPRESSION)
strInfo.AppendFormat(_T(" Compression=1"));
if (dwFlags & SRV_TCPFLG_NEWTAGS)
strInfo.AppendFormat(_T(" NewTags=1"));
if (dwFlags & SRV_TCPFLG_UNICODE)
strInfo.AppendFormat(_T(" Unicode=1"));
if (dwFlags & SRV_TCPFLG_RELATEDSEARCH)
strInfo.AppendFormat(_T(" RelatedSearch=1"));
if (dwFlags & SRV_TCPFLG_TYPETAGINTEGER)
strInfo.AppendFormat(_T(" IntTypeTags=1"));
if (dwFlags & SRV_TCPFLG_LARGEFILES)
strInfo.AppendFormat(_T(" LargeFiles=1"));
if (dwFlags & SRV_TCPFLG_TCPOBFUSCATION)
strInfo.AppendFormat(_T(" TCP_Obfscation=1"));
Debug(_T("%s\n"), strInfo);
}
cur_server->SetTCPFlags(dwFlags);
}
else
cur_server->SetTCPFlags(0);
// copy TCP flags into the server in the server list
pServer = CGlobalVariable::serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort());
if (pServer)
pServer->SetTCPFlags(cur_server->GetTCPFlags());
}
uint32 dwServerReportedIP = 0;
uint32 dwObfuscationTCPPort = 0;
if (size >= 20){
dwServerReportedIP = *((uint32*)(packet + 12));
if (::IsLowID(dwServerReportedIP)){
ASSERT( false );
dwServerReportedIP = 0;
}
ASSERT( dwServerReportedIP == la->clientid || ::IsLowID(la->clientid) );
dwObfuscationTCPPort = *((uint32*)(packet + 16));
if (cur_server != NULL && dwObfuscationTCPPort != 0)
cur_server->SetObfuscationPortTCP((uint16)dwObfuscationTCPPort);
if (pServer != NULL && dwObfuscationTCPPort != 0)
pServer->SetObfuscationPortTCP((uint16)dwObfuscationTCPPort);
}
if (la->clientid == 0){
uint8 state = thePrefs.GetSmartIdState();
if ( state > 0 ){
state++;
if( state > 3 )
thePrefs.SetSmartIdState(0);
else
thePrefs.SetSmartIdState(state);
}
break;
}
if( thePrefs.GetSmartIdCheck() ){
if (!IsLowID(la->clientid))
thePrefs.SetSmartIdState(1);
else{
uint8 state = thePrefs.GetSmartIdState();
if ( state > 0 ){
state++;
if( state > 3 )
thePrefs.SetSmartIdState(0);
else
thePrefs.SetSmartIdState(state);
break;
}
}
}
// we need to know our client's HighID when sending our shared files (done indirectly on SetConnectionState)
serverconnect->clientid = la->clientid;
if (connectionstate != CS_CONNECTED) {
SetConnectionState(CS_CONNECTED);
// Comment UI
//theApp.OnlineSig(); // Added By Bouc7
PostMessage(CGlobalVariable::m_hListenWnd, WM_LINE_SIG, 0, 0);
}
serverconnect->SetClientID(la->clientid);
if (::IsLowID(la->clientid) && dwServerReportedIP != 0)
CGlobalVariable::SetPublicIP(dwServerReportedIP);
AddLogLine(false, GetResString(IDS_NEWCLIENTID), la->clientid);
CGlobalVariable::downloadqueue->ResetLocalServerRequests();
break;
}
case OP_SEARCHRESULT:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_SearchResult\n"));
CServer* cur_srv = (serverconnect) ? serverconnect->GetCurrentServer() : NULL;
CServer* pServer = cur_srv ? CGlobalVariable::serverlist->GetServerByAddress(cur_srv->GetAddress(), cur_srv->GetPort()) : NULL;
(void)pServer;
bool bMoreResultsAvailable;
UINT uSearchResults = CGlobalVariable::searchlist->ProcessSearchAnswer(packet, size, true/*pServer ? pServer->GetUnicodeSupport() : false*/, cur_srv ? cur_srv->GetIP() : 0, cur_srv ? cur_srv->GetPort() : (uint16)0, &bMoreResultsAvailable);
// Comment UI
//theApp.emuledlg->searchwnd->LocalEd2kSearchEnd(uSearchResults, bMoreResultsAvailable);
PostMessage(CGlobalVariable::m_hListenWnd, WM_SEARCH_LOCALED2KEND, (WPARAM)uSearchResults, (LPARAM)bMoreResultsAvailable);
break;
}
case OP_FOUNDSOURCES_OBFU:
case OP_FOUNDSOURCES:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_FoundSources%s; Sources=%u %s\n"), (opcode == OP_FOUNDSOURCES_OBFU) ? _T("_OBFU") : _T(""), (UINT)packet[16], DbgGetFileInfo(packet));
ASSERT( cur_server );
if (cur_server)
{
CSafeMemFile sources(packet, size);
uchar fileid[16];
sources.ReadHash16(fileid);
if (CPartFile* file = CGlobalVariable::downloadqueue->GetFileByID(fileid))
file->AddSources(&sources,cur_server->GetIP(), cur_server->GetPort(), (opcode == OP_FOUNDSOURCES_OBFU));
}
break;
}
case OP_SERVERSTATUS:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_ServerStatus\n"));
// FIXME some statuspackets have a different size -> why? structur?
if (size < 8)
break;//throw "Invalid status packet";
uint32 cur_user = PeekUInt32(packet);
uint32 cur_files = PeekUInt32(packet+4);
CServer* pServer = cur_server ? CGlobalVariable::serverlist->GetServerByAddress(cur_server->GetAddress(), cur_server->GetPort()) : NULL;
if (pServer){
pServer->SetUserCount(cur_user);
pServer->SetFileCount(cur_files);
// Comment UI
/*theApp.emuledlg->ShowUserCount();
theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer);
theApp.emuledlg->serverwnd->UpdateMyInfo();*/
PostMessage(CGlobalVariable::m_hListenWnd, WM_SHOW_USERCOUNT, 0, 0);
UINotify(WM_SERVER_REFRESH, 1, (LPARAM)pServer, pServer);
}
if (thePrefs.GetDebugServerTCPLevel() > 0){
if (size > 8){
Debug(_T("*** NOTE: OP_ServerStatus: ***AddData: %u bytes\n"), size - 8);
DebugHexDump(packet + 8, size - 8);
}
}
break;
}
case OP_SERVERIDENT:{
// OP_SERVERIDENT - this is sent by the server only if we send a OP_GETSERVERLIST
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_ServerIdent\n"));
if (size<16+4+2+4){
if (thePrefs.GetVerbose())
DebugLogError(_T("%s"), GetResString(IDS_ERR_KNOWNSERVERINFOREC));
break;// throw "Invalid server info received";
}
CServer* pServer = cur_server ? CGlobalVariable::serverlist->GetServerByAddress(cur_server->GetAddress(),cur_server->GetPort()) : NULL;
CString strInfo;
CSafeMemFile data(packet, size);
uint8 aucHash[16];
data.ReadHash16(aucHash);
if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T("Hash=%s (%s)"), md4str(aucHash), DbgGetHashTypeString(aucHash));
uint32 nServerIP = data.ReadUInt32();
uint16 nServerPort = data.ReadUInt16();
if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T(" IP=%s:%u"), ipstr(nServerIP), nServerPort);
UINT nTags = data.ReadUInt32();
if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T(" Tags=%u"), nTags);
CString strName;
CString strDescription;
for (UINT i = 0; i < nTags; i++){
CTag tag(&data, pServer ? pServer->GetUnicodeSupport() : false);
if (tag.GetNameID() == ST_SERVERNAME){
if (tag.IsStr()){
strName = tag.GetStr();
if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T(" Name=%s"), strName);
}
}
else if (tag.GetNameID() == ST_DESCRIPTION){
if (tag.IsStr()){
strDescription = tag.GetStr();
if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T(" Desc=%s"), strDescription);
}
}
else if (thePrefs.GetDebugServerTCPLevel() > 0)
strInfo.AppendFormat(_T(" ***UnkTag: 0x%02x=%u"), tag.GetNameID(), tag.GetInt());
}
if (thePrefs.GetDebugServerTCPLevel() > 0){
strInfo += _T('\n');
Debug(_T("%s"), strInfo);
UINT uAddData = (UINT)(data.GetLength() - data.GetPosition());
if (uAddData > 0){
Debug(_T("*** NOTE: OP_ServerIdent: ***AddData: %u bytes\n"), uAddData);
DebugHexDump(packet + data.GetPosition(), uAddData);
}
}
if (pServer){
pServer->SetListName(strName);
pServer->SetDescription(strDescription);
if (((uint32*)aucHash)[0] == 0x2A2A2A2A){
const CString& rstrVersion = pServer->GetVersion();
if (!rstrVersion.IsEmpty())
pServer->SetVersion(_T("eFarm ") + rstrVersion);
else
pServer->SetVersion(_T("eFarm"));
}
// Comment UI
PostMessage(CGlobalVariable::m_hListenWnd, WM_SHOW_CONNECTION_STATE, 0, 0);
/*theApp.emuledlg->ShowConnectionState();
theApp.emuledlg->serverwnd->serverlistctrl.RefreshServer(pServer); */
UINotify(WM_SERVER_REFRESH, 0, (LPARAM)pServer, pServer);
}
break;
}
// tecxx 1609 2002 - add server's serverlist to own serverlist
case OP_SERVERLIST:{
if (!thePrefs.GetAddServersFromServer())
break;
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_ServerList\n"));
try{
CSafeMemFile servers(packet, size);
UINT count = servers.ReadUInt8();
// check if packet is valid
if (1 + count*(4+2) > size)
count = 0;
int addcount = 0;
while(count)
{
uint32 ip = servers.ReadUInt32();
uint16 port = servers.ReadUInt16();
CServer* srv = new CServer(port, ipstr(ip));
srv->SetListName(srv->GetFullIP());
srv->SetPreference(SRV_PR_LOW);
// Comment UI
if(! ::SendMessage(CGlobalVariable::m_hListenWnd, WM_SERVER_ADD_SVR, (WPARAM)srv, 0x0001))
{
delete srv;
}
else addcount++;
/*if (!theApp.emuledlg->serverwnd->serverlistctrl.AddServer(srv, true))
delete srv;
else
addcount++;*/
count--;
}
if (addcount)
AddLogLine(false, GetResString(IDS_NEWSERVERS), addcount);
if (thePrefs.GetDebugServerTCPLevel() > 0){
UINT uAddData = (UINT)(servers.GetLength() - servers.GetPosition());
if (uAddData > 0){
Debug(_T("*** NOTE: OP_ServerList: ***AddData: %u bytes\n"), uAddData);
DebugHexDump(packet + servers.GetPosition(), uAddData);
}
}
}
catch(CFileException* error){
if (thePrefs.GetVerbose())
DebugLogError(_T("%s"), GetResString(IDS_ERR_BADSERVERLISTRECEIVED));
error->Delete();
}
break;
}
case OP_CALLBACKREQUESTED:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_CallbackRequested: %s\n"), (size >= 23) ? _T("With Cryptflag and Userhash") : _T("Without Cryptflag and Userhash"));
if (size >= 6)
{
uint32 dwIP = PeekUInt32(packet);
if (CGlobalVariable::ipfilter->IsFiltered(dwIP)){
theStats.filteredclients++;
if (thePrefs.GetLogFilteredIPs())
AddDebugLogLine(false, _T("Ignored callback request (IP=%s) - IP filter (%s)"), ipstr(dwIP), CGlobalVariable::ipfilter->GetLastHit());
break;
}
if (CGlobalVariable::clientlist->IsBannedClient(dwIP)){
if (thePrefs.GetLogBannedClients()){
CUpDownClient* pClient = CGlobalVariable::clientlist->FindClientByIP(dwIP);
AddDebugLogLine(false, _T("Ignored callback request from banned client %s; %s"), ipstr(dwIP), pClient->DbgGetClientInfo());
}
break;
}
uint16 nPort = PeekUInt16(packet+4);
uint8 byCryptOptions = 0;
uchar achUserHash[16];
if (size >= 23){
byCryptOptions = packet[6];
md4cpy(achUserHash, packet + 7);
}
CUpDownClient* client = CGlobalVariable::clientlist->FindClientByIP(dwIP,nPort);
if (client == NULL)
{
client = new CEd2kUpDownClient(0,nPort,dwIP,0,0,true);
CGlobalVariable::clientlist->AddClient(client);
}
if (size >= 23 && client->HasValidHash()){
if (md4cmp(client->GetUserHash(), achUserHash) != 0){
DebugLogError(_T("Reported Userhash from OP_CALLBACKREQUESTED differs with our stored hash"));
// disable crypt support since we dont know which hash is true
client->SetCryptLayerRequest(false);
client->SetCryptLayerSupport(false);
client->SetCryptLayerRequires(false);
}
else{
client->SetConnectOptions(byCryptOptions, true, false);
client->SetDirectUDPCallbackSupport(false);
}
}
else if (size >= 23){
client->SetUserHash(achUserHash);
client->SetCryptLayerSupport((byCryptOptions & 0x01) != 0);
client->SetCryptLayerRequest((byCryptOptions & 0x02) != 0);
client->SetCryptLayerRequires((byCryptOptions & 0x04) != 0);
}
client->TryToConnect(true);
}
break;
}
case OP_CALLBACK_FAIL:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_Callback_Fail %s\n"), DbgGetHexDump(packet, size));
break;
}
case OP_REJECT:{
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("ServerMsg - OP_Reject %s\n"), DbgGetHexDump(packet, size));
// this could happen if we send a command with the wrong protocol (e.g. sending a compressed packet to
// a server which does not support that protocol).
if (thePrefs.GetVerbose())
DebugLogError(_T("Server rejected last command"));
break;
}
default:
if (thePrefs.GetDebugServerTCPLevel() > 0)
Debug(_T("***NOTE: ServerMsg - Unknown message; opcode=0x%02x %s\n"), opcode, DbgGetHexDump(packet, size));
;
}
return true;
}
catch(CFileException* error)
{
if (thePrefs.GetVerbose())
{
TCHAR szError[MAX_CFEXP_ERRORMSG];
error->m_strFileName = _T("server packet");
error->GetErrorMessage(szError, ARRSIZE(szError));
ProcessPacketError(size, opcode, szError);
}
ASSERT(0);
error->Delete();
if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
return true;
}
catch(CMemoryException* error)
{
ProcessPacketError(size, opcode, _T("CMemoryException"));
ASSERT(0);
error->Delete();
if (opcode==OP_SEARCHRESULT || opcode==OP_FOUNDSOURCES)
return true;
}
catch(CString error)
{
ProcessPacketError(size, opcode, error);
ASSERT(0);
}
#ifndef _DEBUG
catch(...)
{
ProcessPacketError(size, opcode, _T("Unknown exception"));
ASSERT(0);
}
#endif
SetConnectionState(CS_DISCONNECTED);
return false;
}
void CServerSocket::ProcessPacketError(UINT size, UINT opcode, LPCTSTR pszError)
{
if (thePrefs.GetVerbose())
{
CString strServer;
try{
if (cur_server)
strServer.Format(_T("%s:%u"), cur_server->GetAddress(), cur_server->GetPort());
else
strServer = _T("Unknown");
}
catch(...){
}
DebugLogWarning(false, _T("Error: Failed to process server TCP packet from %s: opcode=0x%02x size=%u - %s"), strServer, opcode, size, pszError);
}
}
void CServerSocket::ConnectTo(CServer* server, bool bNoCrypt)
{
if (cur_server){
ASSERT(0);
delete cur_server;
cur_server = NULL;
}
uint16 nPort = 0;
cur_server = new CServer(server);
if ( !bNoCrypt && thePrefs.IsServerCryptLayerTCPRequested() && server->GetObfuscationPortTCP() != 0 && server->SupportsObfuscationTCP()){
Log(GetResString(IDS_CONNECTINGTOOBFUSCATED), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetObfuscationPortTCP());
nPort = cur_server->GetObfuscationPortTCP();
SetConnectionEncryption(true, NULL, true);
}
else{
Log(GetResString(IDS_CONNECTINGTO), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetPort());
nPort = cur_server->GetPort();
SetConnectionEncryption(false, NULL, true);
}
// IP-filter: We do not need to IP-filter any servers here, even dynIP-servers are not
// needed to get filtered here.
// 1.) Non dynIP-servers were already IP-filtered when they were added to the server
// list.
// 2.) Whenever the IP-filter is updated all servers for which an IP is known (this
// includes also dynIP-servers for which we received already an IP) get filtered.
// 3.) dynIP-servers get filtered after their DN was resolved. For TCP-connections this
// is done in OnConnect. For outgoing UDP packets this is done when explicitly
// resolving the DN right before sending the UDP packet.
//
SetConnectionState(CS_CONNECTING);
if (!Connect(CStringA(server->GetAddress()), nPort)){
DWORD dwError = GetLastError();
if (dwError != WSAEWOULDBLOCK){
LogError(GetResString(IDS_ERR_CONNECTIONERROR), cur_server->GetListName(), cur_server->GetAddress(), nPort, GetFullErrorMessage(dwError));
SetConnectionState(CS_FATALERROR);
return;
}
}
}
void CServerSocket::OnError(int nErrorCode)
{
SetConnectionState(CS_DISCONNECTED);
if (thePrefs.GetVerbose())
DebugLogError(GetResString(IDS_ERR_SOCKET), cur_server->GetListName(), cur_server->GetAddress(), cur_server->GetPort(), GetFullErrorMessage(nErrorCode));
}
bool CServerSocket::PacketReceived(Packet* packet)
{
#ifndef _DEBUG
try {
#endif
theStats.AddDownDataOverheadServer(packet->size);
if (packet->prot == OP_PACKEDPROT)
{
uint32 uComprSize = packet->size;
if (!packet->UnPackPacket(250000)){
if (thePrefs.GetVerbose())
DebugLogError(_T("Failed to decompress server TCP packet: protocol=0x%02x opcode=0x%02x size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
return true;
}
packet->prot = OP_EDONKEYPROT;
if (thePrefs.GetDebugServerTCPLevel() > 1)
Debug(_T("Received compressed server TCP packet; opcode=0x%02x size=%u uncompr size=%u\n"), packet->opcode, uComprSize, packet->size);
}
if (packet->prot == OP_EDONKEYPROT)
{
ProcessPacket((const BYTE*)packet->pBuffer, packet->size, packet->opcode);
}
else
{
if (thePrefs.GetVerbose())
DebugLogWarning(_T("Received server TCP packet with unknown protocol: protocol=0x%02x opcode=0x%02x size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
}
#ifndef _DEBUG
}
catch(...)
{
if (thePrefs.GetVerbose())
DebugLogError(_T("Error: Unhandled exception while processing server TCP packet: protocol=0x%02x opcode=0x%02x size=%u"), packet ? packet->prot : 0, packet ? packet->opcode : 0, packet ? packet->size : 0);
ASSERT(0);
return false;
}
#endif
return true;
}
void CServerSocket::OnClose(int /*nErrorCode*/)
{
CEMSocket::OnClose(0);
if (connectionstate == CS_WAITFORLOGIN){
SetConnectionState(CS_SERVERFULL);
}
else if (connectionstate == CS_CONNECTED){
SetConnectionState(CS_DISCONNECTED);
}
else{
SetConnectionState(CS_NOTCONNECTED);
}
serverconnect->DestroySocket(this);
}
void CServerSocket::SetConnectionState(int newstate){
connectionstate = newstate;
if (newstate < 1){
serverconnect->ConnectionFailed(this);
}
else if (newstate == CS_CONNECTED || newstate == CS_WAITFORLOGIN){
if (serverconnect)
serverconnect->ConnectionEstablished(this);
}
}
void CServerSocket::SendPacket(Packet* packet, bool delpacket, bool controlpacket, uint32 actualPayloadSize, bool bForceImmediateSend){
m_dwLastTransmission = GetTickCount();
CEMSocket::SendPacket(packet, delpacket, controlpacket, actualPayloadSize, bForceImmediateSend);
}
| [
"damoguyan8844@3a4e9f68-f5c2-36dc-e45a-441593085838"
]
| [
[
[
1,
823
]
]
]
|
6d3d1fbbea5b27cb2dbed5f2dffbb356736628b2 | d609fb08e21c8583e5ad1453df04a70573fdd531 | /trunk/开发库/include/HListCtrl.h | 72275f4eae3c4f92195672b3ed4c4168b0c24940 | []
| no_license | svn2github/openxp | d68b991301eaddb7582b8a5efd30bc40e87f2ac3 | 56db08136bcf6be6c4f199f4ac2a0850cd9c7327 | refs/heads/master | 2021-01-19T10:29:42.455818 | 2011-09-17T10:27:15 | 2011-09-17T10:27:15 | 21,675,919 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,566 | h | #ifndef __HLISTCTRL__H__
#define __HLISTCTRL__H__
#pragma once
#include "HHeaderCtrl.h"
#include <atlimage.h>
#include <map>
#define WM_HITCARLISTCTRL WM_USER+1500 //点击某一行时发送消息
class UI_CONTROL_API HListCtrl : public CListCtrl
{
DECLARE_DYNAMIC(HListCtrl)
public:
HListCtrl();
virtual ~HListCtrl();
//外部接口
public:
void LoadResource(LPCTSTR lpstHeader,LPCTSTR lpstBk,LPCTSTR lpstCheckBox=NULL,LPCTSTR lpstSelected=NULL);//设置图片资源
void LoadResource(HINSTANCE hInstance,UINT nHeader,UINT nBk,UINT nCheckBox=0,UINT nSelected=0);//设置图片资源
void SetRowHeigt(int nHeight); //设置行高
void SetHeaderHeight(float Height);// 设置表头高度
void SetHeaderTextColor(COLORREF color);//设置表头颜色
void SetTextColor(COLORREF color);//设置列表文本颜色
int InsertColumn(int nCol, LPCTSTR lpszColumnHeading,
int nFormat = LVCFMT_LEFT, int nWidth = -1, int nSubItem = -1);
int InsertItem(int nItem, LPCTSTR lpszItem);
void SetHeaderLock(BOOL bLock=TRUE){m_Header.Lock(bLock);}
void GetSelected(int *nCount);//得到复选框被选中的项目
void SetRowSelected(int nIndex);//设置某行被选中
//成员
private:
HHeaderCtrl m_Header;
int m_nRowHeight;// 行高
CImage m_imgBk;
CImage m_imgSeleted;
CImage m_imgCheckBox;
COLORREF m_color;
int m_nCurHighlighted;
bool m_bCheckBox;
std::map<int,int> m_mapCheckMgr;//复选框的勾选管理
//实现复查
protected:
int GetColNum();
int SearchSelectIndex();
CString SearchSelectText();
void ReMoveSelect();
int GetIndexFromPoint();
CRect GetShowRect();
void UpdataCheckBox(CPoint point,int nHighLight);
void UpdateSelected();
//消息映射
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnMeasureItem(int nIDCtl, LPMEASUREITEMSTRUCT lpMeasureItemStruct);
virtual void PreSubclassWindow();
virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam);
virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct);
void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnPaint();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnDestroy();
virtual BOOL OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult);
public:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
};
#endif | [
"[email protected]@f92b348d-55a1-4afa-8193-148a6675784b"
]
| [
[
[
1,
75
]
]
]
|
d1fc732bc55c0a8fb8174216bee7ea517b45f154 | d94c6cce730a771c18a6d84c7991464129ed3556 | /safeFatPrinter/trunk/src/dcontroller.h | 55b6d34586a063ee5f2c997bfb50e19a65c18119 | []
| no_license | S1aNT/cupsfilter | 09afbcedb4f011744e670fae74d71fce4cebdd25 | 26ecc1e76eefecde2b00173dff9f91ebd92fb349 | refs/heads/master | 2021-01-02T09:26:27.015991 | 2011-03-15T06:43:47 | 2011-03-15T06:43:47 | 32,496,994 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,208 | h | #ifndef dController_H
#define dController_H
#include <QDebug>
#include <QSettings>
#include <QUuid>
#include <QDate>
#include <QStringList>
#include <QMap>
#include <QStandardItemModel>
#include <QPrinter>
#include <QPrintPreviewDialog>
#include "template_painter.h"
#include "proc_thread.h"
#include "netagent.h"
class dController : public QObject{
Q_OBJECT
public:
dController( QObject *parent = 0 );
~dController();
bool isConnect();
void read_settings();
void write_settings();
QStandardItemModel *document_model () const;
void insertDocToModel();
void insertDocToModel(QString &item);
public slots:
// Преобразует выходной файл в pdf
void convert2PDF(QString &in_file);
// Объединяет два файла в один печатая шаблон поверх исходного файла
void mergeTwoPDF(QString &fg_file,QString &bg_file,QString &out_file);
void setPrinter(QString selected_printer);
void savebase(QString wide_msg);
void printOverSide(int RowId);
void printWithTemplate (int RowId);
void checkMB(QString mb);
signals:
void error(int ErrorCode,QString ErrorString);
void inputFileConverted(); // Файл преобразован в pdf
void inputFileMerged(); // Файл объединен
void connect2Demon();
void sendServerCmd(commands_t cmd,QString & body);
// в базе аудита такого документа (с таким МБ) нет
void mbNumberChecked(QString &mb);
// В базе аудита есть такой документ, RowID -1 документ помечен ка распечатаный
void mbNumberExist(int RowID);
// Выдает форматированну строчку с данными полученными от демона в ответ на запрос документа по МБ
//void exchangeData2MB(QString field_data);
void sayMeGood();
private slots:
void parseCnvThread(int Code,QString output);
void parseMergeThread(int Code,QString output);
void parseNetwork(QString &message);
private:
QString userName;
QString userMandat;
void connect2Server(QString &host,int port);
void createDocModel();
protected:
QString SID;
QStandardItemModel *doc_model;
QStringList header;
netAgent *netClient;
QString serverHostName;
int serverPort;
bool conn_state;
// задержки сети для тонкой настройки
int timeout_connect;
int timeout_read;
int timeout_write;
QStringList args;
QStringList currentDoc;
QString mainPDF; // Файл который получился в результате конвертирования исходного
QString gsBin; // путь к исполняемому файлу ghostscript
QString pdftkBin; // Путь к файлу pdfTK
QString outPDF;
QString spoolDIR;
QString curPrinter; // Текущий выбранный пользователем принтер
};
#endif // dController_H
| [
"[email protected]"
]
| [
[
[
1,
100
]
]
]
|
f39df1853627a7be4705bd45244acc4eeed1f3d0 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/math/test/compile_test/dist_laplace_incl_test.cpp | eefcbfe727996dcd981f46f2328c9785a02153e6 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 946 | cpp | // Copyright John Maddock 2008.
// 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)
//
// Basic sanity check that header <boost/math/distributions/laplace.hpp>
// #includes all the files that it needs to.
//
#include <boost/math/distributions/laplace.hpp>
//
// Note this header includes no other headers, this is
// important if this test is to be meaningful:
//
#include "test_compile_result.hpp"
void check()
{
TEST_DIST_FUNC(laplace)
}
template class boost::math::laplace_distribution<float, boost::math::policies::policy<> >;
template class boost::math::laplace_distribution<double, boost::math::policies::policy<> >;
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
template class boost::math::laplace_distribution<long double, boost::math::policies::policy<> >;
#endif
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
25
]
]
]
|
0660bd2b2f34634327003588f65cb260eede636d | e822fb29110ffae9e404e72ad244cd81d41b0335 | /lib/Ogre/include/OgreMeshSerializerImpl.h | c4cc657a983a9c2f3dc9f1fde6e8b0df5ce9276d | []
| no_license | communityus-branch/LookingGlass-Viewer | 4dda6d78973149d21e2bfc49296e77f1b7379f20 | c80120e3e5cc8ed699280763c95ca8bb8db8174b | refs/heads/master | 2020-06-02T17:50:41.255708 | 2011-07-28T05:37:50 | 2011-07-28T05:37:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,143 | h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2009 Torus Knot Software Ltd
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 __MeshSerializerImpl_H__
#define __MeshSerializerImpl_H__
#include "OgrePrerequisites.h"
#include "OgreString.h"
#include "OgreSerializer.h"
#include "OgreMaterial.h"
#include "OgreMesh.h"
#include "OgreEdgeListBuilder.h"
namespace Ogre {
class MeshSerializerListener;
class LodStrategy;
/** \addtogroup Core
* @{
*/
/** \addtogroup Resources
* @{
*/
/** Internal implementation of Mesh reading / writing for the latest version of the
.mesh format.
@remarks
In order to maintain compatibility with older versions of the .mesh format, there
will be alternative subclasses of this class to load older versions, whilst this class
will remain to load the latest version.
*/
class _OgrePrivate MeshSerializerImpl : public Serializer
{
public:
MeshSerializerImpl();
virtual ~MeshSerializerImpl();
/** Exports a mesh to the file specified.
@remarks
This method takes an externally created Mesh object, and exports both it
and optionally the Materials it uses to a .mesh file.
@param pMesh Pointer to the Mesh to export
@param filename The destination filename
@param endianMode The endian mode for the written file
*/
void exportMesh(const Mesh* pMesh, const String& filename,
Endian endianMode = ENDIAN_NATIVE);
/** Imports Mesh and (optionally) Material data from a .mesh file DataStream.
@remarks
This method imports data from a DataStream opened from a .mesh file and places it's
contents into the Mesh object which is passed in.
@param stream The DataStream holding the .mesh data. Must be initialised (pos at the start of the buffer).
@param pDest Pointer to the Mesh object which will receive the data. Should be blank already.
*/
void importMesh(DataStreamPtr& stream, Mesh* pDest, MeshSerializerListener *listener);
protected:
// Internal methods
virtual void writeSubMeshNameTable(const Mesh* pMesh);
virtual void writeMesh(const Mesh* pMesh);
virtual void writeSubMesh(const SubMesh* s);
virtual void writeSubMeshOperation(const SubMesh* s);
virtual void writeSubMeshTextureAliases(const SubMesh* s);
virtual void writeGeometry(const VertexData* pGeom);
virtual void writeSkeletonLink(const String& skelName);
virtual void writeMeshBoneAssignment(const VertexBoneAssignment& assign);
virtual void writeSubMeshBoneAssignment(const VertexBoneAssignment& assign);
virtual void writeLodInfo(const Mesh* pMesh);
virtual void writeLodSummary(unsigned short numLevels, bool manual, const LodStrategy *strategy);
virtual void writeLodUsageManual(const MeshLodUsage& usage);
virtual void writeLodUsageGenerated(const Mesh* pMesh, const MeshLodUsage& usage, unsigned short lodNum);
virtual void writeBoundsInfo(const Mesh* pMesh);
virtual void writeEdgeList(const Mesh* pMesh);
virtual void writeAnimations(const Mesh* pMesh);
virtual void writeAnimation(const Animation* anim);
virtual void writePoses(const Mesh* pMesh);
virtual void writePose(const Pose* pose);
virtual void writeAnimationTrack(const VertexAnimationTrack* track);
virtual void writeMorphKeyframe(const VertexMorphKeyFrame* kf, size_t vertexCount);
virtual void writePoseKeyframe(const VertexPoseKeyFrame* kf);
virtual void writePoseKeyframePoseRef(const VertexPoseKeyFrame::PoseRef& poseRef);
virtual void writeExtremes(const Mesh *pMesh);
virtual void writeSubMeshExtremes(unsigned short idx, const SubMesh* s);
virtual size_t calcMeshSize(const Mesh* pMesh);
virtual size_t calcSubMeshSize(const SubMesh* pSub);
virtual size_t calcGeometrySize(const VertexData* pGeom);
virtual size_t calcSkeletonLinkSize(const String& skelName);
virtual size_t calcBoneAssignmentSize(void);
virtual size_t calcSubMeshOperationSize(const SubMesh* pSub);
virtual size_t calcSubMeshNameTableSize(const Mesh* pMesh);
virtual size_t calcEdgeListSize(const Mesh* pMesh);
virtual size_t calcEdgeListLodSize(const EdgeData* data, bool isManual);
virtual size_t calcEdgeGroupSize(const EdgeData::EdgeGroup& group);
virtual size_t calcPosesSize(const Mesh* pMesh);
virtual size_t calcPoseSize(const Pose* pose);
virtual size_t calcAnimationsSize(const Mesh* pMesh);
virtual size_t calcAnimationSize(const Animation* anim);
virtual size_t calcAnimationTrackSize(const VertexAnimationTrack* track);
virtual size_t calcMorphKeyframeSize(const VertexMorphKeyFrame* kf, size_t vertexCount);
virtual size_t calcPoseKeyframeSize(const VertexPoseKeyFrame* kf);
virtual size_t calcPoseKeyframePoseRefSize(void);
virtual size_t calcPoseVertexSize(void);
virtual size_t calcSubMeshTextureAliasesSize(const SubMesh* pSub);
virtual void readTextureLayer(DataStreamPtr& stream, Mesh* pMesh, MaterialPtr& pMat);
virtual void readSubMeshNameTable(DataStreamPtr& stream, Mesh* pMesh);
virtual void readMesh(DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener);
virtual void readSubMesh(DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener);
virtual void readSubMeshOperation(DataStreamPtr& stream, Mesh* pMesh, SubMesh* sub);
virtual void readSubMeshTextureAlias(DataStreamPtr& stream, Mesh* pMesh, SubMesh* sub);
virtual void readGeometry(DataStreamPtr& stream, Mesh* pMesh, VertexData* dest);
virtual void readGeometryVertexDeclaration(DataStreamPtr& stream, Mesh* pMesh, VertexData* dest);
virtual void readGeometryVertexElement(DataStreamPtr& stream, Mesh* pMesh, VertexData* dest);
virtual void readGeometryVertexBuffer(DataStreamPtr& stream, Mesh* pMesh, VertexData* dest);
virtual void readSkeletonLink(DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener);
virtual void readMeshBoneAssignment(DataStreamPtr& stream, Mesh* pMesh);
virtual void readSubMeshBoneAssignment(DataStreamPtr& stream, Mesh* pMesh,
SubMesh* sub);
virtual void readMeshLodInfo(DataStreamPtr& stream, Mesh* pMesh);
virtual void readMeshLodUsageManual(DataStreamPtr& stream, Mesh* pMesh,
unsigned short lodNum, MeshLodUsage& usage);
virtual void readMeshLodUsageGenerated(DataStreamPtr& stream, Mesh* pMesh,
unsigned short lodNum, MeshLodUsage& usage);
virtual void readBoundsInfo(DataStreamPtr& stream, Mesh* pMesh);
virtual void readEdgeList(DataStreamPtr& stream, Mesh* pMesh);
virtual void readEdgeListLodInfo(DataStreamPtr& stream, EdgeData* edgeData);
virtual void readPoses(DataStreamPtr& stream, Mesh* pMesh);
virtual void readPose(DataStreamPtr& stream, Mesh* pMesh);
virtual void readAnimations(DataStreamPtr& stream, Mesh* pMesh);
virtual void readAnimation(DataStreamPtr& stream, Mesh* pMesh);
virtual void readAnimationTrack(DataStreamPtr& stream, Animation* anim,
Mesh* pMesh);
virtual void readMorphKeyFrame(DataStreamPtr& stream, VertexAnimationTrack* track);
virtual void readPoseKeyFrame(DataStreamPtr& stream, VertexAnimationTrack* track);
virtual void readExtremes(DataStreamPtr& stream, Mesh *pMesh);
/// Flip an entire vertex buffer from little endian
virtual void flipFromLittleEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems);
/// Flip an entire vertex buffer to little endian
virtual void flipToLittleEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems);
/// Flip the endianness of an entire vertex buffer, passed in as a
/// pointer to locked or temporary memory
virtual void flipEndian(void* pData, size_t vertexCount, size_t vertexSize, const VertexDeclaration::VertexElementList& elems);
};
/** Class for providing backwards-compatibility for loading version 1.4 of the .mesh format. */
class _OgrePrivate MeshSerializerImpl_v1_4 : public MeshSerializerImpl
{
public:
MeshSerializerImpl_v1_4();
~MeshSerializerImpl_v1_4();
protected:
virtual void writeLodSummary(unsigned short numLevels, bool manual, const LodStrategy *strategy);
virtual void readMeshLodInfo(DataStreamPtr& stream, Mesh* pMesh);
};
/** Class for providing backwards-compatibility for loading version 1.3 of the .mesh format. */
class _OgrePrivate MeshSerializerImpl_v1_3 : public MeshSerializerImpl
{
public:
MeshSerializerImpl_v1_3();
~MeshSerializerImpl_v1_3();
protected:
virtual void readEdgeListLodInfo(DataStreamPtr& stream, EdgeData* edgeData);
/// Reorganise triangles of the edge list to group by vertex set
virtual void reorganiseTriangles(EdgeData* edgeData);
};
/** Class for providing backwards-compatibility for loading version 1.2 of the .mesh format. */
class _OgrePrivate MeshSerializerImpl_v1_2 : public MeshSerializerImpl_v1_3
{
public:
MeshSerializerImpl_v1_2();
~MeshSerializerImpl_v1_2();
protected:
virtual void readMesh(DataStreamPtr& stream, Mesh* pMesh, MeshSerializerListener *listener);
virtual void readGeometry(DataStreamPtr& stream, Mesh* pMesh, VertexData* dest);
virtual void readGeometryPositions(unsigned short bindIdx, DataStreamPtr& stream,
Mesh* pMesh, VertexData* dest);
virtual void readGeometryNormals(unsigned short bindIdx, DataStreamPtr& stream,
Mesh* pMesh, VertexData* dest);
virtual void readGeometryColours(unsigned short bindIdx, DataStreamPtr& stream,
Mesh* pMesh, VertexData* dest);
virtual void readGeometryTexCoords(unsigned short bindIdx, DataStreamPtr& stream,
Mesh* pMesh, VertexData* dest, unsigned short set);
};
/** Class for providing backwards-compatibility for loading version 1.1 of the .mesh format. */
class _OgrePrivate MeshSerializerImpl_v1_1 : public MeshSerializerImpl_v1_2
{
public:
MeshSerializerImpl_v1_1();
~MeshSerializerImpl_v1_1();
protected:
void readGeometryTexCoords(unsigned short bindIdx, DataStreamPtr& stream,
Mesh* pMesh, VertexData* dest, unsigned short set);
};
/** @} */
/** @} */
}
#endif
| [
"Robert@LAKEOZ.(none)"
]
| [
[
[
1,
238
]
]
]
|
7f60b279e44c88e4b8d5aa886b3c0c39371be240 | 507511ecc4d58017e035c9a40139a1b142ea5a2f | /network/fill.cpp | e2121b8f11e70dc601daa0e97c0ae60123a1927e | []
| no_license | stefansundin/twug | a15a02efc500aec8f271d1c80e2631fd4b2d05d9 | 654a1f6d4540baba742a1002821802057fec1bb8 | refs/heads/master | 2020-05-01T01:39:48.605865 | 2008-05-01T15:21:08 | 2008-05-01T15:21:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | #include <string>
#include "fill.h"
bool fill(std::string &p_str, unsigned int p_length)
{
if(p_str.length() > p_length)
return false;
while(p_str.length() < p_length)
{
p_str += FILL_CHAR;
}
return true;
}
| [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
3ea816467e876e1237136c536b3d3b88611241a0 | 061348a6be0e0e602d4a5b3e0af28e9eee2d257f | /Examples/Tutorial/UserInterface/16TextField.cpp | 4cbde85d2328ef3bd72efc0aeeb540d686573591 | []
| no_license | passthefist/OpenSGToolbox | 4a76b8e6b87245685619bdc3a0fa737e61a57291 | d836853d6e0647628a7dd7bb7a729726750c6d28 | refs/heads/master | 2023-06-09T22:44:20.711657 | 2010-07-26T00:43:13 | 2010-07-26T00:43:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,884 | cpp | // OpenSG Tutorial Example: Creating a Button Component
//
// This tutorial explains how to edit the basic features of
// a Button created in the OSG User Interface library.
//
// Includes: Button PreferredSize, MaximumSize, MinimumSize, Font,
// Text,and adding a Button to a Scene. Also note that clicking
// the Button causes it to appear pressed
// General OpenSG configuration, needed everywhere
#include "OSGConfig.h"
// Methods to create simple geometry: boxes, spheres, tori etc.
#include "OSGSimpleGeometry.h"
// A little helper to simplify scene management and interaction
#include "OSGSimpleSceneManager.h"
#include "OSGNode.h"
#include "OSGGroup.h"
#include "OSGViewport.h"
// The general scene file loading handler
#include "OSGSceneFileHandler.h"
// Input
#include "OSGWindowUtils.h"
// UserInterface Headers
#include "OSGUIForeground.h"
#include "OSGLayers.h"
#include "OSGInternalWindow.h"
#include "OSGUIDrawingSurface.h"
#include "OSGGraphics2D.h"
#include "OSGLookAndFeelManager.h"
// Activate the OpenSG namespace
OSG_USING_NAMESPACE
// The SimpleSceneManager to manage simple applications
SimpleSceneManager *mgr;
WindowEventProducerRefPtr TutorialWindow;
// Forward declaration so we can have the interesting stuff upfront
void display(void);
void reshape(Vec2f Size);
// 16TextField Headers
#include "OSGButton.h"
#include "OSGLineBorder.h"
#include "OSGFlowLayout.h"
#include "OSGLookAndFeelManager.h"
#include "OSGUIFont.h"
#include "OSGTextField.h"
// Create a class to allow for the use of the Ctrl+q
class TutorialKeyListener : public KeyListener
{
public:
virtual void keyPressed(const KeyEventUnrecPtr e)
{
if(e->getKey() == KeyEvent::KEY_Q && e->getModifiers() & KeyEvent::KEY_MODIFIER_COMMAND)
{
TutorialWindow->closeWindow();
}
}
virtual void keyReleased(const KeyEventUnrecPtr e)
{
}
virtual void keyTyped(const KeyEventUnrecPtr e)
{
}
};
int main(int argc, char **argv)
{
// OSG init
osgInit(argc,argv);
// Set up Window
TutorialWindow = createNativeWindow();
TutorialWindow->initWindow();
TutorialWindow->setDisplayCallback(display);
TutorialWindow->setReshapeCallback(reshape);
TutorialKeyListener TheKeyListener;
TutorialWindow->addKeyListener(&TheKeyListener);
// Make Torus Node (creates Torus in background of scene)
NodeRefPtr TorusGeometryNode = makeTorus(.5, 2, 16, 16);
// Make Main Scene Node and add the Torus
NodeRefPtr scene = OSG::Node::create();
scene->setCore(OSG::Group::create());
scene->addChild(TorusGeometryNode);
// Create the Graphics
GraphicsRefPtr TutorialGraphics = OSG::Graphics2D::create();
// Initialize the LookAndFeelManager to enable default settings
LookAndFeelManager::the()->getLookAndFeel()->init();
// Create a simple Font to be used with the TextField
UIFontRefPtr sampleFont = OSG::UIFont::create();
sampleFont->setSize(16);
/******************************************************
Create and edit the TextField. A TextField is
a Component which allows a single line of text
to be displayed. Text can be entered via the
keyboard, and selected with arrow keys or
the Mouse.
-setTextColor(Color4f): Determine the
Text Color.
setSelectionBoxColor(Color4f): Determine
the Color of highlighting around
selected Text.
-setSelectionTextColor(Color4f): Determine
the Color of selected Text.
-setText("TextToBeDisplayed"): Determine
initial Text within TextField.
-setFont(FontName): Determine the Font
used within TextField.
-setSelectionStart(StartCharacterNumber):
Determine the character with which
the selection will initially start.
-setSelectionEnd(EndCharacterNumber):
Determine the character which the
selection ends before.
-setAlignment(float): Determine
the alignment of the text.
The float is a percentage is from the
top of the text [0.0-1.0]. Note: be
sure to visually verify this, as due
to font size and line size this does
not always place it exactly
at the percentage point.
******************************************************/
// Create a TextField component
TextFieldRefPtr ExampleTextField = OSG::TextField::create();
ExampleTextField->setPreferredSize(Vec2f(100, 50));
ExampleTextField->setTextColor(Color4f(0.0, 0.0, 0.0, 1.0));
ExampleTextField->setSelectionBoxColor(Color4f(0.0, 0.0, 1.0, 1.0));
ExampleTextField->setSelectionTextColor(Color4f(1.0, 1.0, 1.0, 1.0));
ExampleTextField->setText("What");
ExampleTextField->setFont(sampleFont);
// The next two functions will select the "a" from above
ExampleTextField->setSelectionStart(2);
ExampleTextField->setSelectionEnd(3);
ExampleTextField->setAlignment(Vec2f(0.0,0.5));
// Create another TextField Component
TextFieldRefPtr ExampleTextField2 = OSG::TextField::create();
ExampleTextField2->setText("");
ExampleTextField2->setEmptyDescText("Write in me, please");
ExampleTextField2->setPreferredSize(Vec2f(200.0f,ExampleTextField2->getPreferredSize().y()));
// Create The Main InternalWindow
// Create Background to be used with the Main InternalWindow
ColorLayerRefPtr MainInternalWindowBackground = OSG::ColorLayer::create();
MainInternalWindowBackground->setColor(Color4f(1.0,1.0,1.0,0.5));
LayoutRefPtr MainInternalWindowLayout = OSG::FlowLayout::create();
InternalWindowRefPtr MainInternalWindow = OSG::InternalWindow::create();
MainInternalWindow->pushToChildren(ExampleTextField);
MainInternalWindow->pushToChildren(ExampleTextField2);
MainInternalWindow->setLayout(MainInternalWindowLayout);
MainInternalWindow->setBackgrounds(MainInternalWindowBackground);
MainInternalWindow->setAlignmentInDrawingSurface(Vec2f(0.5f,0.5f));
MainInternalWindow->setScalingInDrawingSurface(Vec2f(0.5f,0.5f));
MainInternalWindow->setDrawTitlebar(false);
MainInternalWindow->setResizable(false);
// Create the Drawing Surface
UIDrawingSurfaceRefPtr TutorialDrawingSurface = UIDrawingSurface::create();
TutorialDrawingSurface->setGraphics(TutorialGraphics);
TutorialDrawingSurface->setEventProducer(TutorialWindow);
TutorialDrawingSurface->openWindow(MainInternalWindow);
// Create the UI Foreground Object
UIForegroundRefPtr TutorialUIForeground = OSG::UIForeground::create();
TutorialUIForeground->setDrawingSurface(TutorialDrawingSurface);
// Create the SimpleSceneManager helper
mgr = new SimpleSceneManager;
// Tell the Manager what to manage
mgr->setWindow(TutorialWindow);
mgr->setRoot(scene);
// Add the UI Foreground Object to the Scene
ViewportRefPtr TutorialViewport = mgr->getWindow()->getPort(0);
TutorialViewport->addForeground(TutorialUIForeground);
// Show the whole Scene
mgr->showAll();
//Open Window
Vec2f WinSize(TutorialWindow->getDesktopSize() * 0.85f);
Pnt2f WinPos((TutorialWindow->getDesktopSize() - WinSize) *0.5);
TutorialWindow->openWindow(WinPos,
WinSize,
"16TextField");
//Enter main Loop
TutorialWindow->mainLoop();
osgExit();
return 0;
}
// Callback functions
// Redraw the window
void display(void)
{
mgr->redraw();
}
// React to size changes
void reshape(Vec2f Size)
{
mgr->resize(Size.x(), Size.y());
}
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
10
],
[
12,
13
],
[
15,
16
],
[
21,
22
],
[
24,
25
],
[
27,
28
],
[
35,
40
],
[
42,
44
],
[
46,
47
],
[
54,
54
],
[
77,
82
],
[
88,
88
],
[
92,
92
],
[
94,
95
],
[
98,
100
],
[
102,
106
],
[
108,
135
],
[
138,
147
],
[
149,
149
],
[
151,
158
],
[
160,
161
],
[
163,
163
],
[
166,
167
],
[
184,
185
],
[
187,
187
],
[
192,
192
],
[
194,
200
],
[
202,
204
],
[
207,
210
],
[
223,
235
],
[
237,
238
]
],
[
[
11,
11
],
[
14,
14
],
[
17,
20
],
[
23,
23
],
[
26,
26
],
[
29,
34
],
[
41,
41
],
[
45,
45
],
[
48,
53
],
[
55,
76
],
[
83,
87
],
[
89,
91
],
[
93,
93
],
[
96,
97
],
[
101,
101
],
[
107,
107
],
[
136,
137
],
[
148,
148
],
[
150,
150
],
[
159,
159
],
[
162,
162
],
[
164,
165
],
[
168,
183
],
[
186,
186
],
[
188,
191
],
[
193,
193
],
[
201,
201
],
[
205,
206
],
[
211,
222
],
[
236,
236
],
[
239,
239
]
]
]
|
ddfb5811da36dee84c02a2b343fd424d9bb47a00 | e7c45d18fa1e4285e5227e5984e07c47f8867d1d | /Common/ModelsC/MG/MG_SWF.H | effe40d15a1f56163e971e7543ad8eca2e276465 | []
| no_license | abcweizhuo/Test3 | 0f3379e528a543c0d43aad09489b2444a2e0f86d | 128a4edcf9a93d36a45e5585b70dee75e4502db4 | refs/heads/master | 2021-01-17T01:59:39.357645 | 2008-08-20T00:00:29 | 2008-08-20T00:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,011 | h | //================== SysCAD - Copyright Kenwalt (Pty) Ltd ===================
// $Nokeywords: $
//===========================================================================
// SysCAD Copyright Kenwalt (Pty) Ltd 1992
#ifndef __MG_SWF_H
#define __MG_SWF_H
#ifndef __SC_DEFS_H
#include "sc_defs.h"
#endif
#ifndef __FLWNODE_H
#include "flwnode.h"
#endif
#ifndef __MODELS_H
#include "models.h"
#endif
//#ifndef __M_BSTRES_H
// #include "m_bstres.h"
//#endif
//#ifndef __VALVE_GP_H
// #include "valve_gp.h"
//#endif
#define DllImportExport
DEFINE_TAGOBJ(SWF_Package);
class SWF_Package : public MN_BstRes
{
public:
SWF_Package(pTagObjClass pClass_, pchar TagIn, pTaggedObject pAttach, TagObjAttachment eAttach);
virtual ~SWF_Package (){};
// void Initialise();
virtual void BuildDataDefn(DataDefnBlk & DDB);
//virtual flag EvalFlowEquations(CSpPropInfo *pProps, int iJoinId, int FE);
};
#undef DllImportExport
#endif
| [
"[email protected]"
]
| [
[
[
1,
42
]
]
]
|
f6c8b416f30a0e85ef18c8c0d1eec5d29add0d50 | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume CXIII/11387.cpp | 04406cd9363974d82f350e1141bd8c5fded04cb1 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | cpp | /////////////////////////////////
// 11387 - The 3-Regular Graph
/////////////////////////////////
#include<stdio.h>
#include<string.h>
unsigned int i,j,k,n;
const char *imp = "Impossible";
int main(void) {
int i,j,n;
while(scanf("%u",&n) && n){
if(n > 3 && !(n%2)){
printf("%u\n",(3*n)>>1);
k = n>>1;
for(i = 1; i < k; i++){
printf("%u %u\n",i,i+1);
printf("%u %u\n",i,k+i);
}
printf("1 %u\n",n);
printf("%u %u\n",k,n);
while(i < n)
printf("%u %u\n",i,i+1), i++;
} else puts(imp);
}
}
| [
"[email protected]"
]
| [
[
[
1,
25
]
]
]
|
3b9602f7e7cd541e192f3be00b869261281af449 | 6a1a184ceb7be1f73c490fcbaf8fba7a64cab1ff | /Source/Fluidic/Fluid3D.h | 9f06a79777ce9bf50853f304700f616351c100cd | [
"MIT"
]
| permissive | alexsaen/fluidic | c8aa913ce03e8d3d9bc8091a31aa96a7d1e5b4ad | bf7eb0f3e9ca4e15f53623020c7f0313315f4e49 | refs/heads/master | 2020-12-24T15:14:17.261742 | 2010-04-06T13:10:54 | 2010-04-06T13:10:54 | 32,979,664 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,860 | h | /*
Copyright (c) 2010 Steven Leigh
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.
*/
#pragma once
#include "Fluid.h"
namespace Fluidic
{
/**
* \brief Sets up, solves and renders a 2d fluid in real time using the GPU.
*/
class Fluid3D : public Fluid
{
public:
Fluid3D(std::string cgHomeDir);
~Fluid3D(void);
void SetColorDensities(float r, float g, float b);
void GenerateCircularVortex();
void InjectCheckeredData();
void Update(float time);
void Render();
static FluidOptions DefaultOptions();
private:
static const int SlicesPerRow = 8;
inline int Index(int x, int y, int z) {
//transform 3d to 1d index (commenting - easier to read than above #define)
return 4 * (
x + // x coord INSIDE slab
SlicesPerRow * mOptions.SolverResolution.xi() * y + // y coord INSIDE slab
(z % SlicesPerRow) * mOptions.SolverResolution.xi() + // moves slab to appropriate x-slab offset
(z / SlicesPerRow) * SlicesPerRow * mOptions.SolverResolution.xi() * mOptions.SolverResolution.yi()// moves slab to appropriate y-slab offset
);
}
inline Vector Coords2D(Vector pos) {
//transform 3d coords to 2d coords (commenting - easier to read than above #define)
return Vector(
pos.x + (pos.zi() % SlicesPerRow)* mOptions.SolverResolution.xi(),
pos.y + (pos.zi() / SlicesPerRow)* mOptions.SolverResolution.yi()
);
}
// Methods...
void InitCallLists();
void InitPrograms(const std::string &cgHomeDir);
void SetGlobalProgramParams();
void InitTextures();
void InitBuffers();
void DeletePrograms();
void Poll(float time);
void UpdateStep(float time);
void ZCullStep(bool clearFirst);
void AdvectDataStep(float time);
void AdvectVelocityStep(float time);
void VorticityConfinementStep(float time);
void DiffuseDataStep(float time);
void DiffuseVelocityStep(float time);
void UpdatePressureStep(float time);
void SubtractPressureGradientStep(float time);
void PerturbDensityStep(float time);
void UpdateArbitraryBoundaryStep();
void UpdateOffsetStep();
void BoundaryVelocityStep();
void BoundaryPressureStep();
void InjectInkStep();
void PerturbFluidStep();
void PrePostUpdate(bool pre);
inline void GLCubeVertex(float x, float y, float z)
{
float x1 = x > 0.f ? 1.f : 0.f;
float y1 = y > 0.f ? 1.f : 0.f;
float z1 = z > 0.f ? 1.f : 0.f;
glColor3f(x1, y1, z1);
glTexCoord3f(x1, y1, z1);
glVertex3f(x, y, z);
}
Vector mSlabs; // 2d, number of slabs for texture atlas
CGprofile mCgVertexProfile; ///< vertex profile
// Additional programs for rendering
GPUProgram *mRaycastVProgram;
GPUProgram *mRaycastFProgram;
GPUProgram *mIlluminate;
// Additional texture for rendering
int backface;
};
} | [
"xwipeoutx@6c3c8482-2914-11df-ad47-1d73243ccc9f"
]
| [
[
[
1,
127
]
]
]
|
d05ec077b0bfbd73125ac5014c9a10f229dfe58a | 4ab592fb354f75b42181d5375d485031960aaa7d | /hgeParticleEditor/hgeParticleEditor.cpp | d36561f89d21f48730cbc136a5ba0b7ced5a534c | []
| no_license | CBE7F1F65/cca610e2e115c51cef211fafb0f66662 | 806ced886ed61762220b43300cb993ead00949dc | b3cdff63d689e2b1748e9cd93cedd7e8389a7057 | refs/heads/master | 2020-12-24T14:55:56.999923 | 2010-07-23T04:24:59 | 2010-07-23T04:24:59 | 32,192,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,166 | cpp | #include "../include/hge.h"
#include "../DES_GOBSTG/DES_GOBSTG/Header/Export.h"
#include "../DES_GOBSTG/DES_GOBSTG/Header/BResource.h"
#include "../DES_GOBSTG/DES_GOBSTG/Header/Data.h"
#include "../include/hgeEffectSystem.h"
#include "EditorRes.h"
#include "EditorUI.h"
HGE * hge = hgeCreate(HGE_VERSION);
bool FrameFunc()
{
if(hge->Input_GetKeyState(HGEK_ESCAPE))
return true;
if(hge->Input_GetKeyState(HGEK_CTRL) && hge->Input_GetKeyState(HGEK_BACKSPACE))
{
if(!eres.Load())
return true;
ui.timer = 0;
}
ui.Update();
return false;
}
bool RenderFunc()
{
if (hge->System_GetState(HGE_2DMODE))
{
Export::clientSetMatrix();
}
else
{
D3DXMATRIXA16 matWorld;
D3DXMatrixIdentity(&matWorld);
D3DXMATRIXA16 matView;
D3DXVECTOR3 vEyePt( M_ACTIVECLIENT_CENTER_X, M_ACTIVECLIENT_CENTER_Y, M_ACTIVECLIENT_HEIGHT/2);
D3DXVECTOR3 vLookatPt( M_ACTIVECLIENT_CENTER_X, M_ACTIVECLIENT_CENTER_Y, 0 );
D3DXVECTOR3 vUpVec( 0.0f, -1.0f, 0.0f );
D3DXMatrixLookAtLH( &matView, &vEyePt, &vLookatPt, &vUpVec );
D3DXMATRIXA16 matProj;
D3DXMATRIXA16 tmat;
D3DXMatrixIdentity(&matProj);
D3DXMatrixTranslation(&tmat, -0.5f, 0.5f, 0.0f);
D3DXMatrixMultiply(&matProj, &matProj, &tmat);
D3DXMatrixPerspectiveOffCenterLH( &tmat, -M_ACTIVECLIENT_CENTER_X, M_ACTIVECLIENT_CENTER_X+(M_CLIENT_WIDTH-M_ACTIVECLIENT_WIDTH), -M_CLIENT_CENTER_Y, M_CLIENT_CENTER_Y, M_CLIENT_HEIGHT/2, 0 );
D3DXMatrixMultiply(&matProj, &matProj, &tmat);
Export::clientSetMatrixUser(matWorld, matView, matProj);
}
hge->Gfx_BeginScene();
hge->Gfx_Clear(0x00000000);
ui.Render();
hge->Gfx_EndScene();
return false;
}
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
hge->System_SetState(HGE_FRAMEFUNC, FrameFunc);
hge->System_SetState(HGE_RENDERFUNC, RenderFunc);
if (!Export::clientInitial(false, true))
{
hge->System_SetState(HGE_TITLE, "HGE Effect System Editor by h5nc");
}
if(hge->System_Initiate())
{
Export::clientAfterInitial();
if(eres.Load())
{
hge->System_Start();
}
}
eres.Release();
// hge->System_Shutdown();
hge->Release();
} | [
"CBE7F1F65@4a173d03-4959-223b-e14c-e2eaa5fc8a8b"
]
| [
[
[
1,
86
]
]
]
|
2a7c1b83a8e9f3dd7736c65a389c5a2db62e43ea | 2dbbca065b62a24f47aeb7ec5cd7a4fd82083dd4 | /OUAN/OUAN/Src/Game/GameObject/GameObjectSnakeCreeper.h | e03925d771424d886ca453d9e18b48c12e89147d | []
| no_license | juanjmostazo/once-upon-a-night | 9651dc4dcebef80f0475e2e61865193ad61edaaa | f8d5d3a62952c45093a94c8b073cbb70f8146a53 | refs/heads/master | 2020-05-28T05:45:17.386664 | 2010-10-06T12:49:50 | 2010-10-06T12:49:50 | 38,101,059 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,067 | h | #ifndef GameObjectSnakeCreeperH_H
#define GameObjectSnakeCreeperH_H
#include "GameObject.h"
#include "../../Graphics/RenderComponent/RenderComponentInitial.h"
#include "../../Graphics/RenderComponent/RenderComponentPositional.h"
#include "../../Graphics/RenderComponent/RenderComponentEntity.h"
#include "../../Physics/PhysicsComponent/PhysicsComponentCharacter.h"
#include "../../Logic/LogicComponent/LogicComponentEnemy.h"
namespace OUAN
{
/// Class modelling a particular enemy type
class GameObjectSnakeCreeper : public GameObject, public boost::enable_shared_from_this<GameObjectSnakeCreeper>
{
private:
/// Visual component
RenderComponentEntityPtr mRenderComponentEntityDreams;
RenderComponentEntityPtr mRenderComponentEntityNightmares;
/// Positional component
RenderComponentInitialPtr mRenderComponentInitial;
RenderComponentPositionalPtr mRenderComponentPositional;
/// Physics information
PhysicsComponentCharacterPtr mPhysicsComponentCharacter;
/// Logic component: it'll represent the 'brains' of the game object
/// containing information on its current state, its life and health(if applicable),
/// or the world(s) the object belongs to
LogicComponentEnemyPtr mLogicComponentEnemy;
public:
/// Constructor
/// @param name name of the game object, specific to this class
/// @param id unique id of the game object
GameObjectSnakeCreeper(const std::string& name);
//Destructor
~GameObjectSnakeCreeper();
/// Set logic component
void setLogicComponentEnemy(LogicComponentEnemyPtr logicComponentEnemy);
/// return logic component
LogicComponentEnemyPtr getLogicComponentEnemy();
/// Return render component entity
/// @return render component entity
RenderComponentEntityPtr getRenderComponentEntityDreams() const;
RenderComponentEntityPtr getRenderComponentEntityNightmares() const;
/// Set render component
/// @param pRenderComponentEntity
void setRenderComponentEntityDreams(RenderComponentEntityPtr pRenderComponentEntityDreams);
void setRenderComponentEntityNightmares(RenderComponentEntityPtr pRenderComponentEntityNightmares);
/// Set positional component
/// @param pRenderComponentPositional the component containing the positional information
void setRenderComponentPositional(RenderComponentPositionalPtr pRenderComponentPositional);
/// Set initial component
void setRenderComponentInitial(RenderComponentInitialPtr pRenderComponentInitial);
/// Return positional component
/// @return positional component
RenderComponentPositionalPtr getRenderComponentPositional() const;
/// Return initial component
/// @return initial component
RenderComponentInitialPtr getRenderComponentInitial() const;
/// Set physics component
void setPhysicsComponentCharacter(PhysicsComponentCharacterPtr pPhysicsComponentCharacter);
/// Get physics component
PhysicsComponentCharacterPtr getPhysicsComponentCharacter() const;
/// Update object
virtual void update(double elapsedSeconds);
/// Reset object
virtual void reset();
/// React to a world change to the one given as a parameter
/// @param world world to change to
void changeToWorld(int newWorld, double perc);
void changeWorldFinished(int newWorld);
void changeWorldStarted(int newWorld);
bool hasPositionalComponent() const;
RenderComponentPositionalPtr getPositionalComponent() const;
bool hasPhysicsComponent() const;
PhysicsComponentPtr getPhysicsComponent() const;
bool hasRenderComponentEntity() const;
RenderComponentEntityPtr getEntityComponent() const;
/// Process collision event
/// @param gameObject which has collision with
void processCollision(GameObjectPtr pGameObject, Ogre::Vector3 pNormal);
/// Process collision event
/// @param gameObject which has collision with
void processEnterTrigger(GameObjectPtr pGameObject);
/// Process collision event
/// @param gameObject which has collision with
void processExitTrigger(GameObjectPtr pGameObject);
bool hasLogicComponent() const;
LogicComponentPtr getLogicComponent() const;
};
/// Information data structure to carry around data between the
/// level loader and the "GameObjectSnakeCreeper"
class TGameObjectSnakeCreeperParameters: public TGameObjectParameters
{
public:
/// Default constructor
TGameObjectSnakeCreeperParameters();
/// Default destructor
~TGameObjectSnakeCreeperParameters();
///Parameters specific to an Ogre Entity
TRenderComponentEntityParameters tRenderComponentEntityDreamsParameters;
TRenderComponentEntityParameters tRenderComponentEntityNightmaresParameters;
///Positional parameters
TRenderComponentPositionalParameters tRenderComponentPositionalParameters;
///Physics parameters
TPhysicsComponentCharacterParameters tPhysicsComponentCharacterParameters;
///Logic parameters
TLogicComponentEnemyParameters tLogicComponentEnemyParameters;
};
}
#endif | [
"wyern1@1610d384-d83c-11de-a027-019ae363d039",
"juanj.mostazo@1610d384-d83c-11de-a027-019ae363d039",
"ithiliel@1610d384-d83c-11de-a027-019ae363d039"
]
| [
[
[
1,
4
],
[
6,
9
],
[
11,
20
],
[
22,
55
],
[
59,
62
],
[
67,
74
],
[
79,
84
],
[
88,
89
],
[
93,
95
],
[
97,
105
],
[
110,
139
]
],
[
[
5,
5
],
[
10,
10
],
[
21,
21
],
[
56,
58
],
[
63,
66
],
[
75,
78
],
[
96,
96
]
],
[
[
85,
87
],
[
90,
92
],
[
106,
109
]
]
]
|
32d2112fb60de37c9ac8d9ff94cd15c48104b145 | 8f1601062c4a5452f2bdd0f75f3d12a79b98ba62 | /examples/aegis/me519/terrain/FlyCamera.h | 11ad69b5598dd24e818094eff20ec8b49153d286 | []
| no_license | chadaustin/isugamedev | 200a54f55a2581cd2c62c94eb96b9e238abcf3dd | d3008ada042d2dd98c6e05711773badf6f1fd85c | refs/heads/master | 2016-08-11T17:59:38.504631 | 2005-01-25T23:17:11 | 2005-01-25T23:17:11 | 36,483,500 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | h | #ifndef FLY_CAMERA_H
#define FLY_CAMERA_H
#include "Camera.h"
#include "Vector.h"
class FlyCamera : public Camera {
public:
FlyCamera();
~FlyCamera();
const char* getName();
void apply();
void update(int elapsedTime);
void onKeyDown(unsigned char key);
void onKeyUp(unsigned char key);
void onSpecialDown(int key);
void onSpecialUp(int key);
private:
Vector mPosition;
float mVelocity;
float mVerticalVelocity;
float mHeading;
float mPitch;
float mPitchVelocity;
bool mLeftPressed;
bool mRightPressed;
bool mUpPressed;
bool mDownPressed;
};
#endif
| [
"aegis@84b32ba4-53c3-423c-be69-77cca6335494"
]
| [
[
[
1,
38
]
]
]
|
da3d793958ce912ed7d393f9ad8a8a42e672b640 | b14d5833a79518a40d302e5eb40ed5da193cf1b2 | /cpp/extern/xercesc++/2.6.0/src/xercesc/framework/psvi/XSAttributeDeclaration.hpp | a86de5aa3252f68741802869bb500cd5466f5070 | [
"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 | 7,425 | hpp | /*
* 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: XSAttributeDeclaration.hpp,v $
* Revision 1.10 2004/09/08 13:56:07 peiyongz
* Apache License Version 2.0
*
* Revision 1.9 2004/05/04 19:02:40 cargilld
* Enable IDs to work on all kinds of schema components
*
* Revision 1.8 2003/12/24 17:42:02 knoaman
* Misc. PSVI updates
*
* Revision 1.7 2003/12/01 23:23:26 neilg
* fix for bug 25118; thanks to Jeroen Witmond
*
* Revision 1.6 2003/11/21 22:34:45 neilg
* More schema component model implementation, thanks to David Cargill.
* In particular, this cleans up and completes the XSModel, XSNamespaceItem,
* XSAttributeDeclaration and XSAttributeGroup implementations.
*
* Revision 1.5 2003/11/21 17:19:30 knoaman
* PSVI update.
*
* Revision 1.4 2003/11/14 22:47:53 neilg
* fix bogus log message from previous commit...
*
* Revision 1.3 2003/11/14 22:33:30 neilg
* Second phase of schema component model implementation.
* Implement XSModel, XSNamespaceItem, and the plumbing necessary
* to connect them to the other components.
* Thanks to David Cargill.
*
* Revision 1.2 2003/11/06 15:30:04 neilg
* first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse.
*
* Revision 1.1 2003/09/16 14:33:36 neilg
* PSVI/schema component model classes, with Makefile/configuration changes necessary to build them
*
*/
#if !defined(XSATTRIBUTEDECLARATION_HPP)
#define XSATTRIBUTEDECLARATION_HPP
#include <xercesc/framework/psvi/XSObject.hpp>
XERCES_CPP_NAMESPACE_BEGIN
/**
* This class describes all properties of a Schema Attribute
* Declaration component.
* This is *always* owned by the validator /parser object from which
* it is obtained.
*/
// forward declarations
class XSAnnotation;
class XSComplexTypeDefinition;
class XSSimpleTypeDefinition;
class SchemaAttDef;
class XMLPARSER_EXPORT XSAttributeDeclaration : public XSObject
{
public:
// Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors */
//@{
/**
* The default constructor
*
* @param attDef
* @param typeDef
* @param annot
* @param xsModel
* @param scope
* @param enclosingCTDefinition
* @param manager The configurable memory manager
*/
XSAttributeDeclaration
(
SchemaAttDef* const attDef
, XSSimpleTypeDefinition* const typeDef
, XSAnnotation* const annot
, XSModel* const xsModel
, XSConstants::SCOPE scope
, XSComplexTypeDefinition* enclosingCTDefinition
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
);
//@};
/** @name Destructor */
//@{
~XSAttributeDeclaration();
//@}
//---------------------
/** @name overridden XSObject methods */
//@{
/**
* The name of type <code>NCName</code> of this declaration as defined in
* XML Namespaces.
*/
const XMLCh* getName();
/**
* The [target namespace] of this object, or <code>null</code> if it is
* unspecified.
*/
const XMLCh* getNamespace();
/**
* A namespace schema information item corresponding to the target
* namespace of the component, if it's globally declared; or null
* otherwise.
*/
XSNamespaceItem* getNamespaceItem();
//@}
/** @name XSAttributeDeclaration methods **/
//@{
/**
* [type definition]: A simple type definition
*/
XSSimpleTypeDefinition *getTypeDefinition() const;
/**
* Optional. One of <code>SCOPE_GLOBAL</code>, <code>SCOPE_LOCAL</code>,
* or <code>SCOPE_ABSENT</code>. If the scope is local, then the
* <code>enclosingCTDefinition</code> is present.
*/
XSConstants::SCOPE getScope() const;
/**
* The complex type definition for locally scoped declarations (see
* <code>scope</code>).
*/
XSComplexTypeDefinition *getEnclosingCTDefinition();
/**
* Value constraint: one of <code>VC_NONE, VC_DEFAULT, VC_FIXED</code>.
*/
XSConstants::VALUE_CONSTRAINT getConstraintType() const;
/**
* Value constraint: The actual value with respect to the [type definition
* ].
*/
const XMLCh *getConstraintValue();
/**
* Optional. Annotation.
*/
XSAnnotation *getAnnotation() const;
//@}
//----------------------------------
/** methods needed by implementation */
//@{
bool getRequired() const;
//@}
private:
void setEnclosingCTDefinition(XSComplexTypeDefinition* const toSet);
friend class XSObjectFactory;
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
XSAttributeDeclaration(const XSAttributeDeclaration&);
XSAttributeDeclaration & operator=(const XSAttributeDeclaration &);
protected:
// -----------------------------------------------------------------------
// data members
// -----------------------------------------------------------------------
SchemaAttDef* fAttDef;
XSSimpleTypeDefinition* fTypeDefinition;
XSAnnotation* fAnnotation;
XSConstants::SCOPE fScope;
XSComplexTypeDefinition* fEnclosingCTDefinition;
};
// ---------------------------------------------------------------------------
// XSAttributeDeclaration: inline methods
// ---------------------------------------------------------------------------
inline XSSimpleTypeDefinition* XSAttributeDeclaration::getTypeDefinition() const
{
return fTypeDefinition;
}
inline XSAnnotation *XSAttributeDeclaration::getAnnotation() const
{
return fAnnotation;
}
inline XSConstants::SCOPE XSAttributeDeclaration::getScope() const
{
return fScope;
}
inline XSComplexTypeDefinition *XSAttributeDeclaration::getEnclosingCTDefinition()
{
return fEnclosingCTDefinition;
}
inline void XSAttributeDeclaration::setEnclosingCTDefinition
(
XSComplexTypeDefinition* const toSet
)
{
fEnclosingCTDefinition = toSet;
}
XERCES_CPP_NAMESPACE_END
#endif
| [
"[email protected]"
]
| [
[
[
1,
244
]
]
]
|
e90e3ed1a5943bc7d6c78abd92ea3ed9d280f3f7 | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume CII/10209.cpp | 6e562eb0f8fcabcde1d83575360e1b8ce500b518 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | /////////////////////////////////
// 10209 - Is This Integration ?
/////////////////////////////////
#include<cstdio>
double a,a1,a2,a3;
int main(void){
while(scanf("%lf",&a)!=EOF){
a*=a;
a1 = 0.315146743627720*a;
a2 = 0.511299166334351*a;
a3 = 0.173554090037927*a;
printf("%.3lf %.3lf %.3lf\n",a1,a2,a3);
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
16
]
]
]
|
57330505796fe246f8efb22bfaf4ec8dd0c8280b | b12c8bedabab93fd03df9dd300f66ce85d269ad2 | /Source/Vect2.cpp | 501270f078f1998d62abffb5c5c5909513b9db50 | []
| no_license | olegp/v3d | 114de0dbc4702f4ca7e388d648ab32bef135d6f6 | a09df4398e402d19405fddc7ebfc52bbf13e8aca | refs/heads/master | 2020-12-24T16:50:12.760019 | 2010-07-14T12:48:35 | 2010-07-14T12:48:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 935 | cpp | // by Oleg Podsechin
#include "Vect2.h"
void Vect2::operator *= (float scaler)
{
x *= scaler; y *= scaler;
}
void Vect2::operator += (const Vect2 &p)
{
x += p.x; y += p.y;
}
void Vect2::operator -= (const Vect2 &p)
{
x -= p.x; y -= p.y;
}
void Vect2::Zero()
{
x = y = 0.f;
}
Vect2 operator -(const Vect2 &p)
{
return Vect2(-p.x, -p.y);
}
Vect2 operator +(const Vect2 &a, const Vect2 &b)
{
return Vect2(a.x + b.x, a.y + b.y);
}
Vect2 operator -(const Vect2 &a, const Vect2 &b)
{
return Vect2(a.x - b.x, a.y - b.y);
}
Vect2 operator *(const Vect2 &p, const Mat3 &m)
{
return Vect2( m._11*p.x + m._21*p.y + m._31, m._12*p.x + m._22*p.y + m._32 );
}
Vect2 operator *(const Vect2 &p, const Mat2 &m)
{
return Vect2( m._11*p.x + m._21*p.y, m._12*p.x + m._22*p.y );
}
bool Vect2::operator == (const Vect2& v)
{
return (x == v.x && y == v.y);
}
| [
"[email protected]"
]
| [
[
[
1,
52
]
]
]
|
168954fc975fee159bbab988b53babb6758be8ad | b2155efef00dbb04ae7a23e749955f5ec47afb5a | /source/OECore/OEMesh_Impl.cpp | 02f15609b7f01f3c47ff759581eb6090d69b85ca | []
| no_license | zjhlogo/originengine | 00c0bd3c38a634b4c96394e3f8eece86f2fe8351 | a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f | refs/heads/master | 2021-01-20T13:48:48.015940 | 2011-04-21T04:10:54 | 2011-04-21T04:10:54 | 32,371,356 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,650 | cpp | /*!
* \file OEMesh_Impl.cpp
* \date 30-7-2009 16:50:37
*
*
* \author zjhlogo ([email protected])
*/
#include "OEMesh_Impl.h"
#include "OEPiece_Impl.h"
#include <OEBase/IOEFileMgr.h>
#include <OECore/OEFmtMesh.h>
COEMesh_Impl::COEMesh_Impl(const tstring& strFile)
{
Init();
m_bOK = CreatePieces(strFile);
}
COEMesh_Impl::~COEMesh_Impl()
{
Destroy();
}
void COEMesh_Impl::Init()
{
m_vBoundingBoxMin.Init(COEMath::FLOAT_MAX, COEMath::FLOAT_MAX, COEMath::FLOAT_MAX);
m_vBoundingBoxMax.Init(COEMath::FLOAT_MIN, COEMath::FLOAT_MIN, COEMath::FLOAT_MIN);
}
void COEMesh_Impl::Destroy()
{
DestroyPieces();
}
int COEMesh_Impl::GetNumPieces() const
{
return (int)m_vPiece.size();
}
IOEPiece* COEMesh_Impl::GetPiece(int nIndex) const
{
if (nIndex < 0 || nIndex >= (int)m_vPiece.size()) return NULL;
return m_vPiece[nIndex];
}
IOEPiece* COEMesh_Impl::FindPiece(const tstring& strName) const
{
for (TV_PIECE::const_iterator it = m_vPiece.begin(); it != m_vPiece.end(); ++it)
{
if ((*it)->GetName() == strName) return (*it);
}
return NULL;
}
const CVector3& COEMesh_Impl::GetBoundingBoxMin() const
{
return m_vBoundingBoxMin;
}
const CVector3& COEMesh_Impl::GetBoundingBoxMax() const
{
return m_vBoundingBoxMax;
}
bool COEMesh_Impl::CreatePieces(const tstring& strFile)
{
DestroyPieces();
IOEFile* pFile = g_pOEFileMgr->OpenFile(strFile);
if (!pFile) return false;
COEFmtMesh::FILE_HEADER Header;
pFile->Read(&Header, sizeof(Header));
if (Header.nMagicNumber != COEFmtMesh::MAGIC_NUMBER
|| Header.nVersion != COEFmtMesh::CURRENT_VERSION)
{
SAFE_RELEASE(pFile);
return false;
}
m_vBoundingBoxMin.Init(Header.fBoundingBoxMin[0], Header.fBoundingBoxMin[1], Header.fBoundingBoxMin[2]);
m_vBoundingBoxMax.Init(Header.fBoundingBoxMax[0], Header.fBoundingBoxMax[1], Header.fBoundingBoxMax[2]);
// read piece info
std::vector<COEFmtMesh::PIECE> vPieces;
if (Header.nNumPieces > 0)
{
vPieces.resize(Header.nNumPieces);
pFile->Read(&vPieces[0], sizeof(COEFmtMesh::PIECE)*Header.nNumPieces);
}
// create pieces
for (int i = 0; i < Header.nNumPieces; ++i)
{
COEPiece_Impl* pPiece = new COEPiece_Impl(vPieces[i], pFile);
if (!pPiece || !pPiece->IsOK())
{
SAFE_RELEASE(pFile);
DestroyPieces();
return false;
}
m_vPiece.push_back(pPiece);
}
SAFE_RELEASE(pFile);
return true;
}
void COEMesh_Impl::DestroyPieces()
{
for (TV_PIECE::iterator it = m_vPiece.begin(); it != m_vPiece.end(); ++it)
{
IOEPiece* pPiece = (*it);
SAFE_RELEASE(pPiece);
}
m_vPiece.clear();
}
| [
"zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571"
]
| [
[
[
1,
119
]
]
]
|
13032523887b3642cbe2df0d65db80fb69f538c0 | 96fefafdfbb413a56e0a2444fcc1a7056afef757 | /MQ2Main/MQ2DataTypes.cpp | da1a338b6aa1b5d33e4e3d931ce5e7196440b625 | []
| no_license | kevrgithub/peqtgc-mq2-sod | ffc105aedbfef16060769bb7a6fa6609d775b1fa | d0b7ec010bc64c3f0ac9dc32129a62277b8d42c0 | refs/heads/master | 2021-01-18T18:57:16.627137 | 2011-03-06T13:05:41 | 2011-03-06T13:05:41 | 32,849,784 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 179,932 | cpp | /*****************************************************************************
MQ2Main.dll: MacroQuest2's extension DLL for EverQuest
Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
******************************************************************************/
#if !defined(CINTERFACE)
#error /DCINTERFACE
#endif
#define DBG_SPEW
#include "MQ2Main.h"
#ifdef ISXEQ
#define ISINDEX() (argc>0)
#define ISNUMBER() (IsNumber(argv[0]))
#define GETNUMBER() (atoi(argv[0]))
#define GETFIRST() argv[0]
#else
#define ISINDEX() (Index[0])
#define ISNUMBER() (IsNumber(Index))
#define GETNUMBER() (atoi(Index))
#define GETFIRST() Index
#endif
#ifndef ISXEQ
class MQ2FloatType *pFloatType=0;
class MQ2IntType *pIntType=0;
class MQ2ByteType *pByteType=0;
class MQ2BoolType *pBoolType=0;
class MQ2StringType *pStringType=0;
class MQ2MathType *pMathType=0;
class MQ2TimeType *pTimeType=0;
class MQ2ArrayType *pArrayType=0;
#endif
class MQ2SpawnType *pSpawnType=0;
class MQ2BuffType *pBuffType=0;
class MQ2SpellType *pSpellType=0;
class MQ2TicksType *pTicksType=0;
class MQ2CharacterType *pCharacterType=0;
class MQ2ClassType *pClassType=0;
class MQ2RaceType *pRaceType=0;
class MQ2BodyType *pBodyType=0;
class MQ2SkillType *pSkillType=0;
class MQ2AltAbilityType *pAltAbilityType=0;
class MQ2GroundType *pGroundType=0;
class MQ2SwitchType *pSwitchType=0;
class MQ2CorpseType *pCorpseType=0;
class MQ2MacroType *pMacroType=0;
class MQ2MacroQuestType *pMacroQuestType=0;
class MQ2WindowType *pWindowType=0;
class MQ2MerchantType *pMerchantType=0;
class MQ2ZoneType *pZoneType=0;
class MQ2CurrentZoneType *pCurrentZoneType=0;
class MQ2ItemType *pItemType=0;
class MQ2DeityType *pDeityType=0;
class MQ2ArgbType *pArgbType=0;
class MQ2TypeType *pTypeType=0;
class MQ2HeadingType *pHeadingType=0;
class MQ2InvSlotType *pInvSlotType=0;
class MQ2TimerType *pTimerType=0;
class MQ2PluginType *pPluginType=0;
class MQ2RaidType *pRaidType=0;
class MQ2RaidMemberType *pRaidMemberType=0;
class MQ2GroupType *pGroupType=0;
class MQ2GroupMemberType *pGroupMemberType=0;
class MQ2EvolvingItemType *pEvolvingItemType=0;
class MQ2DynamicZoneType *pDynamicZoneType=0;
class MQ2DZMemberType *pDZMemberType=0;
class MQ2FellowshipType *pFellowshipType=0;
class MQ2FellowshipMemberType *pFellowshipMemberType=0;
class MQ2FriendsType *pFriendsType=0;
class MQ2TargetType *pTargetType=0;
#ifndef ISXEQ
void InitializeMQ2DataTypes()
{
pFloatType = new MQ2FloatType;
pIntType = new MQ2IntType;
pByteType = new MQ2ByteType;
pStringType = new MQ2StringType;
pSpawnType = new MQ2SpawnType;
pSpellType = new MQ2SpellType;
pBuffType = new MQ2BuffType;
pTicksType = new MQ2TicksType;
pCharacterType = new MQ2CharacterType;
pClassType=new MQ2ClassType;
pRaceType=new MQ2RaceType;
pGroundType = new MQ2GroundType;
pSwitchType = new MQ2SwitchType;
pMacroType = new MQ2MacroType;
pMacroQuestType = new MQ2MacroQuestType;
pMathType = new MQ2MathType;
pWindowType = new MQ2WindowType;
pMerchantType = new MQ2MerchantType;
pZoneType = new MQ2ZoneType;
pItemType = new MQ2ItemType;
pBoolType = new MQ2BoolType;
pBodyType = new MQ2BodyType;
pDeityType = new MQ2DeityType;
pArgbType = new MQ2ArgbType;
pCorpseType = new MQ2CorpseType;
pCurrentZoneType = new MQ2CurrentZoneType;
pTypeType = new MQ2TypeType;
pTimeType = new MQ2TimeType;
pHeadingType = new MQ2HeadingType;
pInvSlotType = new MQ2InvSlotType;
pArrayType = new MQ2ArrayType;
pTimerType = new MQ2TimerType;
pPluginType = new MQ2PluginType;
pSkillType = new MQ2SkillType;
pAltAbilityType = new MQ2AltAbilityType;
pRaidType = new MQ2RaidType;
pRaidMemberType = new MQ2RaidMemberType;
pGroupType = new MQ2GroupType;
pGroupMemberType = new MQ2GroupMemberType;
pGroupMemberType->SetInheritance(pSpawnType);
pEvolvingItemType=new MQ2EvolvingItemType;
pDynamicZoneType=new MQ2DynamicZoneType;
pDZMemberType=new MQ2DZMemberType;
pFellowshipType=new MQ2FellowshipType;
pFellowshipMemberType=new MQ2FellowshipMemberType;
pFriendsType = new MQ2FriendsType;
pTargetType = new MQ2TargetType;
// NOTE: SetInheritance does NOT make it inherit, just notifies the syntax checker...
pCharacterType->SetInheritance(pSpawnType);
pBuffType->SetInheritance(pSpellType);
// pCurrentZoneType->SetInheritance(pZoneType);
pRaidMemberType->SetInheritance(pSpawnType);
pTargetType->SetInheritance(pSpawnType);
}
void ShutdownMQ2DataTypes()
{
delete pSpawnType;
delete pFloatType;
delete pIntType;
delete pByteType;
delete pStringType;
delete pBuffType;
delete pSpellType;
delete pTicksType;
delete pCharacterType;
delete pClassType;
delete pRaceType;
delete pGroundType;
delete pSwitchType;
delete pMacroType;
delete pMacroQuestType;
delete pMathType;
delete pWindowType;
delete pMerchantType;
delete pZoneType;
delete pItemType;
delete pBoolType;
delete pBodyType;
delete pDeityType;
delete pArgbType;
delete pCorpseType;
delete pCurrentZoneType;
delete pTypeType;
delete pTimeType;
delete pHeadingType;
delete pArrayType;
delete pTimerType;
delete pPluginType;
delete pSkillType;
delete pAltAbilityType;
delete pRaidType;
delete pRaidMemberType;
delete pGroupType;
delete pGroupMemberType;
delete pEvolvingItemType;
delete pDynamicZoneType;
delete pFriendsType;
delete pTargetType;
}
bool MQ2TypeType::GETMEMBER()
{
#define pType ((MQ2Type*)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2TypeType::FindMember(Member);
if (!pMember)
return false;
switch((TypeMembers)pMember->ID)
{
case Name:
Dest.Ptr=pType->GetName();
Dest.Type=pStringType;
return true;
case TypeMember:
if (ISINDEX())
{
if (ISNUMBER())
{
// name by number
if (Dest.Ptr=pType->GetMemberName(GETNUMBER()))
{
Dest.Type=pStringType;
return true;
}
}
else
{
// number by name
if (pType->GetMemberID(Index,Dest.DWord))
{
Dest.Type=pIntType;
return true;
}
}
}
return false;
}
return false;
#undef pType
}
bool MQ2PluginType::GETMEMBER()
{
#define pPlugin ((PMQPLUGIN)VarPtr.Ptr)
if (!pPlugin)
return false;
PMQ2TYPEMEMBER pMember=MQ2PluginType::FindMember(Member);
if (!pMember)
return false;
switch((PluginMembers)pMember->ID)
{
case Name:
Dest.Ptr=pPlugin->szFilename;
Dest.Type=pStringType;
return true;
case Version:
Dest.Float=pPlugin->fpVersion;
Dest.Type=pFloatType;
return true;
}
return false;
#undef pPlugin
}
bool MQ2FloatType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2FloatType::FindMember(Member);
if (!pMember)
{
return false;
}
switch((FloatMembers)pMember->ID)
{
case Deci:
sprintf(DataTypeTemp,"%.1f",VarPtr.Float);
Dest.Type=pStringType;
Dest.Ptr=&DataTypeTemp[0];
return true;
case Centi:
sprintf(DataTypeTemp,"%.2f",VarPtr.Float);
Dest.Type=pStringType;
Dest.Ptr=&DataTypeTemp[0];
return true;
case Milli:
sprintf(DataTypeTemp,"%.3f",VarPtr.Float);
Dest.Type=pStringType;
Dest.Ptr=&DataTypeTemp[0];
return true;
case Int:
Dest.Type=pIntType;
Dest.Int=(int)(VarPtr.Float);
return true;
case Precision:
if (ISNUMBER())
{
sprintf(DataTypeTemp,"%.*f",GETNUMBER(),VarPtr.Float);
Dest.Type=pStringType;
Dest.Ptr=&DataTypeTemp[0];
return true;
}
return false;
}
return false;
}
bool MQ2IntType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2IntType::FindMember(Member);
if (!pMember)
{
return false;
}
switch((IntMembers)pMember->ID)
{
case Float:
Dest.Float=(FLOAT)1.0f*(VarPtr.Int);
Dest.Type=pFloatType;
return true;
case Hex:
sprintf(DataTypeTemp,"%x",VarPtr.Int);
Dest.Ptr=&DataTypeTemp[0],
Dest.Type=pStringType;
return true;
case Reverse:
{
Dest.Array[0]=VarPtr.Array[3];
Dest.Array[1]=VarPtr.Array[2];
Dest.Array[2]=VarPtr.Array[1];
Dest.Array[3]=VarPtr.Array[0];
Dest.Type=pIntType;
}
return true;
}
return false;
}
bool MQ2StringType::GETMEMBER()
{
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2StringType::FindMember(Member);
if (!pMember)
{
return false;
}
switch((StringMembers)pMember->ID)
{
case Length:
Dest.DWord=strlen((const char *)VarPtr.Ptr);
Dest.Type=pIntType;
return true;
case Left:
if (!ISINDEX())
return false;
{
int Len=GETNUMBER();
if (Len==0)
return false;
if (Len>0)
{
unsigned long StrLen=strlen((char *)VarPtr.Ptr);
if ((unsigned long)Len>StrLen)
Len=StrLen;
memmove(DataTypeTemp,(char *)VarPtr.Ptr,Len);
DataTypeTemp[Len]=0;
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
else
{
Len=-Len;
unsigned long StrLen=strlen((char *)VarPtr.Ptr);
if ((unsigned long)Len>=StrLen)
{
Dest.Ptr="";
Dest.Type=pStringType;
return true;
}
memmove(DataTypeTemp,(char *)VarPtr.Ptr,StrLen-Len);
DataTypeTemp[StrLen-Len]=0;
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
}
return true;
case Right:
if (!ISINDEX())
return false;
{
int Len=GETNUMBER();
if (Len==0)
return false;
if (Len<0)
{
Len=-Len;
unsigned long StrLen=strlen((char *)VarPtr.Ptr);
if ((unsigned long)Len>=StrLen)
{
Dest.Ptr="";
Dest.Type=pStringType;
return true;
}
char *pStart=(char*)VarPtr.Ptr;
pStart=&pStart[Len];
Len=StrLen-Len;
memmove(DataTypeTemp,pStart,Len+1);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
else
{
char *pStart=(char*)VarPtr.Ptr;
pStart=&pStart[strlen(pStart)-Len];
if (pStart<VarPtr.Ptr)
pStart=(char*)VarPtr.Ptr;
memmove(DataTypeTemp,pStart,Len+1);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
}
return true;
case Find:
if (!ISINDEX())
return false;
{
char A[MAX_STRING]={0};
char B[MAX_STRING]={0};
strcpy(A,(char*)VarPtr.Ptr);
strcpy(B,(char*)Index);
strlwr(A);
strlwr(B);
if (char *pFound=strstr(A,B))
{
Dest.DWord=(pFound-&A[0])+1;
Dest.Type=pIntType;
return true;
}
}
return false;
case Replace:
if (!ISINDEX())
return false;
{
char A[MAX_STRING]={0};
char B[MAX_STRING]={0};
char C[MAX_STRING]={0};
char *pos;
if (!ISINDEX())
return false;
if (PCHAR pComma=strchr(Index,','))
{
strcpy(A,(char*)VarPtr.Ptr);
*pComma=0;
strcpy(B,(char*)Index);
*pComma=',';
strcpy(C,(char*)&pComma[1]);
if (!A || !B || !C)
return false;
while( ( pos = strstr( A , B ) ) != NULL ) /* if -> while */
{
DataTypeTemp[0] = '\0' ;
strncat( DataTypeTemp , A , pos - A ) ;
strcat( DataTypeTemp , C ) ;
strcat( DataTypeTemp , pos + strlen( B ) ) ;
strcpy( A, DataTypeTemp); /* added */
}
if (Dest.Ptr = DataTypeTemp)
{
Dest.Type = pStringType;
return true;
}
}
}
case Upper:
strcpy(DataTypeTemp,(char*)VarPtr.Ptr);
strupr(DataTypeTemp);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Lower:
strcpy(DataTypeTemp,(char*)VarPtr.Ptr);
strlwr(DataTypeTemp);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Compare:
if (ISINDEX())
{
Dest.Int=stricmp((char*)VarPtr.Ptr,Index);
Dest.Type=pIntType;
return true;
}
return false;
case CompareCS:
if (ISINDEX())
{
Dest.Int=strcmp((char*)VarPtr.Ptr,Index);
Dest.Type=pIntType;
return true;
}
return false;
case Mid:
{
if (PCHAR pComma=strchr(Index,','))
{
*pComma=0;
pComma++;
PCHAR pStr=(char *)VarPtr.Ptr;
unsigned long nStart=GETNUMBER()-1;
unsigned long Len=atoi(pComma);
if (nStart>=strlen(pStr))
{
Dest.Ptr="";
Dest.Type=pStringType;
return true;
}
pStr+=nStart;
unsigned long StrLen=strlen(pStr);
if (Len>StrLen)
Len=StrLen;
memmove(DataTypeTemp,pStr,Len);
DataTypeTemp[Len]=0;
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
return false;
case Equal:
if (ISINDEX())
{
Dest.DWord=(stricmp((char*)VarPtr.Ptr,Index)==0);
Dest.Type=pBoolType;
return true;
}
return false;
case NotEqual:
if (ISINDEX())
{
Dest.DWord=(stricmp((char*)VarPtr.Ptr,Index)!=0);
Dest.Type=pBoolType;
return true;
}
return false;
case EqualCS:
if (ISINDEX())
{
Dest.DWord=(strcmp((char*)VarPtr.Ptr,Index)==0);
Dest.Type=pBoolType;
return true;
}
return false;
case NotEqualCS:
if (ISINDEX())
{
Dest.DWord=(strcmp((char*)VarPtr.Ptr,Index)!=0);
Dest.Type=pBoolType;
return true;
}
return false;
case Count:
if (ISINDEX())
{
Dest.DWord=0;
PCHAR pLast=(PCHAR)VarPtr.Ptr-1;
while(pLast=strchr(&pLast[1],Index[0]))
Dest.DWord++;
Dest.Type=pIntType;
return true;
}
return false;
case Arg:
if (IsNumberToComma(Index))
{
CHAR Temp[MAX_STRING]={0};
strcpy(Temp,(char *)VarPtr.Ptr);
if (PCHAR pComma=strchr(Index,','))
{
*pComma=0;
GetArg(DataTypeTemp,Temp,GETNUMBER(),FALSE,FALSE,FALSE,pComma[1]);
*pComma=',';
if (DataTypeTemp[0])
{
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
else
{
GetArg(DataTypeTemp,Temp,GETNUMBER());
if (DataTypeTemp[0])
{
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
}
return false;
case Token:
if (IsNumberToComma(Index))
{
DWORD N=GETNUMBER();
if (!N)
return false;
// CHAR Temp[MAX_STRING]={0};
// strcpy(Temp,(char *)VarPtr.Ptr);
if (PCHAR pComma=strchr(Index,','))
{
*pComma=0;
PCHAR pPos=(PCHAR)VarPtr.Ptr;//strchr((char *)VarPtr.Ptr,pComma[1]);
N--;
while(N && pPos)
{
pPos=strchr(&pPos[1],pComma[1]);
N--;
}
*pComma=',';
if (pPos)
{
if (pPos!=(PCHAR)VarPtr.Ptr)
pPos++;
PCHAR pEnd=strchr(&pPos[0],pComma[1]);
if (pEnd)
{
if (pEnd!=pPos)
{
strncpy(DataTypeTemp,pPos,pEnd-pPos);
DataTypeTemp[pEnd-pPos]=0;
}
else
DataTypeTemp[0]=0;
}
else
strcpy(DataTypeTemp,pPos);
// allows empty returned strings
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
}
return false;
}
return false;
}
bool MQ2ArrayType::GETMEMBER()
{
#define pArray ((CDataArray*)VarPtr.Ptr)
if (!pArray)
return false;
PMQ2TYPEMEMBER pMember=MQ2ArrayType::FindMember(Member);
if (!pMember)
return false;
switch((ArrayMembers)pMember->ID)
{
case Dimensions:
Dest.DWord=pArray->nExtents;
Dest.Type=pIntType;
return true;
case Size:
if (ISINDEX())
{
DWORD N=GETNUMBER()-1;
if (N<pArray->nExtents)
{
Dest.DWord=pArray->pExtents[N];
Dest.Type=pIntType;
return true;
}
}
else
{
Dest.DWord=pArray->TotalElements;
Dest.Type=pIntType;
return true;
}
return false;
}
return false;
#undef pArray
}
bool MQ2MathType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2MathType::FindMember(Member);
if (!pMember)
return false;
if (!ISINDEX())
return false;
DOUBLE CalcResult;
switch((MathMembers)pMember->ID)
{
case Abs:
if (Calculate(Index,CalcResult))
{
Dest.Float=(FLOAT)CalcResult;
if (Dest.Float<0)
Dest.Float*=-1;
Dest.Type=pFloatType;
return true;
}
return false;
case Rand:
Dest.DWord=atol(Index);
if (Dest.DWord==0 || Dest.DWord==0xFFFFFFFF)
return false;
Dest.DWord=rand() % Dest.DWord;
Dest.Type=pIntType;
return true;
case Sqrt:
if (Calculate(Index,CalcResult))
{
Dest.Float=(FLOAT)sqrt(CalcResult);
Dest.Type=pFloatType;
return true;
}
return false;
case Calc:
if (Calculate(Index,CalcResult))
{
Dest.Float=(FLOAT)CalcResult;
Dest.Type=pFloatType;
return true;
}
return false;
case Sin:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)sin(CalcResult/DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Cos:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)cos(CalcResult/DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Tan:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)tan(CalcResult/DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Asin:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)(asin(CalcResult)*DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Acos:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)(acos(CalcResult)*DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Atan:
if (Calculate(Index,CalcResult))
{
Dest.Float=(float)(atan(CalcResult)*DegToRad);
Dest.Type=pFloatType;
return true;
}
return false;
case Not:
Dest.DWord=~atol(Index);
Dest.Type=pIntType;
return true;
case Hex:
sprintf(DataTypeTemp,"%x",atol(Index));
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Dec:
sscanf(Index,"%x",&Dest.DWord);
Dest.Type=pIntType;
return true;
case Distance:
if (ISINDEX())
{
FLOAT P1[3];
FLOAT P2[3];
P1[0]=P2[0]=((PSPAWNINFO)pCharSpawn)->Y;
P1[1]=P2[1]=((PSPAWNINFO)pCharSpawn)->X;
P1[2]=P2[2]=((PSPAWNINFO)pCharSpawn)->Z;
if (PCHAR pColon=strchr(Index,':'))
{
*pColon=0;
if (PCHAR pComma=strchr(&pColon[1],','))
{
*pComma=0;
P2[0]=(FLOAT)atof(&pColon[1]);
*pComma=',';
if (PCHAR pComma2=strchr(&pComma[1],','))
{
*pComma2=0;
P2[1]=(FLOAT)atof(&pComma[1]);
*pComma2=',';
P2[2]=(FLOAT)atof(&pComma2[1]);
}
else
{
P2[1]=(FLOAT)atof(&pComma[1]);
}
}
else
P2[0]=(FLOAT)atof(&pColon[1]);
}
if (PCHAR pComma=strchr(Index,','))
{
*pComma=0;
P1[0]=(FLOAT)atof(Index);
*pComma=',';
if (PCHAR pComma2=strchr(&pComma[1],','))
{
*pComma2=0;
P1[1]=(FLOAT)atof(&pComma[1]);
*pComma2=',';
P1[2]=(FLOAT)atof(&pComma2[1]);
}
else
{
P1[1]=(FLOAT)atof(&pComma[1]);
}
}
else
P1[0]=(FLOAT)atof(Index);
DebugSpew("GetDistance3D(%1.0f,%1.0f,%1.0f,%1.0f,%1.0f,%1.0f)",P1[0],P1[1],P1[2],P2[0],P2[1],P2[2]);
Dest.Float=(FLOAT)GetDistance3D(P1[0],P1[1],P1[2],P2[0],P2[1],P2[2]);
Dest.Type=pFloatType;
return true;
}
return false;
}
return false;
}
bool MQ2MacroType::GETMEMBER()
{
if (!gMacroStack)
return false;
PMQ2TYPEMEMBER pMember=MQ2MacroType::FindMember(Member);
if (!pMember)
return false;
switch((MacroMembers)pMember->ID)
{
case Name:
Dest.Ptr=&gszMacroName[0];
Dest.Type=pStringType;
return true;
case RunTime:
Dest.DWord=(DWORD)((GetTickCount()-gRunning)/1000);
Dest.Type=pIntType;
return true;
case Paused:
Dest.DWord=gMacroPause;
Dest.Type=pBoolType;
return true;
case Return:
Dest.Ptr=&DataTypeTemp[0];
strcpy(DataTypeTemp,gMacroStack->Return);
Dest.Type=pStringType;
return true;
case Params:
Dest.DWord=0;
{
PDATAVAR pVar=gMacroStack->Parameters;
while(pVar)
{
Dest.DWord++;
pVar=pVar->pNext;
}
}
Dest.Type=pIntType;
return true;
/*
TypeMember(Param);
/**/
}
return false;
}
#endif
bool MQ2TicksType::GETMEMBER()
{
#define nTicks (VarPtr.DWord)
unsigned long N=MemberMap[Member];
if (!N)
return false;
N--;
PMQ2TYPEMEMBER pMember=Members[N];
if (!pMember)
return false;
switch((TicksMembers)pMember->ID)
{
case Hours:
Dest.DWord=nTicks/600;
Dest.Type=pIntType;
return true;
case Minutes:
Dest.DWord=(nTicks/10)%60;
Dest.Type=pIntType;
return true;
case Seconds:
Dest.DWord=(nTicks*6)%60;
Dest.Type=pIntType;
return true;
case TimeHMS:
{
int Secs=nTicks*6;
int Mins=(Secs/60)%60;
int Hrs=(Secs/3600);
Secs=Secs%60;
if (Secs<0)
sprintf(DataTypeTemp,"Perm");
else if (Hrs)
sprintf(DataTypeTemp,"%d:%02d:%02d",Hrs,Mins,Secs);
else
sprintf(DataTypeTemp,"%d:%02d",Mins,Secs);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
return true;
case Time:
{
int Secs=nTicks*6;
int Mins=(Secs/60);
Secs=Secs%60;
if (Secs<0)
sprintf(DataTypeTemp,"Perm");
else
sprintf(DataTypeTemp,"%d:%02d",Mins,Secs);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
}
return true;
case TotalMinutes:
Dest.DWord=nTicks/10;
Dest.Type=pIntType;
return true;
case TotalSeconds:
Dest.DWord=nTicks*6;
Dest.Type=pIntType;
return true;
case Ticks:
Dest.DWord=nTicks;
Dest.Type=pIntType;
return true;
}
return false;
#undef nTicks
}
bool MQ2ArgbType::GETMEMBER()
{
unsigned long N=MemberMap[Member];
if (!N)
return false;
N--;
PMQ2TYPEMEMBER pMember=Members[N];
if (!pMember)
return false;
switch((ArgbMembers)pMember->ID)
{
case A:
Dest.DWord=VarPtr.Argb.A;
Dest.Type=pIntType;
return true;
case R:
Dest.DWord=VarPtr.Argb.R;
Dest.Type=pIntType;
return true;
case G:
Dest.DWord=VarPtr.Argb.G;
Dest.Type=pIntType;
return true;
case B:
Dest.DWord=VarPtr.Argb.B;
Dest.Type=pIntType;
return true;
case Int:
Dest.DWord=VarPtr.DWord;
Dest.Type=pIntType;
return true;
}
return false;
}
bool MQ2SpawnType::GETMEMBER()
{
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2SpawnType::FindMember(Member);
if (!pMember)
{
return false;
}
PSPAWNINFO pSpawn=(PSPAWNINFO)VarPtr.Ptr;
switch((SpawnMembers)pMember->ID)
{
case Level:
Dest.DWord=pSpawn->Level;
Dest.Type=pIntType;
return true;
case ID:
Dest.Type=pIntPtrType;
INTPTR(pSpawn->SpawnID);
return true;
case Name:
Dest.Type=pStringType;
Dest.Ptr=&pSpawn->Name[0];
return true;
case Surname:
Dest.Type=pStringType;
Dest.Ptr=&pSpawn->Lastname[0];
return true;
case CleanName:
strcpy(DataTypeTemp,pSpawn->Name);
CleanupName(DataTypeTemp,FALSE,FALSE);
Dest.Type=pStringType;
Dest.Ptr=&DataTypeTemp[0];
return true;
case DisplayName:
Dest.Ptr=&pSpawn->DisplayedName[0];
Dest.Type=pStringType;
return true;
case E:
Dest.Type=pFloatType;
Dest.Float=-pSpawn->X;
return true;
case W:
case X:
Dest.Type=pFloatPtrType;
FLOATPTR(pSpawn->X);
return true;
case S:
Dest.Type=pFloatType;
Dest.Float=-pSpawn->Y;
return true;
case N:
case Y:
Dest.Type=pFloatPtrType;
FLOATPTR(pSpawn->Y);
return true;
case D:
Dest.Type=pFloatType;
Dest.Float=-pSpawn->Z;
return true;
case U:
case Z:
Dest.Type=pFloatPtrType;
FLOATPTR(pSpawn->Z);
return true;
case Next:
if (Dest.Ptr=pSpawn->pNext)
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Prev:
if (Dest.Ptr=pSpawn->pPrev)
{
Dest.Type=pSpawnType;
return true;
}
return false;
case CurrentHPs:
Dest.Type=pIntType;
Dest.Int=pSpawn->HPCurrent;
return true;
case MaxHPs:
Dest.Type=pIntType;
Dest.Int=pSpawn->HPMax;
return true;
case PctHPs:
Dest.Type=pIntType;
Dest.Int=pSpawn->HPCurrent*100/pSpawn->HPMax;
return true;
case AARank:
if (pSpawn->AARank!=0xFF)
Dest.Int=pSpawn->AARank;
else
Dest.Int=0;
Dest.Type=pIntType;
return true;
case Speed:
Dest.Float=FindSpeed(pSpawn);
Dest.Type=pFloatType;
return true;
case Heading:
Dest.Float=pSpawn->Heading*0.703125f;
Dest.Type=pHeadingType;
return true;
case Pet:
if (Dest.Ptr=GetSpawnByID(pSpawn->PetID))
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Master:
if (Dest.Ptr=GetSpawnByID(pSpawn->MasterID))
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Gender:
Dest.Ptr=szGender[pSpawn->Gender];
Dest.Type=pStringType;
return true;
case Race:
Dest.DWord=pSpawn->Race;
Dest.Type=pRaceType;
return true;
case Class:
if (GetSpawnType(pSpawn)!=AURA && GetSpawnType(pSpawn)!=BANNER && GetSpawnType(pSpawn)!=CAMPFIRE)
Dest.DWord=pSpawn->Class;
else
if (GetSpawnType(pSpawn)==AURA)
Dest.DWord=0xFF;
else if (GetSpawnType(pSpawn)==BANNER)
Dest.DWord=0xFE;
else
Dest.DWord=0xFD;
Dest.Type=pClassType;
return true;
case Body:
Dest.DWord=GetBodyType(pSpawn);
Dest.Type=pBodyType;
return true;
case GM:
Dest.DWord=pSpawn->GM;
Dest.Type=pBoolType;
return true;
case Levitating:
Dest.DWord=(pSpawn->Levitate==2);
Dest.Type=pBoolType;
return true;
case Sneaking:
Dest.DWord=pSpawn->Sneak;
Dest.Type=pBoolType;
return true;
case Invis:
Dest.DWord=pSpawn->HideMode;
Dest.Type=pBoolType;
return true;
case Height:
Dest.Float=pSpawn->AvatarHeight;
Dest.Type=pFloatType;
return true;
case MaxRange:
if (GetSpawnType(pSpawn)!=ITEM)
{
Dest.Float=get_melee_range((EQPlayer*)pSpawn,(EQPlayer*)pSpawn);
Dest.Type=pFloatType;
return true;
}
return false;
case MaxRangeTo:
if (GetSpawnType(pSpawn)!=ITEM)
{
Dest.Float=get_melee_range(pLocalPlayer,(EQPlayer*)pSpawn);
Dest.Type=pFloatType;
return true;
}
return false;
case Guild:
if (pSpawn->GuildID < MAX_GUILDS)
{
Dest.Ptr=GetGuildByID(pSpawn->GuildID);
Dest.Type=pStringType;
return true;
}
return false;
case GuildStatus:
if (pSpawn->GuildID < MAX_GUILDS)
{
Dest.Ptr=szGuildStatus[pSpawn->GuildStatus];
Dest.Type=pStringType;
return true;
}
return false;
case Type:
switch(GetSpawnType(pSpawn))
{
case MOUNT:
Dest.Ptr="Mount";
Dest.Type=pStringType;
return true;
case UNTARGETABLE:
Dest.Ptr="Untargetable";
Dest.Type=pStringType;
return true;
case NPC:
Dest.Ptr="NPC";
Dest.Type=pStringType;
return true;
case PC:
Dest.Ptr="PC";
Dest.Type=pStringType;
return true;
case CHEST:
Dest.Ptr="Chest";
Dest.Type=pStringType;
return true;
case TRAP:
Dest.Ptr="Trap";
Dest.Type=pStringType;
return true;
case TRIGGER:
Dest.Ptr="Trigger";
Dest.Type=pStringType;
return true;
case TIMER:
Dest.Ptr="Timer";
Dest.Type=pStringType;
return true;
case PET:
Dest.Ptr="Pet";
Dest.Type=pStringType;
return true;
case ITEM:
Dest.Ptr="Item";
Dest.Type=pStringType;
return true;
case CORPSE:
Dest.Ptr="Corpse";
Dest.Type=pStringType;
return true;
case AURA:
Dest.Ptr="Aura";
Dest.Type=pStringType;
return true;
case OBJECT:
Dest.Ptr="Object";
Dest.Type=pStringType;
return true;
case BANNER:
Dest.Ptr="Banner";
Dest.Type=pStringType;
return true;
case CAMPFIRE:
Dest.Ptr="Campfire";
Dest.Type=pStringType;
return true;
case MERCENARY:
Dest.Ptr="Mercenary";
Dest.Type=pStringType;
return true;
case FLYER:
Dest.Ptr="Flyer";
Dest.Type=pStringType;
return true;
}
return false;
case Light:
Dest.Ptr=GetLightForSpawn(pSpawn);
Dest.Type=pStringType;
return true;
case StandState:
Dest.Int=pSpawn->StandState;
Dest.Type=pIntType;
return true;
case State:
if (GetCharInfo() && GetCharInfo()->Stunned==1)
{
Dest.Ptr="STUN";
}
else if(pSpawn->RespawnTimer)
{
Dest.Ptr="HOVER";
}
else if(pSpawn->Mount)
{
Dest.Ptr="MOUNT";
}
else
switch (pSpawn->StandState) {
case STANDSTATE_STAND:
Dest.Ptr="STAND";
break;
case STANDSTATE_SIT:
Dest.Ptr="SIT";
break;
case STANDSTATE_DUCK:
Dest.Ptr="DUCK";
break;
case STANDSTATE_BIND:
Dest.Ptr="BIND";
break;
case STANDSTATE_FEIGN:
Dest.Ptr="FEIGN";
break;
case STANDSTATE_DEAD:
Dest.Ptr="DEAD";
break;
default:
Dest.Ptr="UNKNOWN";
break;
}
Dest.Type=pStringType;
return true;
case Standing:
Dest.DWord=pSpawn->StandState==STANDSTATE_STAND;
Dest.Type=pBoolType;
return true;
case Sitting:
Dest.DWord=pSpawn->StandState==STANDSTATE_SIT;
Dest.Type=pBoolType;
return true;
case Ducking:
Dest.DWord=pSpawn->StandState==STANDSTATE_DUCK;
Dest.Type=pBoolType;
return true;
case Feigning:
Dest.DWord=pSpawn->StandState==STANDSTATE_FEIGN;
Dest.Type=pBoolType;
return true;
case Binding:
Dest.DWord=pSpawn->StandState==STANDSTATE_BIND;
Dest.Type=pBoolType;
return true;
case Dead:
Dest.DWord=pSpawn->StandState==STANDSTATE_DEAD;
Dest.Type=pBoolType;
return true;
case Stunned:
Dest.DWord=(GetCharInfo() && GetCharInfo()->Stunned==1);
Dest.Type=pBoolType;
return true;
case Hovering:
Dest.DWord=(pSpawn->RespawnTimer);
Dest.Type=pBoolType;
return true;
case Deity:
Dest.DWord=pSpawn->Deity;
Dest.Type=pDeityType;
return true;
case Distance:
Dest.Float=GetDistance(pSpawn->X,pSpawn->Y);
Dest.Type=pFloatType;
return true;
case Distance3D:
Dest.Float=DistanceToSpawn3D((PSPAWNINFO)pCharSpawn,pSpawn);
Dest.Type=pFloatType;
return true;
case DistancePredict:
Dest.Float=EstimatedDistanceToSpawn((PSPAWNINFO)pCharSpawn,pSpawn);
Dest.Type=pFloatType;
return true;
case DistanceW:
case DistanceX:
Dest.Float=(FLOAT)fabs(((PSPAWNINFO)pCharSpawn)->X-pSpawn->X);
Dest.Type=pFloatType;
return true;
case DistanceN:
case DistanceY:
Dest.Float=(FLOAT)fabs(((PSPAWNINFO)pCharSpawn)->Y-pSpawn->Y);
Dest.Type=pFloatType;
return true;
case DistanceU:
case DistanceZ:
Dest.Float=(FLOAT)fabs(((PSPAWNINFO)pCharSpawn)->Z-pSpawn->Z);
Dest.Type=pFloatType;
return true;
case HeadingTo:
Dest.Float=(FLOAT)(atan2f(((PSPAWNINFO)pCharSpawn)->Y - pSpawn->Y, pSpawn->X - ((PSPAWNINFO)pCharSpawn)->X) * 180.0f / PI + 90.0f);
if (Dest.Float<0.0f)
Dest.Float += 360.0f;
else if (Dest.Float>=360.0f)
Dest.Float -= 360.0f;
Dest.Type=pHeadingType;
return true;
case Casting:
if (Dest.Ptr=GetSpellByID(pSpawn->CastingData.SpellID))
{
Dest.Type=pSpellType;
return true;
}
return false;
case Mount:
if (Dest.Ptr=pSpawn->Mount)
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Underwater:
Dest.DWord=(pSpawn->UnderWater==5);
Dest.Type=pBoolType;
return true;
case FeetWet:
Dest.DWord=(pSpawn->FeetWet==5);
Dest.Type=pBoolType;
return true;
case Animation:
Dest.DWord=pSpawn->Animation;
Dest.Type=pIntType;
return true;
case Holding:
Dest.DWord=pSpawn->Holding;
Dest.Type=pIntType;
return true;
case Look:
Dest.Float=pSpawn->CameraAngle;
Dest.Type=pFloatType;
return true;
case xConColor:
switch(ConColor(pSpawn))
{
case CONCOLOR_GREY:
Dest.Ptr="GREY";
break;
case CONCOLOR_GREEN:
Dest.Ptr="GREEN";
break;
case CONCOLOR_LIGHTBLUE:
Dest.Ptr="LIGHT BLUE";
break;
case CONCOLOR_BLUE:
Dest.Ptr="BLUE";
break;
case CONCOLOR_WHITE:
Dest.Ptr="WHITE";
break;
case CONCOLOR_YELLOW:
Dest.Ptr="YELLOW";
break;
case CONCOLOR_RED:
default:
Dest.Ptr="RED";
break;
}
Dest.Type=pStringType;
return true;
case Invited:
Dest.DWord=(pSpawn->InvitedToGroup);
Dest.Type=pBoolType;
return true;
#ifndef ISXEQ
case NearestSpawn:
if (pSpawn==(PSPAWNINFO)pCharSpawn)
{
return (dataNearestSpawn(Index,Dest)!=0);// use top-level object if it's you
}
if (ISINDEX())
{
PCHAR pSearch;
unsigned long nth;
SEARCHSPAWN ssSpawn;
ClearSearchSpawn(&ssSpawn);
ssSpawn.FRadius=999999.0f;
if (pSearch=strchr(Index,','))
{
*pSearch=0;
++pSearch;
ParseSearchSpawn(pSearch,&ssSpawn);
nth=GETNUMBER();
}
else
{
if (ISNUMBER())
{
nth=GETNUMBER();
}
else
{
nth=1;
ParseSearchSpawn(Index,&ssSpawn);
}
}
if (Dest.Ptr=NthNearestSpawn(&ssSpawn,nth,pSpawn))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
#else
case NearestSpawn:
if (pSpawn==(PSPAWNINFO)pCharSpawn)
{
return (dataNearestSpawn(argc,argv,Dest)!=0);// use top-level object if it's you
}
if (argc)
{
unsigned long nth;
SEARCHSPAWN ssSpawn;
ClearSearchSpawn(&ssSpawn);
ssSpawn.FRadius=999999.0f;
if (argc>=2 || !IsNumber(argv[0]))
{
ParseSearchSpawn(1,argc,argv,ssSpawn);
nth=atoi(argv[0]);
}
else
{
nth=atoi(argv[0]);
}
if (Dest.Ptr=NthNearestSpawn(&ssSpawn,nth,pSpawn))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
#endif
case Trader:
Dest.DWord=pSpawn->Trader;
Dest.Type=pBoolType;
return true;
case AFK:
Dest.DWord=pSpawn->AFK;
Dest.Type=pBoolType;
return true;
case LFG:
Dest.DWord=pSpawn->LFG;
Dest.Type=pBoolType;
return true;
case Linkdead:
Dest.DWord=pSpawn->Linkdead;
Dest.Type=pBoolType;
return true;
case AATitle: // Leaving this in for older macros/etc.."Title" should be used instead.
Dest.Type=pStringType;
Dest.Ptr=&pSpawn->Title[0];
return true;
case Title:
Dest.Type=pStringType;
Dest.Ptr=&pSpawn->Title[0];
return true;
case Suffix:
Dest.Type=pStringType;
Dest.Ptr=&pSpawn->Suffix[0];
return true;
case xGroupLeader:
if (GetCharInfo()->pGroupInfo && GetCharInfo()->pGroupInfo->pLeader)
{
CHAR Name[MAX_STRING]={0};
GetCXStr(GetCharInfo()->pGroupInfo->pLeader->pName,Name,MAX_STRING);
Dest.DWord=(pSpawn->Type==SPAWN_PLAYER && !stricmp(Name,pSpawn->Name));
Dest.Type=pBoolType;
return true;
}
return false;
case Assist:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn && pSpawn)
{
DWORD nAssist;
{
if (GetCharInfo()->pSpawn->GroupAssistNPC[0]==pSpawn->SpawnID)
{
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
}
for (nAssist=0 ; nAssist < 3 ; nAssist++)
{
if (GetCharInfo()->pSpawn->RaidAssistNPC[nAssist]==pSpawn->SpawnID)
{
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
}
}
Dest.DWord=0;
Dest.Type=pBoolType;
return true;
case Mark:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn && pSpawn)
{
DWORD nMark;
for (nMark=0 ; nMark < 3 ; nMark++)
{
if (GetCharInfo()->pSpawn->RaidMarkNPC[nMark]==pSpawn->SpawnID)
{
Dest.DWord=nMark+1;
Dest.Type=pIntType;
return true;
}
}
for (nMark=0 ; nMark < 3 ; nMark++)
{
if (GetCharInfo()->pSpawn->GroupMarkNPC[nMark]==pSpawn->SpawnID)
{
Dest.DWord=nMark+1;
Dest.Type=pIntType;
return true;
}
}
}
return false;
case Anonymous:
Dest.DWord=(pSpawn->Anon==1);
Dest.Type=pBoolType;
return true;
case Roleplaying:
Dest.DWord=(pSpawn->Anon==2);
Dest.Type=pBoolType;
return true;
case xLineOfSight:
Dest.DWord=(LineOfSight(GetCharInfo()->pSpawn,pSpawn));
Dest.Type=pBoolType;
return true;
case HeadingToLoc:
#ifndef ISXEQ
if (!ISINDEX())
return false;
if (PCHAR pComma=strchr(Index,','))
{
*pComma=0;
FLOAT Y=(FLOAT)atof(Index);
*pComma=',';
FLOAT X=(FLOAT)atof(&pComma[1]);
#else
if (!argc)
return false;
if (argc==2)
{
FLOAT Y=(FLOAT)atof(argv[0]);
FLOAT X=(FLOAT)atof(argv[1]);
#endif
Dest.Float=(FLOAT)(atan2f(pSpawn->Y - Y, X - pSpawn->X) * 180.0f / PI + 90.0f);
if (Dest.Float<0.0f)
Dest.Float += 360.0f;
else if (Dest.Float>=360.0f)
Dest.Float -= 360.0f;
Dest.Type=pHeadingType;
return true;
}
return false;
case Fleeing:
Dest.DWord=IsMobFleeing(GetCharInfo()->pSpawn,pSpawn);
Dest.Type=pBoolType;
return true;
case Named:
Dest.DWord=IsNamed(pSpawn);
Dest.Type=pBoolType;
return true;
case Buyer:
Dest.DWord=pSpawn->Buyer;
Dest.Type=pBoolType;
return true;
case Moving:
Dest.DWord=fabs(pSpawn->SpeedRun)>0.0f;
Dest.Type=pBoolType;
return true;
case CurrentMana:
Dest.DWord=pSpawn->ManaCurrent;
Dest.Type=pIntType;
return true;
case MaxMana:
Dest.DWord=pSpawn->ManaMax;
Dest.Type=pIntType;
return true;
case CurrentEndurance:
Dest.DWord=pSpawn->EnduranceCurrent;
Dest.Type=pIntType;
return true;
case MaxEndurance:
Dest.DWord=pSpawn->EnduranceMax;
Dest.Type=pIntType;
return true;
case Loc:
sprintf(DataTypeTemp,"%.2f, %.2f",pSpawn->Y,pSpawn->X);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case LocYX:
sprintf(DataTypeTemp,"%.0f, %.0f",pSpawn->Y,pSpawn->X);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2BuffType::GETMEMBER()
{
#define pBuff ((PSPELLBUFF)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
if ((int)pBuff->SpellID<=0)
return false;
PMQ2TYPEMEMBER pMember=MQ2BuffType::FindMember(Member);
if (!pMember)
{
if (PSPELL pSpell=GetSpellByID(pBuff->SpellID))
{
#ifndef ISXEQ
return pSpellType->GetMember(*(MQ2VARPTR*)&pSpell,Member,Index,Dest);
#else
return pSpellType->GetMember(*(LSVARPTR*)&pSpell,Member,argc,argv,Dest);
#endif
}
return false;
}
static CHAR Temp[128];
switch((BuffMembers)pMember->ID)
{
case ID:
{
if (GetBuffID(pBuff,(DWORD&)Dest.DWord))
{
Dest.Type=pIntType;
return true;
}
if (GetShortBuffID(pBuff,(DWORD&)Dest.DWord))
{
Dest.Type=pIntType;
return true;
}
}
return false;
case Level:
Dest.DWord=pBuff->Level;
Dest.Type=pIntType;
return true;
case Spell:
if (Dest.Ptr=GetSpellByID(pBuff->SpellID))
{
Dest.Type=pSpellType;
return true;
}
return false;
case Mod:
Dest.Float=(((float)pBuff->Modifier)/10.0f);
if (Dest.Float!=1.0f)
{
Dest.Type=pFloatType;
return true;
}
return false;
case Duration:
Dest.DWord=pBuff->Duration+1;// 0 is actually 6 seconds ;)
Dest.Type=pTicksType;
return true;
case Dar:
if(PSPELL pSpell = GetSpellByID(pBuff->SpellID))
{
if(pSpell->SpellType != 0)
{
Dest.DWord=pBuff->DamageAbsorbRemaining;
Dest.Type=pIntType;
return true;
}
}
return false;
case Counters:
if(GetSpellByID(pBuff->SpellID)->SpellType == 0)
{
Dest.DWord=pBuff->DamageAbsorbRemaining;
Dest.Type=pIntType;
return true;
}
}
return false;
#undef pBuff
}
bool MQ2CharacterType::GETMEMBER()
{
#define pChar ((PCHARINFO)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2CharacterType::FindMember(Member);
if (!pMember)
{
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)&pChar->pSpawn,Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)&pChar->pSpawn,Member,argc,argv,Dest);
#endif
}
int nLang = 0;
char buf[MAX_STRING] = {0};
unsigned long nBuff;
char buf2[MAX_STRING] = {0};
switch((CharacterMembers)pMember->ID)
{
case ID:
Dest.DWord=pChar->pSpawn->SpawnID;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=&pChar->Name[0];
Dest.Type=pStringType;
return true;
case Surname:
Dest.Ptr=&pChar->Lastname[0];
Dest.Type=pStringType;
return true;
case Level:
Dest.DWord=GetCharInfo2()->Level;
Dest.Type=pIntType;
return true;
case Exp:
Dest.DWord=pChar->Exp;
Dest.Type=pIntType;
return true;
case PctExp:
Dest.Float=(float)pChar->Exp/3.30f;
Dest.Type=pFloatType;
return true;
case PctAAExp:
Dest.Float=(float)pChar->AAExp/3.30f;
Dest.Type=pFloatType;
return true;
case Spawn:
Dest.Ptr=pChar->pSpawn;
Dest.Type=pSpawnType;
return true;
case CurrentHPs:
Dest.DWord=GetCurHPS();
Dest.Type=pIntType;
return true;
case MaxHPs:
Dest.Type=pIntType;
Dest.Int=GetMaxHPS();
return true;
case PctHPs:
Dest.Type=pIntType;
Dest.Int=GetCurHPS()*100/GetMaxHPS();
return true;
case CurrentMana:
Dest.DWord=GetCharInfo2()->Mana;
Dest.Type=pIntType;
return true;
case MaxMana:
Dest.DWord=GetMaxMana();
Dest.Type=pIntType;
return true;
case PctMana:
{
if (unsigned long Temp=GetMaxMana())
Dest.DWord=GetCharInfo2()->Mana*100/Temp;
else
Dest.DWord=0;
Dest.Type=pIntType;
}
return true;
case CountBuffs:
Dest.DWord=0;
{
for (unsigned long nBuff=0 ; nBuff<25 ; nBuff++)
{
if (GetCharInfo2()->Buff[nBuff].SpellID>0)
Dest.DWord++;
}
Dest.Type=pIntType;
}
return true;
case Buff:
if (!ISINDEX())
return false;
if (ISNUMBER())
{
unsigned long nBuff=GETNUMBER()-1;
if (nBuff>=25)
return false;
if (GetCharInfo2()->Buff[nBuff].SpellID<=0)
return false;
Dest.Ptr=&GetCharInfo2()->Buff[nBuff];
Dest.Type=pBuffType;
return true;
}
else
{
for (unsigned long nBuff=0 ; nBuff < 25 ; nBuff++)
{
if (PSPELL pSpell=GetSpellByID(GetCharInfo2()->Buff[nBuff].SpellID))
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
Dest.Ptr=&GetCharInfo2()->Buff[nBuff];
Dest.Type=pBuffType;
return true;
}
}
}
}
return false;
case Song:
if (!ISINDEX())
return false;
if (ISNUMBER())
{
unsigned long nBuff=GETNUMBER()-1;
if (nBuff>=15)
return false;
if (GetCharInfo2()->ShortBuff[nBuff].SpellID<=0)
return false;
Dest.Ptr=&GetCharInfo2()->ShortBuff[nBuff];
Dest.Type=pBuffType;
return true;
}
else
{
for (unsigned long nBuff=0 ; nBuff < 35 ; nBuff++)
{
if (PSPELL pSpell=GetSpellByID(GetCharInfo2()->ShortBuff[nBuff].SpellID))
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
Dest.Ptr=&GetCharInfo2()->ShortBuff[nBuff];
Dest.Type=pBuffType;
return true;
}
}
}
}
return false;
case HPBonus:
Dest.DWord=pChar->HPBonus;
Dest.Type=pIntType;
return true;
case ManaBonus:
Dest.DWord=pChar->ManaBonus;
Dest.Type=pIntType;
return true;
case EnduranceBonus:
Dest.DWord=pChar->EnduranceBonus;
Dest.Type=pIntType;
return true;
case CombatEffectsBonus:
Dest.DWord=pChar->CombatEffectsBonus;
Dest.Type=pIntType;
return true;
case ShieldingBonus:
Dest.DWord=pChar->ShieldingBonus;
Dest.Type=pIntType;
return true;
case SpellShieldBonus:
Dest.DWord=pChar->SpellShieldBonus;
Dest.Type=pIntType;
return true;
case AvoidanceBonus:
Dest.DWord=pChar->AvoidanceBonus;
Dest.Type=pIntType;
return true;
case AccuracyBonus:
Dest.DWord=pChar->AccuracyBonus;
Dest.Type=pIntType;
return true;
case StunResistBonus:
Dest.DWord=pChar->StunResistBonus;
Dest.Type=pIntType;
return true;
case StrikeThroughBonus:
Dest.DWord=pChar->StrikeThroughBonus;
Dest.Type=pIntType;
return true;
case DoTShieldBonus:
Dest.DWord=pChar->DoTShieldBonus;
Dest.Type=pIntType;
return true;
case AttackBonus:
Dest.DWord=pChar->AttackBonus;
Dest.Type=pIntType;
return true;
case HPRegenBonus:
Dest.DWord=pChar->HPRegenBonus;
Dest.Type=pIntType;
return true;
case ManaRegenBonus:
Dest.DWord=pChar->ManaRegenBonus;
Dest.Type=pIntType;
return true;
case DamageShieldBonus:
Dest.DWord=pChar->DamageShieldBonus;
Dest.Type=pIntType;
return true;
case DamageShieldMitigationBonus:
Dest.DWord=pChar->DamageShieldMitigationBonus;
Dest.Type=pIntType;
return true;
case HeroicSTRBonus:
Dest.DWord=pChar->HeroicSTRBonus;
Dest.Type=pIntType;
return true;
case HeroicINTBonus:
Dest.DWord=pChar->HeroicINTBonus;
Dest.Type=pIntType;
return true;
case HeroicWISBonus:
Dest.DWord=pChar->HeroicWISBonus;
Dest.Type=pIntType;
return true;
case HeroicAGIBonus:
Dest.DWord=pChar->HeroicAGIBonus;
Dest.Type=pIntType;
return true;
case HeroicDEXBonus:
Dest.DWord=pChar->HeroicDEXBonus;
Dest.Type=pIntType;
return true;
case HeroicSTABonus:
Dest.DWord=pChar->HeroicSTABonus;
Dest.Type=pIntType;
return true;
case HeroicCHABonus:
Dest.DWord=pChar->HeroicCHABonus;
Dest.Type=pIntType;
return true;
case HealAmountBonus:
Dest.DWord=pChar->HealAmountBonus;
Dest.Type=pIntType;
return true;
case SpellDamageBonus:
Dest.DWord=pChar->SpellDamageBonus;
Dest.Type=pIntType;
return true;
case ClairvoyanceBonus:
Dest.DWord=pChar->ClairvoyanceBonus;
Dest.Type=pIntType;
return true;
case EnduranceRegenBonus:
Dest.DWord=pChar->EnduranceRegenBonus;
Dest.Type=pIntType;
return true;
case AttackSpeed:
Dest.DWord=pChar->AttackSpeed;
Dest.Type=pIntType;
return true;
case Endurance: //Grandfathered, CurrentEndurance should be used instead.
Dest.DWord=GetCharInfo2()->Endurance;
Dest.Type=pIntType;
return true;
case CurrentEndurance:
Dest.DWord=GetCharInfo2()->Endurance;
Dest.Type=pIntType;
return true;
case MaxEndurance:
Dest.DWord=GetMaxEndurance();
Dest.Type=pIntType;
return true;
case PctEndurance:
{
if (unsigned long Temp=GetMaxEndurance())
Dest.DWord=(GetCharInfo2()->Endurance*100)/Temp;
else
Dest.DWord=0;
Dest.Type=pIntType;
}
return true;
case GukEarned:
return false;//TODO
// Dest.DWord=pChar->GukEarned;
Dest.Type=pIntType;
return true;
case MMEarned:
return false;//TODO
// Dest.DWord=pChar->MMEarned;
Dest.Type=pIntType;
return true;
case RujEarned:
return false;//TODO
// Dest.DWord=pChar->RujEarned;
Dest.Type=pIntType;
return true;
case TakEarned:
return false;//TODO
// Dest.DWord=pChar->TakEarned;
Dest.Type=pIntType;
return true;
case MirEarned:
return false;//TODO
// Dest.DWord=pChar->MirEarned;
Dest.Type=pIntType;
return true;
case LDoNPoints:
return false;//TODO
// Dest.DWord=pChar->LDoNPoints;
Dest.Type=pIntType;
return true;
case CurrentFavor:
Dest.DWord=pChar->CurrFavor;
Dest.Type=pIntType;
return true;
case CareerFavor:
Dest.DWord=pChar->CareerFavor;
Dest.Type=pIntType;
return true;
case Inventory:
if (ISINDEX())
{
if (ISNUMBER())
{
unsigned long nSlot=GETNUMBER()%NUM_INV_SLOTS;
if (nSlot<NUM_INV_SLOTS)
{
if (Dest.Ptr=GetCharInfo2()->InventoryArray[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
else
{
for (unsigned long nSlot=0 ; szItemSlot[nSlot] ; nSlot++)
{
if (!stricmp(GETFIRST(),szItemSlot[nSlot]))
{
if (Dest.Ptr=GetCharInfo2()->InventoryArray[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
}
}
return false;
case Bank:
if (ISINDEX())
{
if (ISNUMBER())
{
unsigned long nSlot=GETNUMBER()-1;
if (nSlot<NUM_BANK_SLOTS)
{
if (Dest.Ptr=pChar->Bank[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
}
return false;
case PlatinumShared:
Dest.DWord=pChar->BankSharedPlat;
Dest.Type=pIntType;
return true;
case Cash:
Dest.DWord=GetCharInfo2()->Plat*1000+GetCharInfo2()->Gold*100+GetCharInfo2()->Silver*10+GetCharInfo2()->Copper;
Dest.Type=pIntType;
return true;
case Platinum:
Dest.DWord=GetCharInfo2()->Plat;
Dest.Type=pIntType;
return true;
case Gold:
Dest.DWord=GetCharInfo2()->Gold;
Dest.Type=pIntType;
return true;
case Silver:
Dest.DWord=GetCharInfo2()->Silver;
Dest.Type=pIntType;
return true;
case Copper:
Dest.DWord=GetCharInfo2()->Copper;
Dest.Type=pIntType;
return true;
case CashBank:
Dest.DWord=pChar->BankPlat*1000+pChar->BankGold*100+pChar->BankSilver*10+pChar->BankCopper;
Dest.Type=pIntType;
return true;
case PlatinumBank:
Dest.DWord=pChar->BankPlat;
Dest.Type=pIntType;
return true;
case GoldBank:
Dest.DWord=pChar->BankGold;
Dest.Type=pIntType;
return true;
case SilverBank:
Dest.DWord=pChar->BankSilver;
Dest.Type=pIntType;
return true;
case CopperBank:
Dest.DWord=pChar->BankCopper;
Dest.Type=pIntType;
return true;
case AAExp:
Dest.DWord=pChar->AAExp;
Dest.Type=pIntType;
return true;
case AAPoints:
Dest.DWord=GetCharInfo2()->AAPoints;
Dest.Type=pIntType;
return true;
case Combat:
Dest.DWord=*EQADDR_ATTACK;
Dest.Type=pBoolType;
return true;
case HPRegen:
Dest.DWord=HealthGained;
Dest.Type=pIntType;
return true;
case ManaRegen:
Dest.DWord=ManaGained;
Dest.Type=pIntType;
return true;
case EnduranceRegen:
Dest.DWord=EnduranceGained;
Dest.Type=pIntType;
return true;
case Dar:
Dest.DWord=0;
{
for (unsigned long k=0; k<23 ; k++)
if(PSPELL pSpell = GetSpellByID(GetCharInfo2()->Buff[k].SpellID))
if(pSpell->SpellType != 0)
Dest.DWord+=GetCharInfo2()->Buff[k].DamageAbsorbRemaining;
}
Dest.Type=pIntType;
return true;
case Grouped:
if(!pChar->pGroupInfo) return false;
Dest.DWord= pChar->pGroupInfo->pMember[1] ||
pChar->pGroupInfo->pMember[2] ||
pChar->pGroupInfo->pMember[3] ||
pChar->pGroupInfo->pMember[4] ||
pChar->pGroupInfo->pMember[5];
Dest.Type=pBoolType;
return true;
case GroupList: // This isn't really working as intended just yet
{
if(!pChar->pGroupInfo) return false;
for(int i=1; i<6; i++)
if(pChar->pGroupInfo->pMember[i])
{
char tmp[MAX_STRING];
GetCXStr(pChar->pGroupInfo->pMember[i]->pName, tmp, sizeof(tmp));
strcat(buf, tmp);
if(i<5 && pChar->pGroupInfo->pMember[i+1])
strcat(buf, " ");
}
}
Dest.Ptr=&buf[0];
Dest.Type=pStringType;
return true;
case AmIGroupLeader:
if (!pChar->pGroupInfo) return false;
if (!pChar->pGroupInfo->pLeader) return false;
GetCXStr(pChar->pGroupInfo->pLeader->pName, buf, sizeof(buf));
if(!stricmp(buf, pChar->Name))
Dest.Ptr="TRUE";
else
Dest.Ptr="FALSE";
Dest.Type=pStringType;
return true;
case FreeBuffSlots:
Dest.DWord=GetAAIndexByName("mystical attuning");
if (PlayerHasAAAbility(Dest.DWord))
{
for (unsigned int j=0; j < AA_CHAR_MAX_REAL; j++)
{
if ( pPCData->GetAltAbilityIndex(j) == Dest.DWord)
{
Dest.DWord=15+(GetCharInfo2()->AAList[j].PointsSpent/5);
break;
}
}
} else Dest.DWord = 15;
if(GetAAIndexByName("Embrace of the Dark Reign")) Dest.DWord++;
if(GetAAIndexByName("Embrace of the Keepers")) Dest.DWord++;
if(GetCharInfo()->pSpawn->Level > 71) Dest.DWord++;
if(GetCharInfo()->pSpawn->Level > 74) Dest.DWord++;
for (nBuff=0 ; nBuff<25 ; nBuff++)
{
if (GetCharInfo2()->Buff[nBuff].SpellID>0)
Dest.DWord--;
}
Dest.Type = pIntType;
return true;
case Gem:
if (!ISINDEX())
return false;
if (ISNUMBER())
{
// number
unsigned long nGem=GETNUMBER()-1;
if (nGem<NUM_SPELL_GEMS)
{
if (Dest.Ptr=GetSpellByID(GetCharInfo2()->MemorizedSpells[nGem]))
{
Dest.Type=pSpellType;
return true;
}
}
}
else
{
// name
for (unsigned long nGem=0 ; nGem < NUM_SPELL_GEMS ; nGem++)
{
if (PSPELL pSpell=GetSpellByID(GetCharInfo2()->MemorizedSpells[nGem]))
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
Dest.DWord=nGem+1;
Dest.Type=pIntType;
return true;
}
}
}
}
return false;
case LanguageSkill:
if (!ISINDEX())
return false;
if (ISNUMBER())
nLang=GETNUMBER()-1;
else
nLang=GetLanguageIDByName(GETFIRST())-1;
if (nLang < 0 || nLang >= 25 )
return false;
Dest.DWord=pChar->languages[nLang];
Dest.Type=pIntType;
return true;
case CombatAbility:
if (!ISINDEX())
return false;
if (ISNUMBER())
{
// number
unsigned long nCombatAbility=GETNUMBER()-1;
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
Dest.Ptr=pSpell;
Dest.Type=pSpellType;
return true;
}
}
else
{
// name
for (unsigned long nCombatAbility=0 ; nCombatAbility < NUM_COMBAT_ABILITIES ; nCombatAbility++)
{
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
Dest.DWord=nCombatAbility+1;
Dest.Type=pIntType;
return true;
}
}
}
}
return false;
case CombatAbilityTimer:
if (ISINDEX())
{
if (ISNUMBER())
{
// number
unsigned long nCombatAbility=GETNUMBER()-1;
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
DWORD timeNow = (DWORD)time(NULL);
if (pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID) > timeNow)
{
Dest.Int=pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID)-timeNow+6;
Dest.Int/=6;
}
else Dest.Int=0;
Dest.Type=pTicksType;
return true;
}
}
else
{
// by name
for (unsigned long nCombatAbility=0 ; nCombatAbility < NUM_COMBAT_ABILITIES ; nCombatAbility++)
{
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
DWORD timeNow = (DWORD)time(NULL);
if (pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID) > timeNow)
{
Dest.Int=pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID)-timeNow+6;
Dest.Int/=6;
}
else Dest.Int=0;
Dest.Type=pTicksType;
return true;
}
}
}
}
}
return false;
case CombatAbilityReady:
Dest.DWord=0;
Dest.Type=pBoolType;
if (ISINDEX())
{
if (ISNUMBER())
{
// number
unsigned long nCombatAbility=GETNUMBER()-1;
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
DWORD timeNow = (DWORD)time(NULL);
if (pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID) < timeNow)
{
Dest.DWord=1;
return true;
}
}
}
else
{
// by name
for (unsigned long nCombatAbility=0 ; nCombatAbility < NUM_COMBAT_ABILITIES ; nCombatAbility++)
{
if ( PSPELL pSpell = GetSpellByID(pPCData->GetCombatAbility(nCombatAbility)) )
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
DWORD timeNow = (DWORD)time(NULL);
if (pPCData->GetCombatAbilityTimer(pSpell->CARecastTimerID) < timeNow)
{
Dest.DWord=1;
return true;
}
}
}
}
}
}
return true;
case Moving:
Dest.DWord=((((gbMoving) && ((PSPAWNINFO)pCharSpawn)->SpeedRun==0.0f) && (pChar->pSpawn->Mount == NULL )) || (fabs(FindSpeed((PSPAWNINFO)pCharSpawn)) > 0.0f ));
Dest.Type=pBoolType;
return true;
case Hunger:
Dest.DWord=GetCharInfo2()->hungerlevel;
Dest.Type=pIntType;
return true;
case Thirst:
Dest.DWord=GetCharInfo2()->thirstlevel;
Dest.Type=pIntType;
return true;
case AltAbilityTimer:
if (ISINDEX()) {
if (ISNUMBER()) {
//numeric
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (pAbility->ID == GETNUMBER() ) {
pAltAdvManager->IsAbilityReady(pPCData,pAbility,&Dest.Int);
if (Dest.Int<0)
return false;
Dest.Int/=6;
Dest.Type=pTicksType;
return true;
}
}
}
} else {
// by name
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (PCHAR pName=pCDBStr->GetString(pAbility->nName, 1, NULL)) {
if (!stricmp(GETFIRST(),pName)) {
pAltAdvManager->IsAbilityReady(pPCData,pAbility,&Dest.Int);
if (Dest.Int<0)
return false;
Dest.Int/=6;
Dest.Type=pTicksType;
return true;
}
}
}
}
}
}
return false;
case AltAbilityReady:
if (ISINDEX()) {
if (ISNUMBER()) {
//numeric
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (pAbility->ID == GETNUMBER()) {
Dest.DWord=pAltAdvManager->IsAbilityReady(pPCData,pAbility,0);
Dest.Type=pBoolType;
return true;
}
}
}
} else {
// by name
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (PCHAR pName=pCDBStr->GetString(pAbility->nName, 1, NULL)) {
if (!stricmp(GETFIRST(),pName)) {
Dest.DWord=pAltAdvManager->IsAbilityReady(pPCData,pAbility,0);
Dest.Type=pBoolType;
return true;
}
}
}
}
}
}
return false;
case AltAbility:
if (ISINDEX()) {
if (ISNUMBER()) {
//numeric
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (pAbility->ID == GETNUMBER()) {
Dest.Ptr = pAbility;
Dest.Type = pAltAbilityType;
return true;
}
}
}
} else {
// by name
for (unsigned long nAbility=0 ; nAbility<AA_CHAR_MAX_REAL ; nAbility++) {
if ( PALTABILITY pAbility=pAltAdvManager->GetAltAbility(pPCData->GetAltAbilityIndex(nAbility)) ) {
if (PCHAR pName=pCDBStr->GetString(pAbility->nName, 1, NULL)) {
if (!stricmp(GETFIRST(),pName)) {
Dest.Ptr = pAbility;
Dest.Type = pAltAbilityType;
return true;
}
}
}
}
}
}
return false;
case Skill:
if (ISINDEX())
{
if (ISNUMBER())
{
// numeric
unsigned long nSkill=GETNUMBER()-1;
if (nSkill<0x64)
{
Dest.DWord=GetCharInfo2()->Skill[nSkill];
Dest.Type=pIntType;
if (!Dest.DWord) {
if(pSkillMgr->pSkill[nSkill]->Activated) {
for(int btn=0; !Dest.DWord && btn<10; btn++) {
if(EQADDR_DOABILITYLIST[btn]==nSkill) Dest.DWord=1;
}
}
}
return true;
}
}
else
{
// name
for (DWORD nSkill=0;nSkill<NUM_SKILLS;nSkill++)
if (!stricmp(GETFIRST(),szSkills[nSkill]))
{
Dest.DWord=GetCharInfo2()->Skill[nSkill];
Dest.Type=pIntType;
// note: this change fixes the problem where ${Me.Skill[Forage]} returns
// 0 even if you have bought the aa for cultural forage...
if (!Dest.DWord) {
if(pSkillMgr->pSkill[nSkill]->Activated) {
for(int btn=0; !Dest.DWord && btn<10; btn++) {
if(EQADDR_DOABILITYLIST[btn]==nSkill) Dest.DWord=1;
}
}
}
return true;
}
}
}
return false;
case Ability:
if (ISINDEX())
{
if (ISNUMBER())
{
// numeric
if (unsigned long nSkill=GETNUMBER())
{
if (nSkill<7)
{
nSkill+=3;
}
else if (nSkill<11)
{
nSkill-=7;
}
else
return false;
if (EQADDR_DOABILITYLIST[nSkill]!=0xFFFFFFFF)
{
Dest.Ptr=szSkills[EQADDR_DOABILITYLIST[nSkill]];
Dest.Type=pStringType;
return true;
}
}
}
else
{
// name
for (DWORD nSkill=0;szSkills[nSkill];nSkill++)
if (!stricmp(GETFIRST(),szSkills[nSkill]))
{
// found name
for (DWORD nAbility=0;nAbility<10;nAbility++)
if (EQADDR_DOABILITYLIST[nAbility] == nSkill)
{
if (nAbility<4)
nAbility+=7;
else
nAbility-=3;
Dest.DWord=nAbility;
Dest.Type=pIntType;
return true;
}
}
}
}
return false;
case AbilityReady:
if (ISINDEX())
{
if (ISNUMBER())
{
// numeric
if (unsigned long nSkill=GETNUMBER())
{
if (nSkill<7)
{
nSkill+=3;
}
else if (nSkill<11)
{
nSkill-=7;
}
else
return false;
/**/
if (EQADDR_DOABILITYLIST[nSkill]!=0xFFFFFFFF)
{
if (pSkillMgr->pSkill[EQADDR_DOABILITYLIST[nSkill]]->AltTimer==2)
Dest.DWord=gbAltTimerReady;
else
Dest.DWord=EQADDR_DOABILITYAVAILABLE[EQADDR_DOABILITYLIST[nSkill]];
Dest.Type=pBoolType;
return true;
}
}
}
else
{
// name
for (DWORD nSkill=0;szSkills[nSkill];nSkill++)
if (!stricmp(GETFIRST(),szSkills[nSkill]))
{
// found name
for (DWORD nAbility=0;nAbility<10;nAbility++)
if (EQADDR_DOABILITYLIST[nAbility] == nSkill)
{
// thanks s0rcier!
if (nSkill<100) {
if (pSkillMgr->pSkill[nSkill]->AltTimer==2)
Dest.DWord=gbAltTimerReady;
else
Dest.DWord=EQADDR_DOABILITYAVAILABLE[nSkill];
Dest.Type=pBoolType;
return true;
}
if (nSkill==111) {
Dest.DWord=gbAltTimerReady;
Dest.Type=pBoolType;
return true;
}
if (nSkill==105 || nSkill==107) {
Dest.DWord=LoH_HT_Ready();
Dest.Type=pBoolType;
return true;
}
return false;
}
}
}
}
return false;
case RangedReady:
Dest.DWord=gbRangedAttackReady;
Dest.Type=pBoolType;
return true;
case AltTimerReady:
Dest.DWord=gbAltTimerReady;
Dest.Type=pBoolType;
return true;
case Book:
if (ISINDEX())
{
if (ISNUMBER())
{
// numeric
unsigned long nSpell=GETNUMBER()-1;
if (nSpell<NUM_BOOK_SLOTS)
if (Dest.Ptr=GetSpellByID(GetCharInfo2()->SpellBook[nSpell]))
{
Dest.Type=pSpellType;
return true;
}
}
else
{
// name
for (DWORD nSpell=0 ; nSpell < NUM_BOOK_SLOTS ; nSpell++)
if (GetCharInfo2()->SpellBook[nSpell] != 0xFFFFFFFF)
{
if (!stricmp(GetSpellNameByID(GetCharInfo2()->SpellBook[nSpell]),GETFIRST()))
{
Dest.DWord=nSpell+1;
Dest.Type=pIntType;
return true;
}
}
}
}
return false;
case SpellReady:
if (pCastSpellWnd && ISINDEX())
{
if (ISNUMBER())
{
// numeric
unsigned long nGem=GETNUMBER()-1;
if (nGem<NUM_SPELL_GEMS)
{
if (!((PEQCASTSPELLWINDOW)pCastSpellWnd)->SpellSlots[nGem])
Dest.DWord=0;
else
Dest.DWord = (((PEQCASTSPELLWINDOW)pCastSpellWnd)->SpellSlots[nGem]->spellstate!=1);
Dest.Type=pBoolType;
return true;
}
}
else
{
for (unsigned long nGem=0 ; nGem < NUM_SPELL_GEMS ; nGem++)
{
if (PSPELL pSpell=GetSpellByID(GetCharInfo2()->MemorizedSpells[nGem]))
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
if (!((PEQCASTSPELLWINDOW)pCastSpellWnd)->SpellSlots[nGem])
Dest.DWord=0;
else
Dest.DWord = (((PEQCASTSPELLWINDOW)pCastSpellWnd)->SpellSlots[nGem]->spellstate!=1);
Dest.Type=pBoolType;
return true;
}
}
}
}
}
return false;
case PetBuff:
if (!ISINDEX() || !pPetInfoWnd)
return false;
#define pPetInfoWindow ((PEQPETINFOWINDOW)pPetInfoWnd)
if (ISNUMBER())
{
unsigned long nBuff=GETNUMBER()-1;
if (nBuff>29)
return false;
if (pPetInfoWindow->Buff[nBuff]==0xFFFFFFFF || pPetInfoWindow->Buff[nBuff]==0)
return false;
if (Dest.Ptr=GetSpellByID(pPetInfoWindow->Buff[nBuff]))
{
Dest.Type=pSpellType;
return true;
}
}
else
{
for (unsigned long nBuff=0 ; nBuff < 29 ; nBuff++)
{
if (PSPELL pSpell=GetSpellByID(pPetInfoWindow->Buff[nBuff]))
{
if (!stricmp(GETFIRST(),pSpell->Name))
{
Dest.DWord=nBuff+1;
Dest.Type=pIntType;
return true;
}
}
}
}
#undef pPetInfoWindow
return false;
case GroupLeaderExp:
Dest.Float=(FLOAT)pChar->GroupLeadershipExp;
Dest.Type=pFloatType;
return true;
case RaidLeaderExp:
Dest.Float=(FLOAT)pChar->RaidLeadershipExp;
Dest.Type=pFloatType;
return true;
case PctGroupLeaderExp:
Dest.Float=(float)pChar->GroupLeadershipExp/10.0f;
Dest.Type=pFloatType;
return true;
case PctRaidLeaderExp:
Dest.Float=(float)pChar->RaidLeadershipExp/10.0f;
Dest.Type=pFloatType;
return true;
case GroupLeaderPoints:
Dest.DWord=pChar->GroupLeadershipPoints;
Dest.Type=pIntType;
return true;
case RaidLeaderPoints:
Dest.DWord=pChar->RaidLeadershipPoints;
Dest.Type=pIntType;
return true;
case Stunned:
Dest.DWord=(pChar->Stunned==1);
Dest.Type=pBoolType;
return true;
case LargestFreeInventory:
{
Dest.DWord=0;
Dest.Type=pIntType;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pItem = GetCharInfo2()->InventoryArray[slot])
{
if (pItem->Item->Type==ITEMTYPE_PACK && pItem->Item->SizeCapacity>Dest.DWord)
{
for (DWORD pslot=0;pslot<(pItem->Item->Slots);pslot++)
{
if (!pItem->Contents[pslot])
{
Dest.DWord=pItem->Item->SizeCapacity;
break;// break the loop for this pack
}
}
}
}
else
{
Dest.DWord=4;
return true;
}
}
}
return true;
case FreeInventory:
if (ISINDEX())
{
DWORD nSize=GETNUMBER();
if (nSize>4)
nSize=4;
Dest.DWord=0;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pItem = GetCharInfo2()->InventoryArray[slot])
{
if (pItem->Item->Type==ITEMTYPE_PACK && pItem->Item->SizeCapacity>=nSize)
{
for (DWORD pslot=0;pslot<(pItem->Item->Slots);pslot++)
{
if (!pItem->Contents[pslot])
Dest.DWord++;
}
}
}
else
{
Dest.DWord++;
}
}
Dest.Type=pIntType;
return true;
}
else
{
Dest.DWord=0;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pItem = GetCharInfo2()->InventoryArray[slot])
{
if (pItem->Item->Type==ITEMTYPE_PACK)
{
for (DWORD pslot=0;pslot<(pItem->Item->Slots);pslot++)
{
if (!pItem->Contents[pslot])
Dest.DWord++;
}
}
}
else
{
Dest.DWord++;
}
}
Dest.Type=pIntType;
return true;
}
case Drunk:
Dest.DWord=GetCharInfo2()->Drunkenness;
Dest.Type=pIntType;
return true;
case TargetOfTarget:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn)
if (Dest.Ptr=GetSpawnByID(pChar->pSpawn->TargetOfTarget))
{
Dest.Type=pSpawnType;
return true;
}
return false;
case RaidAssistTarget:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn)
if (ISINDEX() && ISNUMBER())
{
DWORD N=GETNUMBER()-1;
if (N>=3)
return false;
if (Dest.Ptr=GetSpawnByID(pChar->pSpawn->RaidAssistNPC[N]))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
case GroupAssistTarget:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn)
{
if (Dest.Ptr=GetSpawnByID(pChar->pSpawn->GroupAssistNPC[0]))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
case RaidMarkNPC:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn)
if (ISINDEX() && ISNUMBER())
{
DWORD N=GETNUMBER()-1;
if (N>=3)
return false;
if (Dest.Ptr=GetSpawnByID(pChar->pSpawn->RaidMarkNPC[N]))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
case GroupMarkNPC:
if (gGameState==GAMESTATE_INGAME && GetCharInfo()->pSpawn)
if (ISINDEX() && ISNUMBER())
{
DWORD N=GETNUMBER()-1;
if (N>=3)
return false;
if (Dest.Ptr=GetSpawnByID(pChar->pSpawn->GroupMarkNPC[N]))
{
Dest.Type=pSpawnType;
return true;
}
}
return false;
case STR:
Dest.DWord=pChar->STR;
Dest.Type=pIntType;
return true;
case STA:
Dest.DWord=pChar->STA;
Dest.Type=pIntType;
return true;
case AGI:
Dest.DWord=pChar->AGI;
Dest.Type=pIntType;
return true;
case DEX:
Dest.DWord=pChar->DEX;
Dest.Type=pIntType;
return true;
case WIS:
Dest.DWord=pChar->WIS;
Dest.Type=pIntType;
return true;
case INT:
Dest.DWord=pChar->INT;
Dest.Type=pIntType;
return true;
case CHA:
Dest.DWord=pChar->CHA;
Dest.Type=pIntType;
return true;
case svMagic:
Dest.DWord=pChar->SaveMagic;
Dest.Type=pIntType;
return true;
case svFire:
Dest.DWord=pChar->SaveFire;
Dest.Type=pIntType;
return true;
case svCold:
Dest.DWord=pChar->SaveCold;
Dest.Type=pIntType;
return true;
case svPoison:
Dest.DWord=pChar->SavePoison;
Dest.Type=pIntType;
return true;
case svDisease:
Dest.DWord=pChar->SaveDisease;
Dest.Type=pIntType;
return true;
case CurrentWeight:
Dest.DWord=pChar->CurrWeight;
Dest.Type=pIntType;
return true;
case AAPointsSpent:
Dest.DWord=GetCharInfo2()->AAPointsSpent;
Dest.Type=pIntType;
return true;
case AAPointsTotal:
Dest.DWord=GetCharInfo2()->AAPointsSpent+GetCharInfo2()->AAPoints;
Dest.Type=pIntType;
return true;
case TributeActive:
Dest.DWord=*pTributeActive;
Dest.Type=pBoolType;
return true;
case Running:
Dest.DWord=(*EQADDR_RUNWALKSTATE);
Dest.Type=pBoolType;
return true;
case GroupSize:
Dest.DWord= 0;
{
if(!pChar->pGroupInfo) return false;
for(int i=1; i<6; i++)
if (pChar->pGroupInfo->pMember[i]) Dest.DWord++;
if (Dest.DWord) Dest.DWord++;
}
Dest.Type=pIntType;
return true;
case TributeTimer:
Dest.DWord=pChar->TributeTimer/60/100;
Dest.Type=pTicksType;
return true;
case RadiantCrystals:
Dest.DWord=pChar->RadiantCrystals;
Dest.Type=pIntType;
return true;
case EbonCrystals:
Dest.DWord=pChar->EbonCrystals;
Dest.Type=pIntType;
return true;
case Shrouded:
Dest.DWord=GetCharInfo2()->Shrouded;
Dest.Type=pBoolType;
return true;
case AutoFire:
Dest.DWord=gAutoFire;
Dest.Type=pBoolType;
return true;
case Language:
if(!ISINDEX())
return false;
if(ISNUMBER())
{
nLang=GETNUMBER()-1;
Dest.Ptr=pEverQuest->GetLangDesc(nLang);
Dest.Type=pStringType;
return true;
}
else
nLang=GetLanguageIDByName(GETFIRST())-1;
if(nLang<0 || nLang>=25)
return false;
Dest.DWord=nLang;
Dest.Type=pIntType;
return true;
case Aura:
if(PAURAMGR pAura=(PAURAMGR)pAuraMgr)
{
if(pAura->NumAuras)
{
PAURAS pAuras = (PAURAS)(*pAura->pAuraInfo);
if(ISINDEX())
{
DWORD n = 0;
if(ISNUMBER())
{
n = GETNUMBER();
if(n > pAura->NumAuras)
return false;
n--;
strcpy(DataTypeTemp, pAuras->Aura[n].Name);
}
else
{
for(n = 0; n < pAura->NumAuras; n++)
{
if(!stricmp(GETFIRST(), pAuras->Aura[n].Name))
{
strcpy(DataTypeTemp, pAuras->Aura[n].Name);
}
}
}
}
else
{
strcpy(DataTypeTemp, pAuras->Aura[0].Name);
}
if(DataTypeTemp[0])
{
// fucking SoE punctuation error
if(!strcmp(DataTypeTemp, "Disciples Aura"))
Dest.Ptr = GetSpellByName("Disciple's Aura");
else
Dest.Ptr = GetSpellByName(DataTypeTemp);
Dest.Type = pSpellType;
return true;
}
}
}
return false;
case LAMarkNPC:
Dest.DWord=GetCharInfo()->ActiveAbilities.MarkNPC;
Dest.Type=pIntType;
return true;
case LANPCHealth:
Dest.DWord=GetCharInfo()->ActiveAbilities.NPCHealth;
Dest.Type=pIntType;
return true;
case LADelegateMA:
Dest.DWord=GetCharInfo()->ActiveAbilities.DelegateMA;
Dest.Type=pIntType;
return true;
case LADelegateMarkNPC:
Dest.DWord=GetCharInfo()->ActiveAbilities.DelegateMarkNPC;
Dest.Type=pIntType;
return true;
case LAInspectBuffs:
Dest.DWord=GetCharInfo()->ActiveAbilities.InspectBuffs;
Dest.Type=pIntType;
return true;
case LASpellAwareness:
Dest.DWord=GetCharInfo()->ActiveAbilities.SpellAwareness;
Dest.Type=pIntType;
return true;
case LAOffenseEnhancement:
Dest.DWord=GetCharInfo()->ActiveAbilities.OffenseEnhancement;
Dest.Type=pIntType;
return true;
case LAManaEnhancement:
Dest.DWord=GetCharInfo()->ActiveAbilities.ManaEnhancement;
Dest.Type=pIntType;
return true;
case LAHealthEnhancement:
Dest.DWord=GetCharInfo()->ActiveAbilities.HealthEnhancement;
Dest.Type=pIntType;
return true;
case LAHealthRegen:
Dest.DWord=GetCharInfo()->ActiveAbilities.HealthRegen;
Dest.Type=pIntType;
return true;
case LAFindPathPC:
Dest.DWord=GetCharInfo()->ActiveAbilities.FindPathPC;
Dest.Type=pIntType;
return true;
case LAHoTT:
Dest.DWord=GetCharInfo()->ActiveAbilities.HoTT;
Dest.Type=pIntType;
return true;
case ActiveFavorCost:
if(*pTributeActive)
{
Dest.Int=pEQMisc->GetActiveFavorCost();
Dest.Type=pIntType;
return true;
}
return false;
case CombatState:
switch(((PCPLAYERWND)pPlayerWnd)->CombatState)
{
case 0:
if(((CXWnd*)pPlayerWnd)->GetChildItem("PW_CombatStateAnim"))
{
Dest.Ptr="COMBAT";
break;
}
Dest.Ptr="NULL";
break;
case 1:
Dest.Ptr="DEBUFFED";
break;
case 2:
Dest.Ptr="COOLDOWN";
break;
case 3:
Dest.Ptr="ACTIVE";
break;
case 4:
Dest.Ptr="RESTING";
break;
default:
Dest.Ptr="UNKNOWN";
break;
}
Dest.Type=pStringType;
return true;
case svCorruption:
Dest.DWord=pChar->SaveCorruption;
Dest.Type=pIntType;
return true;
case svPrismatic:
Dest.DWord=(pChar->SaveMagic + pChar->SaveFire + pChar->SaveCold + pChar->SavePoison + pChar->SaveDisease)/5;
Dest.Type=pIntType;
return true;
case svChromatic:
{
unsigned int lowSave;
lowSave = pChar->SaveMagic;
if(lowSave > pChar->SaveFire)
lowSave = pChar->SaveFire;
if(lowSave > pChar->SaveCold)
lowSave = pChar->SaveCold;
if(lowSave > pChar->SavePoison)
lowSave = pChar->SavePoison;
if(lowSave > pChar->SaveDisease)
lowSave = pChar->SaveDisease;
Dest.DWord=lowSave;
Dest.Type=pIntType;
return true;
}
case Doubloons:
Dest.DWord=pOtherCharData->GetAltCurrency(ALTCURRENCY_DOUBLOONS);
Dest.Type=pIntType;
return true;
case Orux:
Dest.DWord=pOtherCharData->GetAltCurrency(ALTCURRENCY_ORUX);
Dest.Type=pIntType;
return true;
case Phosphenes:
Dest.DWord=pOtherCharData->GetAltCurrency(ALTCURRENCY_PHOSPHENES);
Dest.Type=pIntType;
return true;
case Phosphites:
Dest.DWord=pOtherCharData->GetAltCurrency(ALTCURRENCY_PHOSPHITES);
Dest.Type=pIntType;
return true;
case Fellowship:
Dest.Ptr=&pChar->pSpawn->Fellowship;
Dest.Type=pFellowshipType;
return true;
case Downtime:
if(pChar->DowntimeStamp)
Dest.DWord=((pChar->Downtime-(GetFastTime()-pChar->DowntimeStamp))/6)+1;
else
Dest.DWord=0;
Dest.Type=pTicksType;
return true;
case Counters:
Dest.DWord=0;
{
for (unsigned long k=0; k<23 ; k++)
if(PSPELL pSpell = GetSpellByID(GetCharInfo2()->Buff[k].SpellID))
if(pSpell->SpellType == 0 && GetCharInfo2()->Buff[k].DamageAbsorbRemaining)
Dest.DWord += GetCharInfo2()->Buff[k].DamageAbsorbRemaining;
}
Dest.Type=pIntType;
return true;
/*Reno*/
case Silenced:
for(int i = 0; i < 25; ++i) {
if (PSPELL spell = GetSpellByID(GetCharInfo2()->Buff[i].SpellID)) {
for(int k = 0; k < 12; ++k) {
if (spell->Attrib[k] == 96) {
Dest.Type = pBoolType;
Dest.DWord = true;
}
}
}
}
return false;
}
return false;
#undef pChar
}
bool MQ2SpellType::GETMEMBER()
{
#define pSpell ((PSPELL)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2SpellType::FindMember(Member);
if (!pMember)
return false;
switch((SpellMembers)pMember->ID)
{
case ID:
Dest.DWord=pSpell->ID;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=&pSpell->Name[0];
Dest.Type=pStringType;
return true;
case Level:
if (!ISINDEX() && GetCharInfo()->pSpawn)
{
Dest.DWord=pSpell->Level[GetCharInfo()->pSpawn->Class-1];
Dest.Type=pIntType;
return true;
}
else
{
if (ISNUMBER())
{
unsigned long nIndex=GETNUMBER()-1;
Dest.DWord=pSpell->Level[nIndex];
Dest.Type=pIntType;
return true;
}
}
return false;
case Mana:
Dest.DWord=pSpell->Mana;
Dest.Type=pIntType;
return true;
case ResistAdj:
Dest.DWord=pSpell->ResistAdj;
Dest.Type=pIntType;
return true;
case Range:
Dest.Float=pSpell->Range;
Dest.Type=pFloatType;
return true;
case AERange:
Dest.Float=pSpell->AERange;
Dest.Type=pFloatType;
return true;
case PushBack:
Dest.Float=pSpell->PushBack;
Dest.Type=pFloatType;
return true;
case CastTime:
Dest.Float=(FLOAT)pSpell->CastTime/1000;
Dest.Type=pFloatType;
return true;
case RecoveryTime:
case FizzleTime:
Dest.Float=(FLOAT)pSpell->FizzleTime/1000;
Dest.Type=pFloatType;
return true;
case RecastTime:
Dest.Float=(FLOAT)pSpell->RecastTime/1000;
Dest.Type=pFloatType;
return true;
case ResistType:
switch(pSpell->Resist)
{
case 9: Dest.Ptr="Corruption"; break;
case 7: Dest.Ptr="Prismatic"; break;
case 6: Dest.Ptr="Chromatic"; break;
case 5: Dest.Ptr="Disease"; break;
case 4: Dest.Ptr="Poison"; break;
case 3: Dest.Ptr="Cold"; break;
case 2: Dest.Ptr="Fire"; break;
case 1: Dest.Ptr="Magic"; break;
case 0: Dest.Ptr="Unresistable"; break;
default: Dest.Ptr="Unknown"; break;
}
Dest.Type=pStringType;
return true;
case SpellType:
switch(pSpell->SpellType)
{
case 2: Dest.Ptr="Beneficial(Group)"; break;
case 1: Dest.Ptr="Beneficial"; break;
case 0: Dest.Ptr="Detrimental"; break;
default: Dest.Ptr="Unknown"; break;
}
Dest.Type=pStringType;
return true;
case TargetType:
switch(pSpell->TargetType)
{
case 41: Dest.Ptr="Group v2"; break;
case 40: Dest.Ptr="AE PC v2"; break;
case 25: Dest.Ptr="AE Summoned"; break;
case 24: Dest.Ptr="AE Undead"; break;
case 20: Dest.Ptr="Targeted AE Tap"; break;
case 18: Dest.Ptr="Uber Dragons"; break;
case 17: Dest.Ptr="Uber Giants"; break;
case 16: Dest.Ptr="Plant"; break;
case 15: Dest.Ptr="Corpse"; break;
case 14: Dest.Ptr="Pet"; break;
case 13: Dest.Ptr="LifeTap"; break;
case 11: Dest.Ptr="Summoned"; break;
case 10: Dest.Ptr="Undead"; break;
case 9: Dest.Ptr="Animal"; break;
case 8: Dest.Ptr="Targeted AE"; break;
case 6: Dest.Ptr="Self"; break;
case 5: Dest.Ptr="Single"; break;
case 4: Dest.Ptr="PB AE"; break;
case 3: Dest.Ptr="Group v1"; break;
case 2: Dest.Ptr="AE PC v1"; break;
case 1: Dest.Ptr="Line of Sight"; break;
default: Dest.Ptr="Unknown"; break;
}
Dest.Type=pStringType;
return true;
case Skill:
Dest.Ptr=szSkills[pSpell->Skill];
Dest.Type=pStringType;
return true;
case MyCastTime:
{
float mct = (FLOAT)(pCharData1->GetAACastingTimeModifier((EQ_Spell*)pSpell)+pCharData1->GetFocusCastingTimeModifier((EQ_Spell*)pSpell,0)+pSpell->CastTime)/1000.0f;
if (mct < 0.50 * pSpell->CastTime/1000.0f)
Dest.Float=(FLOAT)0.50 * (pSpell->CastTime/1000.0f);
else
Dest.Float=(FLOAT) mct;
}
Dest.Type=pFloatType;
return true;
case Duration:
Dest.DWord=GetSpellDuration(pSpell,(PSPAWNINFO)pCharSpawn);
Dest.Type=pTicksType;
return true;
case CastOnYou:
Dest.Ptr=pSpell->CastOnYou;
Dest.Type=pStringType;
return true;
case CastOnAnother:
Dest.Ptr=pSpell->CastOnAnother;
Dest.Type=pStringType;
return true;
case WearOff:
Dest.Ptr=pSpell->WearOff;
Dest.Type=pStringType;
return true;
case CounterType:
{
Dest.Type=pStringType;
int i;
for (i=0; i<=11; i++){
switch(pSpell->Attrib[i])
{
case 35:
Dest.Ptr="Disease";
return true;
case 36:
Dest.Ptr="Poison";
return true;
case 116:
Dest.Ptr="Curse";
return true;
case 369:
Dest.Ptr="Corruption";
return true;
}
}
Dest.Ptr="None";
return true;
}
case CounterNumber:
{
Dest.Type=pIntType;
int i;
for (i=0; i<=11; i++){
if ((pSpell->Attrib[i] == 35) || (pSpell->Attrib[i] == 36) || (pSpell->Attrib[i] == 116) || (pSpell->Attrib[i] == 369)){
Dest.DWord = (int)pSpell->Base[i];
return true;
}
}
Dest.DWord = 0;
return true;
}
case Stacks:
{
unsigned long duration=99999;
if (ISNUMBER())
duration=GETNUMBER();
unsigned long nBuff;
PCHARINFO2 pChar = GetCharInfo2();
Dest.DWord = true;
Dest.Type = pBoolType;
for (nBuff=0; nBuff<25; nBuff++){
if (pChar->Buff[nBuff].SpellID>0) {
PSPELL tmpSpell = GetSpellByID(pChar->Buff[nBuff].SpellID);
if (!BuffStackTest(pSpell, tmpSpell) || ((pSpell==tmpSpell) && (pChar->Buff[nBuff].Duration>duration))){
Dest.DWord = false;
return true;
}
}
}
return true;
}
case StacksPet:
{
unsigned long petbuffduration;
unsigned long duration=99999;
if (ISNUMBER())
duration=GETNUMBER();
unsigned long nBuff;
Dest.DWord = true;
Dest.Type = pBoolType;
PEQPETINFOWINDOW pPet = ((PEQPETINFOWINDOW)pPetInfoWnd);
for (nBuff=0; nBuff<29; nBuff++){
if (pPet->Buff[nBuff]>0 && !(pPet->Buff[nBuff]==0xFFFFFFFF || pPet->Buff[nBuff]==0)) {
PSPELL tmpSpell = GetSpellByID(pPet->Buff[nBuff]);
petbuffduration = ((pPet->BuffFadeETA[nBuff]+5999)/1000)/6;
if (!BuffStackTest(pSpell, tmpSpell) || ((pSpell==tmpSpell) && (petbuffduration>duration))){
Dest.DWord = false;
return true;
}
}
}
return true;
}
case WillStack:
{
if (!ISINDEX())
return false;
PSPELL tmpSpell = NULL;
if (ISNUMBER())
tmpSpell = GetSpellByID(GETNUMBER());
else
tmpSpell = GetSpellByName(GETFIRST());
if (!tmpSpell)
return false;
Dest.Type = pBoolType;
Dest.DWord = BuffStackTest(pSpell, tmpSpell);
return true;
}
case MyRange:
Dest.Float=pSpell->Range+(float)pCharData1->GetFocusRangeModifier((EQ_Spell*)pSpell,0);
Dest.Type=pFloatType;
return true;
}
return false;
#undef pSpell
}
bool MQ2ItemType::GETMEMBER()
{
DWORD N, cmp, tmp;
#define pItem ((PCONTENTS)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2ItemType::FindMember(Member);
if (!pMember)
return false;
switch((ItemMembers)pMember->ID)
{
case ID:
Dest.DWord=pItem->Item->ItemNumber;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=&pItem->Item->Name[0];
Dest.Type=pStringType;
return true;
case Lore:
Dest.DWord=pItem->Item->Lore;
Dest.Type=pBoolType;
return true;
case NoDrop:
Dest.DWord=!pItem->Item->NoDrop;
Dest.Type=pBoolType;
return true;
case NoRent:
Dest.DWord=!pItem->Item->NoRent;
Dest.Type=pBoolType;
return true;
case Magic:
Dest.DWord=((pItem->Item->Type == ITEMTYPE_NORMAL) && (pItem->Item->Magic));
Dest.Type=pBoolType;
return true;
case Value:
Dest.DWord=pItem->Item->Cost;
Dest.Type=pIntType;
return true;
case Size:
Dest.DWord=pItem->Item->Size;
Dest.Type=pIntType;
return true;
case SizeCapacity:
Dest.DWord=pItem->Item->SizeCapacity;
Dest.Type=pIntType;
return true;
case Weight:
Dest.DWord=pItem->Item->Weight;
Dest.Type=pIntType;
return true;
case Stack:
if ((pItem->Item->Type != ITEMTYPE_NORMAL) || (((EQ_Item*)pItem)->IsStackable()!=1))
Dest.DWord=1;
else
Dest.DWord=pItem->StackCount;
Dest.Type=pIntType;
return true;
case Type:
if (pItem->Item->Type == ITEMTYPE_NORMAL)
{
if ((pItem->Item->ItemType < MAX_ITEMTYPES) && (szItemTypes[pItem->Item->ItemType] != NULL))
{
Dest.Ptr=szItemTypes[pItem->Item->ItemType];
}
else
{
Dest.Ptr=&DataTypeTemp[0];
sprintf(DataTypeTemp,"*UnknownType%d",pItem->Item->ItemType);
}
}
else if (pItem->Item->Type == ITEMTYPE_PACK)
{
if ((pItem->Item->Combine < MAX_COMBINES) && (szCombineTypes[pItem->Item->Combine] != NULL))
{
Dest.Ptr=szCombineTypes[pItem->Item->Combine];
}
else
{
Dest.Ptr=&DataTypeTemp[0];
sprintf(DataTypeTemp,"*UnknownCombine%d",pItem->Item->Combine);
}
}
else if (pItem->Item->Type == ITEMTYPE_BOOK)
Dest.Ptr="Book";
Dest.Type=pStringType;
return true;
case Charges:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Charges;
Dest.Type=pIntType;
return true;
case LDoNTheme:
Dest.Ptr=GetLDoNTheme(pItem->Item->LDTheme);
Dest.Type=pStringType;
return true;
case DMGBonusType:
Dest.Ptr=szDmgBonusType[pItem->Item->DmgBonusType];
Dest.Type=pStringType;
return true;
case Container:
if (pItem->Item->Type == ITEMTYPE_PACK)
{
Dest.DWord=pItem->Item->Slots;
}
else
Dest.DWord=0;
Dest.Type=pIntType;
return true;
case Items:
if (pItem->Item->Type == ITEMTYPE_PACK)
{
Dest.DWord=0;
for (unsigned long N=0 ; N < pItem->Item->Slots ; N++)
{
if (pItem->Contents[N])
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
}
return false;
case Item:
if (pItem->Item->Type == ITEMTYPE_PACK && ISNUMBER())
{
unsigned long N=GETNUMBER();
N--;
if (N<pItem->Item->Slots)
{
if (Dest.Ptr=pItem->Contents[N])
{
Dest.Type=pItemType;
return true;
}
}
} else if (pItem->Item->Type == ITEMTYPE_NORMAL && ISNUMBER()) {
unsigned long N=GETNUMBER();
N--;
Dest.Ptr=NULL;
switch (N)
{
case 0:
if (pItem->Item->AugSlot1) Dest.Ptr=pItem->Contents[N];
break;
case 1:
if (pItem->Item->AugSlot2) Dest.Ptr=pItem->Contents[N];
break;
case 2:
if (pItem->Item->AugSlot3) Dest.Ptr=pItem->Contents[N];
break;
case 3:
if (pItem->Item->AugSlot4) Dest.Ptr=pItem->Contents[N];
break;
case 4:
if (pItem->Item->AugSlot5) Dest.Ptr=pItem->Contents[N];
break;
}
if (Dest.Ptr) return true;
}
return false;
case Stackable:
Dest.DWord=((EQ_Item*)pItem)->IsStackable();
Dest.Type=pBoolType;
return true;
case InvSlot:
Dest.Int=FindInvSlotForContents(pItem);
if (Dest.Int>=0)
{
Dest.Type=pInvSlotType;
return true;
}
return false;
case BuyPrice:
if (pActiveMerchant && pItem->MerchantSlot)
{
Dest.DWord=pItem->Price;
Dest.Type=pIntType;
return true;
}
return false;
case SellPrice:
if (pActiveMerchant)
{
Dest.DWord=(DWORD)((FLOAT)pItem->Item->Cost*(1.0f/((PEQMERCHWINDOW)pMerchantWnd)->Markup));
Dest.Type=pIntType;
return true;
}
return false;
case WornSlot:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count)
return false;
cmp=pItem->Item->EquipSlots;
for (N = 0 ; N < 32 ; N++)
{
if (cmp&(1<<N))
{
Count--;
if (Count==0)
{
Dest.DWord=N;
Dest.Type=pInvSlotType;
return true;
}
}
}
}
else
{
// by name
DWORD nInvSlot=ItemSlotMap[GETFIRST()];
if ((nInvSlot || !stricmp(GETFIRST(),"charm")) && nInvSlot<32)
{
Dest.DWord=(pItem->Item->EquipSlots&(1<<nInvSlot));
Dest.Type=pBoolType;
return true;
}
}
}
return false;
case WornSlots:
{
Dest.DWord=0;
// count bits
cmp=pItem->Item->EquipSlots;
for (N = 0 ; N < 32 ; N++)
{
if (cmp&(1<<N))
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
}
case CastTime:
Dest.Float=(FLOAT)pItem->Item->Clicky.CastTime/1000;
Dest.Type=pFloatType;
return true;
case Spell:
if (Dest.Ptr=GetSpellByID(pItem->Item->Clicky.SpellID))
{
Dest.Type=pSpellType;
return true;
}
if (Dest.Ptr=GetSpellByID(pItem->Item->Scroll.SpellID))
{
Dest.Type=pSpellType;
return true;
}
if (Dest.Ptr=GetSpellByID(pItem->Item->Proc.SpellID))
{
Dest.Type=pSpellType;
return true;
}
if (Dest.Ptr=GetSpellByID(pItem->Item->Focus.SpellID))
{
Dest.Type=pSpellType;
return true;
}
if (Dest.Ptr=GetSpellByID(pItem->Item->Worn.SpellID))
{
Dest.Type=pSpellType;
return true;
}
return false;
case EffectType:
//0 Proc
//1 Clickable from inventory (any class)
//2 Worn effect (haste, cleave)
//3 Unknown
//4 Clickable must be worn
//5 Clickable from inventory (class restricted)
//6 Focus effect
//7 Memmable spell scroll
// This used to return an int type with a case statment, items could have
// only one effect. For backwards compatibility we return based on a hierarchy.
// A zero in any field indicates no effect (others will also be zero)
if (!pItem->Item->Clicky.SpellID)
{
return false;
}
else if (pItem->Item->Scroll.SpellID!=-1)
{
Dest.Ptr="Spell Scroll";
}
else if (pItem->Item->Clicky.SpellID!=-1)
{
// code to detect must-be-worn etc here
switch (pItem->Item->Clicky.EffectType)
{
case 4:
Dest.Ptr="Click Worn";
break;
case 1:
case 5:
Dest.Ptr="Click Inventory";
break;
default:
Dest.Ptr="Click Unknown";
}
}
else if (pItem->Item->Focus.SpellID!=-1 || pItem->Item->Worn.SpellID!=-1)
{
Dest.Ptr="Worn";
}
else if (pItem->Item->Proc.SpellID!=-1)
{
Dest.Ptr="Combat";
}
else
{
return false;
}
Dest.Type=pStringType;
return true;
case InstrumentMod:
Dest.Float=((FLOAT)pItem->Item->InstrumentMod)/10.0f;
Dest.Type=pFloatType;
return true;
case Tribute:
Dest.DWord=pItem->Item->Favor;
Dest.Type=pIntType;
return true;
case Attuneable:
Dest.DWord=pItem->Item->Attuneable;
Dest.Type=pBoolType;
return true;
case Timer:
if(pItem->Item->Clicky.TimerID!=0xFFFFFFFF)
{
Dest.DWord=(GetItemTimer(pItem)+5)/6;
Dest.Type=pTicksType;
return true;
}
if (pItem->Item->Clicky.SpellID!=-1)
{
Dest.DWord=0; // insta-clicky
Dest.Type=pTicksType;
return true;
}
return false;
case ItemDelay:
Dest.DWord=pItem->Item->Delay;
Dest.Type=pIntType;
return true;
case TimerReady:
if(pItem->Item->Clicky.TimerID!=0xFFFFFFFF)
{
Dest.DWord=GetItemTimer(pItem);
Dest.Type=pIntType;
return true;
}
if (pItem->Item->Clicky.SpellID!=-1)
{
Dest.DWord=0; // insta-click or instant recast
Dest.Type=pIntType;
return true;
}
return false;
case StackSize:
if ((pItem->Item->Type != ITEMTYPE_NORMAL) || (((EQ_Item*)pItem)->IsStackable()!=1))
Dest.DWord=1;
else
Dest.DWord=pItem->Item->StackSize;
Dest.Type=pIntType;
return true;
case Stacks:
{
Dest.DWord=0;
Dest.Type=pIntType;
if (!((EQ_Item*)pItem)->IsStackable()) return true;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pTempItem = GetCharInfo2()->InventoryArray[slot])
{
if (pTempItem->Item->Type==ITEMTYPE_PACK)
{
for (DWORD pslot=0;pslot<(pTempItem->Item->Slots);pslot++)
{
if (pTempItem->Contents[pslot])
{
if (PCONTENTS pSlotItem = pTempItem->Contents[pslot])
{
if (pSlotItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord++;
}
}
}
}
}
else {
if (pTempItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord++;
}
}
}
}
return true;
}
case StackCount:
{
Dest.DWord=0;
Dest.Type=pIntType;
if (!((EQ_Item*)pItem)->IsStackable()) return true;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pTempItem = GetCharInfo2()->InventoryArray[slot])
{
if (pTempItem->Item->Type==ITEMTYPE_PACK)
{
for (DWORD pslot=0;pslot<(pTempItem->Item->Slots);pslot++)
{
if (pTempItem->Contents[pslot])
{
if (PCONTENTS pSlotItem = pTempItem->Contents[pslot])
{
if (pSlotItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord+=pSlotItem->StackCount;
}
}
}
}
}
else {
if (pTempItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord+=pTempItem->StackCount;
}
}
}
}
return true;
}
case FreeStack:
{
Dest.DWord=0;
Dest.Type=pIntType;
if (!((EQ_Item*)pItem)->IsStackable()) return true;
for (DWORD slot=BAG_SLOT_START;slot<NUM_INV_SLOTS;slot++)
{
if (PCONTENTS pTempItem = GetCharInfo2()->InventoryArray[slot])
{
if (pTempItem->Item->Type==ITEMTYPE_PACK)
{
for (DWORD pslot=0;pslot<(pTempItem->Item->Slots);pslot++)
{
if (pTempItem->Contents[pslot])
{
if (PCONTENTS pSlotItem = pTempItem->Contents[pslot])
{
if (pSlotItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord+=(pSlotItem->Item->StackSize-pSlotItem->StackCount);
}
}
}
}
}
else {
if (pTempItem->Item->ItemNumber==pItem->Item->ItemNumber)
{
Dest.DWord+=(pTempItem->Item->StackSize-pTempItem->StackCount);
}
}
}
}
return true;
}
case MerchQuantity:
if (pActiveMerchant && pItem->MerchantSlot) {
Dest.DWord=pItem->MerchantQuantity;
Dest.Type=pIntType;
return true;
}
return false;
case Classes:
Dest.DWord=0;
// count bits
cmp=pItem->Item->Classes;
for (N = 0 ; N < 16 ; N++)
{
if (cmp&(1<<N))
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
case Class:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count)
return false;
cmp=pItem->Item->Classes;
for (N = 0 ; N < 16 ; N++)
{
if (cmp&(1<<N))
{
Count--;
if (Count==0)
{
Dest.DWord=N+1;
Dest.Type=pClassType;
return true;
}
}
}
}
else
{
// by name
cmp=pItem->Item->Classes;
for (N = 0 ; N < 16 ; N++) {
if (cmp&(1<<N)) {
if (!stricmp(GETFIRST(), GetClassDesc(N+1)) ||
!stricmp(GETFIRST(), pEverQuest->GetClassThreeLetterCode(N+1))) {
Dest.DWord=N+1;
Dest.Type=pClassType;
return true;
}
}
}
return false;
}
}
return false;
case Races:
Dest.DWord=0;
// count bits
cmp=pItem->Item->Races;
for (N = 0 ; N < 15 ; N++)
{
if (cmp&(1<<N))
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
case Race:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count)
return false;
cmp=pItem->Item->Races;
for (N = 0 ; N < 15 ; N++)
{
if (cmp&(1<<N))
{
Count--;
if (Count==0) {
Dest.DWord=N+1;
switch (N) {
case 12:
Dest.DWord = 128; // IKS
break;
case 13:
Dest.DWord = 130; // VAH
break;
case 14:
Dest.DWord = 330; // FRG
break;
}
Dest.Type=pRaceType;
return true;
}
}
}
}
else
{
// by name
cmp=pItem->Item->Races;
for (N = 0 ; N < 15 ; N++) {
if (cmp&(1<<N)) {
tmp = N+1;
switch (N) {
case 12:
tmp = 128; // IKS
break;
case 13:
tmp = 130; // VAH
break;
case 14:
tmp = 330; // FRG
break;
}
if (!stricmp(GETFIRST(), pEverQuest->GetRaceDesc(tmp))) {
Dest.DWord=tmp;
Dest.Type=pRaceType;
return true;
}
}
}
return false;
}
}
return false;
case Deities:
Dest.DWord=0;
// count bits
cmp=pItem->Item->Diety;
for (N = 0 ; N < 15 ; N++)
{
if (cmp&(1<<N))
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
case Deity:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count)
return false;
cmp=pItem->Item->Diety;
for (N = 0 ; N < 15 ; N++)
{
if (cmp&(1<<N))
{
Count--;
if (Count==0)
{
Dest.DWord=N+200;
Dest.Type=pDeityType;
return true;
}
}
}
}
else
{
// by name
cmp=pItem->Item->Diety;
for (N = 0 ; N < 16 ; N++) {
if (cmp&(1<<N)) {
if (!stricmp(GETFIRST(), pEverQuest->GetDeityDesc(N+200))) {
Dest.DWord=N+200;
Dest.Type=pDeityType;
return true;
}
}
}
return false;
}
}
return false;
case RequiredLevel:
Dest.DWord=pItem->Item->RequiredLevel;
Dest.Type=pIntType;
return true;
case Evolving:
Dest.Ptr=pItem;
Dest.Type=pEvolvingItemType;
return true;
case AC:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AC;
Dest.Type=pIntType;
return true;
case HP:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HP;
Dest.Type=pIntType;
return true;
case STR:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->STR;
Dest.Type=pIntType;
return true;
case STA:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->STA;
Dest.Type=pIntType;
return true;
case AGI:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->AGI;
Dest.Type=pIntType;
return true;
case DEX:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->DEX;
Dest.Type=pIntType;
return true;
case CHA:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->CHA;
Dest.Type=pIntType;
return true;
case INT:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->INT;
Dest.Type=pIntType;
return true;
case WIS:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->WIS;
Dest.Type=pIntType;
return true;
case Mana:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->Mana;
Dest.Type=pIntType;
return true;
case ManaRegen:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->ManaRegen;
Dest.Type=pIntType;
return true;
case HPRegen:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HPRegen;
Dest.Type=pIntType;
return true;
case Attack:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->Attack;
Dest.Type=pIntType;
return true;
case svCold:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvCold;
Dest.Type=pIntType;
return true;
case svFire:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvFire;
Dest.Type=pIntType;
return true;
case svMagic:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvMagic;
Dest.Type=pIntType;
return true;
case svDisease:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvDisease;
Dest.Type=pIntType;
return true;
case svPoison:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvPoison;
Dest.Type=pIntType;
return true;
case svCorruption:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SvCorruption;
Dest.Type=pIntType;
return true;
case Haste:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->Haste;
Dest.Type=pIntType;
return true;
case DamShield:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->DamShield;
Dest.Type=pIntType;
return true;
case AugType:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugType;
Dest.Type=pIntType;
return true;
case AugRestrictions:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugRestrictions;
Dest.Type=pIntType;
return true;
case AugSlot1:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugSlot1;
Dest.Type=pIntType;
return true;
case AugSlot2:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugSlot2;
Dest.Type=pIntType;
return true;
case AugSlot3:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugSlot3;
Dest.Type=pIntType;
return true;
case AugSlot4:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugSlot4;
Dest.Type=pIntType;
return true;
case AugSlot5:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->AugSlot5;
Dest.Type=pIntType;
return true;
case Power:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Power;
Dest.Type=pIntType;
return true;
case MaxPower:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->MaxPower;
Dest.Type=pIntType;
return true;
case Purity:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->Purity;
Dest.Type=pIntType;
return true;
case Avoidance:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->Avoidance;
Dest.Type=pIntType;
return true;
case SpellShield:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->SpellShield;
Dest.Type=pIntType;
return true;
case StrikeThrough:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->StrikeThrough;
Dest.Type=pIntType;
return true;
case StunResist:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->StunResist;
Dest.Type=pIntType;
return true;
case Shielding:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->Shielding;
Dest.Type=pIntType;
return true;
case Accuracy:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->Accuracy;
Dest.Type=pIntType;
return true;
case CombatEffects:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->CombatEffects;
Dest.Type=pIntType;
return true;
case DoTShielding:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=(char)pItem->Item->DoTShielding;
Dest.Type=pIntType;
return true;
case HeroicSTR:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSTR;
Dest.Type=pIntType;
return true;
case HeroicINT:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicINT;
Dest.Type=pIntType;
return true;
case HeroicWIS:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicWIS;
Dest.Type=pIntType;
return true;
case HeroicAGI:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicAGI;
Dest.Type=pIntType;
return true;
case HeroicDEX:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicDEX;
Dest.Type=pIntType;
return true;
case HeroicSTA:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSTA;
Dest.Type=pIntType;
return true;
case HeroicCHA:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicCHA;
Dest.Type=pIntType;
return true;
case HeroicSvMagic:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvMagic;
Dest.Type=pIntType;
return true;
case HeroicSvFire:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvFire;
Dest.Type=pIntType;
return true;
case HeroicSvCold:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvCold;
Dest.Type=pIntType;
return true;
case HeroicSvDisease:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvDisease;
Dest.Type=pIntType;
return true;
case HeroicSvPoison:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvPoison;
Dest.Type=pIntType;
return true;
case HeroicSvCorruption:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HeroicSvCorruption;
Dest.Type=pIntType;
return true;
case EnduranceRegen:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->EnduranceRegen;
Dest.Type=pIntType;
return true;
case HealAmount:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->HealAmount;
Dest.Type=pIntType;
return true;
case Clairvoyance:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->Clairvoyance;
Dest.Type=pIntType;
return true;
case DamageShieldMitigation:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->DamageShieldMitigation;
Dest.Type=pIntType;
return true;
case SpellDamage:
if (pItem->Item->Type != ITEMTYPE_NORMAL)
Dest.DWord=0;
else
Dest.DWord=pItem->Item->SpellDamage;
Dest.Type=pIntType;
return true;
case Augs:
Dest.DWord = 0;
Dest.Type=pIntType;
if (pItem->Item->Type == ITEMTYPE_NORMAL) {
if (pItem->Item->AugSlot5) Dest.DWord++;
if (pItem->Item->AugSlot4) Dest.DWord++;
if (pItem->Item->AugSlot3) Dest.DWord++;
if (pItem->Item->AugSlot2) Dest.DWord++;
if (pItem->Item->AugSlot1) Dest.DWord++;
Dest.Type=pIntType;
}
return true;
case Tradeskills:
Dest.DWord=pItem->Item->TradeSkills;
Dest.Type=pBoolType;
return true;
}
return false;
#undef pItem
}
bool MQ2WindowType::GETMEMBER()
{
#define pWnd ((PCSIDLWND)VarPtr.Ptr)
PMQ2TYPEMEMBER pMember=MQ2WindowType::FindMember(Member);
if (!pMember)
return false;
switch((WindowMembers)pMember->ID)
{
case Open:
Dest.DWord=pWnd->Show;
Dest.Type=pBoolType;
return true;
case Child:
if (Dest.Ptr=((CSidlScreenWnd*)VarPtr.Ptr)->GetChildItem(GETFIRST()))
{
Dest.Type=pWindowType;
return true;
}
Dest.DWord=0;
Dest.Type=pIntType;
return true;
case Parent:
if (Dest.Ptr=pWnd->pParentWindow)
{
Dest.Type=pWindowType;
return true;
}
Dest.DWord=0;
Dest.Type=pIntType;
return true;
case FirstChild:
if (Dest.Ptr=pWnd->pFirstChildWnd)
{
Dest.Type=pWindowType;
return true;
}
Dest.DWord=0;
Dest.Type=pIntType;
return true;
case Next:
if (Dest.Ptr=pWnd->pNextSiblingWnd)
{
Dest.Type=pWindowType;
return true;
}
Dest.DWord=0;
Dest.Type=pIntType;
return true;
case VScrollMax:
Dest.DWord=pWnd->VScrollMax;
Dest.Type=pIntType;
return true;
case VScrollPos:
Dest.DWord=pWnd->VScrollPos;
Dest.Type=pIntType;
return true;
case VScrollPct:
Dest.DWord=(pWnd->VScrollPos*100)/pWnd->VScrollMax;
Dest.Type=pIntType;
return true;
case HScrollMax:
Dest.DWord=pWnd->HScrollMax;
Dest.Type=pIntType;
return true;
case HScrollPos:
Dest.DWord=pWnd->HScrollPos;
Dest.Type=pIntType;
return true;
case HScrollPct:
Dest.DWord=(pWnd->HScrollPos*100)/pWnd->HScrollMax;
Dest.Type=pIntType;
return true;
case Children:
Dest.DWord=(DWORD)pWnd->pFirstChildWnd;
Dest.Type=pBoolType;
return true;
case Siblings:
Dest.DWord=(DWORD)pWnd->pNextSiblingWnd;
Dest.Type=pBoolType;
return true;
case Minimized:
Dest.DWord=pWnd->Minimized;
Dest.Type=pBoolType;
return true;
case MouseOver:
Dest.DWord=pWnd->MouseOver;
Dest.Type=pBoolType;
return true;
case X:
Dest.DWord=pWnd->Location.left;
Dest.Type=pIntType;
return true;
case Y:
Dest.DWord=pWnd->Location.top;
Dest.Type=pIntType;
return true;
case Width:
Dest.DWord=pWnd->Location.right-pWnd->Location.left;
Dest.Type=pIntType;
return true;
case Height:
Dest.DWord=pWnd->Location.bottom-pWnd->Location.top;
Dest.Type=pIntType;
return true;
case BGColor:
Dest.DWord=pWnd->BGColor.ARGB;
Dest.Type=pArgbType;
return true;
case Text:
if(((CXWnd*)pWnd)->GetType()==UI_STMLBox)
GetCXStr(pWnd->SidlText,DataTypeTemp,MAX_STRING);
else
GetCXStr(pWnd->WindowText,DataTypeTemp,MAX_STRING);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Tooltip:
GetCXStr(pWnd->Tooltip,DataTypeTemp,MAX_STRING);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Checked:
Dest.Int=pWnd->Checked;
Dest.Type=pBoolType;
return true;
case Highlighted:
Dest.Int=pWnd->Highlighted;
Dest.Type=pBoolType;
return true;
case Enabled:
Dest.Int=(pWnd->Enabled!=0);
Dest.Type=pBoolType;
return true;
case Style:
Dest.DWord=pWnd->WindowStyle;
Dest.Type=pIntType;
return true;
case List:
{
int n = 0;
if (((CXWnd*)pWnd)->GetType()==UI_Combobox)
VarPtr.Ptr=pWnd->SidlText;
else if (((CXWnd*)pWnd)->GetType()!=UI_Listbox)
return false;
#ifndef ISXEQ
if (PCHAR pComma=strchr(Index,',')) {
n = atoi(pComma+1) - 1;
if (n < 0) n=0;
DebugSpew("List: index is %d\n", n);
*pComma = '\0';
}
#else
if (argc==2)
n=atoi(argv[1]);
if (n<0)
n=0;
#endif
if (ISNUMBER())
{
unsigned long nIndex=GETNUMBER();
if (!nIndex)
return false;
nIndex--;
CXStr Str;
((CListWnd*)pWnd)->GetItemText(&Str, nIndex, n);
GetCXStr(Str.Ptr,DataTypeTemp,MAX_STRING);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else
{
// name
BOOL bEqual=false;
CHAR Name[MAX_STRING]={0};
if (GETFIRST()[0]=='=')
{
bEqual=true;
strcpy(Name,&GETFIRST()[1]);
}
else
strcpy(Name,GETFIRST());
strlwr(Name);
unsigned long nIndex=0;
while(1)
{
CXStr Str;
((CListWnd*)pWnd)->GetItemText(&Str, nIndex,n);
GetCXStr(Str.Ptr,DataTypeTemp,MAX_STRING);
if (DataTypeTemp[0]==0)
return false;
if (bEqual)
{
if (!stricmp(DataTypeTemp,Name))
{
Dest.DWord=nIndex+1;
Dest.Type=pIntType;
return true;
}
}
else
{
strlwr(DataTypeTemp);
if (strstr(DataTypeTemp,Name))
{
Dest.DWord=nIndex+1;
Dest.Type=pIntType;
return true;
}
}
nIndex++;
}
}
return false;
}
case Name:
{
if (CXMLData *pXMLData=((CXWnd*)pWnd)->GetXMLData())
{
if (GetCXStr(pXMLData->Name.Ptr,DataTypeTemp,MAX_STRING))
{
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
}
return false;
case ScreenID:
{
if (CXMLData *pXMLData=((CXWnd*)pWnd)->GetXMLData())
{
if (GetCXStr(pXMLData->ScreenID.Ptr,DataTypeTemp,MAX_STRING))
{
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
}
return false;
case Type:
{
if (CXMLData *pXMLData=((CXWnd*)pWnd)->GetXMLData())
{
if (GetCXStr(pXMLData->TypeName.Ptr,DataTypeTemp,MAX_STRING))
{
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
}
return false;
case Items:
if (((CXWnd*)pWnd)->GetType()==UI_Listbox)
{
Dest.DWord=((CSidlScreenWnd*)pWnd)->Items;
Dest.Type=pIntType;
}
else if (((CXWnd*)pWnd)->GetType()==UI_Combobox)
{
Dest.DWord=((CSidlScreenWnd*)pWnd->SidlText)->Items;
Dest.Type=pIntType;
}
return true;
case HisTradeReady:
if(PTRADEWINDOW pTrade=(PTRADEWINDOW)pTradeWnd) {
Dest.Int=pTrade->HisTradeReady;
Dest.Type=pBoolType;
return true;
}
case MyTradeReady:
if(PTRADEWINDOW pTrade=(PTRADEWINDOW)pTradeWnd) {
Dest.Int=pTrade->MyTradeReady;
Dest.Type=pBoolType;
return true;
}
}
return false;
#undef pWnd
}
bool MQ2CurrentZoneType::GETMEMBER()
{
#define pZone ((PZONEINFO)pZoneInfo)
PMQ2TYPEMEMBER pMember=MQ2CurrentZoneType::FindMember(Member);
if (!pMember)
return false;
// return pZoneType->GetMember(*(MQ2VARPTR*)&((PWORLDDATA)pWorldData)->ZoneArray[GetCharInfo()->zoneId],Member,Index,Dest);
switch((CurrentZoneMembers)pMember->ID)
{
case ID:
Dest.Int = GetCharInfo()->zoneId;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=&pZone->LongName[0];
Dest.Type=pStringType;
return true;
case ShortName:
Dest.Ptr=&pZone->ShortName[0];
Dest.Type=pStringType;
return true;
case Type:
Dest.DWord=pZone->ZoneType;
Dest.Type=pIntType;
return true;
case Gravity:
Dest.Float=pZone->ZoneGravity;
Dest.Type=pFloatType;
return true;
case SkyType:
Dest.DWord=pZone->SkyType;
Dest.Type=pIntType;
return true;
#if 0
case SafeN:
case SafeY:
Dest.Float=pZone->SafeYLoc;
Dest.Type=pFloatType;
return true;
case SafeW:
case SafeX:
Dest.Float=pZone->SafeXLoc;
Dest.Type=pFloatType;
return true;
case SafeU:
case SafeZ:
Dest.Float=pZone->SafeZLoc;
Dest.Type=pFloatType;
return true;
#endif
case MinClip:
Dest.Float=pZone->MinClip;
Dest.Type=pFloatType;
return true;
case MaxClip:
Dest.Float=pZone->MaxClip;
Dest.Type=pFloatType;
return true;
}
return false;
#undef pZone
}
bool MQ2ZoneType::GETMEMBER()
{
#define pZone ((PZONELIST)VarPtr.Ptr)
PMQ2TYPEMEMBER pMember=MQ2ZoneType::FindMember(Member);
if (!pMember)
return false;
switch((ZoneMembers)pMember->ID)
{
case Name:
Dest.Ptr=&pZone->LongName[0];
Dest.Type=pStringType;
return true;
case ShortName:
Dest.Ptr=&pZone->ShortName[0];
Dest.Type=pStringType;
return true;
case ID:
Dest.Int=pZone->Id;
Dest.Type=pIntType;
return true;
}
return false;
#undef pZone
}
bool MQ2BodyType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2BodyType::FindMember(Member);
if (!pMember)
return false;
switch((BodyMembers)pMember->ID)
{
case ID:
Dest.Ptr=VarPtr.Ptr;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=GetBodyTypeDesc(VarPtr.DWord);
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2DeityType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2DeityType::FindMember(Member);
if (!pMember)
return false;
switch((DeityMembers)pMember->ID)
{
case ID:
Dest.Ptr=VarPtr.Ptr;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=pEverQuest->GetDeityDesc(VarPtr.DWord);
Dest.Type=pStringType;
return true;
case Team:
Dest.Ptr=szDeityTeam[GetDeityTeamByID(VarPtr.DWord)];
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2ClassType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2ClassType::FindMember(Member);
if (!pMember)
return false;
switch((ClassMembers)pMember->ID)
{
case ID:
Dest.Ptr=VarPtr.Ptr;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=GetClassDesc(VarPtr.DWord);
Dest.Type=pStringType;
return true;
case ShortName:
Dest.Ptr=pEverQuest->GetClassThreeLetterCode(VarPtr.DWord);
Dest.Type=pStringType;
return true;
case CanCast:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].CanCast;
Dest.Type=pBoolType;
return true;
}
return false;
case PureCaster:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].PureCaster;
Dest.Type=pBoolType;
return true;
}
return false;
case PetClass:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].PetClass;
Dest.Type=pBoolType;
return true;
}
return false;
case DruidType:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].DruidType;
Dest.Type=pBoolType;
return true;
}
return false;
case ShamanType:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].ShamanType;
Dest.Type=pBoolType;
return true;
}
return false;
case NecromancerType:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].NecroType;
Dest.Type=pBoolType;
return true;
}
return false;
case ClericType:
if (VarPtr.DWord<=16)
{
Dest.DWord=ClassInfo[VarPtr.DWord].ClericType;
Dest.Type=pBoolType;
return true;
}
return false;
case HealerType:
Dest.DWord=(VarPtr.DWord==2 || VarPtr.DWord==6 || VarPtr.DWord==10);
Dest.Type=pBoolType;
return true;
}
return false;
}
bool MQ2RaceType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2RaceType::FindMember(Member);
if (!pMember)
return false;
switch((RaceMembers)pMember->ID)
{
case ID:
Dest.Ptr=VarPtr.Ptr;
Dest.Type=pIntType;
return true;
case Name:
Dest.Ptr=pEverQuest->GetRaceDesc(VarPtr.DWord);
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2SwitchType::GETMEMBER()
{
#define pSwitch ((PDOOR)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2SwitchType::FindMember(Member);
if (!pMember)
return false;
switch((SwitchMembers)pMember->ID)
{
case ID:
Dest.DWord=pSwitch->ID;
Dest.Type=pIntType;
return true;
case W:
case X:
Dest.Float=pSwitch->X;
Dest.Type=pFloatType;
return true;
case N:
case Y:
Dest.Float=pSwitch->Y;
Dest.Type=pFloatType;
return true;
case U:
case Z:
Dest.Float=pSwitch->Z;
Dest.Type=pFloatType;
return true;
case DefaultW:
case DefaultX:
Dest.Float=pSwitch->DefaultX;
Dest.Type=pFloatType;
return true;
case DefaultN:
case DefaultY:
Dest.Float=pSwitch->DefaultY;
Dest.Type=pFloatType;
return true;
case DefaultU:
case DefaultZ:
Dest.Float=pSwitch->DefaultZ;
Dest.Type=pFloatType;
return true;
case Heading:
Dest.Float=pSwitch->Heading*0.703125f;
Dest.Type=pHeadingType;
return true;
case DefaultHeading:
Dest.Float=pSwitch->DefaultHeading*0.703125f;
Dest.Type=pHeadingType;
return true;
case Open:
Dest.DWord=((pSwitch->DefaultHeading != pSwitch->Heading) ||
(pSwitch->DefaultZ != pSwitch->Z));
Dest.Type=pBoolType;
return true;
case HeadingTo:
Dest.Float=(FLOAT)(atan2f(((PSPAWNINFO)pCharSpawn)->Y - pSwitch->Y, pSwitch->X - ((PSPAWNINFO)pCharSpawn)->X) * 180.0f / PI + 90.0f);
if (Dest.Float<0.0f)
Dest.Float += 360.0f;
else if (Dest.Float>=360.0f)
Dest.Float -= 360.0f;
Dest.Type=pHeadingType;
return true;
case Name:
Dest.Ptr=&pSwitch->Name[0];
Dest.Type=pStringType;
return true;
case Distance:
Dest.Float=GetDistance(pSwitch->X,pSwitch->Y);
Dest.Type=pFloatType;
return true;
case xLineOfSight:
Dest.DWord=(CastRay(GetCharInfo()->pSpawn,pSwitch->Y,pSwitch->X,pSwitch->Z));
Dest.Type=pBoolType;
return true;
}
return false;
#undef pSwitch
}
bool MQ2GroundType::GETMEMBER()
{
#define pGround ((PGROUNDITEM)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2GroundType::FindMember(Member);
if (!pMember)
return false;
switch((GroundMembers)pMember->ID)
{
case ID:
Dest.DWord=pGround->DropID;
Dest.Type=pIntType;
return true;
case W:
case X:
Dest.Float=pGround->X;
Dest.Type=pFloatType;
return true;
case N:
case Y:
Dest.Float=pGround->Y;
Dest.Type=pFloatType;
return true;
case U:
case Z:
Dest.Float=pGround->Z;
Dest.Type=pFloatType;
return true;
case Name:
Dest.Ptr=&pGround->Name[0];
Dest.Type=pStringType;
return true;
case Heading:
Dest.Float=pGround->Heading*0.703125f;
Dest.Type=pHeadingType;
return true;
case Distance:
Dest.Float=GetDistance(pGround->X,pGround->Y);
Dest.Type=pFloatType;
return true;
case HeadingTo:
Dest.Float=(FLOAT)(atan2f(((PSPAWNINFO)pCharSpawn)->Y - pGround->Y, pGround->X - ((PSPAWNINFO)pCharSpawn)->X) * 180.0f / PI + 90.0f);
if (Dest.Float<0.0f)
Dest.Float += 360.0f;
else if (Dest.Float>=360.0f)
Dest.Float -= 360.0f;
Dest.Type=pHeadingType;
return true;
case xLineOfSight:
Dest.DWord=(CastRay(GetCharInfo()->pSpawn,pGround->Y,pGround->X,pGround->Z));
Dest.Type=pBoolType;
return true;
}
return false;
#undef pGround
}
bool MQ2MacroQuestType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2MacroQuestType::FindMember(Member);
if (!pMember)
return false;
switch((MacroQuestMembers)pMember->ID)
{
case GameState:
if (gGameState==GAMESTATE_CHARSELECT)
Dest.Ptr="CHARSELECT";
else if (gGameState==GAMESTATE_INGAME)
Dest.Ptr="INGAME";
else
Dest.Ptr="UNKNOWN";
Dest.Type=pStringType;
return true;
case LoginName:
{
if (PCHAR pTemp=GetLoginName())
{
strcpy(DataTypeTemp,pTemp);
free(pTemp);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
return false;
case Server:
if (EQADDR_SERVERNAME[0])
{
Dest.Ptr=EQADDR_SERVERNAME;
Dest.Type=pStringType;
return true;
}
return false;
case LastCommand:
if (szLastCommand[0])
{
Dest.Ptr=&szLastCommand[0];
Dest.Type=pStringType;
return true;
}
return false;
case LastTell:
if (EQADDR_LASTTELL[0])
{
Dest.Ptr=&EQADDR_LASTTELL[0];
Dest.Type=pStringType;
return true;
}
return false;
case Error:
if (gszLastNormalError[0])// QUIT SETTING THIS MANUALLY, USE MacroError, FatalError, ETC
{
Dest.Ptr=&gszLastNormalError[0];
Dest.Type=pStringType;
return true;
}
return false;
case SyntaxError:
if (gszLastSyntaxError[0])
{
Dest.Ptr=&gszLastSyntaxError[0];
Dest.Type=pStringType;
return true;
}
return false;
case MQ2DataError:
if (gszLastMQ2DataError[0])
{
Dest.Ptr=&gszLastMQ2DataError[0];
Dest.Type=pStringType;
return true;
}
return false;
case Running:
Dest.DWord=(DWORD)clock();
Dest.Type=pIntType;
return true;
case MouseX:
Dest.DWord=((PMOUSEINFO)EQADDR_MOUSE)->X;
Dest.Type=pIntType;
return true;
case MouseY:
Dest.DWord=((PMOUSEINFO)EQADDR_MOUSE)->Y;
Dest.Type=pIntType;
return true;
case BuildDate:
SYSTEMTIME st;
HANDLE hFile;
WIN32_FIND_DATA FileData;
CHAR szBuffer[MAX_STRING];
sprintf(szBuffer,"%s\\MQ2Main.dll", gszINIPath);
hFile = FindFirstFile(szBuffer, &FileData);
// Convert the creation time time to local time.
FileTimeToSystemTime(&FileData.ftLastWriteTime, &st);
FindClose(hFile);
sprintf(DataTypeTemp, "%d%d%d",st.wYear,st.wMonth,st.wDay);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
case Ping:
Dest.DWord=pConnection->Last;
Dest.Type=pIntType;
return true;
case ChatChannels:
if(((PEVERQUEST)pEverQuest)->ChatService)
{
Dest.DWord=((PEVERQUEST)pEverQuest)->ChatService->ActiveChannels;
Dest.Type=pIntType;
return true;
}
case ChatChannel:
if(((PEVERQUEST)pEverQuest)->ChatService)
{
PCHATSERVICE pChat=((PEVERQUEST)pEverQuest)->ChatService;
if(ISNUMBER())
{
DWORD index=GETNUMBER();
if(pChat->ActiveChannels && index && index<=pChat->ActiveChannels)
{
strcpy(DataTypeTemp,pChat->ChannelList->ChannelName[index-1]);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
}
else
{
CHAR Name[MAX_STRING]={0};
strcpy(Name,GETFIRST());
for(unsigned int i=0; i<pChat->ActiveChannels; i++)
{
if(!stricmp(Name,pChat->ChannelList->ChannelName[i]))
{
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
}
}
}
case ViewportX:
Dest.DWord=ScreenX;
Dest.Type=pIntType;
return true;
case ViewportY:
Dest.DWord=ScreenY;
Dest.Type=pIntType;
return true;
case ViewportXMax:
Dest.DWord=ScreenXMax;
Dest.Type=pIntType;
return true;
case ViewportYMax:
Dest.DWord=ScreenYMax;
Dest.Type=pIntType;
return true;
case ViewportXCenter:
Dest.DWord=ScreenXMax/2;
Dest.Type=pIntType;
return true;
case ViewportYCenter:
Dest.DWord=ScreenYMax/2;
Dest.Type=pIntType;
return true;
case LClickedObject:
Dest.DWord=gLClickedObject;
Dest.Type=pBoolType;
return true;
}
return false;
}
#ifndef ISXEQ
bool MQ2TimeType::GETMEMBER()
{
#define pTime ((struct tm *)VarPtr.Ptr)
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2TimeType::FindMember(Member);
if (!pMember)
return false;
switch((TimeMembers)pMember->ID)
{
case Hour:
Dest.DWord=pTime->tm_hour;
Dest.Type=pIntType;
return true;
case Minute:
Dest.DWord=pTime->tm_min;
Dest.Type=pIntType;
return true;
case Second:
Dest.DWord=pTime->tm_sec;
Dest.Type=pIntType;
return true;
case DayOfWeek:
Dest.DWord=pTime->tm_wday+1;
Dest.Type=pIntType;
return true;
case Day:
Dest.DWord=pTime->tm_mday;
Dest.Type=pIntType;
return true;
case Month:
Dest.DWord=pTime->tm_mon+1;
Dest.Type=pIntType;
return true;
case Year:
Dest.DWord=pTime->tm_year+1900;
Dest.Type=pIntType;
return true;
case Time12:
{
unsigned long Hour=pTime->tm_hour%12;
if (!Hour)
Hour=12;
sprintf(DataTypeTemp,"%02d:%02d:%02d",Hour,pTime->tm_min, pTime->tm_sec);
Dest.Ptr=&DataTypeTemp[0],
Dest.Type=pStringType;
}
return true;
case Time24:
sprintf(DataTypeTemp,"%02d:%02d:%02d",pTime->tm_hour,pTime->tm_min, pTime->tm_sec);
Dest.Ptr=&DataTypeTemp[0],
Dest.Type=pStringType;
return true;
case Date:
sprintf(DataTypeTemp,"%02d/%02d/%04d",pTime->tm_mon+1,pTime->tm_mday, pTime->tm_year+1900);
Dest.Ptr=&DataTypeTemp[0],
Dest.Type=pStringType;
return true;
case Night:
Dest.DWord=((pTime->tm_hour<7) || (pTime->tm_hour>18));
Dest.Type=pBoolType;
return true;
case SecondsSinceMidnight:
Dest.DWord=pTime->tm_hour*3600+pTime->tm_min*60+pTime->tm_sec;
Dest.Type=pIntType;
return true;
}
return false;
#undef pTime
}
#endif
bool MQ2HeadingType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2HeadingType::FindMember(Member);
if (!pMember)
return false;
FLOAT Heading=360.0f-VarPtr.Float;
switch((HeadingMembers)pMember->ID)
{
case Clock:
{
Dest.Int=((int)Heading)+15;
Dest.DWord=((int)Dest.Int/30)%12;
if (Dest.DWord==0)
Dest.DWord=12;
Dest.Type=pIntType;
return true;
}
case Degrees:
Dest.Float=Heading;
Dest.Type=pFloatType;
return true;
case DegreesCCW:
Dest.Float=VarPtr.Float;
Dest.Type=pFloatType;
return true;
case ShortName:
Dest.Ptr=szHeadingNormalShort[(INT)(Heading/ 22.5f + 0.5f)%16];
Dest.Type=pStringType;
return true;
case Name:
Dest.Ptr=szHeadingNormal[(INT)(Heading/ 22.5f + 0.5f)%16];
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2CorpseType::GETMEMBER()
{
if (!pActiveCorpse || !pLootWnd)
return false;
#define pLoot ((PEQLOOTWINDOW)pLootWnd)
PMQ2TYPEMEMBER pMember=MQ2CorpseType::FindMember(Member);
if (!pMember)
{
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)&pActiveCorpse,Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)&pActiveCorpse,Member,argc,argv,Dest);
#endif
}
switch((CorpseMembers)pMember->ID)
{
case Open:
Dest.DWord=1; // obviously, since we're this far
Dest.Type=pBoolType;
return true;
case Item:
if (ISINDEX())
{
if (ISNUMBER())
{
unsigned long nIndex=GETNUMBER()-1;
if (nIndex<31)
{
if (Dest.Ptr=pLoot->ItemDesc[nIndex])
{
Dest.Type=pItemType;
return true;
}
}
}
else
{
// name
BOOL bExact=FALSE;
PCHAR pName=GETFIRST();
if (*pName=='=')
{
bExact=TRUE;
pName++;
}
strlwr(pName);
CHAR Temp[MAX_STRING]={0};
for (unsigned long nIndex = 0 ; nIndex < 31 ; nIndex++)
{
if (PCONTENTS pContents=pLoot->ItemDesc[nIndex])
{
if (bExact)
{
if (!stricmp(pName,pContents->Item->Name))
{
Dest.Ptr=pContents;
Dest.Type=pItemType;
return true;
}
}
else
{
if(strstr(strlwr(strcpy(Temp,pContents->Item->Name)),pName))
{
Dest.Ptr=pContents;
Dest.Type=pItemType;
return true;
}
}
}
}
}
}
return false;
case Items:
{
Dest.DWord=0;
for (unsigned long N = 0 ; N < 31 ; N++)
{
if (pLoot->ItemDesc[N])
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
}
}
return false;
#undef pLoot
}
bool MQ2MerchantType::GETMEMBER()
{
if (!pActiveMerchant || !pMerchantWnd)
return false;
#define pMerch ((PEQMERCHWINDOW)pMerchantWnd)
PMQ2TYPEMEMBER pMember=MQ2MerchantType::FindMember(Member);
if (!pMember)
{
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)&pActiveMerchant,Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)&pActiveMerchant,Member,argc,argv,Dest);
#endif
}
switch((MerchantMembers)pMember->ID)
{
case Open:
Dest.DWord=1; // obviously, since we're this far ;)
Dest.Type=pBoolType;
return true;
case Item:
if (ISINDEX())
{
if (ISNUMBER())
{
unsigned long nIndex=GETNUMBER()-1;
if (nIndex<80)
{
if (Dest.Ptr=pMerch->ItemDesc[nIndex])
{
Dest.Type=pItemType;
return true;
}
}
}
else
{
// name
BOOL bExact=FALSE;
PCHAR pName=GETFIRST();
if (*pName=='=')
{
bExact=TRUE;
pName++;
}
strlwr(pName);
CHAR Temp[MAX_STRING]={0};
for (unsigned long nIndex = 0 ; nIndex < 80 ; nIndex++)
{
if (PCONTENTS pContents=pMerch->ItemDesc[nIndex])
{
if (bExact)
{
if (!stricmp(pName,pContents->Item->Name))
{
Dest.Ptr=pContents;
Dest.Type=pItemType;
return true;
}
}
else
{
if(strstr(strlwr(strcpy(Temp,pContents->Item->Name)),pName))
{
Dest.Ptr=pContents;
Dest.Type=pItemType;
return true;
}
}
}
}
}
}
return false;
case Items:
{
Dest.DWord=0;
for (unsigned long N = 0 ; N < 80 ; N++)
{
if (pMerch->ItemDesc[N])
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
}
case Markup:
Dest.Float=pMerch->Markup;
Dest.Type=pFloatType;
return true;
case Full:
{
Dest.DWord=1;
for (unsigned long N = 0 ; N < 80 ; N++)
{
if (!pMerch->ItemDesc[N])
{
Dest.DWord=0;
break;
}
}
Dest.Type=pBoolType;
return true;
}
}
return false;
#undef pMerch
}
bool MQ2InvSlotType::GETMEMBER()
{
#define nInvSlot (VarPtr.Int)
PMQ2TYPEMEMBER pMember=MQ2InvSlotType::FindMember(Member);
if (!pMember)
return false;
switch((InvSlotMembers)pMember->ID)
{
case ID:
Dest.DWord=VarPtr.Int;
Dest.Type=pIntType;
return true;
case Item:
if (pInvSlotMgr) {
if (CInvSlot *pSlot=pInvSlotMgr->FindInvSlot(nInvSlot))
{
if (((PEQINVSLOT)pSlot)->ppContents)
{
if (Dest.Ptr=*((PEQINVSLOT)pSlot)->ppContents)
{
Dest.Type=pItemType;
return true;
}
}
}
else
{
PCHARINFO pCharInfo=(PCHARINFO)pCharData;
if (nInvSlot>=262 && nInvSlot<342)
{
unsigned long nPack=(nInvSlot-262)/10;
unsigned long nSlot=(nInvSlot-262)%10;
if (PCONTENTS pPack=GetCharInfo2()->Inventory.Pack[nPack])
if (pPack->Item->Type==ITEMTYPE_PACK && nSlot<pPack->Item->Slots)
{
if (Dest.Ptr=pPack->Contents[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
else if (nInvSlot>=2032 && nInvSlot<2272)
{
unsigned long nPack=(nInvSlot-2032)/10;
unsigned long nSlot=(nInvSlot-2)%10;
if (PCONTENTS pPack=pCharInfo->Bank[nPack])
if (pPack->Item->Type==ITEMTYPE_PACK && nSlot<pPack->Item->Slots)
{
if (Dest.Ptr=pPack->Contents[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
else if (nInvSlot>=2532 && nInvSlot<2552)
{
unsigned long nPack=24+((nInvSlot-2532)/10);
unsigned long nSlot=(nInvSlot-2)%10;
if (PCONTENTS pPack=pCharInfo->Bank[nPack])
if (pPack->Item->Type==ITEMTYPE_PACK && nSlot<pPack->Item->Slots)
{
if (Dest.Ptr=pPack->Contents[nSlot])
{
Dest.Type=pItemType;
return true;
}
}
}
else if (nInvSlot>=2000 && nInvSlot<2024)
{
if (Dest.Ptr=pCharInfo->Bank[nInvSlot-2000])
{
Dest.Type=pItemType;
return true;
}
}
else if (nInvSlot==2500 || nInvSlot==2501)
{
if (Dest.Ptr=pCharInfo->Bank[nInvSlot-2500+24])
{
Dest.Type=pItemType;
return true;
}
}
}
}
return false;
case Pack:
if (nInvSlot>=262 && nInvSlot<342)
{
Dest.DWord=((nInvSlot-262)/10)+BAG_SLOT_START;
Dest.Type=pInvSlotType;
return true;
}
else if (nInvSlot>=2032 && nInvSlot<2272)
{
Dest.DWord=((nInvSlot-2032)/10)+2000;
Dest.Type=pInvSlotType;
return true;
}
else if (nInvSlot>=2532 && nInvSlot<2552)
{
Dest.DWord=((nInvSlot-2532)/10)+2500;
Dest.Type=pInvSlotType;
return true;
}
return false;
case Slot:
{
if (nInvSlot>=262 && nInvSlot<342)
{
Dest.DWord=(nInvSlot-262)%10;
Dest.Type=pIntType;
return true;
}
else if (nInvSlot>=2032 && nInvSlot<2272)
{
Dest.DWord=(nInvSlot-2032)%10;
Dest.Type=pIntType;
return true;
}
else if (nInvSlot>=2532 && nInvSlot<2552)
{
Dest.DWord=(nInvSlot-2532)%10;
Dest.Type=pIntType;
return true;
}
}
return false;
case Name:
if (nInvSlot>=0 && nInvSlot<NUM_INV_SLOTS)
{
Dest.Ptr=szItemSlot[nInvSlot];
Dest.Type=pStringType;
return true;
}
if (nInvSlot>=BAG_SLOT_START && nInvSlot<NUM_INV_SLOTS)
{
sprintf(DataTypeTemp,"pack%d",nInvSlot-21);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=2000 && nInvSlot<2024)
{
sprintf(DataTypeTemp,"bank%d",nInvSlot-1999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=2500 && nInvSlot<2502)
{
sprintf(DataTypeTemp,"sharedbank%d",nInvSlot-2499);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=5000 && nInvSlot<5032)
{
sprintf(DataTypeTemp,"loot%d",nInvSlot-4999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=3000 && nInvSlot<3009)
{
sprintf(DataTypeTemp,"trade%d",nInvSlot-2999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=4000 && nInvSlot<4009)
{
sprintf(DataTypeTemp,"enviro%d",nInvSlot-3999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=6000 && nInvSlot<6080)
{
sprintf(DataTypeTemp,"merchant%d",nInvSlot-5999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=7000 && nInvSlot<7089)
{
sprintf(DataTypeTemp,"bazaar%d",nInvSlot-6999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
else if (nInvSlot>=8000 && nInvSlot<8031)
{
sprintf(DataTypeTemp,"inspect%d",nInvSlot-7999);
Dest.Ptr=&DataTypeTemp[0];
Dest.Type=pStringType;
return true;
}
return false;
}
return false;
#undef nInvSlot
}
bool MQ2TimerType::GETMEMBER()
{
#define pTimer ((PMQTIMER)VarPtr.Ptr)
if (!pTimer)
return false;
PMQ2TYPEMEMBER pMember=MQ2TimerType::FindMember(Member);
if (!pMember)
return false;
switch((TimerMembers)pMember->ID)
{
case Value:
Dest.DWord=pTimer->Current;
Dest.Type=pIntType;
return true;
case OriginalValue:
Dest.DWord=pTimer->Original;
Dest.Type=pIntType;
return true;
}
return false;
#undef pTimer
}
bool MQ2SkillType::GETMEMBER()
{
if (!VarPtr.Ptr)
return false;
PSKILL pSkill=*(PSKILL*)VarPtr.Ptr;
if (!pSkill)
return false;
PMQ2TYPEMEMBER pMember=MQ2SkillType::FindMember(Member);
if (!pMember)
return false;
unsigned long nIndex=GetCharInfo2()->Class;
if(ISINDEX())
{
if(ISNUMBER())
{
// class by number
nIndex=GETNUMBER();
}
else
{
// class by name or shortname
for (int N=1 ; N<17 ; N++)
{
if(
!stricmp(GETFIRST(), GetClassDesc(N)) ||
!stricmp(GETFIRST(), pEverQuest->GetClassThreeLetterCode(N))
)
{
nIndex=N;
break;
}
}
}
}
switch((SkillMembers)pMember->ID)
{
case Name:
if (Dest.Ptr=pStringTable->getString(pSkill->nName,0))
{
Dest.Type=pStringType;
return true;
}
return false;
case ID:
Dest.DWord=GetSkillIDFromName(pStringTable->getString(pSkill->nName,0));
Dest.Type=pIntType;
return true;
case ReuseTime:
Dest.DWord=pSkill->ReuseTimer;
Dest.Type=pIntType;
return true;
case MinLevel:
Dest.DWord=pSkill->MinLevel[nIndex];
Dest.Type=pIntType;
return true;
case SkillCap:
{
DWORD i=GetSkillIDFromName(pStringTable->getString(pSkill->nName,0));
Dest.DWord=pCSkillMgr->GetSkillCap((EQ_Character*)GetCharInfo(),GetCharInfo2()->Level,GetCharInfo2()->Class,i);
Dest.Type=pIntType;
return true;
}
case AltTimer:
Dest.DWord=pSkill->AltTimer;
Dest.Type=pIntType;
return true;
case Activated:
Dest.DWord=pSkill->Activated;
Dest.Type=pBoolType;
return true;
}
return false;
}
bool MQ2AltAbilityType::ToString(MQ2VARPTR VarPtr, PCHAR Destination)
{
if (!VarPtr.Ptr)
return false;
PALTABILITY pAbility=(PALTABILITY)VarPtr.Ptr;
itoa(pAbility->PointsSpent, Destination,10);
return true;
}
bool MQ2AltAbilityType::GETMEMBER()
{
if (!VarPtr.Ptr)
return false;
PALTABILITY pAbility=(PALTABILITY)VarPtr.Ptr;
PMQ2TYPEMEMBER pMember=MQ2AltAbilityType::FindMember(Member);
if (!pMember)
return false;
switch((AltAbilityMembers)pMember->ID)
{
case Name:
if (Dest.Ptr= pCDBStr->GetString(pAbility->nName, 1, NULL))
{
Dest.Type=pStringType;
return true;
}
return false;
case ShortName:
if (Dest.Ptr=pStringTable->getString(pAbility->nShortName,0))
{
Dest.Type=pStringType;
return true;
}
return false;
case Description:
if (Dest.Ptr= pCDBStr->GetString(pAbility->nName, 4, NULL))
{
Dest.Type=pStringType;
return true;
}
return false;
case ID:
Dest.DWord=pAbility->ID;
Dest.Type=pIntType;
return true;
case ReuseTime:
Dest.DWord=pAbility->ReuseTimer;
Dest.Type=pIntType;
return true;
case MyReuseTime:
Dest.DWord=pAltAdvManager->GetCalculatedTimer(pPCData,pAbility);
Dest.Type=pIntType;
return true;
case MinLevel:
Dest.DWord=pAbility->MinLevel;
Dest.Type=pIntType;
return true;
case Cost:
Dest.DWord=pAbility->Cost;
Dest.Type=pIntType;
return true;
case Spell:
if (Dest.Ptr=GetSpellByID(pAbility->SpellID))
{
Dest.Type=pSpellType;
return true;
}
return false;
case RequiresAbility:
if (pAbility->RequiresAbility>0)
{
for (unsigned long nAbility=0 ; nAbility<NUM_ALT_ABILITIES_ARRAY ; nAbility++)
{
if ( ((PALTADVMGR)pAltAdvManager)->AltAbilities->AltAbilityList->Abilities[nAbility])
{
if ( PALTABILITY pAA=((PALTADVMGR)pAltAdvManager)->AltAbilities->AltAbilityList->Abilities[nAbility]->Ability)
{
if (pAA->ID == pAbility->RequiresAbility)
{
Dest.Ptr=&pAA;
Dest.Type=pAltAbilityType;
return true;
}
}
}
}
}
return false;
case RequiresAbilityPoints:
Dest.DWord=pAbility->RequiresAbilityPoints;
Dest.Type=pIntType;
return true;
case MaxRank:
Dest.DWord=pAbility->MaxRank;
Dest.Type=pIntType;
return true;
case AARankRequired:
Dest.DWord=pAbility->AARankRequired;
Dest.Type=pIntType;
return true;
case Type:
Dest.DWord=pAbility->Type;
Dest.Type=pIntType;
return true;
}
return false;
}
bool MQ2GroupType::ToString(MQ2VARPTR VarPtr, PCHAR Destination)
{
int nMembers=0;
PCHARINFO pChar=GetCharInfo();
if (!pChar->pGroupInfo) return false;
for (int index=1;index<6;index++)
{
if (pChar->pGroupInfo->pMember[index])
nMembers++;
}
itoa(nMembers,Destination,10);
return true;
}
bool MQ2GroupType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2GroupType::FindMember(Member);
PCHARINFO pChar=GetCharInfo();
int i;
if (!pMember || !pChar->pGroupInfo)
return false;
switch((GroupMembers)pMember->ID)
{
case xMember:
if (!ISINDEX())
return false;
if (ISNUMBER())
{
// by number
Dest.DWord=GETNUMBER();
Dest.Type=pGroupMemberType;
return true;
}
else
{
Dest.DWord=0;
for (i=1;i<6;i++)
if (pChar->pGroupInfo->pMember[i])
{
Dest.DWord++;
CHAR Name[MAX_STRING]={0};
GetCXStr(pChar->pGroupInfo->pMember[i]->pName,Name,MAX_STRING);
if (!stricmp(Name,GETFIRST()))
{
Dest.Type=pIntType;
return true;
}
}
if (!stricmp(pChar->pSpawn->Name,GETFIRST())) {
Dest.DWord=0;
Dest.Type=pIntType;
return true;
}
return false;
}
break;
case Members:
{
Dest.DWord=0;
for (i=1;i<6;i++)
if (pChar->pGroupInfo->pMember[i])
Dest.DWord++;
Dest.Type=pIntType;
}
return true;
case Leader:
{
if (!pChar->pGroupInfo->pLeader) return false;
CHAR LeaderName[MAX_STRING]={0};
GetCXStr(pChar->pGroupInfo->pLeader->pName,LeaderName,MAX_STRING);
Dest.DWord=0;
if (!stricmp(pChar->pSpawn->Name,LeaderName))
{
Dest.Type=pGroupMemberType;
return true;
}
for (i=1;i<6;i++)
{
if (pChar->pGroupInfo->pMember[i])
{
Dest.DWord++;
CHAR Name[MAX_STRING]={0};
GetCXStr(pChar->pGroupInfo->pMember[i]->pName,Name,MAX_STRING);
if (!stricmp(Name,LeaderName))
{
Dest.Type=pGroupMemberType;
return true;
}
}
}
if (!Dest.DWord)
{
// group has no members
Dest.Type=pGroupMemberType;
return true;
}
}
break;
case GroupSize:
{
Dest.DWord=0;
for (i=1;i<6;i++)
if (pChar->pGroupInfo->pMember[i])
Dest.DWord++;
if (Dest.DWord) Dest.DWord++;
Dest.Type=pIntType;
}
return true;
case MainTank:
for(i = 0; i < 6; i++)
{
if(pChar->pGroupInfo->pMember[i] && pChar->pGroupInfo->pMember[i]->MainTank)
{
Dest.DWord=i;
Dest.Type=pGroupMemberType;
return true;
}
}
return false;
case MainAssist:
for(i = 0; i < 6; i++)
{
if(pChar->pGroupInfo->pMember[i] && pChar->pGroupInfo->pMember[i]->MainAssist)
{
Dest.DWord=i;
Dest.Type=pGroupMemberType;
return true;
}
}
return false;
case Puller:
for(i = 0; i < 6; i++)
{
if(pChar->pGroupInfo->pMember[i] && pChar->pGroupInfo->pMember[i]->Puller)
{
Dest.DWord=i;
Dest.Type=pGroupMemberType;
return true;
}
}
}
return false;
}
bool MQ2GroupMemberType::ToString(MQ2VARPTR VarPtr, PCHAR Destination)
{
int i;
if (unsigned long N=VarPtr.DWord)
{
if (N>5)
return false;
PCHARINFO pChar=GetCharInfo();
if (!pChar->pGroupInfo) return false;
for (i=1; i<6 ; i++)
{
if (pChar->pGroupInfo->pMember[i])
{
N--;
if (N==0)
{
CHAR Name[MAX_STRING]={0};
GetCXStr(pChar->pGroupInfo->pMember[i]->pName,Name,MAX_STRING);
strcpy(Destination,Name);
return true;
}
}
}
}
else
{
strcpy(Destination,GetCharInfo()->pSpawn->Name);
return true;
}
return false;
}
bool MQ2GroupMemberType::GETMEMBER()
{
CHAR MemberName[MAX_STRING]={0};
CHAR LeaderName[MAX_STRING]={0};
PSPAWNINFO pGroupMember=0;
PCHARINFO pChar=GetCharInfo();
PGROUPMEMBER pGroupMemberData=0;
DWORD level=0;
int i;
if (!pChar->pGroupInfo) return false;
if (unsigned long N=VarPtr.DWord)
{
if (N>5)
return false;
for (i=1; i<6 ; i++)
{
if (pChar->pGroupInfo->pMember[i])
{
N--;
if (N==0)
{
GetCXStr(pChar->pGroupInfo->pMember[i]->pName,MemberName,MAX_STRING);
pGroupMember=pChar->pGroupInfo->pMember[i]->pSpawn;
level=pChar->pGroupInfo->pMember[i]->Level;
pGroupMemberData=pChar->pGroupInfo->pMember[i];
break;
}
}
}
if (!MemberName)
return false;
}
else
{
pGroupMember=pChar->pSpawn;
strcpy(MemberName,pGroupMember->Name);
level=pGroupMember->Level;
pGroupMemberData=pChar->pGroupInfo->pLeader;
}
PMQ2TYPEMEMBER pMember=MQ2GroupMemberType::FindMember(Member);
if (!pMember)
{
if (!pGroupMember)
return false;
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)&pGroupMember,Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)&pGroupMember,Member,argc,argv,Dest);
#endif
}
switch((GroupMemberMembers)pMember->ID)
{
case Name:
Dest.Ptr=MemberName;
Dest.Type=pStringType;
return true;
case Leader:
if (!pChar->pGroupInfo->pLeader) return false;
GetCXStr(pChar->pGroupInfo->pLeader->pName,LeaderName,MAX_STRING);
Dest.DWord=!stricmp(MemberName,LeaderName);
Dest.Type=pBoolType;
return true;
case Spawn:
if (Dest.Ptr=pGroupMember)
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Level:
Dest.DWord=level;
Dest.Type=pIntType;
return true;
case MainTank:
if(pGroupMemberData)
{
Dest.DWord=pGroupMemberData->MainTank;
Dest.Type=pBoolType;
return true;
}
return false;
case MainAssist:
if(pGroupMemberData)
{
Dest.DWord=pGroupMemberData->MainAssist;
Dest.Type=pBoolType;
return true;
}
return false;
case Puller:
if(pGroupMemberData)
{
Dest.DWord=pGroupMemberData->Puller;
Dest.Type=pBoolType;
return true;
}
case Mercenary:
if(pGroupMemberData)
{
Dest.DWord=pGroupMemberData->Mercenary;
Dest.Type=pBoolType;
return true;
}
}
return false;
}
bool MQ2RaidType::GETMEMBER()
{
int i;
if (!pRaid)
return false;
PMQ2TYPEMEMBER pMember=MQ2RaidType::FindMember(Member);
if (!pMember)
return false;
switch((RaidMembers)pMember->ID)
{
case Locked:
Dest.DWord=pRaid->Locked;
Dest.Type=pBoolType;
return true;
case Invited:
Dest.DWord=pRaid->Invited;
Dest.Type=pBoolType;
return true;
case xMember:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count || Count>pRaid->RaidMemberCount)
return false;
for (DWORD nMember = 0 ; nMember < 72 ; nMember++)
{
if (pRaid->RaidMemberUsed[nMember])
{
Count--;
if (!Count)
{
Dest.DWord=nMember+1;
Dest.Type=pRaidMemberType;
return true;
}
}
}
}
else
{
// by name
for (DWORD nMember=0 ; nMember < 72 ; nMember++)
{
if (pRaid->RaidMemberUsed[nMember] && !stricmp(pRaid->RaidMember[nMember].Name,GETFIRST()))
{
Dest.DWord=nMember+1;
Dest.Type=pRaidMemberType;
return true;
}
}
}
}
return false;
case Members:
Dest.DWord=pRaid->RaidMemberCount;
Dest.Type=pIntType;
return true;
case Target:
Dest.DWord=pRaid->RaidTarget+1;
Dest.Type=pRaidMemberType;
return true;
case Leader:
{
for (DWORD nMember=0 ; nMember < 72 ; nMember++)
{
if (pRaid->RaidMemberUsed[nMember] && !stricmp(pRaid->RaidMember[nMember].Name,pRaid->RaidLeaderName))
{
Dest.DWord=nMember+1;
Dest.Type=pRaidMemberType;
return true;
}
}
}
return false;
case TotalLevels:
Dest.DWord=pRaid->TotalRaidMemberLevels;
Dest.Type=pIntType;
return true;
case AverageLevel:
Dest.Float=(FLOAT)pRaid->TotalRaidMemberLevels/(FLOAT)pRaid->RaidMemberCount;
Dest.Type=pFloatType;
return true;
case LootType:
Dest.DWord=pRaid->LootType;
Dest.Type=pIntType;
return true;
case Looters:
{
Dest.DWord=0;
for (unsigned long N = 0 ; N < 0x13 ; N++)
{
if (pRaid->RaidLooters[N][0])
Dest.DWord++;
}
Dest.Type=pIntType;
return true;
}
case Looter:
if (ISINDEX())
{
if (ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count)
return 0;
for (DWORD nLooter=0; nLooter<0x13 ; nLooter++)
{
if (pRaid->RaidLooters[nLooter][0])
{
Count--;
if (Count==0)
{
Dest.Ptr=&pRaid->RaidLooters[nLooter][0];
Dest.Type=pStringType;
return true;
}
}
}
}
// by name?
}
return false;
case MainAssist:
{
for (i=0; i < 72; i++)
{
if (pRaid->RaidMemberUsed[i] && pRaid->RaidMember[i].RaidMainAssist)
{
Dest.DWord=i+1;
Dest.Type=pRaidMemberType;
return true;
}
}
}
return false;
}
/**/
return false;
}
bool MQ2RaidMemberType::GETMEMBER()
{
DWORD nRaidMember=VarPtr.DWord-1;
if (VarPtr.DWord>=72)
return false;
if (!pRaid->RaidMemberUsed[nRaidMember])
return false;
PEQRAIDMEMBER pRaidMember=&pRaid->RaidMember[nRaidMember];
PMQ2TYPEMEMBER pMember=MQ2RaidMemberType::FindMember(Member);
if (!pMember)
{
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)GetSpawnByName(pRaidMember->Name),Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)GetSpawnByName(pRaidMember->Name),Member,argc,argv,Dest);
#endif
}
switch((RaidMemberMembers)pMember->ID)
{
case Name:
Dest.Ptr=pRaidMember->Name;
Dest.Type=pStringType;
return true;
case Group:
Dest.DWord=pRaidMember->GroupNumber+1;
Dest.Type=pIntType;
return true;
case GroupLeader:
Dest.DWord=pRaidMember->GroupLeader;
Dest.Type=pBoolType;
return true;
case RaidLeader:
Dest.DWord=pRaidMember->RaidLeader;
Dest.Type=pBoolType;
return true;
case Looter:
if (pRaidMember->RaidLeader)
{
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
if (pRaid->LootType==2)
{
Dest.DWord=pRaidMember->GroupLeader;
Dest.Type=pBoolType;
return true;
}
if (pRaid->LootType==3)
{
for (DWORD N = 0 ; N < 0x13 ; N++)
{
if (!stricmp(pRaid->RaidLooters[N],pRaidMember->Name))
{
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
}
}
Dest.DWord=0;
Dest.Type=pBoolType;
return true;
case Spawn:
if (Dest.Ptr=(PSPAWNINFO)GetSpawnByName(pRaidMember->Name))
{
Dest.Type=pSpawnType;
return true;
}
return false;
case Level:
Dest.DWord=atoi(pRaidMember->Level);
Dest.Type=pIntType;
return true;
case Class:
Dest.DWord=pRaidMember->nClass;
Dest.Type=pClassType;
return true;
/*
{
if (PSPAWNINFO pSpawn=(PSPAWNINFO)GetSpawnByName(pRaidMember->Name))
{
Dest.DWord=pSpawn->Class;
Dest.Type=pIntType;
return true;
}
pCharData->KunarkClass(0,0,0x18C,1);
}
return false;
/**/
}
return false;
}
bool MQ2EvolvingItemType::GETMEMBER()
{
if (!VarPtr.Ptr)
return false;
PCONTENTS pItem=(PCONTENTS)VarPtr.Ptr;
PMQ2TYPEMEMBER pMember=MQ2EvolvingItemType::FindMember(Member);
if (!pMember)
return false;
switch((EvolvingItemMembers)pMember->ID)
{
case ExpPct:
Dest.Float=(FLOAT)pItem->EvolvingExpPct;
Dest.Type=pFloatType;
return true;
case ExpOn:
Dest.DWord=pItem->EvolvingExpOn;
Dest.Type=pBoolType;
return true;
case Level:
Dest.DWord=pItem->EvolvingCurrentLevel;
Dest.Type=pIntType;
return true;
case MaxLevel:
Dest.DWord=pItem->EvolvingMaxLevel;
Dest.Type=pIntType;
return true;
}
return false;
}
bool MQ2DynamicZoneType::GETMEMBER()
{
if(!pDZMember)
return false;
PMQ2TYPEMEMBER pMember=MQ2DynamicZoneType::FindMember(Member);
if(!pMember)
return false;
switch((DynamicZoneMembers)pMember->ID)
{
case Name:
Dest.Ptr=pDynamicZone->ExpeditionName;
Dest.Type=pStringType;
return true;
case Members:
{
Dest.DWord=0;
PDZMEMBER pDynamicZoneMember=pDynamicZone->pMemberList;
while(pDynamicZoneMember)
{
Dest.DWord++;
pDynamicZoneMember=pDynamicZoneMember->pNext;
}
}
Dest.Type=pIntType;
return true;
case MaxMembers:
Dest.DWord=pDynamicZone->MaxPlayers;
Dest.Type=pIntType;
return true;
case xMember:
if(ISINDEX())
{
PDZMEMBER pDynamicZoneMember=pDynamicZone->pMemberList;
if(ISNUMBER())
{
DWORD Count=GETNUMBER();
if (!Count || Count>pDynamicZone->MaxPlayers)
return false;
Count--;
for(DWORD i=0; pDynamicZoneMember!=0; i++)
{
if(i==Count)
{
Dest.Ptr=pDynamicZoneMember;
Dest.Type=pDZMemberType;
return true;
}
pDynamicZoneMember=pDynamicZoneMember->pNext;
}
}
else
{
while(pDynamicZoneMember)
{
if(!stricmp(pDynamicZoneMember->Name,GETFIRST()))
{
Dest.Ptr=pDynamicZoneMember;
Dest.Type=pDZMemberType;
return true;
}
pDynamicZoneMember=pDynamicZoneMember->pNext;
}
}
}
return false;
case Leader:
{
PDZMEMBER pDynamicZoneMember=pDynamicZone->pMemberList;
for(DWORD i=0; i<pDynamicZone->MaxPlayers; i++)
{
if(!strcmp(pDynamicZoneMember->Name,(char*)instExpeditionLeader))
{
Dest.Ptr=pDynamicZoneMember;
Dest.Type=pDZMemberType;
return true;
}
pDynamicZoneMember=pDynamicZoneMember->pNext;
}
}
}
return false;
}
bool MQ2DZMemberType::GETMEMBER()
{
if(!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2DZMemberType::FindMember(Member);
if(!pMember)
return false;
PDZMEMBER pDynamicZoneMember=(PDZMEMBER)VarPtr.Ptr;
switch((DZMemberTypeMembers)pMember->ID)
{
case Name:
Dest.Ptr=pDynamicZoneMember->Name;
Dest.Type=pStringType;
return true;
case Status:
switch(pDynamicZoneMember->Status)
{
case 0:
Dest.Ptr="Unknown";
break;
case 1:
Dest.Ptr="Online";
break;
case 2:
Dest.Ptr="Offline";
break;
case 3:
Dest.Ptr="In Dynamic Zone";
break;
case 4:
Dest.Ptr="Link Dead";
break;
}
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2FellowshipType::GETMEMBER()
{
if(!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2FellowshipType::FindMember(Member);
if(!pMember)
return false;
PFELLOWSHIPINFO pFellowship=(PFELLOWSHIPINFO)VarPtr.Ptr;
switch((FellowshipTypeMembers)pMember->ID)
{
case ID:
Dest.DWord=pFellowship->FellowshipID;
Dest.Type=pIntType;
return true;
case Leader:
Dest.Ptr=pFellowship->Leader;
Dest.Type=pStringType;
return true;
case MotD:
Dest.Ptr=pFellowship->MotD;
Dest.Type=pStringType;
return true;
case Members:
Dest.DWord=pFellowship->Members;
Dest.Type=pIntType;
return true;
case xMember:
if(ISINDEX())
{
if(ISNUMBER())
{
DWORD i=GETNUMBER();
if(!i || i>pFellowship->Members)
return false;
Dest.Ptr=&pFellowship->FellowshipMember[--i];
Dest.Type=pFellowshipMemberType;
return true;
}
else
{
for(DWORD i=0; i<pFellowship->Members; i++)
{
if(!stricmp(pFellowship->FellowshipMember[i].Name,GETFIRST()))
{
Dest.Ptr=&pFellowship->FellowshipMember[i];
Dest.Type=pFellowshipMemberType;
return true;
}
}
}
}
return false;
case CampfireDuration:
if(pFellowship->CampfireTimestamp)
{
Dest.DWord=(pFellowship->CampfireTimestamp-GetFastTime())/6;
Dest.Type=pTicksType;
return true;
}
return false;
case CampfireY:
Dest.Float=pFellowship->CampfireY;
Dest.Type=pFloatType;
return true;
case CampfireX:
Dest.Float=pFellowship->CampfireX;
Dest.Type=pFloatType;
return true;
case CampfireZ:
Dest.Float=pFellowship->CampfireZ;
Dest.Type=pFloatType;
return true;
case CampfireZone:
if(pFellowship->CampfireZoneID)
{
Dest.Ptr=((PWORLDDATA)pWorldData)->ZoneArray[pFellowship->CampfireZoneID];
Dest.Type=pZoneType;
return true;
}
return false;
case Campfire:
Dest.Int=pFellowship->Campfire;
Dest.Type=pBoolType;
return true;
}
return false;
}
bool MQ2FellowshipMemberType::GETMEMBER()
{
if(!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2FellowshipMemberType::FindMember(Member);
if(!pMember)
return false;
PFELLOWSHIPMEMBER pFellowshipMember=(PFELLOWSHIPMEMBER)VarPtr.Ptr;
switch((FMTypeMembers)pMember->ID)
{
case Zone:
if(pFellowshipMember->ZoneID)
{
Dest.Ptr=((PWORLDDATA)pWorldData)->ZoneArray[pFellowshipMember->ZoneID];
Dest.Type=pZoneType;
return true;
}
return false;
case Level:
Dest.DWord=pFellowshipMember->Level;
Dest.Type=pIntType;
return true;
case Class:
Dest.DWord=pFellowshipMember->Class;
Dest.Type=pClassType;
return true;
case LastOn:
if(pFellowshipMember->LastOn)
{
Dest.DWord=(GetFastTime()-pFellowshipMember->LastOn)/6;
Dest.Type=pTicksType;
return true;
}
return false;
case Name:
Dest.Ptr=pFellowshipMember->Name;
Dest.Type=pStringType;
return true;
}
return false;
}
bool MQ2FriendsType::GETMEMBER()
{
PMQ2TYPEMEMBER pMember=MQ2FriendsType::FindMember(Member);
if (!pMember)
return false;
switch((FriendsMembers)pMember->ID)
{
case xFriend:
if(ISINDEX() && ((PEVERQUEST)pEverQuest)->ChatService) {
class CChatService *pChat=(class CChatService *) ((PEVERQUEST)pEverQuest)->ChatService;
int i;
if(ISNUMBER()) {
i=GETNUMBER();
if (i > pChat->GetNumberOfFriends())
return false;
if (Dest.Ptr=pChat->GetFriendName(i-1)) {
Dest.Type=pStringType;
return true;
}
} else {
for(i=0; i<pChat->GetNumberOfFriends(); i++) {
if(!stricmp(pChat->GetFriendName(i),GETFIRST())) {
Dest.DWord=1;
Dest.Type=pBoolType;
return true;
}
}
return false;
}
}
return false;
default:
return false;
};
}
bool MQ2TargetType::GETMEMBER()
{
int buffID = 0;
DWORD i,j;
if (!VarPtr.Ptr)
return false;
PMQ2TYPEMEMBER pMember=MQ2TargetType::FindMember(Member);
if (!pMember)
{
#ifndef ISXEQ
return pSpawnType->GetMember(*(MQ2VARPTR*)&VarPtr.Ptr,Member,Index,Dest);
#else
return pSpawnType->GetMember(*(LSVARPTR*)&VarPtr.Ptr,Member,argc,argv,Dest);
#endif
}
switch((TargetMembers)pMember->ID)
{
case Buff:
if(!(((PCTARGETWND)pTargetWnd)->Type > 0))
return false;
if(ISINDEX())
{
if(ISNUMBER())
{
DWORD nBuff = GETNUMBER();
if (!nBuff || nBuff >= 0x55)
return false;
j = 0;
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff && nBuff == ++j)
{
Dest.Ptr = GetSpellByID((DWORD)buffID);
Dest.Type = pSpellType;
return true;
}
}
}
else
{
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff && !stricmp(GETFIRST(), GetSpellNameByID(buffID)))
{
Dest.Ptr = GetSpellByID((DWORD)buffID);
Dest.Type = pSpellType;
return true;
}
}
}
}
else
{
// return first buff
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff)
{
if(PSPELL pSpell = GetSpellByID(buffID))
{
strcpy(DataTypeTemp, pSpell->Name);
Dest.Ptr = &DataTypeTemp[0];
Dest.Type = pStringType;
return true;
}
}
}
}
return false;
case BuffCount:
if(!(((PCTARGETWND)pTargetWnd)->Type > 0))
return false;
Dest.DWord = 0;
for(i = 0; i < 0x55; i++)
if(((PCTARGETWND)pTargetWnd)->BuffSpellID[i] != 0xffffffff)
Dest.DWord++;
Dest.Type = pIntType;
return true;
case BuffDuration:
if(!(((PCTARGETWND)pTargetWnd)->Type > 0))
return false;
if(ISINDEX())
{
if(ISNUMBER())
{
DWORD nBuff = GETNUMBER();
if (!nBuff || nBuff >= 0x55)
return false;
j = 0;
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff && nBuff == ++j)
{
Dest.DWord = ((((PCTARGETWND)pTargetWnd)->BuffTimer[i] / 1000) + 6) / 6;
Dest.Type = pTicksType;
return true;
}
}
}
else
{
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff && !stricmp(GETFIRST(), GetSpellNameByID(buffID)))
{
Dest.DWord = ((((PCTARGETWND)pTargetWnd)->BuffTimer[i] / 1000) + 6) / 6;
Dest.Type = pTicksType;
return true;
}
}
}
}
else
{
// return first buff
for(i = 0; i < 0x55; i++)
{
buffID = ((PCTARGETWND)pTargetWnd)->BuffSpellID[i];
if(buffID != 0xffffffff)
{
Dest.DWord = ((((PCTARGETWND)pTargetWnd)->BuffTimer[i] / 1000) + 6) / 6;
Dest.Type = pTicksType;
return true;
}
}
}
return false;
}
return false;
}
| [
"[email protected]@39408780-f958-9dab-a28b-4b240efc9052"
]
| [
[
[
1,
7196
]
]
]
|
40048ff27e92dc24e5b84d6dd4d3b415461a11e1 | 31483373203784aa269b2f8d275bb291169f7fc7 | /Dependencies/OgreMax/inc/OgreMaxPlatform.hpp | 417f99d5730ba53da2d6b69340fa610a30a0aac0 | []
| no_license | sevas/ogre-ssao | ab057dd1620b1f182318cdccbe9904adea0645eb | 70395c0f5f76fcb2693144de5ef2ee513b973900 | refs/heads/master | 2021-01-01T19:30:55.331117 | 2011-03-23T17:03:32 | 2011-03-23T17:03:32 | 1,112,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,742 | hpp | /*
* OgreMaxViewer - An Ogre 3D-based viewer for .scene and .mesh files
* Copyright 2008 Derek Nedelman
*
* This code is available under the OgreMax Free License:
* -You may use this code for any purpose, commercial or non-commercial.
* -If distributing derived works (that use this source code) in binary or source code form,
* you must give the following credit in your work's end-user documentation:
* "Portions of this work provided by OgreMax (www.ogremax.com)"
*
* Derek Nedelman assumes no responsibility for any harm caused by using this code.
*
* OgreMaxViewer was written by Derek Nedelman and released at www.ogremax.com
*/
#ifndef OgreMax_OgreMaxPlatform_INCLUDED
#define OgreMax_OgreMaxPlatform_INCLUDED
//Macros-----------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#if defined(OGREMAX_SHARED_LIBRARY_EXPORT)
//Exporting from a shared library
#if defined(__MINGW32__)
#define _OgreMaxExport
#else
#define _OgreMaxExport __declspec(dllexport)
#endif
#elif defined(OGREMAX_SHARED_LIBRARY_IMPORT)
//Importing from a shared library
#if defined(__MINGW32__)
#define _OgreMaxExport
#else
#define _OgreMaxExport __declspec(dllimport)
#endif
#else
//Using the source code directly or from a static library
#define _OgreMaxExport
#endif
#else
//Either using the source code directly or from a static library...
//Or compiling on a platform that doesn't require import/export decorations
#define _OgreMaxExport
#endif
#endif | [
"[email protected]"
]
| [
[
[
1,
47
]
]
]
|
4f587c844e746bf7648b6e9c34359d4bcfdeae98 | 566de5d2527a8dec051650d0c629454ae07f79c5 | /include/GLDrawNodeBase.h | 59a0744a57dd75ee002509232d4722fddb641608 | []
| no_license | Byron/BPT | d0b755f214e39a9c0b53c83d7872aa5893dd559a | 6dff5cb9dfe5ba8f86a23e0cb45d0780966bbfa3 | refs/heads/master | 2021-01-23T03:05:30.813921 | 2010-06-28T18:18:08 | 2010-06-28T18:18:08 | 288,696 | 2 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,016 | h | /*
* Copyright (C) 2002 Sebastian Thiel
*
* 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 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.
*/
// GLDrawNode.h: interface for the header class.
//
//////////////////////////////////////////////////////////////////////
#ifndef GLDRAWNODEBASE_H
#define GLDRAWNODEBASE_H
// -----------------
// Maya Includes
// -----------------
#include <maya/M3dView.h>
// -----------------
// Eigene Includes
// -----------------
// -----------------
// Diverse Includes
// -----------------
// Diese Node enthält alles was man braucht, um mit openGl zu zeichnen
//
#include <GL/glu.h>
namespace BPT
{
/* * Ne völlige Unsinnsklasse: Diese Base wird von den Globals included, während sich die GLDRAWNODE die Globals holt
*/
//#################################################
//-------------------------------------------------
// KLASSENBESCHREIBUNG
class GLDrawNodeBase
//-------------------------------------------------
//#################################################
{
//------------------------------
// Konstruktion/Destruktion - nur standard
public:
//------------------------------
//------------------------------
// Methoden
public:
//------------------------------
/* * Zeichnet die abgeleitete Klasse
*/
virtual void draw( M3dView& view) = 0;
};
}
#endif
| [
"[email protected]",
"Byron@47f0d279-f73c-3d47-9f0e-87e2732817b2"
]
| [
[
[
1,
18
]
],
[
[
19,
89
]
]
]
|
247f8f9c5b8164b183ea1267f8cc56a71a3531fe | 221e3e713891c951e674605eddd656f3a4ce34df | /core/OUE/Impl/DXLib/DXDefs.h | b2920bce9c5a92fd4b9cda4e98e6dc37274cc0a0 | [
"MIT"
]
| permissive | zacx-z/oneu-engine | da083f817e625c9e84691df38349eab41d356b76 | d47a5522c55089a1e6d7109cebf1c9dbb6860b7d | refs/heads/master | 2021-05-28T12:39:03.782147 | 2011-10-18T12:33:45 | 2011-10-18T12:33:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,546 | h | /*
This source file is part of OneU Engine.
Copyright (c) 2011 Ladace
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.
*/
/**
* @file DXDefs.h
* @brief DX基础定义
*
* 定义一些操作DX所需的基本。在DXGraphics和DXInput之下,由于无处可放放到了底层。
* @author Ladace
* @version 1.0.0.1
* @date 2011-04-10
*/
#pragma once
#include <windows.h>
#include <dxerr.h>
#pragma comment( lib, "dxerr.lib" )
#pragma comment( lib, "dxerr9.lib" )
#define SAFE_RELEASE( ptr ) OneU::DX::SafeRelease( ptr )
#define DXERRGET_STR(hr) ::DXGetErrorDescription(hr)
#define ONEU_LOG_DXERR(hr) ONEU_LOG(::DXGetErrorDescription(hr))
namespace OneU
{
namespace DX
{
template < class T >
inline void SafeRelease( T *& ptr ){
if( ptr ){
ptr->Release();
ptr = NULL;
}
}
}
}
#define RAISE_HRESULT(hr) ONEU_RAISE(::DXGetErrorDescription(hr))
//检查DX的HRESULT返回值 若有错误会记录到日志 程序继续运行
#define DXCHECK( fn, str ) {\
HRESULT hr;\
if( FAILED( hr = fn ) ) {\
GetLogger().stream(ILogger::ML_CRITICAL) << __FILE__ << ':' << __LINE__ << '\n' << str << '\n' << ::DXGetErrorDescription( hr );\
}\
}void( 0 )/*@记录格式不好看 待重构*/
//检查DX的HRESULT返回值 若有错误会记录到日志 程序抛出错误
#define DXCHECK_RAISE( fn, str ) {\
HRESULT hr;\
if( FAILED( hr = fn ) ){\
ONEU_LOG( str );\
RAISE_HRESULT(hr);\
}\
}void( 0 )
#define XV( fn ) DXCHECK( fn, #fn )
#define XV_RAISE( fn ) DXCHECK_RAISE( fn, #fn );
#ifdef _DEBUG
//仅在调试版本检查返回值 发布版本不会检查
#define DXCHECK_DEBUG( fn, str ) DXCHECK( fn, str )
//仅在调试版本检查返回值 发布版本不会检查
#define XV_DEBUG( fn ) DXCHECK_DEBUG( fn, #fn )
#else
#define DXCHECK_DEBUG( fn, str ) fn;
#define XV_DEBUG( fn ) fn;
#endif
namespace OneU
{
/* ----------------------------------------------------------------------------*/
/*@cond INTERNAL_MPL*/
/* ----------------------------------------------------------------------------*/
//分别表示TRUE FALSE
struct __True_Category{};
struct __False_Category{};
template< bool boolean >
struct __Bool_Category
{
};
template<>
struct __Bool_Category< true >
{
typedef __True_Category Category;
};
template<>
struct __Bool_Category< false >
{
typedef __False_Category Category;
};
/* ----------------------------------------------------------------------------*/
/*@endcond*///INTERNAL_MPL
}
| [
"[email protected]@d30a3831-f586-b1a3-add9-2db6dc386f9c"
]
| [
[
[
1,
112
]
]
]
|
e1c61ee41eeb7be3f85f4d0645c3f06f26947461 | f177993b13e97f9fecfc0e751602153824dfef7e | /ImProSln/tool/BGHomography/BGHomography/main.cpp | 0b1803fee3648e4b95e4423aa46cb6491148d1c1 | []
| no_license | svn2github/imtophooksln | 7bd7412947d6368ce394810f479ebab1557ef356 | bacd7f29002135806d0f5047ae47cbad4c03f90e | refs/heads/master | 2020-05-20T04:00:56.564124 | 2010-09-24T09:10:51 | 2010-09-24T09:10:51 | 11,787,598 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,199 | cpp | #include "BackGroundHomo.h"
#define CALIBRATION true
#define CAMWIDTH 320
#define CAMHEIGHT 240
void main(){
BackGroundHomo* bg = new BackGroundHomo() ;
bool caliFinish = false ;
bool whiteOK = false ;
CvCapture *capture;
IplImage *frame;
IplImage * whiteBG = cvLoadImage("white.bmp",0);
IplImage * blackBG = cvLoadImage("gray.bmp",0);
IplImage * tagBG = cvLoadImage("BG.jpg",0);
IplImage *binary_img = cvCreateImage(cvSize(CAMWIDTH,CAMHEIGHT),8,1);
cvResize(tagBG,bg->backgroundImg);
capture =cvCaptureFromCAM(1);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, CAMWIDTH);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, CAMHEIGHT);
cvNamedWindow("Webcam",0);
if(CALIBRATION){
while(caliFinish == false){
frame = cvQueryFrame(capture);
cvCvtColor( frame, binary_img, CV_RGB2GRAY );
cvShowImage("Webcam",frame);
cvNamedWindow("bgCali");
cvMoveWindow("bgCali",1280,0);
if(whiteOK == false){
cvShowImage("bgCali",whiteBG);
}
char input;
input = cvWaitKey(1);
if(input == 'w'){
bg->setBackground(binary_img);
bg->warpCaliCapture(binary_img,bg->gray255Image);
whiteOK = true ;
}
if(whiteOK == true){
cvShowImage("bgCali",blackBG);
cvWaitKey(1);
if(input == 'b'){
bg->warpCaliCapture(binary_img,bg->gray0Image);
caliFinish = true ;
cvShowImage("bgCali",tagBG);
}
}
}
bg->buildMappingTable();
}
else{
bg->loadHomo("HomoMat.txt","mTable.txt");
}
IplImage *temp = cvCreateImage(cvGetSize(bg->backgroundImg),8,1) ;
cvCopy(bg->backgroundImg,temp) ;
IplConvKernel* element = cvCreateStructuringElementEx(5,5,0,0,CV_SHAPE_ELLIPSE,NULL);
//cvDilate(temp,bg->backgroundImg,element,1);
cvSmooth(temp,bg->backgroundImg ,2,9);
//cvSmooth(temp,bg->backgroundImg ,2,9);
cvNamedWindow("Background");
cvShowImage("Background",bg->backgroundImg);
cvWaitKey(1);
while(true)
{
frame = cvQueryFrame(capture);
cvCvtColor( frame, binary_img, CV_RGB2GRAY );
bg->warpImg(binary_img);
}
cvReleaseCapture(&capture);
cvReleaseImage(&frame);
cvDestroyWindow("Webcam");
} | [
"claire3kao@fa729b96-8d43-11de-b54f-137c5e29c83a"
]
| [
[
[
1,
85
]
]
]
|
dc1eb9ded416cc07e1a4145b53ff14ea854a462e | 8a3fce9fb893696b8e408703b62fa452feec65c5 | /QQTool/QQTool/QQToolDlg.h | 8b929e247022be3290ccea6be3d0f46c8e0a5a4a | []
| no_license | win18216001/tpgame | bb4e8b1a2f19b92ecce14a7477ce30a470faecda | d877dd51a924f1d628959c5ab638c34a671b39b2 | refs/heads/master | 2021-04-12T04:51:47.882699 | 2011-03-08T10:04:55 | 2011-03-08T10:04:55 | 42,728,291 | 0 | 2 | null | null | null | null | GB18030 | C++ | false | false | 847 | h | // QQToolDlg.h : 头文件
//
#pragma once
class CQQToolDlgAutoProxy;
// CQQToolDlg 对话框
class CQQToolDlg : public CDialog
{
DECLARE_DYNAMIC(CQQToolDlg);
friend class CQQToolDlgAutoProxy;
// 构造
public:
CQQToolDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~CQQToolDlg();
// 对话框数据
enum { IDD = IDD_QQTOOL_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
CQQToolDlgAutoProxy* m_pAutoProxy;
HICON m_hIcon;
BOOL CanExit();
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
virtual void OnOK();
virtual void OnCancel();
DECLARE_MESSAGE_MAP()
};
| [
"[email protected]"
]
| [
[
[
1,
43
]
]
]
|
56b988315f437d84decc8bedeeffb007b1ee15a7 | 57855d23617d6a65298c2ae3485ba611c51809eb | /Zen/plugins/ZFMOD/src/SoundServiceFactory.cpp | e87e130249b378245201c6978f190035c0ad9345 | []
| no_license | Azaezel/quillus-daemos | 7ff4261320c29e0125843b7da39b7b53db685cd5 | 8ee6eac886d831eec3acfc02f03c3ecf78cc841f | refs/heads/master | 2021-01-01T20:35:04.863253 | 2011-04-08T13:46:40 | 2011-04-08T13:46:40 | 32,132,616 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,283 | cpp | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Zen Enterprise Framework
//
// Copyright (C) 2001 - 2008 Tony Richards
// Copyright (C) 2008 Walt Collins
//
// 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.
//
// Tony Richards [email protected]
// Walt Collins (Arcanor) - [email protected]
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "SoundServiceFactory.hpp"
#include "SoundService.hpp"
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <stddef.h>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Zen {
namespace ZFMOD {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
SoundServiceFactory::SoundServiceFactory()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
SoundServiceFactory::~SoundServiceFactory()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
static SoundServiceFactory sm_factory;
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
SoundServiceFactory&
SoundServiceFactory::getSingleton()
{
return sm_factory;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
SoundServiceFactory::pSoundService_type
SoundServiceFactory::create(const std::string& _type, config_type& _config)
{
SoundService* pRawService = new SoundService(_config);
pSoundService_type pService(pRawService, boost::bind(&SoundServiceFactory::onDestroy,this,_1));
wpSoundService_type pWeakPtr(pService);
pRawService->setSelfReference(pWeakPtr);
return pService;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
SoundServiceFactory::onDestroy(wpSoundService_type& _pService)
{
/// Fire the service's onDestroyEvent
_pService->onDestroyEvent(_pService);
/// Delete the service
SoundService* pService = dynamic_cast<SoundService*>(_pService.get());
if(pService != NULL)
{
delete pService;
}
else
{
// TODO : Error
}
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace ZFMOD
} // namespace Zen
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| [
"sgtflame@Sullivan",
"[email protected]"
]
| [
[
[
1,
49
],
[
51,
55
],
[
57,
60
],
[
62,
64
],
[
66,
75
],
[
77,
77
],
[
79,
83
],
[
85,
89
],
[
91,
97
]
],
[
[
50,
50
],
[
56,
56
],
[
61,
61
],
[
65,
65
],
[
76,
76
],
[
78,
78
],
[
84,
84
],
[
90,
90
]
]
]
|
c313cd1df514c7f3dba478003bf944095c0ef4bc | 6c8c4728e608a4badd88de181910a294be56953a | /PythonScriptModule/PythonEngine.cpp | 106d91df2070aa1436ffeec90da47650b1e1a748 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | caocao/naali | 29c544e121703221fe9c90b5c20b3480442875ef | 67c5aa85fa357f7aae9869215f840af4b0e58897 | refs/heads/master | 2021-01-21T00:25:27.447991 | 2010-03-22T15:04:19 | 2010-03-22T15:04:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,458 | cpp | // For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "PythonScriptModule.h"
#include "PythonEngine.h"
//#include <stdlib.h> //_putenv for PYTHONHOME on windows
#include <Poco/Environment.h>
#include "MemoryLeakCheck.h"
using namespace Foundation;
namespace PythonScript
{
PythonEngine::PythonEngine(Framework* framework) :
framework_(framework)
{
}
PythonEngine::~PythonEngine()
{
//deinit / free
}
void PythonEngine::Initialize()
{
if (!Py_IsInitialized())
{
#ifdef _WIN32
//for some reason these have no affect when running from inside visual studio,
//so for VS use, the PYTHONHOME env var has to be set in the project file
//_putenv("PYTHONHOME = .\\pymodules");
Poco::Environment::set("PYTHONHOME", ".\\pymodules");
//loads pymodules/lib/site.py which is the windows
//std::cout << "PYTHONHOME SET";
#endif
Py_Initialize();
RunString("import sys; sys.path.append('pymodules');"); //XXX change to the c equivalent
RunString("import sys; sys.path.append('pymodules/lib');"); // libraries directory
}
else
{
//LogWarning() //XXX add module ref here to be able to do logging
std::cout << "Python already initialized in PythonScriptModule init!";
}
}
/* load modules and get pointers to py functions - used to be in module postinitialize
pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
pFunc = PyObject_GetAttrString(pModule, "onChat");
//pFunc is a new reference
if (pFunc && PyCallable_Check(pFunc)) {
LogInfo("Registered callback onChat from chathandler.py");
}
else {
if (PyErr_Occurred())
PyErr_Print();
LogInfo("Cannot find function");
}
}
else
LogInfo("chathandler.py not found");
*/
void PythonEngine::Uninitialize()
{
/*Py_XDECREF(pFunc);
Py_DECREF(pModule);*/
Py_Finalize();
}
/*void PythonEngine::Reset()
{
//should clear own internal state etc too i guess XXX
Py_Finalize();
Py_Initialize();
//no ref to mod here now XXX
//PythonModule::LogInfo("Python interpreter reseted: all memory and state cleared.");
}*/
void PythonEngine::RunString(const std::string& codestr)
{
PyRun_SimpleString(codestr.c_str());
}
void PythonEngine::RunScript(const std::string& scriptname)
{
FILE *fp = fopen(scriptname.c_str(), "r");
if (!fp) {
PythonScriptModule::LogInfo("Failed to open script " + scriptname);
return;
}
PyRun_SimpleFile(fp, scriptname.c_str());
fclose(fp);
}
//===============================================================================================//
// //
// "GENERIC INTERFACE" //
// //
/* deprecated - PythonQt does this too
Foundation::ScriptObject* PythonEngine::LoadScript(const std::string& scriptname, std::string& error)
{
PyObject *pName, *pModule;
error = "None";
//std::string scriptPath("pymodules");
//PyImport_ImportModule(scriptPath.c_str());
pName = PyString_FromString(scriptname.c_str());
//pName = PyString_FromString(scriptPath.c_str());
if(pName==NULL){ error = "name parsing failed"; return NULL;}
pModule = PyImport_Import(pName);
if(pModule==NULL){ error = "module loading failed"; return NULL;}
PythonScriptObject* obj = new PythonScriptObject();
obj->pythonRef = pModule;
return obj;
}
Foundation::ScriptObject* PythonEngine::GetObject(const Foundation::ScriptObject& script,
const std::string& objectname,
std::string& error)
{
PyObject *pDict, *pClass, *pInstance;
error = "None";
// try casting script to PythonScriptObject
PythonScriptObject* pythonscript = (PythonScriptObject*)&script;
pDict = PyModule_GetDict(pythonscript->pythonRef);
if(pDict==NULL){error = "unable to get module namespace"; return NULL;}
// Build the name of a callable class
pClass = PyDict_GetItemString(pDict, objectname.c_str());
if(pClass==NULL){error = "unable get class from module namespace"; return NULL;}
PythonScriptObject* obj = new PythonScriptObject();
obj->pythonRef = pClass;
// Create an instance of the class
if (PyCallable_Check(pClass)) {
pInstance = PyObject_CallObject(pClass, NULL);
} else {
error = "unable to create instance from class"; return NULL;
}
obj->pythonObj = pInstance;
return obj;
}
void PythonEngine::SetCallback(void(*f)(char*), std::string key)
{
try{
//std::map<std::string, std::vector<void(*)(char*)>>::iterator iter = methods_.find(key);
std::map<std::string, StdFunctionVectorPtr>::iterator iter = methods_.find(key);
if(iter==methods_.end()){
//PythonScript::PythonModule::LogInfo("key not found, create new vector");
//std::cout << "key not found, create new vector" << std::endl;
PythonScript::PythonEnginePtr(new PythonScript::PythonEngine(framework_));
methods_[key] = PythonScript::StdFunctionVectorPtr(new std::vector<void(*)(char*)>());
methods_[key]->push_back(f);
} else {
iter->second->push_back(f);
//methods_[iter]->push_back(f);
}
} catch(...){
PythonScriptModule::LogInfo("Failed to add callback");
//std::cout << "Failed to add callback" << std::endl;
}
}
void PythonEngine::NotifyScriptEvent(const std::string& key, const std::string& message)
{
//std::cout << "NotifyScriptEvent" << std::endl;
try{
std::map<std::string, StdFunctionVectorPtr>::iterator iter = methods_.find(key);
if(iter==methods_.end()){
PythonScriptModule::LogInfo("no such event declared:");
PythonScriptModule::LogInfo(key);
} else {
StdFunctionVectorPtr vect = iter->second;
std::vector<void(*)(char*)>::iterator f_iter;
char* m = new char[message.size()+1];
strcpy(m, message.c_str());
for(f_iter = vect->begin(); f_iter != vect->end(); f_iter++){
(*f_iter)(m);
}
}
} catch(...){
//PythonModule::LogInfo("Failed to notify");
PythonScriptModule::LogInfo("Failed to notify");
}
}
//===============================================================================================//
*/
}
| [
"Stinkfist0@5b2332b8-efa3-11de-8684-7d64432d61a3",
"petri.aura@5b2332b8-efa3-11de-8684-7d64432d61a3"
]
| [
[
[
1,
6
],
[
9,
29
],
[
39,
200
]
],
[
[
7,
8
],
[
30,
38
]
]
]
|
b9def3bb5fd215f587ab26fd9431e83eaaeabbab | 30a1e1c0c95239e5fa248fbb1b4ed41c6fe825ff | /jmail/hydra.h | f39d5a06290e6ce293456615619838fd30af739b | []
| no_license | inspirer/history | ed158ef5c04cdf95270821663820cf613b5c8de0 | 6df0145cd28477b23748b1b50e4264a67441daae | refs/heads/master | 2021-01-01T17:22:46.101365 | 2011-06-12T00:58:37 | 2011-06-12T00:58:37 | 1,882,931 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,033 | h | // hydra.h
#define _crc16_poly 0x8408
#define _crc16_init 0xFFFF
#define _crc16_test 0xF0B8
#define max_pkt_size 32768
#define rx_buff_size 32768
// revision : 2b1aab00 (1,01 dec 1992)
#define APPL_ID "2b1aab00jMail,1-4.nt"
//What we can do
#define SUPP_OPT (HOPT_XONXOFF|HOPT_TELENET|HOPT_CTLCHRS|HOPT_HIGHCTL|HOPT_HIGHBIT|HOPT_CANBRK)
#define DESIRED_OPT (HOPT_XONXOFF|HOPT_TELENET)
#define HCAN_OPTIONS (HOPT_XONXOFF|HOPT_TELENET|HOPT_CTLCHRS|HOPT_HIGHCTL|HOPT_HIGHBIT|HOPT_CANBRK)
//Vital options if we ask for any; abort if other side doesn't support them
#define HNEC_OPTIONS (HOPT_XONXOFF|HOPT_TELENET|HOPT_CTLCHRS|HOPT_HIGHCTL|HOPT_HIGHBIT|HOPT_CANBRK)
// Ctrl-Q (^Q) Xmit-On character & Ctrl-S (^S) Xmit-Off character
#define XON 17
#define XOFF 19
// Ctrl-X (^X) HYDRA DataLinkEscape
#define H_DLE 24
#define H_BRAINDEAD 120 // Braindead in 2 mins (120 secs)
#define H_MINBLKLEN 64 // Min. length of a HYDRA data block
#define H_MAXBLKLEN 2048 // Max. length of a HYDRA data block
#define H_OVERHEAD 8 // Max. no. control bytes in a pkt
#define H_MAXPKTLEN ((H_MAXBLKLEN + H_OVERHEAD + 5) * 3) // Encoded pkt
#define H_BUFLEN (H_MAXPKTLEN + 16); // Buffer sizes: max.enc.pkt + slack
#define H_PKTPREFIX 31 // Max length of pkt prefix string
#define H_FLAGLEN 3 // Length of a flag field
#define H_RETRIES 10 // No. retries in case of an error
#define H_MINTIMER 10 // Minimum timeout period
#define H_MAXTIMER 60 // Maximum timeout period
#define H_START 5 // Timeout for re-sending startstuff
#define H_IDLE 20 // Idle? TX IDLE pkt every 20 secs
//HYDRA Packet Types
#define HPKT_START 'A' // Startup sequence
#define HPKT_INIT 'B' // Session initialisation
#define HPKT_INITACK 'C' // Response to INIT pkt
#define HPKT_FINFO 'D' // File info (name, size, time)
#define HPKT_FINFOACK 'E' // Response to FINFO pkt
#define HPKT_DATA 'F' // File data packet
#define HPKT_DATAACK 'G' // File data position ACK packet
#define HPKT_RPOS 'H' // Transmitter reposition packet
#define HPKT_EOF 'I' // End of file packet
#define HPKT_EOFACK 'J' // Response to EOF packet
#define HPKT_END 'K' // End of session
#define HPKT_IDLE 'L' // Idle - just saying I'm alive
#define HPKT_DEVDATA 'M' // Data to specified device
#define HPKT_DEVDACK 'N' // Response to DEVDATA pkt
//HYDRA Packet Format: START[<data>]<type><crc>END
#define HCHR_PKTEND 'a' // End of packet (any format)
#define HCHR_BINPKT 'b' // Start of binary packet
#define HCHR_HEXPKT 'c' // Start of hex encoded packet
#define HCHR_ASCPKT 'd' // Start of shifted 7bit encoded pkt
#define HCHR_UUEPKT 'e' // Start of uuencoded packet
//HYDRA Local Storage of INIT Options (Bitmapped)
#define HOPT_XONXOFF 0x0001 // Escape XON/XOFF
#define HOPT_TELENET 0x0002 // Escape CR-'@'-CR (Telenet escape)
#define HOPT_CTLCHRS 0x0004 // Escape ASCII 0-31 and 127
#define HOPT_HIGHCTL 0x0008 // Escape above 3 with 8th bit too
#define HOPT_HIGHBIT 0x0010 // Escape ASCII 128-255 + strip high
#define HOPT_CANBRK 0x0020 // Can transmit a break signal
#define HOPT_CANASC 0x0040 // Can transmit/handle ASC packets
#define HOPT_CANUUE 0x0080 // Can transmit/handle UUE packets
#define HOPT_CRC32 0x0100 // Packets with CRC-32 allowed
#define HOPT_DEVICE 0x0200 // DEVICE packets allowed
#define HOPT_FPT 0x0400 // Can handle filenames with paths
class CRemoteHydra {
public:
uchar hydra_mailer[80],pktprefix[30];
long TxOptions,RxOptions,rxSize,txSize,Supported,Desired;
time_t _hydra_doc;
int inited;
void getfromrx(uchar *rx);
int hydraGetInitOptions(uchar *l);
};
class CHydraFile : public CJFile {
public:
enum { NOTH, WFIACK, SENDING, WEOFACK,
GODOWN, WAITFORDOWN, DOWN, RECEIVE, RECEIVE_RPOS };
ulong Count,Transaction,last_retry,tries,start_from,pktSize;
time_t et;
};
class CHydra {
private:
ushort crc16table[256];
uchar pkt[max_pkt_size],rx[rx_buff_size],t[max_pkt_size];
int hStep,rxPktStatus,rxPktSize,rxPktLost,rxPrev,rxOld;
long rx_files,tx_files,rx_bytes,tx_bytes;
char tinfo[256];
CRemoteHydra rh;
CHydraFile rx_file,tx_file;
time_t braindead,hydra_start;
void hydraBuildCrc();
inline void hydraCrc(uchar c,ushort *crc);
inline void hydraCrcData(uchar *c,int size,ushort *crc);
void hydraSendPkt(uchar *pk,int psize,uchar ptype);
int hydraReceivePkt();
void hydraMessage(const char *w);
void hydraRefresh();
void hydraSendRPOS();
void hydraMain();
int hydraPrepeareINITpkt();
void hydraSendFINFO();
char *hydraLinkOptions(int LinkOpt);
void GetFromFINFO(CHydraFile *hf);
public:
CFileList *ls;
void Start();
};
| [
"[email protected]"
]
| [
[
[
1,
125
]
]
]
|
085336bbae8f345c77d252c8552c881023fc07a1 | 3472e587cd1dff88c7a75ae2d5e1b1a353962d78 | /TestLibssh2/main.cpp | 22ebc018b8ef86d5c51cc93bd4b44b4593ee3cb3 | []
| no_license | yewberry/yewtic | 9624d05d65e71c78ddfb7bd586845e107b9a1126 | 2468669485b9f049d7498470c33a096e6accc540 | refs/heads/master | 2021-01-01T05:40:57.757112 | 2011-09-14T12:32:15 | 2011-09-14T12:32:15 | 32,363,059 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | cpp | /*
* main.cpp
*
* Created on: 2011-2-25
* Author: Yewberry
*/
#include <iostream>
#include <string>
#include "SSH2Utils.h"
int main(int argc, char* argv[]) {
SSH2Utils ssh2;
ssh2.init();
int rc = 0;
rc = ssh2.connect(argv[1], argv[2], argv[3]);
if(rc == 0){
char *t = "./yew.sh";
rc = ssh2.exec(t);
std::string str = ssh2.execResultStr();
std::cout << "CMD RESULT:\n" << str << std::endl;
}
return 0;
}
| [
"[email protected]@5ddc4e96-dffd-11de-b4b3-6d349e4f6f86"
]
| [
[
[
1,
27
]
]
]
|
026ba181055eb6d99c4002f30efe28f49395f12f | bf7d05c055c5686e4ded30f9705a28a396520d48 | /MGA/MgaGeneric.cpp | 81ffe471cce0f6bd48b2a6af30c0e571131656da | []
| no_license | ghemingway/mgalib | f32438d5abdbeb5739c298e401a0513f91c8d6d0 | c8cf8507a7fe73efe1da19abcdb77b52e75e2de0 | refs/heads/master | 2020-12-24T15:40:33.538434 | 2011-02-04T16:38:09 | 2011-02-04T16:38:09 | 32,185,568 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,639 | cpp | /*** Included Header Files ***/
#include "MgaGeneric.h"
/*** Version 2 of the special sauce ***/
const Result_t MGA::CreateMGACoreMetaProject(CoreMetaProject* &metaProject)
{
// GUID_t guid = {0x028F7444,0x2E51,0x11D3,{0xB3,0x6D,0x00,0x62,0x08,0x2D,0xF8,0x74}};
Uuid uuid = "{DC5D7DEE-A590-47C9-B707ADB3E98E2879}";
metaProject = new CoreMetaProject("MgaProject", "MgaProject", uuid);
ASSERT( metaProject != NULL );
// ------- Macros
Result_t result;
CoreMetaObject* object;
CoreMetaAttribute* attribute;
#define CREATE_OBJECT(metaid, token, name) \
result = metaProject->AddObject(metaid, token, name, object); \
ASSERT( result == S_OK );
#define CREATE_POINTER(metaid, token, name) \
result = object->AddAttribute(metaid, token, name, ValueType::Pointer(), attribute); \
ASSERT( result == S_OK );
#define CREATE_COLLECTION(metaid, token, name) \
result = object->AddAttribute((metaid) + ATTRID_COLLECTION, token, name, ValueType::Collection(), attribute); \
ASSERT( result == S_OK );
#define CREATE_ATTRIBUTE(metaid, token, name, valtype) \
result = object->AddAttribute(metaid, token, name, valtype, attribute); \
ASSERT( result == S_OK );
//////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// COMMON /////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//ROOT
CREATE_OBJECT(DTID_ROOT, "Root", "Template For RootObject");
CREATE_COLLECTION(ATTRID_FATHER, "DummyFather", "Dummy Father");
CREATE_POINTER(ATTRID_FATHER, "DummyChildren", "Dummy Children");
CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "Project Name", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_CDATE, "CDate", "Create Date", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_MDATE, "MDate", "Modification Date", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_CREATOR, "Author", "Created by", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_GUID, "GUID", "GUID", ValueType::LongPointer());
CREATE_ATTRIBUTE(ATTRID_VERSION, "Version", "Version", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_PARADIGMUUID, "ParadigmGUID", "Paradigm GUID", ValueType::LongPointer());
CREATE_ATTRIBUTE(ATTRID_PARADIGMVERSION, "ParadigmVersion", "Paradigm Version", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_PARADIGM, "ExtParadigm", "External Paradigm",ValueType::String());
CREATE_ATTRIBUTE(ATTRID_EXTDATA, "Comment", "Project Comments", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_MGAVERSION, "MGA_Version", "MGA Version Code", ValueType::Long());
CREATE_COLLECTION(ATTRID_PARENT, "Children", "Child Objects");
//CONSTRAINT
CREATE_OBJECT(DTID_CONSTRAINT, "Constraint", "Template For Constraint");
CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "Constraint Name", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_CONSTROCL, "ConstraintOCL", "Constraint Text",ValueType::String());
CREATE_ATTRIBUTE(ATTRID_CONSTRPRIORITY, "ConstrPriority", "Constraint Priority",ValueType::String());
CREATE_POINTER(ATTRID_CONSTROWNER, "ConstraintOf", "Owner Kind");
//REGNODE
// CREATE_OBJECT(DTID_REGNODE, "RegNode", "Template For Registry Node");
// CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "RegNode Name", ValueType::String());
// CREATE_ATTRIBUTE(ATTRID_REGFLAGS, "RegistryFlags", "Registry Flags", ValueType::Long());
// CREATE_POINTER(ATTRID_REGNOWNER, "RegNodeOf", "Parent Object/Regnode");
// CREATE_COLLECTION(ATTRID_REGNOWNER, "RegNodes", "Registry Nodes");
// CREATE_ATTRIBUTE(ATTRID_REGNODEVALUE, "RegNodeValue", "RegNode Value",ValueType::String());
// CREATE_POINTER(ATTRID_XREF, "FCOref", "Referenced FCO");
//////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// DATA ///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//FOLDER
CREATE_OBJECT(DTID_FOLDER, "Folder", "Template For Folder");
CREATE_ATTRIBUTE(ATTRID_CDATE, "CDate", "Create Date", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_MDATE, "MDate", "Modification Date", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "Folder Name", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_META, "Meta", "Meta Identifier",ValueType::Long());
CREATE_ATTRIBUTE(ATTRID_LASTRELID, "LastRelID", "Last Child RelID", ValueType::Long());
CREATE_ATTRIBUTE(ATTRID_RELID, "RelID", "RelID", ValueType::Long());
CREATE_POINTER(ATTRID_PARENT, "Parent", "Parent Object");
CREATE_COLLECTION(ATTRID_PARENT, "Children", "Child Objects");
CREATE_COLLECTION(ATTRID_CONSTROWNER, "Constraints", "Constraints");
CREATE_ATTRIBUTE(ATTRID_REGISTRY, "Registry", "Key-Value Registry", ValueType::Dictionary());
CREATE_ATTRIBUTE(ATTRID_PERMISSIONS, "Permissions", "Permissions", ValueType::Long());
//FCO
#define FCO_DEF \
CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "FCO Name", ValueType::String());\
CREATE_ATTRIBUTE(ATTRID_RELID, "RelID", "RelID", ValueType::Long());\
CREATE_ATTRIBUTE(ATTRID_META, "Meta", "Meta Identifier",ValueType::Long());\
CREATE_ATTRIBUTE(ATTRID_ROLEMETA, "RoleMeta", "Role Meta Identifier",ValueType::Long());\
CREATE_POINTER(ATTRID_FCOPARENT, "Parent", "Parent Object");\
CREATE_COLLECTION(ATTRID_CONSTROWNER, "Constraints", "Constraints");\
CREATE_ATTRIBUTE(ATTRID_REGISTRY, "Registry", "Key-Value Registry", ValueType::Dictionary());\
CREATE_COLLECTION(ATTRID_REFERENCE, "References", "Referenced by");\
CREATE_COLLECTION(ATTRID_XREF, "XReferences", "Cross refs");\
CREATE_COLLECTION(ATTRID_ATTRPARENT,"Attributes", "Attributes");\
CREATE_POINTER(ATTRID_DERIVED, "BaseType", "BaseType");\
CREATE_COLLECTION(ATTRID_DERIVED, "SubTypes", "SubTypes/Instances"); \
CREATE_ATTRIBUTE(ATTRID_PERMISSIONS, "Permissions", "Permissions", ValueType::Long());
//MODEL
CREATE_OBJECT(DTID_MODEL, "Model", "Template For Model");
FCO_DEF
CREATE_ATTRIBUTE(ATTRID_CDATE, "CDate", "Create Date", ValueType::String());
CREATE_ATTRIBUTE(ATTRID_MDATE, "MDate", "Modification Date", ValueType::String());
CREATE_COLLECTION(ATTRID_PARENT, "Children", "Child Objects");
CREATE_ATTRIBUTE(ATTRID_LASTRELID, "LastRelID", "Last Child RelID", ValueType::Long());
//ATOM
CREATE_OBJECT(DTID_ATOM, "Atom", "Template For Atom");
FCO_DEF
//REFERENCE
CREATE_OBJECT(DTID_REFERENCE, "Reference", "Template For Reference");
FCO_DEF
CREATE_POINTER(ATTRID_REFERENCE, "Refers", "Referenced FCO");
CREATE_COLLECTION(ATTRID_SEGREF, "Segments", "Connection Segments");
CREATE_POINTER(ATTRID_MASTEROBJ, "MasterObj", "Master Object");
CREATE_COLLECTION(ATTRID_MASTEROBJ, "MasterOf", "Master Of Objects");
CREATE_ATTRIBUTE(ATTRID_REFASPECT, "RefAspect", "Ref Aspect", ValueType::Long());
//SET
CREATE_OBJECT(DTID_SET, "Set", "Template For Set");
FCO_DEF
CREATE_COLLECTION(ATTRID_SETMEMBER, "Members", "Set Members");
//SETNODE
CREATE_OBJECT(DTID_SETNODE, "SetNode", "Template For Set Member");
CREATE_POINTER(ATTRID_SETMEMBER, "SetOwner", "Owner Set");
CREATE_POINTER(ATTRID_XREF, "FCOref", "Member FCO");
CREATE_POINTER(ATTRID_MASTEROBJ, "MasterObj", "Master Object");
CREATE_COLLECTION(ATTRID_MASTEROBJ, "MasterOf", "Master Of Objects");
//CONNECTION
CREATE_OBJECT(DTID_CONNECTION, "Connection", "Template For Connection");
FCO_DEF
CREATE_COLLECTION(ATTRID_CONNROLE, "ConnRoles", "ConnRoles");
//CONNECTION ROLE
CREATE_OBJECT(DTID_CONNROLE, "ConnRole", "Template for Connection Role");
CREATE_ATTRIBUTE(ATTRID_NAME, "Name", "Connrole Name",ValueType::String());
CREATE_POINTER(ATTRID_XREF, "FCOref", "Connected FCO");
CREATE_POINTER(ATTRID_CONNROLE, "CRoleParent", "Owner of ConnRole");
CREATE_COLLECTION(ATTRID_CONNSEG, "ConnSegments", "Connection Segments");
CREATE_POINTER(ATTRID_MASTEROBJ, "MasterObj", "Master Object");
CREATE_COLLECTION(ATTRID_MASTEROBJ, "MasterOf", "Master Of Objects");
//CONNECTION ROLE SEGMENT
CREATE_OBJECT(DTID_CONNROLESEG, "ConnRoleSeg", "Template for ConnRole Segment");
CREATE_ATTRIBUTE(ATTRID_SEGORDNUM, "SegOrdNum", "Segment Order 1,2,3 ", ValueType::Long());
CREATE_POINTER(ATTRID_CONNSEG, "ConnSRole", "Owner Connection Role");
CREATE_POINTER(ATTRID_SEGREF, "ReferenceObj", "Reference Involved");
// ATTRIBUTE
#define ATTR_DEF \
CREATE_ATTRIBUTE(ATTRID_META, "Meta", "Meta Identifier",ValueType::Long());\
CREATE_POINTER(ATTRID_ATTRPARENT,"Owner", "Owner FCO");\
//STRATTR
CREATE_OBJECT(DTID_STRATTR, "StrAttr", "String Attribute");
ATTR_DEF
CREATE_ATTRIBUTE(ATTRID_STRATTR, "StrValue", "String Value",ValueType::String());
//INTATTR
CREATE_OBJECT(DTID_INTATTR, "IntAttr", "LongInt Attribute");
ATTR_DEF
CREATE_ATTRIBUTE(ATTRID_INTATTR, "IntValue", "LongInt Value",ValueType::Long());
//FLOATATTR
CREATE_OBJECT(DTID_FLOATATTR, "FloatAttr", "Float Attribute");
ATTR_DEF
CREATE_ATTRIBUTE(ATTRID_FLOATATTR, "FloatValue", "Float Value",ValueType::Real());
//BOOLATTR
CREATE_OBJECT(DTID_BOOLATTR, "BoolAttr", "Bool Attribute");
ATTR_DEF
CREATE_ATTRIBUTE(ATTRID_BOOLATTR, "BoolValue", "Bool Value",ValueType::Long());
//REFATTR
CREATE_OBJECT(DTID_REFATTR, "RefAttr", "Reference Attribute");
ATTR_DEF
CREATE_POINTER(ATTRID_XREF, "FCOref", "Referenced FCO");
// Return the project
return S_OK;
}
| [
"graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462"
]
| [
[
[
1,
195
]
]
]
|
71c01bb4f97c4e60b54edd225e7317d204465bab | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/contrib/noctree/src/octree/noctree_main.cc | 81fe0ef27b527a7bbc5340720191179bfec43533 | []
| no_license | moltenguy1/minimangalore | 9f2edf7901e7392490cc22486a7cf13c1790008d | 4d849672a6f25d8e441245d374b6bde4b59cbd48 | refs/heads/master | 2020-04-23T08:57:16.492734 | 2009-08-01T09:13:33 | 2009-08-01T09:13:33 | 35,933,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,792 | cc | //-------------------------------------------------------------------
// noctree_main.cc
// (C) 1999 A.Weissflog
//-------------------------------------------------------------------
#include "kernel/nenv.h"
#include "octree/noctree.h"
//#include "gfx2/nprimitiveserver.h"
nNebulaScriptClass(nOctree, "nroot");
//-------------------------------------------------------------------
/**
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
nOctree::nOctree() :
refGfxServer("/sys/servers/gfx")
//clipPlanes()
{
int i;
this->visualize = false;
this->subdiv_num = 4;
this->tree_root = NULL;
this->free_root = NULL;
this->num_collected = 0;
this->ext_array_size = 0;
this->ext_collect_array = NULL;
// link node to free_pool
for (i=0; i<(N_OCT_MAXNUMNODES-1); i++) {
this->free_pool[i].next = &(this->free_pool[i+1]);
}
this->free_root = this->free_pool;
// create root-node
this->tree_root = this->alloc_node(NULL,
N_OCT_MINX, N_OCT_MAXX,
N_OCT_MINY, N_OCT_MAXY,
N_OCT_MINZ, N_OCT_MAXZ);
}
//-------------------------------------------------------------------
/**
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
nOctree::~nOctree()
{
// make sure that there are no more elements in the tree
n_assert(0 == this->tree_root->all_num_elms);
}
//-------------------------------------------------------------------
/**
@brief Set the maxinum number of elements allowed within an
nOctNode before the node will be subdivided and its elements
spread out over the new subcubes.
This will rebalance the tree.
- 01-Jun-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::SetSubdivNum(int s)
{
this->subdiv_num = s;
this->BalanceTree();
}
//-------------------------------------------------------------------
/**
@return the maximun number of elements allowed within an
nOctNode.
- 01-Jun-99 floh created
*/
//-------------------------------------------------------------------
int nOctree::GetSubdivNum(void)
{
return this->subdiv_num;
}
//-------------------------------------------------------------------
/**
@brief Enable or disable the visualization of the tree.
See nOctree::Visualize() for further information.
- 01-Jun-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::SetVisualize(bool v)
{
this->visualize = v;
}
//-------------------------------------------------------------------
/**
@return whether or not visualization of the tree is enabled.
- 01-Jun-99 floh created
*/
//-------------------------------------------------------------------
bool nOctree::GetVisualize(void)
{
return this->visualize;
}
//-------------------------------------------------------------------
/**
Takes a new nOctNode from the free_pool and initializes
its parent pointer and bounding box
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
nOctNode *nOctree::alloc_node(nOctNode *p,
float x0, float x1,
float y0, float y1,
float z0, float z1)
{
nOctNode *n = this->free_root;
n_assert(n);
this->free_root = n->next;
n->parent = p;
n->minCorner.x=x0; n->minCorner.y=y0; n->minCorner.z=z0;
n->maxCorner.x=x1; n->maxCorner.y=y1; n->maxCorner.z=z1;
// n_printf("# new octnode %d\n",n);
return n;
}
//-------------------------------------------------------------------
/**
Adds an nOctNode back into the free_pool and makes sure it
has been cleaned up properly
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::freenode(nOctNode *n)
{
n_assert(n->elm_list.IsEmpty());
n_assert(0 == n->num_elms);
n_assert(NULL == n->c[0]);
n_assert(NULL == n->c[1]);
n_assert(NULL == n->c[2]);
n_assert(NULL == n->c[3]);
n_assert(NULL == n->c[4]);
n_assert(NULL == n->c[5]);
n_assert(NULL == n->c[6]);
n_assert(NULL == n->c[7]);
n->next = this->free_root;
this->free_root = n;
// n_printf("# freed octnode %d\n",n);
}
//-------------------------------------------------------------------
/**
Returns true if the element completely fits into the nOctNode
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
bool nOctree::elm_inside_node(nOctElement *oe, nOctNode *n)
{
int clip = 0;
if (oe->minCorner.x < n->minCorner.x) clip |= N_OCT_CLIPX0;
if (oe->maxCorner.x > n->maxCorner.x) clip |= N_OCT_CLIPX1;
if (oe->minCorner.y < n->minCorner.y) clip |= N_OCT_CLIPY0;
if (oe->maxCorner.y > n->maxCorner.y) clip |= N_OCT_CLIPY1;
if (oe->minCorner.z < n->minCorner.z) clip |= N_OCT_CLIPZ0;
if (oe->maxCorner.z > n->maxCorner.z) clip |= N_OCT_CLIPZ1;
return (0 == clip);
}
//-------------------------------------------------------------------
/**
Make sure that no child-nodes exist yet. If ok,
create 4 nOctNodes and try to distribute all elements
into them.
Cause for a subdivide is, in general, that the number of
elements in a nOctNode has exceeded 'subdiv_num'
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::subdivide(nOctNode *n)
{
n_assert(NULL == n->c[0]);
// n_printf("# subdividing octnode %d\n",n);
// create new child-nodes
float x = (n->minCorner.x + n->maxCorner.x) * 0.5f;
float y = (n->minCorner.y + n->maxCorner.y) * 0.5f;
float z = (n->minCorner.z + n->maxCorner.z) * 0.5f;
int i;
for (i=0; i<8; i++) {
float x0,x1,y0,y1,z0,z1;
if (i & 1) { x0=n->minCorner.x; x1=x; }
else { x0=x; x1=n->maxCorner.x; }
if (i & 2) { y0=n->minCorner.y; y1=y; }
else { y0=y; y1=n->maxCorner.y; }
if (i & 4) { z0=n->minCorner.z; z1=z; }
else { z0=z; z1=n->maxCorner.z; }
n->c[i] = this->alloc_node(n,x0,x1,y0,y1,z0,z1);
}
// distribute elements to new childnodes
nOctElement *oe = (nOctElement *) n->elm_list.GetHead();
nOctElement *next_oe = NULL;
if (oe) do {
next_oe = (nOctElement *) oe->GetSucc();
int j;
for (j=0; j<8; j++) {
// If element entirely fits into child node,
// move it to the child node
if (this->elm_inside_node(oe,n->c[j])) {
n->RemoveElement(oe);
n->c[j]->AddElm(oe);
break;
}
}
} while ((oe = next_oe));
}
//-------------------------------------------------------------------
/**
Merges all child-nodes recursively into the specified node.
Any elements contained in the child nodes are moved up
into node.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::collapse(nOctNode *n)
{
// n_printf("# collapsing octnode %d\n",n);
// Abort recursion if no childs found
if (n->c[0]) {
// for each child...
int i;
for (i=0; i<8; i++) {
// First, collapse() the childs (recursion)
this->collapse(n->c[i]);
// Overtake all elements from the child nodes
nOctElement *oe;
while ((oe = (nOctElement *) n->c[i]->elm_list.GetHead())) {
n->c[i]->RemoveElement(oe);
n->AddElm(oe);
}
// destroy child
this->freenode(n->c[i]);
n->c[i] = NULL;
}
}
}
//-------------------------------------------------------------------
/**
Starting at the specified nOctNode, searches the first node
towards the root which is able to entirely contain the
nOctElement.
Will return NULL if the element doesn't even fit in the
root node!
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
nOctNode *nOctree::find_node_upward(nOctNode *n, nOctElement *oe)
{
while (n && (!this->elm_inside_node(oe,n))) n = n->parent;
return n;
}
//-------------------------------------------------------------------
/**
Beginning at the specified nOctNode, looks for the smallest
child that still is able to entirely contain the nOctElement.
Search takes place until the current node doesn't contain
any children anymore or none that could entirely contain the
nOctElement
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
nOctNode *nOctree::find_node_downward(nOctNode *n, nOctElement *oe)
{
// outer loop: abort if no children
while (n->c[0]) {
int i;
for (i=0; i<8; i++) {
// If element entirely fits into current child-node,
// go down into the node
if (this->elm_inside_node(oe,n->c[i])) {
n = n->c[i];
break;
}
}
// If we reach this point, then, althought there
// are children, none of them is big enough to contain
// the nOctElement
if (i==8) break;
}
return n;
}
//-------------------------------------------------------------------
/**
Adds a new element into the tree by searching downwards
for the first node entirely covering the element and
linking it into the node.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::insert_element(nOctElement *oe)
{
n_assert(NULL == oe->octnode);
nOctNode *on = this->find_node_downward(this->tree_root,oe);
// n_printf("# adding elm %d to octnode %d\n",oe,on);
on->AddElm(oe);
}
//-------------------------------------------------------------------
/**
Ensured that the nOctElement is located at the right position
in the tree. The element has to be in the tree already.
First, does a find_node_upward() and from there, in general,
a find_node_downward().
If the resulting node doesn't match the current node of
the element, the element is moved from its current node
into the new node.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::move_element(nOctElement *oe)
{
n_assert(oe->octnode);
nOctNode *on = oe->octnode;
// Search for the first node towards root which
// is able to entirely contain the element...
on = this->find_node_upward(on,oe);
// from the, search downward again...
if (!on) on = this->tree_root;
on = this->find_node_downward(on,oe);
// 'on' ist now guaranteed to be the correct node.
// Now look if the element has to be noved...
if (on != oe->octnode) {
// it is... Move element from its current into the new node
// n_printf("# moving elm %d from octnode %d to octnode %d\n",oe,oe->octnode,on);
oe->octnode->RemoveElement(oe);
on->AddElm(oe);
}
}
//-------------------------------------------------------------------
/**
Rebalances the node and all of its child nodes:
- if the node has child nodes and the total number of
elements in the node is smaller then the threshold,
it is collapsed with all of its subnodes
- else, if it is a leaf node and the number of elements
is larger then the threshold, the node gets subdivided
- finally, balance() is recursively called on each child node
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::balance(nOctNode *on)
{
if ((NULL != on->c[0]) && (on->all_num_elms <= this->subdiv_num)) {
// collapse all child nodes
this->collapse(on);
} else if ((NULL == on->c[0]) && (on->num_elms > this->subdiv_num)) {
// to many elements in leaf node -> subdivide
this->subdivide(on);
}
// balance() recursively on all children
if (on->c[0]) {
int i;
for (i=0; i<8; i++) this->balance(on->c[i]);
}
}
//-------------------------------------------------------------------
/**
@brief Add a new empty element to the tree, which is initialized
with position (0,0,0) and radius (N_OCT_MAXRADIUS).
Until this is initialized with actual values by nOctree::UpdateElement(),
this node will live in the root node of the nOctree.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::AddElement(nOctElement *oe)
{
n_assert(NULL == oe->octnode);
vector3 null;
oe->Set(null,N_OCT_MAXRADIUS);
this->insert_element(oe);
}
//-------------------------------------------------------------------
/**
@brief Removes an element from the tree.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::RemoveElement(nOctElement *oe)
{
n_assert(oe->octnode);
oe->octnode->RemoveElement(oe);
}
//-------------------------------------------------------------------
/**
@brief Update position and/or radius of an item.
The item is sorted into the tree, however the tree should
be balanced again prior to executing another CollectX(), so that
the collection process to some extent brings optimal results.
- 31-May-99 floh created
- 04-Jun-99 floh Radius 0.0 wird jetzt auf MaxRadius gesetzt
*/
//-------------------------------------------------------------------
void nOctree::UpdateElement(nOctElement *oe, const vector3& p, float r)
{
n_assert(oe->octnode);
if (r <= 0.0f) r=N_OCT_MAXRADIUS;
oe->Set(p,r);
this->move_element(oe);
}
//-------------------------------------------------------------------
/**
@brief Update position and the bounding-box of an item.
Sets the boundingbox of an object directly rather than using the
radius. Overlapping of objects is minimized to a certain amount.
Since we have a fast sphere-vs-sphere test in the sphere culler
we still supply the radius for the element.
The item is sorted into the tree, however the tree should
be balanced again prior to executing another CollectX(), so that
the collection process to some extent brings optimal results.
- 14-May-04 child created
*/
//-------------------------------------------------------------------
void nOctree::UpdateElement(nOctElement *oe, const vector3& p, const bbox3& box)
{
n_assert(oe->octnode);
const vector3& extents = box.extents();
float rad = n_max( extents.y, n_max( extents.x, extents.z ) );
if (rad <= 0.0f) rad=N_OCT_MAXRADIUS;
oe->Set(p,rad,box.vmin,box.vmax);
this->move_element(oe);
}
//-------------------------------------------------------------------
/**
@brief Balances the tree.
This should always be run directly before a collection is made,
so that the collection process runs in optimal time and the
smallest possible set is returned.
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::BalanceTree(void)
{
n_assert(this->tree_root);
this->balance(this->tree_root);
}
//-------------------------------------------------------------------
/**
Visualizes a node. For each nOctNode a green cube is drawn.
All elements in the node are drawn as red boxes which are
connected to the center of the node with an orange line.
After that, recursively visualizes all of its children
- 31-May-99 floh created
*/
//-------------------------------------------------------------------
void nOctree::visualize_node(nOctNode *on)
{
// nOctNode as green cube
const vector3 nodeCenter( ( on->maxCorner + on->minCorner ) / 2.0f );
matrix44 m;
m.scale( on->maxCorner - on->minCorner );
m.set_translation( nodeCenter );
nGfxServer2::Instance()->DrawShape( nGfxServer2::Box, m, vector4( 0, 1.0f, 0, 0.2f ) );
// Draw each element...
const vector4 red( 1.0f, 0, 0, 0.4f );
//const vector4 orange( 0.7f, 0.7f, 0, 1.0f );
nOctElement *oe;
for (oe = (nOctElement *) on->elm_list.GetHead();
oe;
oe = (nOctElement *) oe->GetSucc())
{
vector3 elementCenter( ( oe->maxCorner + oe->minCorner ) / 2.0f );
m.ident();
m.scale( oe->maxCorner - oe->minCorner );
m.set_translation( elementCenter );
nGfxServer2::Instance()->DrawShape( nGfxServer2::Box, m, red );
// Line to the node's center
//vector3 lineToCenter[] = { elementCenter, nodeCenter };
//nGfxServer2::Instance()->DrawLines3d( lineToCenter, 2, orange );
}
// and recurse all children
if (on->c[0])
{
int i;
for (i=0; i<8; i++) this->visualize_node(on->c[i]);
}
}
//-------------------------------------------------------------------
/**
@brief Render a visualization of the nOctree.
The nOctNodes are drawn in green, with their nOctElements as red
squares, which point with oranges lines to the center of the nOctNode,
in which they're situated.
- 31-May-99 floh created
- 06-Jul-99 floh stellt jetzt Renderstates etc. selbst ein
*/
//-------------------------------------------------------------------
void nOctree::Visualize()
{
if (this->visualize)
{
n_assert(this->tree_root);
nGfxServer2::Instance()->SetTransform(nGfxServer2::Model, matrix44());
nGfxServer2::Instance()->BeginShapes();
this->visualize_node(this->tree_root);
nGfxServer2::Instance()->EndShapes();
}
}
//-------------------------------------------------------------------
// EOF
//-------------------------------------------------------------------
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
571
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.