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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ab19d29e0695a015369fa474d0bc61f04245a29b | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/pcsx2/IopDma.cpp | 739e40f05d7e40360208dd107e8edef6ef8cce10 | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,071 | cpp | /* PCSX2 - PS2 Emulator for PCs
* Copyright (C) 2002-2010 PCSX2 Dev Team
*
* PCSX2 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* PCSX2 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 PCSX2.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "PrecompiledHeader.h"
#include "IopCommon.h"
#include "Sif.h"
using namespace R3000A;
// Dma0/1 in Mdec.c
// Dma3 in CdRom.c
// Dma8 in PsxSpd.c
// Dma11/12 in PsxSio2.c
#ifndef ENABLE_NEW_IOPDMA_SPU2
static void __fastcall psxDmaGeneric(u32 madr, u32 bcr, u32 chcr, u32 spuCore, _SPU2writeDMA4Mem spu2WriteFunc, _SPU2readDMA4Mem spu2ReadFunc)
{
const char dmaNum = spuCore ? '7' : '4';
/*if (chcr & 0x400) DevCon.Status("SPU 2 DMA %c linked list chain mode! chcr = %x madr = %x bcr = %x\n", dmaNum, chcr, madr, bcr);
if (chcr & 0x40000000) DevCon.Warning("SPU 2 DMA %c Unusual bit set on 'to' direction chcr = %x madr = %x bcr = %x\n", dmaNum, chcr, madr, bcr);
if ((chcr & 0x1) == 0) DevCon.Status("SPU 2 DMA %c loading from spu2 memory chcr = %x madr = %x bcr = %x\n", dmaNum, chcr, madr, bcr);*/
const int size = (bcr >> 16) * (bcr & 0xFFFF);
// Update the spu2 to the current cycle before initiating the DMA
if (SPU2async)
{
SPU2async(psxRegs.cycle - psxCounters[6].sCycleT);
//Console.Status("cycles sent to SPU2 %x\n", psxRegs.cycle - psxCounters[6].sCycleT);
psxCounters[6].sCycleT = psxRegs.cycle;
psxCounters[6].CycleT = size * 3;
psxNextCounter -= (psxRegs.cycle - psxNextsCounter);
psxNextsCounter = psxRegs.cycle;
if (psxCounters[6].CycleT < psxNextCounter)
psxNextCounter = psxCounters[6].CycleT;
if((g_iopNextEventCycle - psxNextsCounter) > (u32)psxNextCounter)
{
//DevCon.Warning("SPU2async Setting new counter branch, old %x new %x ((%x - %x = %x) > %x delta)", g_iopNextEventCycle, psxNextsCounter + psxNextCounter, g_iopNextEventCycle, psxNextsCounter, (g_iopNextEventCycle - psxNextsCounter), psxNextCounter);
g_iopNextEventCycle = psxNextsCounter + psxNextCounter;
}
}
switch (chcr)
{
case 0x01000201: //cpu to spu2 transfer
PSXDMA_LOG("*** DMA %c - mem2spu *** %x addr = %x size = %x", dmaNum, chcr, madr, bcr);
spu2WriteFunc((u16 *)iopPhysMem(madr), size*2);
break;
case 0x01000200: //spu2 to cpu transfer
PSXDMA_LOG("*** DMA %c - spu2mem *** %x addr = %x size = %x", dmaNum, chcr, madr, bcr);
spu2ReadFunc((u16 *)iopPhysMem(madr), size*2);
psxCpu->Clear(spuCore ? HW_DMA7_MADR : HW_DMA4_MADR, size);
break;
default:
Console.Error("*** DMA %c - SPU unknown *** %x addr = %x size = %x", dmaNum, chcr, madr, bcr);
break;
}
}
void psxDma4(u32 madr, u32 bcr, u32 chcr) // SPU2's Core 0
{
psxDmaGeneric(madr, bcr, chcr, 0, SPU2writeDMA4Mem, SPU2readDMA4Mem);
}
int psxDma4Interrupt()
{
#ifdef SPU2IRQTEST
Console.Warning("psxDma4Interrupt()");
#endif
HW_DMA4_CHCR &= ~0x01000000;
psxDmaInterrupt(4);
iopIntcIrq(9);
return 1;
}
void spu2DMA4Irq()
{
#ifdef SPU2IRQTEST
Console.Warning("spu2DMA4Irq()");
#endif
SPU2interruptDMA4();
HW_DMA4_CHCR &= ~0x01000000;
psxDmaInterrupt(4);
}
void psxDma7(u32 madr, u32 bcr, u32 chcr) // SPU2's Core 1
{
psxDmaGeneric(madr, bcr, chcr, 1, SPU2writeDMA7Mem, SPU2readDMA7Mem);
}
int psxDma7Interrupt()
{
#ifdef SPU2IRQTEST
Console.Warning("psxDma7Interrupt()");
#endif
HW_DMA7_CHCR &= ~0x01000000;
psxDmaInterrupt2(0);
return 1;
}
void spu2DMA7Irq()
{
#ifdef SPU2IRQTEST
Console.Warning("spu2DMA7Irq()");
#endif
SPU2interruptDMA7();
HW_DMA7_CHCR &= ~0x01000000;
psxDmaInterrupt2(0);
}
#endif
#ifndef DISABLE_PSX_GPU_DMAS
void psxDma2(u32 madr, u32 bcr, u32 chcr) // GPU
{
HW_DMA2_CHCR &= ~0x01000000;
psxDmaInterrupt(2);
}
void psxDma6(u32 madr, u32 bcr, u32 chcr)
{
u32 *mem = (u32 *)iopPhysMem(madr);
PSXDMA_LOG("*** DMA 6 - OT *** %lx addr = %lx size = %lx", chcr, madr, bcr);
if (chcr == 0x11000002)
{
while (bcr--)
{
*mem-- = (madr - 4) & 0xffffff;
madr -= 4;
}
mem++;
*mem = 0xffffff;
}
else
{
// Unknown option
PSXDMA_LOG("*** DMA 6 - OT unknown *** %lx addr = %lx size = %lx", chcr, madr, bcr);
}
HW_DMA6_CHCR &= ~0x01000000;
psxDmaInterrupt(6);
}
#endif
#ifndef ENABLE_NEW_IOPDMA_DEV9
void psxDma8(u32 madr, u32 bcr, u32 chcr)
{
const int size = (bcr >> 16) * (bcr & 0xFFFF) * 8;
switch (chcr & 0x01000201)
{
case 0x01000201: //cpu to dev9 transfer
PSXDMA_LOG("*** DMA 8 - DEV9 mem2dev9 *** %lx addr = %lx size = %lx", chcr, madr, bcr);
DEV9writeDMA8Mem((u32*)iopPhysMem(madr), size);
break;
case 0x01000200: //dev9 to cpu transfer
PSXDMA_LOG("*** DMA 8 - DEV9 dev9mem *** %lx addr = %lx size = %lx", chcr, madr, bcr);
DEV9readDMA8Mem((u32*)iopPhysMem(madr), size);
break;
default:
PSXDMA_LOG("*** DMA 8 - DEV9 unknown *** %lx addr = %lx size = %lx", chcr, madr, bcr);
break;
}
HW_DMA8_CHCR &= ~0x01000000;
psxDmaInterrupt2(1);
}
#endif
void psxDma9(u32 madr, u32 bcr, u32 chcr)
{
SIF_LOG("IOP: dmaSIF0 chcr = %lx, madr = %lx, bcr = %lx, tadr = %lx", chcr, madr, bcr, HW_DMA9_TADR);
sif0.iop.busy = true;
psHu32(SBUS_F240) |= 0x2000;
/*if (sif0.ee.busy)
{*/
SIF0Dma();
psHu32(SBUS_F240) &= ~0x20;
psHu32(SBUS_F240) &= ~0x2000;
//}
}
void psxDma10(u32 madr, u32 bcr, u32 chcr)
{
SIF_LOG("IOP: dmaSIF1 chcr = %lx, madr = %lx, bcr = %lx", chcr, madr, bcr);
sif1.iop.busy = true;
psHu32(SBUS_F240) |= 0x4000;
/*if (sif1.ee.busy)
{*/
SIF1Dma();
psHu32(SBUS_F240) &= ~0x40;
psHu32(SBUS_F240) &= ~0x100;
psHu32(SBUS_F240) &= ~0x4000;
//}
}
/* psxDma11 & psxDma 12 are in IopSio2.cpp, along with the appropriate interrupt functions. */
//////////////////////////////////////////////////////////////////////////////////////////////
//
// Gigaherz's "Improved DMA Handling" Engine WIP...
//
#ifdef ENABLE_NEW_IOPDMA
//////////////////////////////////////////////////////////////////////////////////////////////
// Local Declarations
// in IopSio2.cpp
extern s32 CALLBACK sio2DmaStart(s32 channel, u32 madr, u32 bcr, u32 chcr);
extern s32 CALLBACK sio2DmaRead(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed);
extern s32 CALLBACK sio2DmaWrite(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed);
extern void CALLBACK sio2DmaInterrupt(s32 channel);
// implemented below
s32 CALLBACK errDmaWrite(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed);
s32 CALLBACK errDmaRead(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed);
// pointer types
typedef s32 (CALLBACK * DmaHandler)(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed);
typedef void (CALLBACK * DmaIHandler)(s32 channel);
typedef s32 (CALLBACK * DmaSHandler)(s32 channel, u32 madr, u32 bcr, u32 chcr);
// constants
struct DmaHandlerInfo
{
const char* Name;
// doubles as a "disable" flag
u32 DirectionFlags;
u32 DmacRegisterBase;
DmaHandler Read;
DmaHandler Write;
DmaIHandler Interrupt;
DmaSHandler Start;
__fi u32& REG_MADR(void) const { return psxHu32(DmacRegisterBase + 0x0); }
__fi u32& REG_BCR(void) const { return psxHu32(DmacRegisterBase + 0x4); }
__fi u32& REG_CHCR(void) const { return psxHu32(DmacRegisterBase + 0x8); }
__fi u32& REG_TADR(void) const { return psxHu32(DmacRegisterBase + 0xC); }
};
#define MEM_BASE1 0x1f801080
#define MEM_BASE2 0x1f801500
#define CHANNEL_BASE1(ch) (MEM_BASE1 + ((ch)<<4))
#define CHANNEL_BASE2(ch) (MEM_BASE2 + ((ch)<<4))
// channel disabled
#define _D__ 0
#define _D_W 1
#define _DR_ 2
#define _DRW 3
// channel enabled
#define _E__ 4
#define _E_W 5
#define _ER_ 6
#define _ERW 7
//////////////////////////////////////////////////////////////////////////////////////////////
// Plugin interface accessors
#ifdef ENABLE_NEW_IOPDMA_SPU2
s32 CALLBACK spu2DmaRead (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { return SPU2dmaRead(channel,data,bytesLeft,bytesProcessed); }
s32 CALLBACK spu2DmaWrite (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { return SPU2dmaWrite(channel,data,bytesLeft,bytesProcessed); }
void CALLBACK spu2DmaInterrupt (s32 channel) { SPU2dmaInterrupt(channel); }
#else
s32 CALLBACK spu2DmaRead (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { *bytesProcessed=0; return 0; }
s32 CALLBACK spu2DmaWrite (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { *bytesProcessed=0; return 0; }
void CALLBACK spu2DmaInterrupt (s32 channel) { }
#endif
#ifdef ENABLE_NEW_IOPDMA_DEV9
s32 CALLBACK dev9DmaRead (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { return DEV9dmaRead(channel,data,bytesLeft,bytesProcessed); }
s32 CALLBACK dev9DmaWrite (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { return DEV9dmaWrite(channel,data,bytesLeft,bytesProcessed); }
void CALLBACK dev9DmaInterrupt (s32 channel) { DEV9dmaInterrupt(channel); }
#else
s32 CALLBACK dev9DmaRead (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { *bytesProcessed=0; return 0; }
s32 CALLBACK dev9DmaWrite (s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed) { *bytesProcessed=0; return 0; }
void CALLBACK dev9DmaInterrupt (s32 channel) { }
#endif
//////////////////////////////////////////////////////////////////////////////////////////////
// Dma channel definitions
const DmaHandlerInfo IopDmaHandlers[DMA_CHANNEL_MAX] =
{
// First DMAC, same as PS1
{"Ps1 Mdec in", _D__}, //0
{"Ps1 Mdec out", _D__}, //1
{"Ps1 Gpu", _D__}, //2
#ifdef ENABLE_NEW_IOPDMA_CDVD
{"CDVD", _ER_, CHANNEL_BASE1(3), cdvdDmaRead, errDmaWrite, cdvdDmaInterrupt}, //3: CDVD
#else
{"CDVD", _D__}, //3: CDVD
#endif
#ifdef ENABLE_NEW_IOPDMA_SPU2
{"SPU2 Core0", _ERW, CHANNEL_BASE1(4), spu2DmaRead, spu2DmaWrite, spu2DmaInterrupt}, //4: Spu/Spu2 Core0
#else
{"SPU2 Core0", _D__}, //4: Spu/Spu2 Core0
#endif
{"Ps1 PIO", _D__}, //5: PIO
{"Ps1 OTC", _D__}, //6: "reverse clear OT" - PSX GPU related
// Second DMAC, new in PS2 IOP
#ifdef ENABLE_NEW_IOPDMA_SPU2
{"SPU2 Core1", _ERW, CHANNEL_BASE2(0), spu2DmaRead, spu2DmaWrite, spu2DmaInterrupt}, //7: Spu2 Core1
#else
{"SPU2 Core1", _D__}, //7: Spu2 Core1
#endif
#ifdef ENABLE_NEW_IOPDMA_DEV9
{"Dev9", _ERW, CHANNEL_BASE2(1), dev9DmaRead, dev9DmaWrite, dev9DmaInterrupt}, //8: Dev9
#else
{"Dev9", _D__}, //8: Dev9
#endif
#ifdef ENABLE_NEW_IOPDMA_SIF
{"Sif0", _ERW, CHANNEL_BASE2(2), sif0DmaRead, sif0DmaWrite, sif0DmaInterrupt}, //9: SIF0
{"Sif1", _ERW, CHANNEL_BASE2(3), sif1DmaRead, sif1DmaWrite, sif1DmaInterrupt}, //10: SIF1
#else
{"Sif0", _D__}, //9: SIF0
{"Sif1", _D__}, //10: SIF1
#endif
#ifdef ENABLE_NEW_IOPDMA_SIO
{"Sio2 (writes)", _E_W, CHANNEL_BASE2(4), errDmaRead, sio2DmaWrite, sio2DmaInterrupt, sio2DmaStart}, //11: Sio2
{"Sio2 (reads)", _ER_, CHANNEL_BASE2(5), sio2DmaRead, errDmaWrite, sio2DmaInterrupt, sio2DmaStart}, //12: Sio2
#else
{"Sio2 (writes)", _D__}, //11: Sio2
{"Sio2 (reads)", _D__}, //12: Sio2
#endif
{"?", _D__}, //13
// if each dmac has 7 channels, the list would end here, but I'm not sure :p
};
// runtime variables
struct DmaChannelInfo
{
s32 ByteCount;
s32 NextUpdate;
} IopDmaChannels[DMA_CHANNEL_MAX] = {0};
//////////////////////////////////////////////////////////////////////////////////////////////
// Tool functions
void SetDmaUpdateTarget(u32 delay)
{
psxCounters[8].CycleT = delay;
if (delay < psxNextCounter)
psxNextCounter = delay;
}
void RaiseDmaIrq(u32 channel)
{
if(channel<7)
psxDmaInterrupt(channel);
else
psxDmaInterrupt2(channel-7);
}
//////////////////////////////////////////////////////////////////////////////////////////////
// IopDmaStart: Called from IopHwWrite to test and possibly start a dma transfer
void IopDmaStart(int channel)
{
if(!(IopDmaHandlers[channel].DirectionFlags&_E__))
return;
int chcr = IopDmaHandlers[channel].REG_CHCR();
int pcr = (channel>=7)?(HW_DMA_PCR2 & (8 << ((channel-7) * 4))):(HW_DMA_PCR & (8 << (channel * 4)));
if ( !(chcr & 0x01000000) || !pcr)
return;
// I dont' really understand this, but it's used above. Is this BYTES OR WHAT?
int bcr = IopDmaHandlers[channel].REG_BCR();
int bcr_size = (bcr & 0xFFFF);
int bcr_count = (bcr >> 16);
int size = 4* bcr_count * bcr_size;
int dirf = IopDmaHandlers[channel].DirectionFlags&3;
if(dirf != 3)
{
bool ok = (chcr & DMA_CTRL_DIRECTION)? (dirf==_D_W) : (dirf==_DR_);
if(!ok)
{
// hack?!
IopDmaHandlers[channel].REG_CHCR() &= ~DMA_CTRL_ACTIVE;
return;
}
}
if(IopDmaHandlers[channel].Start)
{
int ret = IopDmaHandlers[channel].Start(channel,
IopDmaHandlers[channel].REG_MADR(),
IopDmaHandlers[channel].REG_BCR(),
IopDmaHandlers[channel].REG_CHCR());
if(ret < 0)
{
IopDmaHandlers[channel].REG_CHCR() &= ~DMA_CTRL_ACTIVE;
return;
}
}
//Console.WriteLn(Color_StrongOrange,"Starting NewDMA ch=%d, size=%d(0x%08x), dir=%d", channel, size, bcr, chcr&DMA_CTRL_DIRECTION);
IopDmaHandlers[channel].REG_CHCR() |= DMA_CTRL_ACTIVE;
IopDmaChannels[channel].ByteCount = size;
IopDmaChannels[channel].NextUpdate = 0;
//SetDmaUpdateTarget(1);
{
const s32 difference = psxRegs.cycle - psxCounters[8].sCycleT;
psxCounters[8].sCycleT = psxRegs.cycle;
psxCounters[8].CycleT = psxCounters[8].rate;
IopDmaUpdate(difference);
s32 c = psxCounters[8].CycleT;
if (c < psxNextCounter) psxNextCounter = c;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// IopDmaProcessChannel: Called from IopDmaUpdate (below) to process a dma channel
template<int channel>
static void __ri IopDmaProcessChannel(int elapsed, int& MinDelay)
{
// Hopefully the compiler would be able to optimize the whole function away if this doesn't pass.
if(!(IopDmaHandlers[channel].DirectionFlags&_E__))
return;
DmaChannelInfo *ch = IopDmaChannels + channel;
const DmaHandlerInfo *hh = IopDmaHandlers + channel;
if (hh->REG_CHCR()&DMA_CTRL_ACTIVE)
{
ch->NextUpdate -= elapsed;
if (ch->NextUpdate <= 0) // Refresh target passed
{
if (ch->ByteCount <= 0) // No more data left, finish dma
{
ch->NextUpdate = 0x7fffffff;
hh->REG_CHCR() &= ~DMA_CTRL_ACTIVE;
RaiseDmaIrq(channel);
hh->Interrupt(channel);
}
else // let the handlers transfer more data
{
int chcr = hh->REG_CHCR();
DmaHandler handler = (chcr & DMA_CTRL_DIRECTION) ? hh->Write : hh->Read;
u32 ProcessedBytes = 0;
s32 RequestedDelay = (handler) ? handler(channel, (u32*)iopPhysMem(hh->REG_MADR()), ch->ByteCount, &ProcessedBytes) : 0;
if(ProcessedBytes>0 && (!(chcr & DMA_CTRL_DIRECTION)))
{
psxCpu->Clear(hh->REG_MADR(), ProcessedBytes/4);
}
int NextUpdateDelay = 100;
if (RequestedDelay < 0) // error code
{
// TODO: ... What to do if the handler gives an error code? :P
DevCon.Warning("ERROR on channel %d",channel);
hh->REG_CHCR() &= ~DMA_CTRL_ACTIVE;
RaiseDmaIrq(channel);
hh->Interrupt(channel);
}
else if (ProcessedBytes > 0) // if not an error, continue transfer
{
//DevCon.WriteLn("Transfer channel %d, ProcessedBytes = %d",i,ProcessedBytes);
hh->REG_MADR()+= ProcessedBytes;
ch->ByteCount -= ProcessedBytes;
NextUpdateDelay = ProcessedBytes/2; // / ch->Width;
}
else if(RequestedDelay==0)
DevCon.Warning("What now? :p"); // its ok as long as there's a delay requeste, autodma requires this.
if (RequestedDelay != 0) NextUpdateDelay = RequestedDelay;
// SPU2 adma early interrupts. PCSX2 likes those better currently.
if((channel==4 || channel==7) && (ch->ByteCount<=0) && (ProcessedBytes <= 1024))
{
ch->NextUpdate = 0;
}
else
ch->NextUpdate += NextUpdateDelay;
//ch->NextUpdate += NextUpdateDelay;
}
}
int nTarget = ch->NextUpdate;
if(nTarget < 0) nTarget = 0;
if (nTarget<MinDelay)
MinDelay = nTarget;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// IopDmaProcessChannel: Called regularly to update the active channels
void IopDmaUpdate(u32 elapsed)
{
s32 MinDelay=0;
do {
MinDelay = 0x7FFFFFFF; // max possible value
// Unrolled
//IopDmaProcessChannel<0>(elapsed, MinDelay);
//IopDmaProcessChannel<1>(elapsed, MinDelay);
//IopDmaProcessChannel<2>(elapsed, MinDelay);
IopDmaProcessChannel<3>(elapsed, MinDelay);
IopDmaProcessChannel<4>(elapsed, MinDelay);
//IopDmaProcessChannel<5>(elapsed, MinDelay);
//IopDmaProcessChannel<6>(elapsed, MinDelay);
IopDmaProcessChannel<7>(elapsed, MinDelay);
IopDmaProcessChannel<8>(elapsed, MinDelay);
IopDmaProcessChannel<9>(elapsed, MinDelay);
IopDmaProcessChannel<10>(elapsed, MinDelay);
IopDmaProcessChannel<11>(elapsed, MinDelay);
IopDmaProcessChannel<12>(elapsed, MinDelay);
//IopDmaProcessChannel<13>(elapsed, MinDelay);
// reset elapsed time in case we loop
elapsed=0;
}
while(MinDelay <= 0);
if(MinDelay<0x7FFFFFFF)
{
// tell the iop when to call this function again
SetDmaUpdateTarget(MinDelay);
}
else
{
// bogus value so the function gets called again, not sure if it's necessary anymore
SetDmaUpdateTarget(10000);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Error functions: dummy functions for unsupported dma "directions"
s32 CALLBACK errDmaRead(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed)
{
Console.Error("ERROR: Tried to read using DMA %d (%s). Ignoring.", channel, IopDmaHandlers[channel]);
*bytesProcessed = bytesLeft;
return 0;
}
s32 CALLBACK errDmaWrite(s32 channel, u32* data, u32 bytesLeft, u32* bytesProcessed)
{
Console.Error("ERROR: Tried to write using DMA %d (%s). Ignoring.", channel, IopDmaHandlers[channel]);
*bytesProcessed = bytesLeft;
return 0;
}
void SaveStateBase::iopDmacFreeze()
{
FreezeTag("iopDmac");
Freeze(IopDmaChannels);
if( IsLoading() )
{
SetDmaUpdateTarget(10000); // Might be needed to kickstart the main updater :p
}
}
#endif
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
607
]
]
]
|
b1746aa9779dbc8ca274576e90db6015249e5d2b | 516b78edbad95d6fb76b6a51c5353eaeb81b56d6 | /engine2/src/util/glhelper/Texture.cpp | de7facd7f137172e92def0ed5319c36d5afca394 | []
| no_license | BackupTheBerlios/lutaprakct | 73d9fb2898e0a1a019d8ea7870774dd68778793e | fee62fa093fa560e51a26598619b97926ea9cb6b | refs/heads/master | 2021-01-18T14:05:20.313781 | 2008-06-16T21:51:13 | 2008-06-16T21:51:13 | 40,252,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,637 | cpp |
#include "Texture.h"
#include "glextensions.h"
#include <cstdlib>
#include <iostream>
//#include <SDL/SDL.h>
Texture::~Texture(){
if (img)
delete img;
}
Texture::Texture(std::string& filename, int target, int format, int internalformat, int flags) : img(NULL), flags(flags){
img = NULL;
load(filename, target, format, internalformat, flags);
}
void Texture::enable(){
glEnable(target);
}
void Texture::disable(){
glDisable(target);
}
void Texture::unbind(){
glDisable(target);
glActiveTextureARB(GL_TEXTURE0_ARB);
glBindTexture(target, 0);
}
void Texture::bind(int slot ){
glActiveTextureARB(GL_TEXTURE0_ARB + slot);
glEnable(target);
GLfloat parm;
glGetTexParameterfv(target, GL_TEXTURE_WRAP_S, &parm);
if (flags & CLAMP){
if (parm != GL_CLAMP){
glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_CLAMP);
glTexParameteri(target,GL_TEXTURE_WRAP_R,GL_CLAMP);
}
}
else if (flags & CLAMP_TO_EDGE) {
if (parm != GL_CLAMP_TO_EDGE){
glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE);
glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE);
glTexParameteri(target,GL_TEXTURE_WRAP_R,GL_CLAMP_TO_EDGE);
}
}
else {
glTexParameteri(target,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(target,GL_TEXTURE_WRAP_T,GL_REPEAT);
glTexParameteri(target,GL_TEXTURE_WRAP_R,GL_REPEAT);
}
glBindTexture(target, id);
}
void Texture::unload(){
glDeleteTextures(1, &id);
}
bool Texture::load(std::string& filename, int target, int format, int internalformat, int flags){
this->flags = flags;
this->target = target;
//primeiro verifica o formato. se tiver compressao o formato interno deve ser outro
//se nao tiver compressao recebe o formato interno passado
if ( format == RGB ){
this->format = GL_RGB;
if (flags &COMPRESSION_ARB)
this->internalformat = GL_COMPRESSED_RGB_ARB;
else if (flags &COMPRESSION_DXT1) //RGB so aceita DXT1
this->internalformat = COMPRESSED_RGB_S3TC_DXT1_EXT;
else
this->internalformat = internalformat;
}
else if (format == RGBA) {
this->format = GL_RGBA;
if (flags &COMPRESSION_ARB)
this->internalformat = GL_COMPRESSED_RGBA_ARB;
else if (flags &COMPRESSION_DXT1)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT1_EXT;
else if (flags &COMPRESSION_DXT3)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT3_EXT;
else if (flags &COMPRESSION_DXT5)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT5_EXT;
else
this->internalformat = internalformat;
}
else if (format == BGR){
this->format = GL_BGR_EXT;
if (flags &COMPRESSION_ARB)
this->internalformat = GL_COMPRESSED_RGB_ARB;
else if (flags &COMPRESSION_DXT1) //RGB so aceita DXT1
this->internalformat = COMPRESSED_RGB_S3TC_DXT1_EXT;
else
this->internalformat = internalformat;
}
else if (format == BGRA){
this->format = GL_BGRA_EXT;
if (flags &COMPRESSION_ARB)
this->internalformat = GL_COMPRESSED_RGBA_ARB;
else if (flags &COMPRESSION_DXT1)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT1_EXT;
else if (flags &COMPRESSION_DXT3)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT3_EXT;
else if (flags &COMPRESSION_DXT5)
this->internalformat = COMPRESSED_RGBA_S3TC_DXT5_EXT;
else
this->internalformat = internalformat;
}else {
this->format = format;
this->internalformat = internalformat;
}
glEnable(this->target);
glGenTextures(1, &id);
glBindTexture(this->target, id);
//verifica algusn flags
if (flags & CLAMP){
glTexParameteri(this->target, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(this->target, GL_TEXTURE_WRAP_T, GL_CLAMP);
glTexParameteri(this->target, GL_TEXTURE_WRAP_R, GL_CLAMP);
}
else if (flags & CLAMP_TO_EDGE) {
glTexParameteri(this->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(this->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(this->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
if (flags & NEAREST){
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
else if (flags & LINEAR) {
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
else if (flags & NEAREST_MIPMAP_NEAREST) {
if ( flags &MIPMAP_SGI)
glTexParameteri(this->target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
}
else if (flags & NEAREST_MIPMAP_LINEAR) {
if ( flags &MIPMAP_SGI)
glTexParameteri(this->target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
}
else if (flags & LINEAR_MIPMAP_NEAREST) {
if ( flags &MIPMAP_SGI)
glTexParameteri(this->target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
}
else if (flags & LINEAR_MIPMAP_LINEAR ) {
if ( flags &MIPMAP_SGI)
glTexParameteri(this->target, GL_GENERATE_MIPMAP_SGIS, GL_TRUE);
glTexParameteri(this->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(this->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
if (flags & ANISOTROPIC_2 )
glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY_EXT, 2);
else if (flags & ANISOTROPIC_4)
glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY_EXT, 4);
else if (flags & ANISOTROPIC_8)
glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY_EXT, 8);
else if (flags & ANISOTROPIC_16)
glTexParameteri(this->target, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16);
if (target == TEXTURE_1D){
img->load(filename.c_str());
width = img->getWidth();
height = 0;
glTexImage1D(this->target, 0, this->internalformat, img->getWidth(), 0, this->format, GL_UNSIGNED_BYTE, img->imagedata);
}
else if ( (target == TEXTURE_2D) || (target == TEXTURE_RECTANGLE) || (target == TEXTURE_RECTANGLENV) ){
img->load(filename.c_str());
width = img->getWidth();
height = img->getHeight();
glTexImage2D(this->target, 0, this->internalformat, img->getWidth(), img->getHeight(), 0, this->format, GL_UNSIGNED_BYTE, img->imagedata);
}
//nao carregue cubemaps com png.
else if (target == TEXTURE_CUBEMAP) {
char buff[1024];
GLuint facetargets[] = {
GL_TEXTURE_CUBE_MAP_POSITIVE_X, GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
char *facenames[] = {"posx", "negx", "posy", "negy", "posz", "negz" };
for (int i = 0; i < 6; i++){
sprintf(buff, filename.c_str(), facenames[i]);
std::string s(buff);
img = NULL;
img->load(s.c_str());
if (!img)
std::cout << "nao achou img " << s << std::endl;
width = img->getWidth();
height = img->getHeight();
glTexImage2D(facetargets[i],0, this->internalformat, img->getWidth(), img->getHeight(), 0, this->format, GL_UNSIGNED_BYTE, img->imagedata);
if (img->imagedata){
delete img->imagedata;
img = NULL;
}
}
}
glDisable(target);
//depois libera a memoria deletando a img
if(img){
delete img;
img = NULL;
}
return id;
}
| [
"gha"
]
| [
[
[
1,
226
]
]
]
|
afbb8ba842ace73025341b579d7aeb0f082f52dd | d9a78f212155bb978f5ac27d30eb0489bca87c3f | /PB/src/PbRpc/GeneratedFiles/Release/moc_rpcconnection.cpp | 4d2f95f405eaa8b0b82a9741ecde9d15def62edc | []
| no_license | marchon/pokerbridge | 1ed4a6a521f8644dcd0b6ec66a1ac46879b8473c | 97d42ef318bf08f3bc0c0cb1d95bd31eb2a3a8a9 | refs/heads/master | 2021-01-10T07:15:26.496252 | 2010-05-17T20:01:29 | 2010-05-17T20:01:29 | 36,398,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,388 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'rpcconnection.h'
**
** Created: Sun 14. Mar 04:04:14 2010
** by: The Qt Meta Object Compiler version 61 (Qt 4.5.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stdafx.h"
#include "..\..\rpcconnection.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'rpcconnection.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 61
#error "This file was generated using the moc from 4.5.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_RpcConnection[] = {
// content:
2, // revision
0, // classname
0, 0, // classinfo
9, 12, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
// signals: signature, parameters, type, tag, flags
22, 15, 14, 14, 0x05,
66, 63, 14, 14, 0x05,
93, 63, 14, 14, 0x05,
// slots: signature, parameters, type, tag, flags
120, 14, 14, 14, 0x09,
139, 15, 14, 14, 0x0a,
180, 176, 14, 14, 0x2a,
205, 63, 14, 14, 0x0a,
229, 176, 14, 14, 0x0a,
265, 63, 14, 14, 0x0a,
0 // eod
};
static const char qt_meta_stringdata_RpcConnection[] = {
"RpcConnection\0\0map,ch\0"
"incomingMessage(QVariantMap,RpcChannel*)\0"
"ch\0channelOpened(RpcChannel*)\0"
"channelClosed(RpcChannel*)\0"
"unregisterSender()\0"
"sendMessage(QVariantMap,RpcChannel*)\0"
"map\0sendMessage(QVariantMap)\0"
"newChannel(RpcChannel*)\0"
"channelIncomingMessage(QVariantMap)\0"
"channelDisconnected(RpcChannel*)\0"
};
const QMetaObject RpcConnection::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_RpcConnection,
qt_meta_data_RpcConnection, 0 }
};
const QMetaObject *RpcConnection::metaObject() const
{
return &staticMetaObject;
}
void *RpcConnection::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_RpcConnection))
return static_cast<void*>(const_cast< RpcConnection*>(this));
return QObject::qt_metacast(_clname);
}
int RpcConnection::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
switch (_id) {
case 0: incomingMessage((*reinterpret_cast< QVariantMap(*)>(_a[1])),(*reinterpret_cast< RpcChannel*(*)>(_a[2]))); break;
case 1: channelOpened((*reinterpret_cast< RpcChannel*(*)>(_a[1]))); break;
case 2: channelClosed((*reinterpret_cast< RpcChannel*(*)>(_a[1]))); break;
case 3: unregisterSender(); break;
case 4: sendMessage((*reinterpret_cast< QVariantMap(*)>(_a[1])),(*reinterpret_cast< RpcChannel*(*)>(_a[2]))); break;
case 5: sendMessage((*reinterpret_cast< QVariantMap(*)>(_a[1]))); break;
case 6: newChannel((*reinterpret_cast< RpcChannel*(*)>(_a[1]))); break;
case 7: channelIncomingMessage((*reinterpret_cast< QVariantMap(*)>(_a[1]))); break;
case 8: channelDisconnected((*reinterpret_cast< RpcChannel*(*)>(_a[1]))); break;
default: ;
}
_id -= 9;
}
return _id;
}
// SIGNAL 0
void RpcConnection::incomingMessage(QVariantMap _t1, RpcChannel * _t2)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void RpcConnection::channelOpened(RpcChannel * _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void RpcConnection::channelClosed(RpcChannel * _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| [
"[email protected]"
]
| [
[
[
1,
122
]
]
]
|
e31c5ca32f9c8fbf2eb8394f3fde13912f8adc5f | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /libs/STLPort-4.0/stlport/old_hp/rope.h | f4fa7afab49c4a4b8dc0eaee73ba66cf7d2644a0 | [
"LicenseRef-scancode-stlport-4.5"
]
| permissive | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,306 | h | /*
* Copyright (c) 1996,1997
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef __SGI_STL_ROPE_H
#define __SGI_STL_ROPE_H
# ifndef __STL_OUTERMOST_HEADER_ID
# define __STL_OUTERMOST_HEADER_ID 0xa022
# include <stl/_prolog.h>
# endif
#include <stl/_rope.h>
#ifdef __STL_USE_NAMESPACES
# ifdef __STL_BROKEN_USING_DIRECTIVE
using namespace STLPORT;
# else
using STLPORT::char_producer;
using STLPORT::sequence_buffer;
using STLPORT::rope;
using STLPORT::crope;
using STLPORT::wrope;
# endif
#endif /* __STL_USE_NAMESPACES */
# if (__STL_OUTERMOST_HEADER_ID == 0xa022)
# include <stl/_epilog.h>
# undef __STL_OUTERMOST_HEADER_ID
# endif
#endif /* __SGI_STL_ROPE_H */
// Local Variables:
// mode:C++
// End:
| [
"[email protected]"
]
| [
[
[
1,
50
]
]
]
|
c0ff0cce5f918c89661f738d8f9c12e7986b444d | d6a28d9d845a20463704afe8ebe644a241dc1a46 | /examples/11.PerPixelLighting/main.cpp | 5b8a0f9ceb38348b95084435b515551cfeaab0bf | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-other-permissive",
"Zlib"
]
| permissive | marky0720/irrlicht-android | 6932058563bf4150cd7090d1dc09466132df5448 | 86512d871eeb55dfaae2d2bf327299348cc5202c | refs/heads/master | 2021-04-30T08:19:25.297407 | 2010-10-08T08:27:33 | 2010-10-08T08:27:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,329 | cpp | /** Example 011 Per-Pixel Lighting
This tutorial shows how to use one of the built in more complex materials in
irrlicht: Per pixel lighted surfaces using normal maps and parallax mapping. It
will also show how to use fog and moving particle systems. And don't panic: You
dont need any experience with shaders to use these materials in Irrlicht.
At first, we need to include all headers and do the stuff we always do, like in
nearly all other tutorials.
*/
#include <irrlicht.h>
#include "driverChoice.h"
using namespace irr;
#ifdef _MSC_VER
#pragma comment(lib, "Irrlicht.lib")
#endif
/*
For this example, we need an event receiver, to make it possible for the user
to switch between the three available material types. In addition, the event
receiver will create some small GUI window which displays what material is
currently being used. There is nothing special done in this class, so maybe you
want to skip reading it.
*/
class MyEventReceiver : public IEventReceiver
{
public:
MyEventReceiver(scene::ISceneNode* room,scene::ISceneNode* earth,
gui::IGUIEnvironment* env, video::IVideoDriver* driver)
{
// store pointer to room so we can change its drawing mode
Room = room;
Earth = earth;
Driver = driver;
// set a nicer font
gui::IGUISkin* skin = env->getSkin();
gui::IGUIFont* font = env->getFont("../../media/fonthaettenschweiler.bmp");
if (font)
skin->setFont(font);
// add window and listbox
gui::IGUIWindow* window = env->addWindow(
core::rect<s32>(460,375,630,470), false, L"Use 'E' + 'R' to change");
ListBox = env->addListBox(
core::rect<s32>(2,22,165,88), window);
ListBox->addItem(L"Diffuse");
ListBox->addItem(L"Bump mapping");
ListBox->addItem(L"Parallax mapping");
ListBox->setSelected(1);
// create problem text
ProblemText = env->addStaticText(
L"Your hardware or this renderer is not able to use the "\
L"needed shaders for this material. Using fall back materials.",
core::rect<s32>(150,20,470,80));
ProblemText->setOverrideColor(video::SColor(100,255,255,255));
// set start material (prefer parallax mapping if available)
video::IMaterialRenderer* renderer =
Driver->getMaterialRenderer(video::EMT_PARALLAX_MAP_SOLID);
if (renderer && renderer->getRenderCapability() == 0)
ListBox->setSelected(2);
// set the material which is selected in the listbox
setMaterial();
}
bool OnEvent(const SEvent& event)
{
// check if user presses the key 'E' or 'R'
if (event.EventType == irr::EET_KEY_INPUT_EVENT &&
!event.KeyInput.PressedDown && Room && ListBox)
{
// change selected item in listbox
int sel = ListBox->getSelected();
if (event.KeyInput.Key == irr::KEY_KEY_R)
++sel;
else
if (event.KeyInput.Key == irr::KEY_KEY_E)
--sel;
else
return false;
if (sel > 2) sel = 0;
if (sel < 0) sel = 2;
ListBox->setSelected(sel);
// set the material which is selected in the listbox
setMaterial();
}
return false;
}
private:
// sets the material of the room mesh the the one set in the
// list box.
void setMaterial()
{
video::E_MATERIAL_TYPE type = video::EMT_SOLID;
// change material setting
switch(ListBox->getSelected())
{
case 0: type = video::EMT_SOLID;
break;
case 1: type = video::EMT_NORMAL_MAP_SOLID;
break;
case 2: type = video::EMT_PARALLAX_MAP_SOLID;
break;
}
Room->setMaterialType(type);
// change material setting
switch(ListBox->getSelected())
{
case 0: type = video::EMT_TRANSPARENT_VERTEX_ALPHA;
break;
case 1: type = video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA;
break;
case 2: type = video::EMT_PARALLAX_MAP_TRANSPARENT_VERTEX_ALPHA;
break;
}
Earth->setMaterialType(type);
/*
We need to add a warning if the materials will not be able to
be displayed 100% correctly. This is no problem, they will be
renderered using fall back materials, but at least the user
should know that it would look better on better hardware. We
simply check if the material renderer is able to draw at full
quality on the current hardware. The
IMaterialRenderer::getRenderCapability() returns 0 if this is
the case.
*/
video::IMaterialRenderer* renderer = Driver->getMaterialRenderer(type);
// display some problem text when problem
if (!renderer || renderer->getRenderCapability() != 0)
ProblemText->setVisible(true);
else
ProblemText->setVisible(false);
}
private:
gui::IGUIStaticText* ProblemText;
gui::IGUIListBox* ListBox;
scene::ISceneNode* Room;
scene::ISceneNode* Earth;
video::IVideoDriver* Driver;
};
/*
Now for the real fun. We create an Irrlicht Device and start to setup the scene.
*/
int main()
{
// let user select driver type
video::E_DRIVER_TYPE driverType=driverChoiceConsole();
if (driverType==video::EDT_COUNT)
return 1;
// create device
IrrlichtDevice* device = createDevice(driverType,
core::dimension2d<u32>(640, 480));
if (device == 0)
return 1; // could not create selected driver.
/*
Before we start with the interesting stuff, we do some simple things:
Store pointers to the most important parts of the engine (video driver,
scene manager, gui environment) to safe us from typing too much, add an
irrlicht engine logo to the window and a user controlled first person
shooter style camera. Also, we let the engine know that it should store
all textures in 32 bit. This necessary because for parallax mapping, we
need 32 bit textures.
*/
video::IVideoDriver* driver = device->getVideoDriver();
scene::ISceneManager* smgr = device->getSceneManager();
gui::IGUIEnvironment* env = device->getGUIEnvironment();
driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true);
// add irrlicht logo
env->addImage(driver->getTexture("../../media/irrlichtlogo3.png"),
core::position2d<s32>(10,10));
// add camera
scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS();
camera->setPosition(core::vector3df(-200,200,-200));
// disable mouse cursor
device->getCursorControl()->setVisible(false);
/*
Because we want the whole scene to look a little bit scarier, we add
some fog to it. This is done by a call to IVideoDriver::setFog(). There
you can set various fog settings. In this example, we use pixel fog,
because it will work well with the materials we'll use in this example.
Please note that you will have to set the material flag EMF_FOG_ENABLE
to 'true' in every scene node which should be affected by this fog.
*/
driver->setFog(video::SColor(0,138,125,81), video::EFT_FOG_LINEAR, 250, 1000, .003f, true, false);
/*
To be able to display something interesting, we load a mesh from a .3ds
file which is a room I modeled with anim8or. It is the same room as
from the specialFX example. Maybe you remember from that tutorial, I am
no good modeler at all and so I totally messed up the texture mapping
in this model, but we can simply repair it with the
IMeshManipulator::makePlanarTextureMapping() method.
*/
scene::IAnimatedMesh* roomMesh = smgr->getMesh("../../media/room.3ds");
scene::ISceneNode* room = 0;
scene::ISceneNode* earth = 0;
if (roomMesh)
{
// The Room mesh doesn't have proper Texture Mapping on the
// floor, so we can recreate them on runtime
smgr->getMeshManipulator()->makePlanarTextureMapping(
roomMesh->getMesh(0), 0.003f);
/*
Now for the first exciting thing: If we successfully loaded the
mesh we need to apply textures to it. Because we want this room
to be displayed with a very cool material, we have to do a
little bit more than just set the textures. Instead of only
loading a color map as usual, we also load a height map which
is simply a grayscale texture. From this height map, we create
a normal map which we will set as second texture of the room.
If you already have a normal map, you could directly set it,
but I simply didn't find a nice normal map for this texture.
The normal map texture is being generated by the
makeNormalMapTexture method of the VideoDriver. The second
parameter specifies the height of the heightmap. If you set it
to a bigger value, the map will look more rocky.
*/
video::ITexture* normalMap =
driver->getTexture("../../media/rockwall_height.bmp");
if (normalMap)
driver->makeNormalMapTexture(normalMap, 9.0f);
/*
// The Normal Map and the displacement map/height map in the alpha channel
video::ITexture* normalMap =
driver->getTexture("../../media/rockwall_NRM.tga");
*/
/*
But just setting color and normal map is not everything. The
material we want to use needs some additional informations per
vertex like tangents and binormals. Because we are too lazy to
calculate that information now, we let Irrlicht do this for us.
That's why we call IMeshManipulator::createMeshWithTangents().
It creates a mesh copy with tangents and binormals from another
mesh. After we've done that, we simply create a standard
mesh scene node with this mesh copy, set color and normal map
and adjust some other material settings. Note that we set
EMF_FOG_ENABLE to true to enable fog in the room.
*/
scene::IMesh* tangentMesh = smgr->getMeshManipulator()->
createMeshWithTangents(roomMesh->getMesh(0));
room = smgr->addMeshSceneNode(tangentMesh);
room->setMaterialTexture(0,
driver->getTexture("../../media/rockwall.jpg"));
room->setMaterialTexture(1, normalMap);
// Stones don't glitter..
room->getMaterial(0).SpecularColor.set(0,0,0,0);
room->getMaterial(0).Shininess = 0.f;
room->setMaterialFlag(video::EMF_FOG_ENABLE, true);
room->setMaterialType(video::EMT_PARALLAX_MAP_SOLID);
// adjust height for parallax effect
room->getMaterial(0).MaterialTypeParam = 1.f / 64.f;
// drop mesh because we created it with a create.. call.
tangentMesh->drop();
}
/*
After we've created a room shaded by per pixel lighting, we add a
sphere into it with the same material, but we'll make it transparent.
In addition, because the sphere looks somehow like a familiar planet,
we make it rotate. The procedure is similar as before. The difference
is that we are loading the mesh from an .x file which already contains
a color map so we do not need to load it manually. But the sphere is a
little bit too small for our needs, so we scale it by the factor 50.
*/
// add earth sphere
scene::IAnimatedMesh* earthMesh = smgr->getMesh("../../media/earth.x");
if (earthMesh)
{
//perform various task with the mesh manipulator
scene::IMeshManipulator *manipulator = smgr->getMeshManipulator();
// create mesh copy with tangent informations from original earth.x mesh
scene::IMesh* tangentSphereMesh =
manipulator->createMeshWithTangents(earthMesh->getMesh(0));
// set the alpha value of all vertices to 200
manipulator->setVertexColorAlpha(tangentSphereMesh, 200);
// scale the mesh by factor 50
core::matrix4 m;
m.setScale ( core::vector3df(50,50,50) );
manipulator->transformMesh( tangentSphereMesh, m );
earth = smgr->addMeshSceneNode(tangentSphereMesh);
earth->setPosition(core::vector3df(-70,130,45));
// load heightmap, create normal map from it and set it
video::ITexture* earthNormalMap = driver->getTexture("../../media/earthbump.jpg");
if (earthNormalMap)
{
driver->makeNormalMapTexture(earthNormalMap, 20.0f);
earth->setMaterialTexture(1, earthNormalMap);
earth->setMaterialType(video::EMT_NORMAL_MAP_TRANSPARENT_VERTEX_ALPHA);
}
// adjust material settings
earth->setMaterialFlag(video::EMF_FOG_ENABLE, true);
// add rotation animator
scene::ISceneNodeAnimator* anim =
smgr->createRotationAnimator(core::vector3df(0,0.1f,0));
earth->addAnimator(anim);
anim->drop();
// drop mesh because we created it with a create.. call.
tangentSphereMesh->drop();
}
/*
Per pixel lighted materials only look cool when there are moving
lights. So we add some. And because moving lights alone are so boring,
we add billboards to them, and a whole particle system to one of them.
We start with the first light which is red and has only the billboard
attached.
*/
// add light 1 (more green)
scene::ILightSceneNode* light1 =
smgr->addLightSceneNode(0, core::vector3df(0,0,0),
video::SColorf(0.5f, 1.0f, 0.5f, 0.0f), 800.0f);
light1->setDebugDataVisible ( scene::EDS_BBOX );
// add fly circle animator to light 1
scene::ISceneNodeAnimator* anim =
smgr->createFlyCircleAnimator (core::vector3df(50,300,0),190.0f, -0.003f);
light1->addAnimator(anim);
anim->drop();
// attach billboard to the light
scene::ISceneNode* bill =
smgr->addBillboardSceneNode(light1, core::dimension2d<f32>(60, 60));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
bill->setMaterialTexture(0, driver->getTexture("../../media/particlegreen.jpg"));
/*
Now the same again, with the second light. The difference is that we
add a particle system to it too. And because the light moves, the
particles of the particlesystem will follow. If you want to know more
about how particle systems are created in Irrlicht, take a look at the
specialFx example. Maybe you will have noticed that we only add 2
lights, this has a simple reason: The low end version of this material
was written in ps1.1 and vs1.1, which doesn't allow more lights. You
could add a third light to the scene, but it won't be used to shade the
walls. But of course, this will change in future versions of Irrlicht
where higher versions of pixel/vertex shaders will be implemented too.
*/
// add light 2 (red)
scene::ISceneNode* light2 =
smgr->addLightSceneNode(0, core::vector3df(0,0,0),
video::SColorf(1.0f, 0.2f, 0.2f, 0.0f), 800.0f);
// add fly circle animator to light 2
anim = smgr->createFlyCircleAnimator(core::vector3df(0,150,0), 200.0f,
0.001f, core::vector3df(0.2f, 0.9f, 0.f));
light2->addAnimator(anim);
anim->drop();
// attach billboard to light
bill = smgr->addBillboardSceneNode(light2, core::dimension2d<f32>(120, 120));
bill->setMaterialFlag(video::EMF_LIGHTING, false);
bill->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
bill->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
bill->setMaterialTexture(0, driver->getTexture("../../media/particlered.bmp"));
// add particle system
scene::IParticleSystemSceneNode* ps =
smgr->addParticleSystemSceneNode(false, light2);
// create and set emitter
scene::IParticleEmitter* em = ps->createBoxEmitter(
core::aabbox3d<f32>(-3,0,-3,3,1,3),
core::vector3df(0.0f,0.03f,0.0f),
80,100,
video::SColor(0,255,255,255), video::SColor(0,255,255,255),
400,1100);
em->setMinStartSize(core::dimension2d<f32>(30.0f, 40.0f));
em->setMaxStartSize(core::dimension2d<f32>(30.0f, 40.0f));
ps->setEmitter(em);
em->drop();
// create and set affector
scene::IParticleAffector* paf = ps->createFadeOutParticleAffector();
ps->addAffector(paf);
paf->drop();
// adjust some material settings
ps->setMaterialFlag(video::EMF_LIGHTING, false);
ps->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
ps->setMaterialTexture(0, driver->getTexture("../../media/fireball.bmp"));
ps->setMaterialType(video::EMT_TRANSPARENT_VERTEX_ALPHA);
MyEventReceiver receiver(room, earth, env, driver);
device->setEventReceiver(&receiver);
/*
Finally, draw everything. That's it.
*/
int lastFPS = -1;
while(device->run())
if (device->isWindowActive())
{
driver->beginScene(true, true, 0);
smgr->drawAll();
env->drawAll();
driver->endScene();
int fps = driver->getFPS();
if (lastFPS != fps)
{
core::stringw str = L"Per pixel lighting example - Irrlicht Engine [";
str += driver->getName();
str += "] FPS:";
str += fps;
device->setWindowCaption(str.c_str());
lastFPS = fps;
}
}
device->drop();
return 0;
}
/*
**/
| [
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475",
"engineer_apple@dfc29bdd-3216-0410-991c-e03cc46cb475",
"cutealien@dfc29bdd-3216-0410-991c-e03cc46cb475"
]
| [
[
[
1,
30
],
[
32,
35
],
[
37,
123
],
[
137,
161
],
[
163,
172
],
[
176,
202
],
[
204,
233
],
[
235,
263
],
[
269,
289
],
[
291,
291
],
[
293,
296
],
[
298,
332
],
[
334,
334
],
[
336,
341
],
[
344,
346
],
[
348,
351
],
[
353,
366
],
[
368,
387
],
[
389,
402
],
[
404,
418
],
[
420,
448
],
[
450,
488
]
],
[
[
31,
31
],
[
36,
36
],
[
124,
136
],
[
162,
162
],
[
203,
203
],
[
234,
234
],
[
264,
268
],
[
290,
290
],
[
292,
292
],
[
297,
297
],
[
333,
333
],
[
335,
335
],
[
342,
343
],
[
347,
347
],
[
352,
352
],
[
367,
367
],
[
388,
388
],
[
403,
403
],
[
419,
419
],
[
449,
449
]
],
[
[
173,
175
]
]
]
|
21158315cc49d7f90a639395d2666e20e34e6be9 | 270515cee0e43cf1ed1b5e295215465f33e72d21 | /skypecheckers/checkers.h | 8b5c78531bae4e149ea55e383b24f9db62fe67d7 | []
| no_license | ramenia/sa2asamples | d45ca12b93bb4530b374aa4cad1d7000e0831bd1 | c0d9317d71f9c2be61fb717599be9af5940a5009 | refs/heads/master | 2021-05-29T16:41:20.471283 | 2007-05-22T17:07:01 | 2007-05-22T17:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,458 | h | // checkers.h
//
#pragma once
class Checkers
{
//Definition
public:
enum Color
{
dark = 1,
light = 2,
};
enum Side
{
blank = 0,
ally,
enemy,
};
//Class
private:
struct Piece
{
//Field
private:
Side side;
bool crowned;
// Constructor
public:
Piece(Side side, int x, int y) : side(side), crowned(false){}
virtual ~Piece(void){}
// Accessor
public:
Side getSide(void){return side;}
bool isCrowned(void){return crowned;}
// Method
public:
bool Crown(void){return (crowned = true);}
};
private:
struct Cell
{
//Field
public:
Piece* piece;
bool available;
// Constructor
public:
Cell(int x = 0, int y = 0) : piece(0), available(false){}
virtual ~Cell(void){}
};
public:
class Board
{
//Field
private:
static const int size = 10;
Cell cell[size][size];
// Constructor
public:
Board();
// Accessor
public:
int getSize()const{return size;}
Cell* getAt(int x, int y){return (IsOnBoard(x, y) ? &cell[x][y] : 0);}
// Method
public:
bool IsOnBoard(int x, int y)const;
bool IsAvailable(int x, int y)const;
bool HasPiece(int x, int y)const;
bool IsEmpty(int x, int y)const;
};
public:
class Player
{
//Field
public:
Checkers* game;
Side side;
Color color;
// Constructor
public:
Player(Checkers* game, Side side, Color color):game(game), side(side), color(color){}
virtual ~Player(void){}
// Method
public:
bool Move(int xf, int yf, int xt, int yt);
};
//Field
public:
Board board;
private:
Player* ally_player;
Player* enemy_player;
Side turn;
bool started;
Side winner;
// Constructor
public:
Checkers(void):ally_player(0), enemy_player(0), turn(blank), started(false){}
virtual ~Checkers(void);
// Accessor
public:
Player* getAlly()const{return ally_player;}
Player* getEnemy()const{return enemy_player;}
Side getTurn()const{return turn;}
bool Started()const{return started;}
Side getWinner(){if(winner == blank)winner = CheckEndOfGame(); return winner;}
bool Finished(){return (getWinner() != blank);}
// Method
private:
bool CreatePlayer(Side side, Color color);
public:
bool Start(Side first);
private:
bool Move(Player* player, int xf, int yf, int xt, int yt);// called by Player::Move
void ChangeTurn(void);
public:
bool DutyJump(Side side);
private:
Side CheckEndOfGame();
};
| [
"komakura@e21e20eb-d230-0410-9e73-79da4af2494c"
]
| [
[
[
1,
139
]
]
]
|
f7f1bbb7ecae3b4b7ec0e38645d525499b94dbbf | e05839a60d267760554e94385d969080c4ea2efb | /wcsph/code/wcsph/wcsph/Poly6SmoothKernel.h | bb037c95a82f0dd626b1c143c7e369bc503dad56 | []
| no_license | naceurCRAAG/pci-sph | 0c207de6b304310b47f165568c1ccdcea7125b9e | e0ccf219ed53ca239065a77ad88dfd1fe62c6cac | refs/heads/master | 2020-06-05T07:40:45.527414 | 2010-03-23T07:00:27 | 2010-03-23T07:00:27 | 35,105,897 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | h | #pragma once
#include "smoothkernel.h"
/**
This class deals with the calculation of
*/
class Poly6SmoothKernel :
public SmoothKernel
{
public:
Poly6SmoothKernel(void);
~Poly6SmoothKernel(void);
public:
vector3 getValue(vector3 *r_i, vector3 *r_j, float h_size);
vector3 getGrads(vector3 *r_i, vector3 *r_j, float h_size);
vector3 getLaplacian(vector3 *r_i, vector3 *r_j, float h_size);
};
| [
"ossupero@039cecf8-1fb2-5f38-3c02-d836a5369e73"
]
| [
[
[
1,
18
]
]
]
|
ed45e44c7b8acb2255726df0a36474c95766a087 | 986d745d6a1653d73a497c1adbdc26d9bef48dba | /oldnewthing/103_textoutfl.cpp | c009634243d9c967556de1c4085738fd0879e8c2 | []
| no_license | AnarNFT/books-code | 879f75327c1dad47a13f9c5d71a96d69d3cc7d3c | 66750c2446477ac55da49ade229c21dd46dffa99 | refs/heads/master | 2021-01-20T23:40:30.826848 | 2011-01-17T11:14:34 | 2011-01-17T11:14:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,116 | cpp | #define STRICT
#include <windows.h>
#include <windowsx.h>
#include <ole2.h>
#include <commctrl.h>
#include <shlwapi.h>
#include <mlang.h>
HINSTANCE g_hinst; /* This application's HINSTANCE */
HWND g_hwndChild; /* Optional child window */
void
OnSize(HWND hwnd, UINT state, int cx, int cy)
{
if (g_hwndChild) {
MoveWindow(g_hwndChild, 0, 0, cx, cy, TRUE);
}
}
BOOL
OnCreate(HWND hwnd, LPCREATESTRUCT lpcs)
{
return TRUE;
}
void
OnDestroy(HWND hwnd)
{
PostQuitMessage(0);
}
HRESULT TextOutFL(HDC hdc, int x, int y, LPCWSTR psz, int cch)
{
HRESULT hr;
IMLangFontLink2 *pfl;
if (SUCCEEDED(hr = CoCreateInstance(CLSID_CMultiLanguage,
NULL, CLSCTX_ALL, IID_IMLangFontLink2,
(void**)&pfl))) {
HFONT hfOrig = (HFONT)GetCurrentObject(hdc, OBJ_FONT);
POINT ptOrig;
DWORD dwAlignOrig = GetTextAlign(hdc);
if (!(dwAlignOrig & TA_UPDATECP)) {
SetTextAlign(hdc, dwAlignOrig | TA_UPDATECP);
}
MoveToEx(hdc, x, y, &ptOrig);
DWORD dwFontCodePages = 0;
hr = pfl->GetFontCodePages(hdc, hfOrig, &dwFontCodePages);
if (SUCCEEDED(hr)) {
while (cch > 0) {
DWORD dwActualCodePages;
long cchActual;
hr = pfl->GetStrCodePages(psz, cch, dwFontCodePages,
&dwActualCodePages, &cchActual);
if (FAILED(hr)) {
break;
}
if (dwActualCodePages & dwFontCodePages) {
TextOutW(hdc, 0, 0, psz, cchActual);
} else {
HFONT hfLinked;
if (FAILED(hr = pfl->MapFont(hdc, dwActualCodePages, 0,
&hfLinked))) {
break;
}
SelectFont(hdc, hfLinked);
TextOutW(hdc, 0, 0, psz, cchActual);
SelectFont(hdc, hfOrig);
pfl->ReleaseFont(hfLinked);
}
psz += cchActual;
cch -= cchActual;
}
if (FAILED(hr)) {
// We started outputting characters so we must finish.
// Do the rest without font linking since we have
// no choice.
TextOutW(hdc, 0, 0, psz, cch);
hr = S_FALSE;
}
}
pfl->Release();
if (!(dwAlignOrig & TA_UPDATECP)) {
SetTextAlign(hdc, dwAlignOrig);
MoveToEx(hdc, ptOrig.x, ptOrig.y, NULL);
}
}
return hr;
}
void TextOutTryFL(HDC hdc, int x, int y, LPCWSTR psz, int cch)
{
if (FAILED(TextOutFL(hdc, x, y, psz, cch))) {
TextOutW(hdc, x, y, psz, cch);
}
}
void
PaintContent(HWND hwnd, PAINTSTRUCT *pps)
{
TextOutTryFL(pps->hdc, 0, 0,
L"ABC\x0410\x0411\x0412\x0E01\x0E02\x0E03", 9);
}
void
OnPaint(HWND hwnd)
{
PAINTSTRUCT ps;
BeginPaint(hwnd, &ps);
PaintContent(hwnd, &ps);
EndPaint(hwnd, &ps);
}
void
OnPrintClient(HWND hwnd, HDC hdc)
{
PAINTSTRUCT ps;
ps.hdc = hdc;
GetClientRect(hwnd, &ps.rcPaint);
ps.fErase = FALSE;
PaintContent(hwnd, &ps);
}
LRESULT CALLBACK
WndProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch (uiMsg) {
HANDLE_MSG(hwnd, WM_CREATE, OnCreate);
HANDLE_MSG(hwnd, WM_SIZE, OnSize);
HANDLE_MSG(hwnd, WM_DESTROY, OnDestroy);
HANDLE_MSG(hwnd, WM_PAINT, OnPaint);
case WM_PRINTCLIENT: OnPrintClient(hwnd, (HDC)wParam); return 0;
}
return DefWindowProc(hwnd, uiMsg, wParam, lParam);
}
BOOL
InitApp(void)
{
WNDCLASS wc;
wc.style = 0;
wc.lpfnWndProc = WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = g_hinst;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.lpszMenuName = NULL;
wc.lpszClassName = TEXT("Scratch");
if (!RegisterClass(&wc)) return FALSE;
InitCommonControls(); /* In case we use a common control */
return TRUE;
}
int WINAPI WinMain(HINSTANCE hinst, HINSTANCE hinstPrev,
LPSTR lpCmdLine, int nShowCmd)
{
MSG msg;
HWND hwnd;
g_hinst = hinst;
if (!InitApp()) return 0;
if (SUCCEEDED(CoInitialize(NULL))) {/* In case we use COM */
hwnd = CreateWindow(
TEXT("Scratch"), /* Class Name */
TEXT("Scratch"), /* Title */
WS_OVERLAPPEDWINDOW, /* Style */
CW_USEDEFAULT, CW_USEDEFAULT, /* Position */
CW_USEDEFAULT, CW_USEDEFAULT, /* Size */
NULL, /* Parent */
NULL, /* No menu */
hinst, /* Instance */
0); /* No special parameters */
ShowWindow(hwnd, nShowCmd);
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
CoUninitialize();
}
return 0;
}
| [
"[email protected]"
]
| [
[
[
1,
197
]
]
]
|
d5d670a6f0a9cb69fee4e656343bef1aab092afe | 6ed8a7f8102c2c90baee79e086e589f553f7d2d3 | /SDL_Layout.cpp | 5f2e492deac2fe636ecdb4c3972b2208093b866a | []
| no_license | snaill/sscs | 3173c150c86b7dee7652c3547271b1f9c9b53c85 | b89f0dd9d9d34ceeeea4988550614ed36bdb1a18 | refs/heads/master | 2021-01-23T13:28:47.551752 | 2009-05-25T10:16:23 | 2009-05-25T10:16:23 | 32,121,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | /*
* SDL_SimpleControls
* Copyright (C) 2008 Snaill
*
SDL_SimpleControls 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.
SDL_SimpleControls 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, see <http://www.gnu.org/licenses/>.
Snaill <[email protected]>
*/
#include "SDL_Layout.h"
| [
"com.chinaos.snaill@db7a99aa-9dca-11dd-b92e-bd4787f9249a"
]
| [
[
[
1,
21
]
]
]
|
6d77c3cb6bbc11776d1b4086b17b8dac32c99d58 | 2da45de42ca48a4732de3577e360929025a50e43 | /src/GUI/guiTypeTextDropDown.h | f2b494ad898f332a9b8e1c050c109b726be6e97d | []
| no_license | armadillu/PointGreyCameraInput | 38acc60d8c36b5917c45c43bfee75508c6d9a90f | 2365a8fe0ce73d50648409d4c5f9ca38e48a1061 | refs/heads/master | 2021-01-23T13:18:24.652957 | 2010-10-24T11:08:27 | 2010-10-24T11:08:27 | 691,896 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,476 | h | #pragma once
#include "guiBaseObject.h"
#include "guiColor.h"
#include "simpleColor.h"
#include "guiValue.h"
class guiTypeTextDropDown : public guiBaseObject{
public:
static const int boxHeight = 15;
//------------------------------------------------
void setup(string dropDownName, int defaultBox, vector <string> boxNames)
{
vecDropList = boxNames;
value.addValue( (int)defaultBox, 0, vecDropList.size()-1);
name = dropDownName;
hitArea.height = boundingBox.height = boxHeight;
bShowDropDown = false;
}
//-----------------------------------------------
virtual void updateValue()
{
if(parameterCallback != NULL) {
parameterCallback->Execute(-1,-1,value.getValueI(), callback_id);
}
}
//-----------------------------------------------.
void update()
{
//setShowText(false);
updateText();
if(bShowDropDown) {
hitArea.height = boundingBox.height = boxHeight * vecDropList.size();
} else {
hitArea.height = boundingBox.height = boxHeight;
state = SG_STATE_NORMAL;
setNormal();
}
}
virtual void release(){
if(state != SG_STATE_SELECTED) {
bShowDropDown = false;
}
state = SG_STATE_NORMAL;
}
//-----------------------------------------------.
void updateGui(float x, float y, bool firstHit, bool isRelative) {
if(!firstHit)return;
if( state == SG_STATE_SELECTED){
float relX = x - hitArea.x;
float relY = y - hitArea.y;
if(bShowDropDown) {
for(unsigned int i = 0; i < vecDropList.size(); i++){
ofRectangle tmpRect(0, i * (boxHeight), boundingBox.width, boxHeight);
if( isInsideRect(relX, relY, tmpRect) ){
value.setValue(i, 0);
bShowDropDown = false;
if(parameterCallback != NULL) {
parameterCallback->Execute(-1,-1,value.getValueI(), callback_id);
}
break;
}
}
} else {
ofRectangle tmpRect(0, 0, boundingBox.width, boxHeight);
if( isInsideRect(relX, relY, tmpRect) ){
bShowDropDown = true;
}
}
}
}
//-----------------------------------------------.
void render(){
ofPushStyle();
guiBaseObject::renderText();
//draw the background
ofFill();
glColor4fv(bgColor.getColorF());
ofRect(hitArea.x, hitArea.y, hitArea.width, hitArea.height);
if(bShowDropDown)
{
glTranslated(1,0,0.1f);
for(int i = 0; i < (int) vecDropList.size(); i++)
{
float bx = hitArea.x + 0;
float by = hitArea.y + i * (boxHeight);
if(value.getValueI() == i){
glColor4fv(fgColor.getSelectedColorF());
}else{
glColor4fv(fgColor.getNormalColorF());
}
ofFill();
ofRect(bx, by, boundingBox.width, boxHeight);
ofNoFill();
glColor4fv(outlineColor.getColorF());
ofRect(bx, by, boundingBox.width, boxHeight);
if(i==0) {
ofFill();
glColor4fv(outlineColor.getColorF());
//ofTriangle(bx + boundingBox.width - 7, by + boxHeight, bx + boundingBox.width - 14, by,bx + boundingBox.width, by);
ofRect(bx + boundingBox.width - boxHeight, by, boxHeight*0.666f, boxHeight*0.666f);
}
glColor4fv(textColor.getColorF());
displayText.renderString(vecDropList[i], bx + 2, by + boxHeight -4);
}
glTranslated(-1,0,-0.1f);
} else {
float bx = hitArea.x;
float by = hitArea.y;
ofFill();
glColor4fv(bgColor.getColorF());
ofRect(bx, by, boundingBox.width, boxHeight);
ofNoFill();
glColor4fv(outlineColor.getColorF());
ofRect(bx, by, boundingBox.width, boxHeight);
ofFill();
glColor4fv(outlineColor.getColorF());
//ofTriangle(bx + boundingBox.width - 7, by + boxHeight, bx + boundingBox.width - 14, by,bx + boundingBox.width, by);
ofRect(bx + boundingBox.width - boxHeight, by, boxHeight*0.666f, boxHeight*0.666f);
glColor4fv(textColor.getColorF());
displayText.renderString(vecDropList[value.getValueI()], bx + 2, by + boxHeight -4);
}
ofPopStyle();
}
vector <string> vecDropList;
bool bShowDropDown;
};
| [
"[email protected]"
]
| [
[
[
1,
164
]
]
]
|
5ac6efdeefd10c7df1f1da07cfd0d89db7ac0d2b | 6dac9369d44799e368d866638433fbd17873dcf7 | /src/branches/win32networkcode/PTNetworkCore.cpp | ad1af97816d53b45a7a6efe06631682dd06492e9 | []
| 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,158 | cpp | #include <PTNetworkCore.h>
#include <PTClientSocket.h>
#include <PTServerSocket.h>
PTNetworkCore::PTNetworkCore(void){}
PTNetworkCore::~PTNetworkCore()
{
// trigger the threads to quit
m_destroy_threads = true;
//===================================
// Clear the send data stack
//===================================
m_senddata.clear();
//===================================
// Clear the socket queue
//===================================
while(m_sockets.size() > 0) RemoveSocket(m_sockets[0]);
// Trigger the quit event (if the thread is still running, it'll unblock)
m_network_events.SetQuitEvent();
// Wait until all the threads exit
m_TerminateThread->wait();
//==============================
// Close all the event handles
//==============================
// Close the send/recv event signals
delete m_SendEvent;
// Close the thread termination events
delete m_TerminateThread;
// Close the thread handles
pthread_join(m_Thread,NULL);
//===================================
// Delete all the mutexes
//===================================
pthread_mutex_destroy(&m_sockets_lock);
pthread_mutex_destroy(&m_senddata_lock);
//===================================
// Close the WSA Networking system
//===================================
WSACleanup();
}
bool PTNetworkCore::Initialise(void)
{
if (WSAStartup(WINSOCK_VERSION, &m_WSAData) == 0){
m_Thread = NULL;
m_ThreadID = 0;
m_SendEvent = new Event(false);
// Trigger + Events to terminate the threads when object dtor is called
m_destroy_threads = false;
m_TerminateThread = new Event(true);
// Initialise all Critical sections
pthread_mutex_init(&m_sockets_lock, NULL);
pthread_mutex_init(&m_senddata_lock, NULL);
return true;
}
// failure
return false;
}
IClientSocket * PTNetworkCore::CreateSocket(void)
{
return new PTClientSocket(this);
}
IServerSocket * PTNetworkCore::CreateServerSocket(void)
{
return new PTServerSocket(this);
}
void PTNetworkCore::AddSocket(ISocket *socket, int events)
{
// Lock/Unlock the server sockets
LockSockets();
{
// Store the socket and create the events it requested
m_sockets.push_back(socket);
m_network_events.AddEvent(socket, events);
}
UnlockSockets();
// If this is the first socket in the list, then either/or the network core's thread has
// a) not been created yet
// b) been suspended and need resuming
if (m_sockets.size() == 1) {
// Create the network core thread
m_ThreadID = pthread_create(&m_Thread, NULL, PTNetworkCoreThread, this);
}
}
bool PTNetworkCore::RemoveSocket(ISocket *socket)
{
bool success = false;
// Lock/Unlock the client sockets
LockSockets();
{
// Loop through the list of available sockets until you can match the ptr
for (unsigned int a = 0; a < m_sockets.size(); a++){
// If you find the ptr
if (m_sockets[a] == socket){
// erase the socket from the list and remove it's event
m_network_events.RemoveEvent(m_sockets[a]);
m_sockets.erase(m_sockets.begin() + a);
success = true;
break;
}
}
} // Remember you've locked the sockets, so you have to unlock it here, or trouble ensues
UnlockSockets();
// return whether you were successful of not
return success;
}
void PTNetworkCore::Send(NetworkPacket *packet)
{
// Lock/Unlock the send data stack
LockSendStack();
{
// Put the data onto the send stack
m_senddata.push_back(packet);
}
UnlockSendStack();
m_network_events.SetSendEvent();
}
Win32SocketEvents * PTNetworkCore::getSocketEvents(void)
{
return &m_network_events;
}
NetworkPacket * PTNetworkCore::getNetworkPacket(void)
{
NetworkPacket *packet = NULL;
LockSendStack();
{
if(m_senddata.size() > 0){
packet = m_senddata[0];
m_senddata.erase(m_senddata.begin());
}
}
UnlockSendStack();
return packet;
}
/*
* MUTEX/THREAD METHODS
*/
void PTNetworkCore::LockSockets(void)
{
pthread_mutex_lock(&m_sockets_lock);
}
void PTNetworkCore::UnlockSockets(void)
{
pthread_mutex_unlock(&m_sockets_lock);
}
void PTNetworkCore::LockSendStack(void)
{
pthread_mutex_lock(&m_senddata_lock);
}
void PTNetworkCore::UnlockSendStack(void)
{
pthread_mutex_unlock(&m_senddata_lock);
}
void PTNetworkCore::startThread(void)
{
// you call wait when you start the thread, cause it's initially set to a signalled state
// therefore it'll drop through the funtion without waiting, but it will reset the signal
// state of the event, therefore when you come to kill the thread, it will WAIT properly
// as opposed to dropping straight through that too, which would be bad.
m_TerminateThread->wait();
}
void PTNetworkCore::killThread(void)
{
if(m_destroy_threads == true || m_sockets.size() == 0){
m_TerminateThread->signal();
pthread_exit(0);
}
}
| [
"chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7"
]
| [
[
[
1,
202
]
]
]
|
2d03da955d9dbbd6d1e5e6f1a49898ad2c5d792c | 216ae2fd7cba505c3690eaae33f62882102bd14a | /utils/nxogre/include/NxOgreHeightFieldManager.h | 23527b8be70cccfcd81bbd73ac84a33f49d04c46 | []
| 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,405 | h | /** File: NxOgreHeightFieldManager.h
Created on: 27-Mar-09
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_HEIGHTFIELDMANAGER_H
#define NXOGRE_HEIGHTFIELDMANAGER_H
#include "NxOgreStable.h"
#include "NxOgreCommon.h"
namespace NxOgre_Namespace
{
/** \brief HeightFieldManager holds all HeightFieldes that are currently in the World.
*/
class NxOgrePublicClass HeightFieldManager: public ::NxOgre_Namespace::Singleton<HeightFieldManager, ::NxOgre_Namespace::Classes::_HeightFieldManager>
{
friend class World;
friend class ManualHeightField;
public: // Functions
/** \brief Load a HeightField into the World, that can be used in any Scene.
\note It will take the resource name as it's name.
*/
HeightField* load(const ArchiveResourceIdentifier&);
/** \brief Load a HeightField into the World, that can be used in any Scene.
*/
HeightField* load(const ArchiveResourceIdentifier&, const String& name);
/** \brief Load a HeightField into the World, that can be used in any Scene.
\note It will try to take the resource name as it's name, otherwise a random one will be generated.
*/
HeightField* load(Resource*);
/** \brief Load a HeightField into the World, that can be used in any Scene.
*/
HeightField* load(Resource*, const String& name);
/** \brief Text
*/
HeightField* getByName(const String& HeightFieldIdentifier);
protected: // Variables
/** \internal See World::precreateSingletons
*/
HeightFieldManager(void);
/** \internal See World::destroySingletons
*/
~HeightFieldManager(void);
/** \brief Known loaded HeightFields in the World.
*/
Array<HeightField*> mLoadedHeightFields;
}; // class ClassName
} // namespace NxOgre_Namespace
#endif
| [
"umutert@b781d008-8b8c-11de-b664-3b115b7b7a9b"
]
| [
[
[
1,
93
]
]
]
|
c71c46e78f8e0e0398e6faf586be4070d5351fb2 | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/OgreMaxLoader/Include/LoadSaveActionMap.hpp | 97a8cb93dad6d858975e022f0e735da19496ff83 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 23,330 | 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_LoadSaveActionMap_INCLUDED
#define OgreMax_LoadSaveActionMap_INCLUDED
//Includes---------------------------------------------------------------------
#include "tinyxml/tinyxml.h"
#include "ActionMap.hpp"
//Classes----------------------------------------------------------------------
namespace OgreMax
{
/**
* ActionMap-derived class that provides the ability to load and save
* the action map settings.
*
* Note that ActionID must be able to evaluate to false/true. It will
* evaluate to false when the value returned by ParseAction is invalid
*/
template <class ActionID, class EventCollection>
class LoadSaveActionMap : public ActionMap<ActionID, EventCollection>
{
public:
/** Describes an action */
class ActionInfo
{
public:
/** Flags */
enum
{
NO_FLAGS = 0,
/** Indicates that the action is private and should not be loaded or saved */
PRIVATE = 0x1
};
/** Constructor used to initialize the null action info */
ActionInfo()
{
this->flags = NO_FLAGS;
this->isNull = true;
}
/** The most commonly used constructor */
ActionInfo(const char* actionName, ActionID action, int flags = NO_FLAGS) : name(actionName)
{
this->action = action;
this->flags = flags;
this->isNull = false;
}
/** Determines if the action is public */
bool IsPublic() const
{
return this->name != 0 && this->name[0] != 0 && !(this->flags & PRIVATE);
}
public:
/**
* The name of the action.
* This will be used when loading and saving mappings, so it's best if
* the name doesn't contain whitespace
*/
const char* name;
/** The action identifier */
ActionID action;
/** Indicates whether the info represents the 'null' action */
bool isNull;
private:
/** Flags */
int flags;
};
/**
* Loads the action map settings from the specified file
* @param fileName [in] - Name of the file to laod
* @return Returns true if the file was successfully loaded, false otherwise
*/
virtual bool LoadFile(const Ogre::String& fileName)
{
TiXmlDocument xmlDocument;
if (!xmlDocument.LoadFile(fileName.c_str()))
return false;
TiXmlElement* rootXmlElement = xmlDocument.RootElement();
//Settings
const TiXmlElement* settingsXmlElement = (const TiXmlElement*)rootXmlElement->FirstChild("settings");
LoadSettings(settingsXmlElement);
//Mappings
const TiXmlElement* mappingsXmlElement = (const TiXmlElement*)rootXmlElement->FirstChild("mappings");
LoadMappings(mappingsXmlElement);
return true;
}
/** Saves the action map settings to the specified file */
virtual void SaveFile(const Ogre::String& fileName)
{
TiXmlDocument xmlDocument;
TiXmlElement* rootXmlElement = (TiXmlElement*)xmlDocument.LinkEndChild(new TiXmlElement("actionMap"));
SaveSettings(rootXmlElement);
SaveMappings(rootXmlElement);
xmlDocument.SaveFile(fileName.c_str());
}
protected:
/**
* Gets a pointer to an array containing information about all the actions
* The final element in the array must be a 'null' ActionInfo
*/
virtual const ActionInfo* GetActionInfo() const = 0;
private:
/** Gets information about an action, using an action identifier. */
const ActionInfo& GetActionInfo(ActionID action) const
{
const ActionInfo* actionInfo = GetActionInfo();
int index = 0;
for (; !actionInfo[index].isNull; index++)
{
if (action == actionInfo[index].action)
return actionInfo[index];
}
//Return null ActionInfo
return actionInfo[index];
}
/** Gets information about an action, using an action name. */
const ActionInfo& GetActionInfo(const Ogre::String& action) const
{
const ActionInfo* actionInfo = GetActionInfo();
int index = 0;
for (; !actionInfo[index].isNull; index++)
{
if (action == actionInfo[index].name)
return actionInfo[index];
}
//Return null ActionInfo
return actionInfo[index];
}
/** Loads data from the 'settings' element */
void LoadSettings(const TiXmlElement* settingsXmlElement)
{
if (settingsXmlElement == 0)
return;
const TiXmlElement* mouseXmlElement = (const TiXmlElement*)settingsXmlElement->FirstChild("mouse");
LoadMouseSettings(mouseXmlElement);
const TiXmlElement* joystickXmlElement = (const TiXmlElement*)settingsXmlElement->FirstChild("joystick");
LoadJoystickSettings(joystickXmlElement);
}
/** Loads data from the 'mappings' element */
void LoadMappings(const TiXmlElement* mappingsXmlElement)
{
if (mappingsXmlElement == 0)
return;
Ogre::String actionName;
Ogre::String sourceName;
const TiXmlNode* childXmlNode = 0;
while (childXmlNode = mappingsXmlElement->IterateChildren("mapping", childXmlNode))
{
if (childXmlNode->Type() == TiXmlNode::ELEMENT)
{
const TiXmlElement* mappingXmlElement = (const TiXmlElement*)childXmlNode;
//Action name
actionName = GetStringAttribute(mappingXmlElement, "action");
//Load the mapping if its action is public
const ActionInfo& actionInfo = GetActionInfo(actionName);
if (actionInfo.IsPublic())
{
//Input source
InputSource inputSource;
LoadInputSource(mappingXmlElement, inputSource);
//Trigger flags
TriggerFlags triggerFlags = LoadTriggerFlags(mappingXmlElement);
//Add the action mapping
AddActionMapping(inputSource, actionInfo.action, triggerFlags);
}
}
}
}
/** Loads data from the 'mouse' element */
void LoadMouseSettings(const TiXmlElement* element)
{
if (element == 0)
return;
const TiXmlNode* childXmlNode = 0;
while (childXmlNode = element->IterateChildren("setting", childXmlNode))
{
if (childXmlNode->Type() == TiXmlNode::ELEMENT)
{
const TiXmlElement* settingXmlElement = (const TiXmlElement*)childXmlNode;
//Axis
int axis;
if (settingXmlElement->Attribute("axis", &axis) && axis >= 0 && axis < Mouse::AXIS_COUNT)
{
//Sensitivity
double sensitivity;
if (settingXmlElement->Attribute("sensitivity", &sensitivity))
this->mouseSensitivity[axis] = (Ogre::Real)sensitivity;
}
}
}
}
/** Loads data from the 'joystick' element */
void LoadJoystickSettings(const TiXmlElement* element)
{
if (element == 0)
return;
const TiXmlNode* childXmlNode = 0;
while (childXmlNode = element->IterateChildren("setting", childXmlNode))
{
if (childXmlNode->Type() == TiXmlNode::ELEMENT)
{
const TiXmlElement* settingXmlElement = (const TiXmlElement*)childXmlNode;
//Axis
int axis;
if (settingXmlElement->Attribute("axis", &axis) && axis >= 0)
{
if (axis >= (int)this->joystickAxisSensitivity.size())
this->joystickAxisSensitivity.resize(axis + 1);
if (axis >= (int)this->joystickAxisDeadZone.size())
this->joystickAxisDeadZone.resize(axis + 1);
//Sensitivity
double sensitivity;
if (settingXmlElement->Attribute("sensitivity", &sensitivity))
this->joystickAxisSensitivity[axis] = (Ogre::Real)sensitivity;
//Dead zone
int deadZone;
if (settingXmlElement->Attribute("deadZone", &deadZone))
this->joystickAxisDeadZone[axis] = deadZone;
}
}
}
}
/** Saves the mappings the 'settings' element */
void SaveSettings(TiXmlElement* rootXmlElement)
{
//Determine which settings have changed from their defaults
bool modifiedMouseSensitivity = this->mouseSensitivity != this->defaultMouseSensitivity;
bool modifiedJoystickAxisDeadZones =
std::find_if
(
this->joystickAxisDeadZone.begin(),
this->joystickAxisDeadZone.end(),
std::bind2nd(std::not_equal_to<int>(), this->defaultJoystickAxisDeadZone)
) != this->joystickAxisDeadZone.end();
bool modifiedJoystickAxisSensitivities =
std::find_if
(
this->joystickAxisSensitivity.begin(),
this->joystickAxisSensitivity.end(),
std::bind2nd(std::not_equal_to<Ogre::Real>(), this->defaultJoystickAxisSensitivity)
) != this->joystickAxisSensitivity.end();
//Only save if some settings have changed
if (modifiedMouseSensitivity || modifiedJoystickAxisDeadZones || modifiedJoystickAxisSensitivities)
{
TiXmlElement* settingsXmlElement =
(TiXmlElement*)rootXmlElement->LinkEndChild(new TiXmlElement("settings"));
//Mouse sensitivities
if (modifiedMouseSensitivity)
{
TiXmlElement* mouseXmlElement =
(TiXmlElement*)settingsXmlElement->LinkEndChild(new TiXmlElement("mouse"));
for (int axisIndex = 0; axisIndex < Mouse::AXIS_COUNT; axisIndex++)
{
if (this->mouseSensitivity[axisIndex] != this->defaultMouseSensitivity[axisIndex])
{
TiXmlElement* settingXmlElement =
(TiXmlElement*)mouseXmlElement->LinkEndChild(new TiXmlElement("setting"));
//Axis index
settingXmlElement->SetAttribute("axis", axisIndex);
//Sensitivity
settingXmlElement->SetDoubleAttribute("sensitivity", this->mouseSensitivity[axisIndex]);
}
}
}
//Joystick axis dead zones and sensitivities
if (modifiedJoystickAxisDeadZones || modifiedJoystickAxisSensitivities)
{
TiXmlElement* joystickXmlElement =
(TiXmlElement*)settingsXmlElement->LinkEndChild(new TiXmlElement("joystick"));
size_t maxAxisCount = (int)std::max(this->joystickAxisDeadZone.size(), this->joystickAxisSensitivity.size());
for (size_t axisIndex = 0; axisIndex < maxAxisCount; axisIndex++)
{
if ((axisIndex < this->joystickAxisDeadZone.size() && this->joystickAxisDeadZone[axisIndex] != this->defaultJoystickAxisDeadZone) ||
(axisIndex < this->joystickAxisSensitivity.size() && this->joystickAxisSensitivity[axisIndex] != this->defaultJoystickAxisSensitivity))
{
TiXmlElement* settingXmlElement =
(TiXmlElement*)joystickXmlElement->LinkEndChild(new TiXmlElement("setting"));
//Axis index
settingXmlElement->SetAttribute("axis", (int)axisIndex);
//Dead zone
if (axisIndex < this->joystickAxisDeadZone.size() && this->joystickAxisDeadZone[axisIndex] != this->defaultJoystickAxisDeadZone)
settingXmlElement->SetAttribute("deadZone", this->joystickAxisDeadZone[axisIndex]);
//Sensitivity
if (axisIndex < this->joystickAxisSensitivity.size() && this->joystickAxisSensitivity[axisIndex] != this->defaultJoystickAxisSensitivity)
settingXmlElement->SetDoubleAttribute("sensitivity", this->joystickAxisSensitivity[axisIndex]);
}
}
}
}
}
/** Saves the mappings a 'mappings' element */
void SaveMappings(TiXmlElement* rootXmlElement)
{
TiXmlElement* mappingsXmlElement = (TiXmlElement*)rootXmlElement->LinkEndChild(new TiXmlElement("mappings"));
for (size_t mappingIndex = 0; mappingIndex < this->mappings.size(); mappingIndex++)
{
ActionMapping& mapping = this->mappings[mappingIndex];
//Save the mapping if its action is public
const ActionInfo& actionInfo = GetActionInfo(mapping.action);
if (actionInfo.IsPublic())
{
TiXmlElement* mappingXmlElement =
(TiXmlElement*)mappingsXmlElement->LinkEndChild(new TiXmlElement("mapping"));
//Action name
mappingXmlElement->SetAttribute("action", actionInfo.name);
//Input source
SaveInputSource(mappingXmlElement, mapping.inputSource);
//Trigger flags
SaveTriggerFlags(mappingXmlElement, mapping.triggerFlags);
}
}
}
/** Loads an InputSource from the specified element's attributes */
static void LoadInputSource(const TiXmlElement* element, InputSource& inputSource)
{
Ogre::String sourceName = GetStringAttribute(element, "source");
inputSource.deviceType = InputSource::DeviceTypeFromString(sourceName);
switch (inputSource.deviceType)
{
case InputSource::KEYBOARD_KEY:
{
int key;
if (element->Attribute("key", &key))
inputSource.keyCode = (OIS::KeyCode)key;
break;
}
case InputSource::MOUSE_BUTTON:
{
element->Attribute("button", &inputSource.button);
break;
}
case InputSource::MOUSE_AXIS:
{
element->Attribute("axis", &inputSource.axis);
element->Attribute("direction", &inputSource.direction);
break;
}
case InputSource::JOYSTICK_BUTTON:
{
element->Attribute("device", &inputSource.deviceIndex);
element->Attribute("button", &inputSource.button);
break;
}
case InputSource::JOYSTICK_AXIS:
{
element->Attribute("device", &inputSource.deviceIndex);
element->Attribute("axis", &inputSource.axis);
element->Attribute("direction", &inputSource.direction);
break;
}
case InputSource::JOYSTICK_POV:
{
element->Attribute("device", &inputSource.deviceIndex);
element->Attribute("index", &inputSource.povIndex);
element->Attribute("direction", &inputSource.direction);
break;
}
}
}
/** Saves an InputSource to the specified element's attributes */
static void SaveInputSource(TiXmlElement* element, const InputSource& inputSource)
{
element->SetAttribute("source", inputSource.GetDeviceTypeString());
switch (inputSource.deviceType)
{
case InputSource::KEYBOARD_KEY:
element->SetAttribute("key", (int)inputSource.keyCode);
break;
case InputSource::MOUSE_BUTTON:
element->SetAttribute("button", inputSource.button);
break;
case InputSource::MOUSE_AXIS:
element->SetAttribute("axis", inputSource.axis);
element->SetAttribute("direction", inputSource.direction);
break;
case InputSource::JOYSTICK_BUTTON:
element->SetAttribute("device", inputSource.deviceIndex);
element->SetAttribute("button", inputSource.button);
break;
case InputSource::JOYSTICK_AXIS:
element->SetAttribute("device", inputSource.deviceIndex);
element->SetAttribute("axis", inputSource.axis);
element->SetAttribute("direction", inputSource.direction);
break;
case InputSource::JOYSTICK_POV:
element->SetAttribute("device", inputSource.deviceIndex);
element->SetAttribute("index", inputSource.povIndex);
element->SetAttribute("direction", inputSource.direction);
break;
}
}
/** Loads TriggerFlags from the specified element's attributes */
static TriggerFlags LoadTriggerFlags(const TiXmlElement* element)
{
TriggerFlags triggerFlags = NO_FLAGS;
if (element->Attribute("pressed"))
triggerFlags = TriggerFlags(triggerFlags | PRESSED);
if (element->Attribute("pressing"))
triggerFlags = TriggerFlags(triggerFlags | PRESSING);
if (element->Attribute("released"))
triggerFlags = TriggerFlags(triggerFlags | RELEASED);
if (element->Attribute("alt"))
triggerFlags = TriggerFlags(triggerFlags | ALT_MODIFIER);
if (element->Attribute("ctrl"))
triggerFlags = TriggerFlags(triggerFlags | CTRL_MODIFIER);
if (element->Attribute("shift"))
triggerFlags = TriggerFlags(triggerFlags | SHIFT_MODIFIER);
if (element->Attribute("noAlt"))
triggerFlags = TriggerFlags(triggerFlags | NO_ALT_MODIFIER);
if (element->Attribute("noCtrl"))
triggerFlags = TriggerFlags(triggerFlags | NO_CTRL_MODIFIER);
if (element->Attribute("noShift"))
triggerFlags = TriggerFlags(triggerFlags | NO_SHIFT_MODIFIER);
if (element->Attribute("povWeak"))
triggerFlags = TriggerFlags(triggerFlags | POV_WEAK);
if (element->Attribute("povStrong"))
triggerFlags = TriggerFlags(triggerFlags | POV_STRONG);
return triggerFlags;
}
/** Saves TriggerFlags to the specified element's attributes */
static void SaveTriggerFlags(TiXmlElement* element, TriggerFlags triggerFlags)
{
if (triggerFlags & PRESSED)
element->SetAttribute("pressed", "true");
if (triggerFlags & PRESSING)
element->SetAttribute("pressing", "true");
if (triggerFlags & RELEASED)
element->SetAttribute("released", "true");
if (triggerFlags & ALT_MODIFIER)
element->SetAttribute("alt", "true");
if (triggerFlags & CTRL_MODIFIER)
element->SetAttribute("ctrl", "true");
if (triggerFlags & SHIFT_MODIFIER)
element->SetAttribute("shift", "true");
if (triggerFlags & NO_ALT_MODIFIER)
element->SetAttribute("noAlt", "true");
if (triggerFlags & NO_CTRL_MODIFIER)
element->SetAttribute("noCtrl", "true");
if (triggerFlags & NO_SHIFT_MODIFIER)
element->SetAttribute("noShift", "true");
if (triggerFlags & POV_WEAK)
element->SetAttribute("povWeak", "true");
if (triggerFlags & POV_STRONG)
element->SetAttribute("povStrong", "true");
}
static Ogre::String GetStringAttribute(const TiXmlElement* xmlElement, const char* name)
{
const char* value = xmlElement->Attribute(name);
if (value != 0)
return value;
else
return Ogre::StringUtil::BLANK;
}
};
}
#endif | [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
535
]
]
]
|
32119541573bbde1cd9324172def7575cb7e2940 | bfdfb7c406c318c877b7cbc43bc2dfd925185e50 | /stdlib/ffi/HSca_Float.cpp | a76602196bdf21525a7144802f95a8267768f72e | [
"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 | TIS-620 | C++ | false | false | 3,397 | cpp | /* -*- coding: sjis-dos; -*- */
/*
* copyright 2010 FUKUZAWA Tadashi. All rights reserved.
*/
#include <math.h>
#include "HSca_Float.h"
FFI_DEFINITION_START {
// StringBufferฬ๖ษถ๑\ป๐วม
StringBuffer* FFI_FUNC(concatToStringBuffer) (Value selfVal, StringBuffer* sb, hys32 mode)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
hyf32 self = selfVal.toFloat();
sb->sprintf("%g", self);
if (mode < 0)
sb->concat(":<Float>");
return sb;
}
DEEP_FFI_FUNC(hashCode) {
HMD_ASSERT(numArgs == 0);
hyf32 self = context->popFloat();
context->pushInt((hys32)self);
}
// "+@" PvX
DEEP_FFI_FUNC_X(2b40)
{
HMD_ASSERT(numArgs == 0);
(void)context;
//hyf32 self = context->popFloat();
//context->pushFloat(self);
}
// "+" มZ
hyf32 FFI_FUNC_X(2b) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() + x;
}
// "-@" P}CiX
hyf32 FFI_FUNC_X(2d40) (Value selfVal)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return -selfVal.toFloat();
}
// "-" ธZ
hyf32 FFI_FUNC_X(2d) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() - x;
}
// "*" ๆZ
hyf32 FFI_FUNC_X(2a) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() * x;
}
// "/" Z
DEEP_FFI_FUNC_X(2f)
{
HMD_ASSERT(numArgs == 1);
hyf32 self = context->popFloat();
hyf32 o = context->popFloat();
context->pushFloat(self / o);
}
// "**" ืซๆ
hyf32 FFI_FUNC_X(2a2a) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return powf(selfVal.toFloat(), x);
}
// "==" ไr
bool FFI_FUNC_X(3d3d) (Value selfVal, Value x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
if (x.type->symCheck(HSym_Float)) {
return selfVal.toFloat() == x.toFloat();
} else {
return false;
}
}
// "<=>" ไr
hys32 FFI_FUNC_X(3c3d3e) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
hyf32 self = selfVal.toFloat();
if (self == x)
return 0;
else if (self < x)
return -1;
else
return 1;
}
// "<" ไr
bool FFI_FUNC_X(3c) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() < x;
}
// "<=" ไr
bool FFI_FUNC_X(3c3d) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() <= x;
}
// ">" ไr
bool FFI_FUNC_X(3e) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() > x;
}
// ">=" ไr
bool FFI_FUNC_X(3e3d) (Value selfVal, hyf32 x)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return selfVal.toFloat() >= x;
}
// Intป (0ษ฿ขฎ)
hys32 FFI_FUNC(toInt) (Value selfVal)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return (hys32)selfVal.toFloat();
}
// Intป (ณฬภ๐zฆศขฎ)
hys32 FFI_FUNC(floor) (Value selfVal)
{
FFI_DEBUG_ASSERT_INSTANCEMETHOD(selfVal);
return (hys32)floorf(selfVal.toFloat());
}
} FFI_DEFINITION_END
| [
"[email protected]"
]
| [
[
[
1,
150
]
]
]
|
c5552c9bb4008744374638aec5fd2ca82696978e | d0cf8820b4ad21333e15f7cec1e4da54efe1fdc5 | /DES_GOBSTG/DES_GOBSTG/Core/DataMap.cpp | 719910872cda016d614916deb897570aa7cb027f | []
| no_license | CBE7F1F65/c1bf2614b1ec411ee7fe4eb8b5cfaee6 | 296b31d342e39d1d931094c3dfa887dbb2143e54 | 09ed689a34552e62316e0e6442c116bf88a5a88b | refs/heads/master | 2020-05-30T14:47:27.645751 | 2010-10-12T16:06:11 | 2010-10-12T16:06:11 | 32,192,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,269 | cpp | #include "Data.h"
dataMapTable dataMap[] =
{
{"_DATASTART_", 0xffffffff},
{"_E", 0x00100000},
{"_N", 0x00200000},
{"_H", 0x00300000},
{"_X", 0x00400000},
{"_P", 0x00500000},
{"_L", 0x00600000},
{"_A", 0x00010000},
{"_B", 0x00020000},
{"_C", 0x00030000},
{"_D", 0x00040000},
{"Header", 0x01000000},
{"GameVersion", 0x01010000},
{"Signature", 0x01020000},
{"FileType", 0x01030000},
{"Top", 0x02000000},
{"Score", 0x02010000},
{"LastStage", 0x02020000},
{"Username", 0x02030000},
{"Year", 0x02040000},
{"Month", 0x02050000},
{"Day", 0x02060000},
{"Hour", 0x02070000},
{"Minute", 0x02080000},
{"Lost", 0x02090000},
{"CircleRate", 0x020A0000},
{"FastRate", 0x020B0000},
{"AllTime", 0x020C0000},
{"RangeGet", 0x020D0000},
{"MaxPlayer", 0x020E0000},
{"Point", 0x020F0000},
{"Aliveness", 0x02100000},
{"Miss", 0x02110000},
{"Bomb", 0x02120000},
{"Continue", 0x02130000},
{"Pause", 0x02140000},
{"GetRange", 0x02150000},
{"Range", 0x03000000},
{"GetGame", 0x03010000},
{"MeetGame", 0x03020000},
{"GetPractice", 0x03030000},
{"MeetPractice", 0x03040000},
{"TopBonus", 0x03050000},
{"StagePractice", 0x04000000},
{"TryTime", 0x04010000},
{"TopScore", 0x04020000},
{"Total", 0x05000000},
{"PlayTime", 0x05010000},
{"ClearTime", 0x05020000},
{"PracticeTime", 0x05030000},
{"FirstRunTime", 0x05040000},
{"TotalPlayTime", 0x05050000},
{"IsRange", 0x06010000},
{"RangeNumber", 0x06020000},
{"RangeName", 0x06030000},
{"TimeLimit", 0x06040000},
{"Remain", 0x06050000},
{"EnemyName", 0x06060000},
{"EnemyPinYin", 0x06070000},
{"Bonus", 0x06080000},
{"TurnToScene", 0x06090000},
{"IsWait", 0x060A0000},
{"AutoRank", 0x060B0000},
{"Explain", 0x060C0000},
{"Music", 0x07000000},
{"MusicName", 0x07010000},
{"MusicFileName", 0x07020000},
{"StartPos", 0x07030000},
{"EndPos", 0x07040000},
{"LoopPos", 0x07050000},
{"CustomConst", 0x08000000},
{"StringDesc", 0x09000000},
{"_RESOURCESTART_", 0xffffffff},
//////////RESOURCE//////////
{"FileName", 0x10010000},
{"Name", 0x10020000},
{"Type", 0x10030000},
{"Font", 0x12000000},
{"FontName", 0x12010000},
{"DataFile", 0x13000000},
{"BinFile", 0x13010000},
{"RangeAccessFile", 0x13020000},
{"ScriptFile", 0x13030000},
{"StringDescFile", 0x13210000},
{"CustomConstFile", 0x13220000},
{"RangeDefineFile", 0x13230000},
{"MusicDefineFile", 0x13240000},
{"Package", 0x20000000},
{"Texture", 0x21000000},
{"SoundEffect", 0x22000000},
{"Ghost", 0x23000000},
{"Effectsys", 0x24000000},
{"Folder", 0x32000000},
{"ScriptFolder", 0x32010000},
{"SnapShotFolder", 0x32020000},
{"ReplayFolder", 0x32030000},
{"DataFolder", 0x32040000},
{"EffectsysFolder", 0x32050000},
{"Extension", 0x33000000},
{"ScriptExt_7", 0x33010000},
{"ReplayExt_7", 0x33020000},
{"ReplayHeader", 0x40000000},
{"Signature_11", 0x40010000},
{"TempSign_3", 0x40020000},
{"CompleteSign_3", 0x40030000},
{"Tag_3", 0x40040000},
{"_END_", 0xffffffff}
}; | [
"CBE7F1F65@e00939f0-95ee-11de-8df0-bd213fda01be"
]
| [
[
[
1,
133
]
]
]
|
cf680fbb66ca5a840c8b4a6ad4dbdf7a9ce4ce37 | 35ae0e99b77bc61a60fbeb75a9e9ba5f659349b9 | /include/PNM.h | e023c06e37779c2176a250521da3caa189a79eab | []
| no_license | lamhaianh/SPIL | 308636ca64bfffe3b39108ef8ca3fc6ab0767210 | 48cb8db15d4be84c0bbf1dac1b1fee4aff98ee7c | refs/heads/master | 2021-01-23T00:20:27.088278 | 2011-10-01T06:29:35 | 2011-10-01T06:29:35 | 2,493,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 155 | h | #ifndef PNM_H
#define PNM_H
class PNM
{
public:
PNM();
virtual ~PNM();
protected:
private:
};
#endif // PNM_H
| [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
e823c4a35856019824db9ab2a16b4d27c18a9db9 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Collide/Util/KdTree/Mediator/hkpCollidableMediator.h | 2df91bf52324ba1c2f9da9362a4d9995379af5d9 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDABLE_MEDIATOR_H
#define HK_COLLIDABLE_MEDIATOR_H
#include <Common/Internal/KdTree/Build/hkKdTreeBuilder.h>
// Collidable mediator
class hkpCollidableMediator : public hkKdTreeBuildInput::Mediator
{
public:
hkpCollidableMediator( hkArray<const class hkpCollidable*>& collidables, const class hkpWorld* world = HK_NULL );
virtual int getNumPrimitives() const;
virtual void projectPrimitive( hkPrimitiveId primitiveId, hkKdTreeProjectedEntry& bounds );
virtual hkPrimitiveId getPrimitiveId( int primitiveIdx ) const;
public:
hkArray<const hkpCollidable*>& m_collidables;
};
#endif //HK_COLLIDABLE_MEDIATOR_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
48
]
]
]
|
5c3a54c0863318541991b8dc990a179dfc69c887 | 975d45994f670a7f284b0dc88d3a0ebe44458a82 | /servidor/WarBugsServer/WarBugsServer/Includes/CPersonagemJogador.cpp | 6fa9a74258d3c4574088c7cc169c7bfcda4bd72e | []
| no_license | phabh/warbugs | 2b616be17a54fbf46c78b576f17e702f6ddda1e6 | bf1def2f8b7d4267fb7af42df104e9cdbe0378f8 | refs/heads/master | 2020-12-25T08:51:02.308060 | 2010-11-15T00:37:38 | 2010-11-15T00:37:38 | 60,636,297 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 15,216 | cpp | /*
* Classe CPersonagemJogador
*
* Autor: Eder Figueiredo
*
* Objetivo: Descrever cada personagem controlado por um jogador
*
*/
#ifndef _CPERSONAGEMJOGADOR_CPP_
#define _CPERSONAGEMJOGADOR_CPP_
#include "CPersonagemJogador.h"
#ifndef _CCENARIO_H_
#include "CCenario.h"
#endif
CPersonagemJogador::CPersonagemJogador()
{
initCPersonagem();
setID(-1);
coordenada = new Ponto();
dinheiro = 0;
habilidadesPrimarias = new CHabilidades();
bonusPrimario = new CBonusPrimario();
inventario = new CBolsa();
habilidadesSecundarias = new CHabilidadesSecundarias();
bonusSecundario = new CBonusSecundario();
status = new CBuffList();
setState(E_PARADO);
setMoney(0);
setBolsa(new CBolsa());
setStats(new CHabilidadesSecundarias());
setBonus(new CBonusSecundario());
setBaseStats(new CHabilidades());
setBaseBonus(new CBonusPrimario());
setBuffs(new CBuffList());
_pontoDistribuir = 0;
_lealdade = new CLealdade();
_quest = new CQuest(this);
//_party = new irr::core::array<CPersonagemJogador*>();
//_friends = new irr::core::array<CPersonagemJogador*>();
_jogadorID = 0;
alvo = NULL;
_bareHands = true;
_ataque = 0;
_dano = 0;
_range = 0;
_speed = 0;
_tradeOn = false;
_tradeConfirmation = false;
_idTrader = -1;
_idItemTrade = -1;
_idMoneyTrade = -1;
_skillPontoDistribuir = 0;
_skillLevel[0] = 0;
_skillLevel[1] = 0;
_skillLevel[2] = 0;
}
//Getters e setters
int CPersonagemJogador::getSkillLevel(int skillIndex)
{
if((skillIndex > 0)&&(skillIndex < 3))
{
return(_skillLevel[skillIndex]);
}
else
{
return(-1);
}
}
int CPersonagemJogador::getAttack()
{
if(_range <= MAXMELEERANGE)
return(_ataque + getBonus()->getTotalBonusOf(ATTACKMELEE));
else
return(_ataque + getBonus()->getTotalBonusOf(ATTACKRANGED));
}
int CPersonagemJogador::getDamage()
{
if(_range <= MAXMELEERANGE)
return(_dano + getBonus()->getTotalBonusOf(DAMAGEMELEE));
else
return(_dano + getBonus()->getTotalBonusOf(DAMAGERANGED));
}
bool CPersonagemJogador::isTradeOn()
{
return(_tradeOn);
}
bool CPersonagemJogador::isTradeConfirmated()
{
return(_tradeConfirmation);
}
int CPersonagemJogador::getIDTrader()
{
return(_idTrader);
}
int CPersonagemJogador::getIDItemTrade()
{
return(_idItemTrade);
}
int CPersonagemJogador::getIDMoneyTrade()
{
return(_idMoneyTrade);
}
CLealdade *CPersonagemJogador::getLoyalty()
{
return(_lealdade);
}
CEquipamento *CPersonagemJogador::getEquip()
{
return(_equip);
}
int CPersonagemJogador::getPointsLeft()
{
return(_pontoDistribuir);
}
int CPersonagemJogador::getSkillPointsLeft()
{
return(_skillPontoDistribuir);
}
CClientSocketThread *CPersonagemJogador::getSocket()
{
return(_socketJogador);
}
//Setters
void CPersonagemJogador::setPointsToDistribute(int points)
{
_pontoDistribuir = points;
}
void CPersonagemJogador::setSkillPointsToDistribute(int value)
{
_skillPontoDistribuir = value;
}
void CPersonagemJogador::setEquip(CEquipamento *equip)
{
_equip = equip;
}
/*void CPersonagemJogador::setStatus(CBuff *status)
{
_status = status;
}*/
void CPersonagemJogador::setLoyalty(CLealdade *lealdade)
{
_lealdade = lealdade;
}
/*void CPersonagemJogador::setParty(irr::core::array<CPersonagemJogador*> *lista)
{
_party = lista;
}
void CPersonagemJogador::setFriends(irr::core::array<CPersonagemJogador*> *lista)
{
_friends = lista;
}*/
void CPersonagemJogador::setPlayer(int playerID)
{
_jogadorID = playerID;
}
void CPersonagemJogador::setBareHands(bool isBareHands)
{
_bareHands = isBareHands;
}
void CPersonagemJogador::setAttack(int ataque)
{
_ataque = ataque;
}
void CPersonagemJogador::setDamage(int dano)
{
_dano = dano;
}
void CPersonagemJogador::setRange(int range)
{
_range = range;
}
void CPersonagemJogador::setSpeed(int speed)
{
_speed = speed;
}
void CPersonagemJogador::setTradeOn(bool value)
{
_tradeOn = value;
}
void CPersonagemJogador::setTradeConfirmated(bool value)
{
_tradeConfirmation = value;
}
void CPersonagemJogador::setIDTrader(int value)
{
_idTrader = value;
}
void CPersonagemJogador::setIDItemTrade(int value)
{
_idItemTrade = value;
}
void CPersonagemJogador::setIDMoneyTrade(int value)
{
_idMoneyTrade = value;
}
void CPersonagemJogador::setSocket(CClientSocketThread * socket)
{
_socketJogador = socket;
}
//Outros Métodos
//Manipulação de itens
int CPersonagemJogador::haveItem(CItem * item)
{
return(inventario->haveItem(item->getID()));
}
void CPersonagemJogador::addItem(CItem *item)
{
if(inventario->size() < MAXITENS)
{
inventario->addItem(item);
}
}
void CPersonagemJogador::dropItem(CItem *item)
{
CBolsa *temp = new CBolsa();
if((item->isDropable())&&(inventario->removeItem(item->getID()) != NULL))
{
temp->addItem(item);
temp->setPosition(this->getPosition());
getScene()->addBag(temp);
}
else
{
//ERRO: O ITEM NÃO ESTÁ NO INVENTRÁRIO
}
temp = NULL;
delete temp;
}
void CPersonagemJogador::useItem(CItem *item)
{
if(haveItem(item))
{
if(item->getType() == USO)
{
switch(item->getAtribute())
{
case NENHUM:
break;
case PV:
habilidadesSecundarias->addPV(item->getValue());
break;
case PM:
habilidadesSecundarias->addPM(item->getValue());
break;
default:
break;
}
getBolsa()->removeItem(item->getID());
delete item;
}
else
{
//ERRO: EQUIPAMENTOS NÃO PODEM SER USADOS
}
}
else
{
//ERRO: NÃO PÓSSUI O ITEM INDICADO
}
}
void CPersonagemJogador::equip(CItem *item)
{
//Possui o item?
if(this->haveItem(item))
{
//É arma?
if(item->getType() == ARMA)
{
//Estou equipado?
if(_equip->arma == NULL)//Se não estou equipado
{
_equip->arma = (CWeapon*)item;
item->setEstado(EQUIPADO);
habilidadesSecundarias->generate(habilidadesPrimarias, _equip);
if(_equip->arma->getRange() <= MAXMELEERANGE)
{
_ataque = habilidadesSecundarias->getMeleeAttack();
_dano = habilidadesSecundarias->getMeleeDamage();
}
else
{
_ataque = habilidadesSecundarias->getRangedAttack();
_dano = habilidadesSecundarias->getRangedDamage();
}
_range = _equip->arma->getRange();
_speed = _equip->arma->getSpeed();
_bareHands = false;
}
else if(inventario->size() < MAXITENS)//Se estou equipado e possuo espaço no inventário
{
CItem *temp = new CWeapon();
temp = _equip->arma;
inventario->addItem(temp);
_equip->arma = (CWeapon*)item;
temp = NULL;
delete temp;
habilidadesSecundarias->generate(habilidadesPrimarias, _equip);
if(_equip->arma->getRange() <= MAXMELEERANGE)
{
_ataque = habilidadesSecundarias->getMeleeAttack();
_dano = habilidadesSecundarias->getMeleeDamage();
}
else
{
_ataque = habilidadesSecundarias->getRangedAttack();
_dano = habilidadesSecundarias->getRangedDamage();
}
_range = _equip->arma->getRange();
_speed = _equip->arma->getSpeed();
_bareHands = false;
}
else
{
//ERRO: INVENTÁRIO CHEIO
}
}
else if(item->getType() == ARMADURA)
{
if(_equip->armadura == NULL)
{
_equip->armadura = (CArmor*)item;
item->setEstado(EQUIPADO);
habilidadesSecundarias->generate(habilidadesPrimarias, _equip);
}
else if(inventario->size() < MAXITENS)
{
CItem *temp = new CArmor();
temp = _equip->armadura;
inventario->addItem(temp);
_equip->armadura = (CArmor*)item;
habilidadesSecundarias->generate(habilidadesPrimarias, _equip);
temp = NULL;
delete temp;
}
else
{
//ERRO: INVENTÁRIO CHEIO
}
}
else
{
//ERRO: O ITEM NÃO É UMA ARMA/ARMADURA
}
}
else
{
//ERRO: O ITEM NÃO ESTÁ NO INVENTRÁRIO
}
}
void CPersonagemJogador::unequip(CItem *item)
{
if(_equip->arma->getID() == item->getID())
{
if(inventario->size() < MAXITENS)
{
_equip->arma = NULL;
habilidadesSecundarias->generate(habilidadesPrimarias, _equip);
item->setEstado(NAMOCHILA);
inventario->addItem(item);
_ataque = habilidadesPrimarias->getFOR();
_dano = habilidadesPrimarias->getFOR();
_range = MAXMELEERANGE;
_speed = habilidadesPrimarias->getAGI();
_bareHands = true;
}
else
{
//ERRO: O INVENTÁRIO ESTÁ CHEIO
}
}
else if(_equip->armadura->getID() == item->getID())
{
_equip->arma = NULL;
item->setEstado(NAMOCHILA);
}
else
{
//ERRO: O ITEM ESPECIFICADO NÃO ESTÁ EQUIPADO
}
}
//Friends Manipulation
/*int CPersonagemJogador::isFriend(CPersonagemJogador *jogador)
{
return(_friends->binary_search_const(jogador));
}
void CPersonagemJogador::addFriend(CPersonagemJogador *newFriend)
{
if(_friends->size() < MAXFRIENDS)
{
_friends->push_back(newFriend);
_friends->sort();
}
else return; // ERRO: NÚMERO MÁXIMO DE AMIGOS PERMITIDOS ATINGIDO
}
void CPersonagemJogador::removeFriend(CPersonagemJogador *jogador)
{
irr::s32 i = this->isFriend(jogador);
if(i >= 0)
{
_friends->erase(i);
}
else
{
//ERRO: O AMIGO NÃO CONSTA NA LISTA
}
return;
}
//Party Manipulation
bool CPersonagemJogador::isPartyLeader()
{
return((!_party->empty())&&(_party->getLast() == this));
}
int CPersonagemJogador::isPartyMember(CPersonagemJogador* jogador)
{
return(_party->binary_search_const(jogador));
}
void CPersonagemJogador::addPartyMember (CPersonagemJogador *jogador)
{
if((this->isPartyLeader()) && (!this->isPartyMember(jogador)))
{
_party->push_front(jogador);
_party->sort();
}
else
{
//ERRO: NÃO É LÍDER DO GRUPO
}
}
void CPersonagemJogador::removePartyMember(CPersonagemJogador *jogador)
{
if((_party->empty()) && ((this->isPartyMember(jogador))>=0))
{
_party->erase(this->isPartyMember(jogador));
}
else
{
//ERRO: O JOGADOR NÃO PERTENCE AO GRUPO
}
return;
}
void CPersonagemJogador::givePartyAlliesID(irr::core::array<CPersonagemJogador*> *lista)
{
lista = _party;
}
void CPersonagemJogador::updateAlliesID()
{
}
void CPersonagemJogador::createParty()
{
if(_party->empty())
{
_party->push_back(this);
}
else
{
//ERRO: JÁ FAZ PARTE DE UMA PARTY
}
}
void CPersonagemJogador::joinParty(CPersonagemJogador *lider)
{
if(_party->empty())
{
lider->addPartyMember(this);
lider->givePartyAlliesID(_party);
}
else
{
//ERRO: JÁ FAZ PARTE DE UMA PARTY
}
}
void CPersonagemJogador::leaveParty(CPersonagemJogador *lider)
{
if(!(_party->empty()))
{
lider->removePartyMember(this);
_party->clear();
}
}*/
//Quest
void CPersonagemJogador::acceptQuest(CQuest *quest)
{
_quest = new CQuest(this);
_quest->setPlayer(quest->getPlayer());
_quest->setNPC(quest->getNPC());
_quest->setRequestedItem(quest->getRequestedItem());
_quest->setRequestedEnemy(quest->getRequestedEnemy());
_quest->setRequestedNumberOfItens(quest->getRequestedNumberOfItens());
_quest->setRequestedNumberOfEnemies(quest->getRequestedNumberOfEnemies());
_quest->setReward(quest->getReward());
_quest->setXPReward(quest->getXPReward());
_quest->setItemReward(quest->getItemReward());
_quest->setLoyaltyReward(quest->getLoyaltyReward());
_quest->beginQuest();
}
//Speaking
void CPersonagemJogador::speakToPlayer(CPersonagemJogador *alvo){}
void CPersonagemJogador::speakToNPC(CPersonagem *alvo){}
//Batalha
void CPersonagemJogador::takeDamage(int damage, CPersonagem *atkr)
{
if((_equip != NULL)&&(_equip->armadura != NULL))
{
int dam = damage/4;
damage = (damage*3)/4;
_equip->armadura->setDurability(_equip->armadura->getDurability()-dam);
checkInventory();
habilidadesSecundarias->addPV((-1)*damage);
divisorxp->addAttacker(atkr, damage);
}
else
{
habilidadesSecundarias->addPV((-1)*damage);
divisorxp->addAttacker(atkr, damage);
}
}
int CPersonagemJogador::getDEF()
{
if((_equip!= NULL)&&(_equip->armadura!=NULL))
return(this->getStats()->getDefense()+_equip->armadura->getDef());
else
return(this->getStats()->getDefense());
}
bool CPersonagemJogador::tryAttack()
{
int testValue = 0;
if((this->getStats()->getChargeTime() == 100)&&(this->getDistanceToPoint(alvo->getPosition()) <= _range))
{
this->getStats()->addChargeTime((-1)*CTATTACKCOST);
testValue = _ataque;
if((_equip != NULL)&&(_equip->arma != NULL)&&(clock()%10 == 0))
{
_equip->arma->setDurability(_equip->arma->getDurability()-1);
checkInventory();
}
if(testValue > alvo->getDEF())
{
return(true);
}
else
{
return(false);
}
}
else
{
return(false);
}
}
void CPersonagemJogador::attack()
{
if(tryAttack())
{
if(_bareHands)
{
alvo->takeDamage(_dano, this);
}
else
{
int dano = _dano +((clock()%(_equip->arma->getMaxDamage() - _equip->arma->getMinDamage()))+_equip->arma->getMinDamage());
}
}
}
//Level Up
void CPersonagemJogador::updateXP(){/*Acessa banco de dados pra atualizar _xpToNextLv*/}
bool CPersonagemJogador::haveLevelUp()
{
if(experiencia >= xpToNextLv)
{
_pontoDistribuir = _pontoDistribuir + 5;
nivel = nivel + 1;
if(nivel%2 == 0)
{
_skillPontoDistribuir = _skillPontoDistribuir + 1;
}
updateXP();
return(true);
}
else return(false);
}
bool CPersonagemJogador::haveLevelDown()
{
if(experiencia < 0)
{
if(nivel%2 == 0)
{
_skillPontoDistribuir = _skillPontoDistribuir - 1;
}
nivel = nivel - 1;
_pontoDistribuir = _pontoDistribuir - 5;
updateXP();
return(true);
}
else return(false);
}
void CPersonagemJogador::distibutePoints(int points, int atribute)
{
if(points <= _pontoDistribuir)
{
switch(atribute)
{
case 0:
habilidadesPrimarias->addFOR(points);
_pontoDistribuir = _pontoDistribuir - points;
break;
case 1:
habilidadesPrimarias->addDES(points);
_pontoDistribuir = _pontoDistribuir - points;
break;
case 2:
habilidadesPrimarias->addAGI(points);
_pontoDistribuir = _pontoDistribuir - points;
break;
case 3:
habilidadesPrimarias->addRES(points);
_pontoDistribuir = _pontoDistribuir - points;
break;
case 4:
habilidadesPrimarias->addINS(points);
_pontoDistribuir = _pontoDistribuir - points;
break;
default:
break;
}
}
return;
}
void CPersonagemJogador::distibuteSkillPoints(int points, int skillIndex)
{
if((points <= _skillPontoDistribuir)&&((skillIndex > 0)&&(skillIndex < MAXSKILLNUMBER)))
{
_skillLevel[skillIndex] = _skillLevel[skillIndex] + points;
}
}
void CPersonagemJogador::die()
{
divisorxp->giveXP();
}
void CPersonagemJogador::checkInventory()
{
if(_equip != NULL)
{
if(_equip->arma != NULL)
{
if(!(_equip->arma->getDurability() > 0))
{
_equip->arma = NULL;
}
}
if(_equip->armadura != NULL)
{
if(!(_equip->armadura->getDurability() > 0))
{
_equip->armadura = NULL;
}
}
}
}
void CPersonagemJogador::update()
{
status->executeBuffs(this, this->status);
}
#endif | [
"[email protected]"
]
| [
[
[
1,
667
]
]
]
|
893e08471e439513761660939bb7e32e1bc813d5 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /TEST_MyGUI_Source/MyGUIEngine/include/TSize.h | 3a3c00e95d18ec4ab0060a90c1092768bb998571 | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,506 | h | /*!
@file
@author Albert Semenov
@date 11/2007
@module
*/
#ifndef __TSIZE_H__
#define __TSIZE_H__
#include <string>
#include <sstream>
namespace types
{
template< typename T > struct TSize
{
T width, height;
TSize() : width( 0 ), height( 0 ) { }
TSize( T const & w, T const & h) : width( w ), height( h ) { }
TSize( TSize const & o ) : width( o.width ), height( o.height ) { }
explicit TSize(const std::string& _value) {*this = parse(_value);}
inline TSize & operator-=( TSize const & o )
{
width -= o.width;
height -= o.height;
return *this;
}
inline TSize & operator+=( TSize const & o )
{
width += o.width;
height += o.height;
return *this;
}
inline TSize operator-( TSize const & o ) const
{
return TSize(width - o.width, height - o.height);
}
inline TSize operator+( TSize const & o ) const
{
return TSize(width + o.width, height + o.height);
}
inline TSize & operator=( TSize const & o )
{
width = o.width;
height = o.height;
return *this;
}
inline bool operator==( TSize const & o ) const
{
return ((width == o.width) && (height == o.height));
}
inline bool operator!=( TSize const & o ) const
{
return ! ((width == o.width) && (height == o.height));
}
inline void clear()
{
width = height = 0;
}
inline void set( T const & w, T const & h)
{
width = w;
height = h;
}
inline void swap(TSize& _value)
{
TSize tmp = _value;
_value = *this;
*this = tmp;
}
inline bool empty() const
{
return ((width == 0) && (height == 0));
}
inline std::string print() const
{
std::ostringstream stream;
stream << *this;
return stream.str();
}
inline static TSize<T> parse(const std::string& _value)
{
TSize<T> ret;
std::istringstream stream(_value);
stream >> ret;
return ret;
}
inline friend std::ostream& operator << ( std::ostream& _stream, const TSize<T>& _value )
{
_stream << _value.width << " " << _value.height;
return _stream;
}
inline friend std::istream& operator >> ( std::istream& _stream, TSize<T>& _value )
{
_stream >> _value.width >> _value.height;
if (_stream.fail()) _value.clear();
return _stream;
}
};
} // namespace types
#endif // __TSIZE_H__
| [
"[email protected]"
]
| [
[
[
1,
121
]
]
]
|
b176a144bb7ec2d0268ebd6efbaaac4c85a40d2f | fb71c08b1c1e7ea4d7abc82e65b36272069993e1 | /src/keys.hpp | e37fe956c2ab20356d7a8ee3193be4a66f0f42e2 | []
| no_license | cezarygerard/fpteacher | 1bb4ea61bc86cbadcf47a810c8bb441f598d278a | 7bdfcf7c047caa9382e22a9d26a2d381ce2d9166 | refs/heads/master | 2021-01-23T03:47:54.994165 | 2010-03-25T01:12:04 | 2010-03-25T01:12:04 | 39,897,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,232 | hpp | /** @file keys.hpp
* @author Rafal Malinowski
* @date 2009.12.09
* @version 0.6
* @brief Plik naglowkowy keys zawiera definicje enum eKey ktora ulatwia dzialanie klasy Cinput
*
*
*/
#ifndef KEYS
#define KEYS
#include "SDL.h"
//using namespace std;
///maps all keys to sdl keys
typedef enum klawisze{
KEY_UNKNOWN = SDLK_UNKNOWN,
KEY_FIRST = SDLK_FIRST,
KEY_BACKSPACE = SDLK_BACKSPACE,
KEY_TAB = SDLK_TAB,
KEY_CLEAR = SDLK_CLEAR,
KEY_RETURN = SDLK_RETURN,
KEY_PAUSE = SDLK_PAUSE,
KEY_ESCAPE = SDLK_ESCAPE,
KEY_SPACE = SDLK_SPACE,
KEY_EXCLAIM = SDLK_EXCLAIM,
KEY_QUOTEDBL = SDLK_QUOTEDBL,
KEY_HASH = SDLK_HASH,
KEY_DOLLAR = SDLK_DOLLAR,
KEY_AMPERSAND = SDLK_AMPERSAND,
KEY_QUOTE = SDLK_QUOTE,
KEY_LEFTPAREN = SDLK_LEFTPAREN,
KEY_RIGHTPAREN = SDLK_RIGHTPAREN,
KEY_ASTERISK = SDLK_ASTERISK,
KEY_PLUS = SDLK_PLUS,
KEY_COMMA = SDLK_COMMA,
KEY_MINUS = SDLK_MINUS,
KEY_PERIOD = SDLK_PERIOD,
KEY_SLASH = SDLK_SLASH,
KEY_0 = SDLK_0,
KEY_1 = SDLK_1,
KEY_2 = SDLK_2,
KEY_3 = SDLK_3,
KEY_4 = SDLK_4,
KEY_5 = SDLK_5,
KEY_6 = SDLK_6,
KEY_7 = SDLK_7,
KEY_8 = SDLK_8,
KEY_9 = SDLK_9,
KEY_COLON = SDLK_COLON,
KEY_SEMICOLON = SDLK_SEMICOLON,
KEY_LESS = SDLK_LESS,
KEY_EQUALS = SDLK_EQUALS,
KEY_GREATER = SDLK_GREATER,
KEY_QUESTION = SDLK_QUESTION,
KEY_AT = SDLK_AT,
/*
Skip uppercase letters
*/
KEY_LEFTBRACKET = SDLK_LEFTBRACKET,
KEY_BACKSLASH = SDLK_BACKSLASH,
KEY_RIGHTBRACKET = SDLK_RIGHTBRACKET,
KEY_CARET = SDLK_CARET,
KEY_UNDERSCORE = SDLK_UNDERSCORE,
KEY_BACKQUOTE = SDLK_BACKQUOTE,
KEY_a = SDLK_a,
KEY_b = SDLK_b,
KEY_c = SDLK_c,
KEY_d = SDLK_d,
KEY_e = SDLK_e,
KEY_f = SDLK_f,
KEY_g = SDLK_g,
KEY_h = SDLK_h,
KEY_i = SDLK_i,
KEY_j = SDLK_j,
KEY_k = SDLK_k,
KEY_l = SDLK_l,
KEY_m = SDLK_m,
KEY_n = SDLK_n,
KEY_o = SDLK_o,
KEY_p = SDLK_p,
KEY_q = SDLK_q,
KEY_r = SDLK_r,
KEY_s = SDLK_s,
KEY_t = SDLK_t,
KEY_u = SDLK_u,
KEY_v = SDLK_v,
KEY_w = SDLK_w,
KEY_x = SDLK_x,
KEY_y = SDLK_y,
KEY_z = SDLK_z,
KEY_DELETE = SDLK_DELETE,
/* End of ASCII mapped keysyms */
/* Numeric keypad */
KEY_KP0 = SDLK_KP0,
KEY_KP1 = SDLK_KP1,
KEY_KP2 = SDLK_KP2,
KEY_KP3 = SDLK_KP3,
KEY_KP4 = SDLK_KP4,
KEY_KP5 = SDLK_KP5,
KEY_KP6 = SDLK_KP6,
KEY_KP7 = SDLK_KP7,
KEY_KP8 = SDLK_KP8,
KEY_KP9 = SDLK_KP9,
KEY_KP_PEROID = SDLK_KP_PERIOD,
KEY_KP_DIVIDE = SDLK_KP_DIVIDE,
KEY_KP_MULTIPLY = SDLK_KP_MULTIPLY,
KEY_KP_MINUS = SDLK_KP_MINUS,
KEY_KP_PLUS = SDLK_KP_PLUS,
KEY_KP_ENTER = SDLK_KP_ENTER,
KEY_KP_EQUALS = SDLK_KP_EQUALS,
/* Arrows + Home/End pad */
KEY_UP = SDLK_UP,
KEY_DOWN = SDLK_DOWN,
KEY_RIGHT = SDLK_RIGHT,
KEY_LEFT = SDLK_LEFT,
KEY_INSERT = SDLK_INSERT,
KEY_HOME = SDLK_HOME,
KEY_END = SDLK_END,
KEY_PAGEUP = SDLK_PAGEUP,
KEY_PAGEDOWN = SDLK_PAGEDOWN,
/* Function keys */
KEY_F1 = SDLK_F1,
KEY_F2 = SDLK_F2,
KEY_F3 = SDLK_F3,
KEY_F4 = SDLK_F4,
KEY_F5 = SDLK_F5,
KEY_F6 = SDLK_F6,
KEY_F7 = SDLK_F7,
KEY_F8 = SDLK_F8,
KEY_F9 = SDLK_F9,
KEY_F10 = SDLK_F10,
KEY_F11 = SDLK_F11,
KEY_F12 = SDLK_F12,
KEY_F13 = SDLK_F13,
KEY_F14 = SDLK_F14,
KEY_F15 = SDLK_F15,
/* Key state modifier keys */
KEY_NUMLOCK = SDLK_NUMLOCK,
KEY_CAPSLOCK = SDLK_CAPSLOCK,
KEY_SCROLLOCK = SDLK_SCROLLOCK,
KEY_RSHIFT = SDLK_RSHIFT,
KEY_LSHFIT = SDLK_LSHIFT,
KEY_RCTRL = SDLK_RCTRL,
KEY_LCTRL = SDLK_LCTRL,
KEY_RALT = SDLK_RALT,
KEY_LALT = SDLK_LALT,
KEY_RMETA = SDLK_RMETA,
KEY_LMETA = SDLK_LMETA,
KEY_LSUPER = SDLK_LSUPER, /* Left "Windows" key */
KEY_RSUPER = SDLK_RSUPER, /* Right "Windows" key */
/* Miscellaneous function keys */
KEY_HELP = SDLK_HELP,
KEY_PRINT = SDLK_PRINT,
KEY_SYSREQ = SDLK_SYSREQ,
KEY_BREAK = SDLK_BREAK,
KEY_MENU = SDLK_MENU,
/* Add any other keys here */
} eKey;
#endif
//~~keys.hpp | [
"r.malinowski88@8e29c490-c8d6-11de-b6dc-25c59a28ecba",
"fester3000@8e29c490-c8d6-11de-b6dc-25c59a28ecba",
"czarek.zawadka@8e29c490-c8d6-11de-b6dc-25c59a28ecba"
]
| [
[
[
1,
3
],
[
5,
172
],
[
174,
174
]
],
[
[
4,
4
]
],
[
[
173,
173
]
]
]
|
569622156113f2a1a278ba860b59cf4bc2e04591 | 22438bd0a316b62e88380796f0a8620c4d129f50 | /libs/napl/lame_wrapper.cpp | d22840a36a2290a0fe356d43f5ee68532a9c1485 | [
"BSL-1.0"
]
| permissive | DannyHavenith/NAPL | 1578f5e09f1b825f776bea9575f76518a84588f4 | 5db7bf823bdc10587746d691cb8d94031115b037 | refs/heads/master | 2021-01-20T02:17:01.186461 | 2010-11-26T22:26:25 | 2010-11-26T22:26:25 | 1,856,141 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,765 | cpp | #include "stdafx.h"
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include "BladeMP3EncDLL.h"
#include ".\lame_wrapper.h"
struct lame_wrapper_impl
{
HINSTANCE handle;
BEINITSTREAM beInitStream;
BEENCODECHUNK beEncodeChunk;
BEDEINITSTREAM beDeinitStream;
BECLOSESTREAM beCloseStream;
BEWRITEVBRHEADER beWriteVBRHeader;
BEWRITEINFOTAG beWriteInfoTag;
lame_wrapper_impl()
: handle(0)
{
// nop
}
~lame_wrapper_impl()
{
if (handle)
{
::FreeLibrary( handle);
}
}
bool load( const char *lib_path = "lame_enc.dll")
{
handle = ::LoadLibrary( lib_path);
if (!handle)
{
return false;
}
// Get Interface functions from the DLL
beInitStream = (BEINITSTREAM) ::GetProcAddress(handle, TEXT_BEINITSTREAM);
beEncodeChunk = (BEENCODECHUNK) ::GetProcAddress(handle, TEXT_BEENCODECHUNK);
beDeinitStream = (BEDEINITSTREAM) ::GetProcAddress(handle, TEXT_BEDEINITSTREAM);
beCloseStream = (BECLOSESTREAM) ::GetProcAddress(handle, TEXT_BECLOSESTREAM);
beWriteVBRHeader= (BEWRITEVBRHEADER) ::GetProcAddress(handle,TEXT_BEWRITEVBRHEADER);
beWriteInfoTag = (BEWRITEINFOTAG) ::GetProcAddress(handle,TEXT_BEWRITEINFOTAG);
if(!beInitStream ||
!beEncodeChunk ||
!beDeinitStream ||
!beCloseStream ||
!beWriteVBRHeader)
{
return false;
}
return true;
};
};
lame_wrapper::lame_wrapper(void)
: pimpl(NULL)
{
lame_wrapper_impl *new_pimpl = new lame_wrapper_impl();
if (new_pimpl->load())
{
pimpl = new_pimpl;
}
else
{
delete new_pimpl;
}
}
lame_wrapper::~lame_wrapper(void)
{
delete pimpl;
}
lame_wrapper * lame_wrapper::get_instance(void)
{
static std::auto_ptr<lame_wrapper> the_instance_ptr( new lame_wrapper);
if (the_instance_ptr->is_ok())
{
return the_instance_ptr.get();
}
else
{
return 0;
}
return NULL;
}
bool lame_wrapper::is_ok(void)
{
return pimpl != NULL;
}
lame_wrapper_impl *lame_wrapper::get_impl(void)
{
if (!pimpl)
{
throw std::runtime_error( "mp3 encoder DLL could not be loaded");
}
return pimpl;
}
lame_stream * lame_wrapper::init_stream( unsigned long input_samplerate,
unsigned short output_bitrate,
unsigned short channels)
{
BE_CONFIG beConfig ={0,};
HBE_STREAM stream_handle;
memset(&beConfig,0,sizeof(beConfig)); // clear all fields
// use the LAME config structure
beConfig.dwConfig = BE_CONFIG_LAME;
// this are the default settings for testcase.wav
beConfig.format.LHV1.dwStructVersion = 1;
beConfig.format.LHV1.dwStructSize = sizeof(beConfig);
beConfig.format.LHV1.dwSampleRate = input_samplerate; // INPUT FREQUENCY
beConfig.format.LHV1.dwReSampleRate = 0; // DON"T RESAMPLE
if (channels == 2)
{
beConfig.format.LHV1.nMode = BE_MP3_MODE_JSTEREO; // OUTPUT IN STREO
} // if (channels == 2)
else if (channels ==1)
{
beConfig.format.LHV1.nMode = BE_MP3_MODE_MONO;
}
else
{
throw std::runtime_error( "mp3 output should be 1- or 2-channel");
}
beConfig.format.LHV1.dwBitrate = output_bitrate; // MINIMUM BIT RATE
beConfig.format.LHV1.nPreset = LQP_R3MIX; // QUALITY PRESET SETTING
beConfig.format.LHV1.dwMpegVersion = MPEG1; // MPEG VERSION (I or II)
beConfig.format.LHV1.dwPsyModel = 0; // USE DEFAULT PSYCHOACOUSTIC MODEL
beConfig.format.LHV1.dwEmphasis = 0; // NO EMPHASIS TURNED ON
beConfig.format.LHV1.bOriginal = TRUE; // SET ORIGINAL FLAG
beConfig.format.LHV1.bWriteVBRHeader = TRUE; // Write INFO tag
beConfig.format.LHV1.bNoRes = TRUE; // No Bit resorvoir
// Init the MP3 Stream
err = beInitStream(&beConfig, &dwSamples, &dwMP3Buffer, &hbeStream);
return NULL;
}
| [
"[email protected]"
]
| [
[
[
1,
156
]
]
]
|
826f9275b68354832ca7e3637c927913143f3e3a | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/test/example/cla/optional.cpp | 59d5838da60ef0aca33d9a80b38810f520c178d6 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | willrebuild/flyffsf | e5911fb412221e00a20a6867fd00c55afca593c7 | d38cc11790480d617b38bb5fc50729d676aef80d | refs/heads/master | 2021-01-19T20:27:35.200154 | 2011-02-10T12:34:43 | 2011-02-10T12:34:43 | 32,710,780 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | cpp | // (C) Copyright Gennadiy Rozental 2001-2006.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
// Boost.Runtime.Param
#include <boost/test/utils/runtime/cla/named_parameter.hpp>
#include <boost/test/utils/runtime/cla/parser.hpp>
namespace rt = boost::runtime;
namespace cla = boost::runtime::cla;
// STL
#include <iostream>
int main() {
char* argv[] = { "basic", "-abc", "25" };
int argc = 1;
cla::parser P;
try {
P << cla::named_parameter<std::string>( "abcd" ) - cla::optional;
P.parse( argc, argv );
if( P["abcd"] )
std::cout << "abcd = " << P.get<std::string>( "abcd" ) << std::endl;
else
std::cout << "not present" << std::endl;
std::string s = P.get<std::string>( "abcd" );
}
catch( rt::logic_error const& ex ) {
std::cout << "Logic error: " << ex.msg() << std::endl;
return -1;
}
///////////////////////////////////////////////////////////
try {
cla::parser P1;
P1 << cla::named_parameter<std::string>( "abc" ) - cla::optional;
argc = sizeof(argv)/sizeof(char*);
P1.parse( argc, argv );
if( P1["abc"] )
std::cout << "abc = " << P1.get<std::string>( "abc" ) << std::endl;
else
std::cout << "not present" << std::endl;
}
catch( rt::logic_error const& ex ) {
std::cout << "Logic error: " << ex.msg() << std::endl;
return -1;
}
return 0;
}
// EOF
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
66
]
]
]
|
661fbf4a9d323ab5ee4638aac2c8a1425c2b0634 | 41aafaf2fc329d82af50ecff758ccf82064bb73e | /ookCore/ookMsgDispatcher.h | 1a6a8145573236fc1787563471505e8dfa8232a4 | []
| no_license | base851/ookLibs | 6ec038aaa66f86dac973e7adc153170a9e5f2dee | b116048277d4adc385078faa2319cf7727a83e11 | refs/heads/master | 2021-01-20T04:32:37.770110 | 2011-07-19T05:30:02 | 2011-07-19T05:30:02 | 2,070,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | h | /*
Copyright © 2011, Ted Biggs
All rights reserved.
http://tbiggs.com
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.
- Neither the name of Ted Biggs, nor the names of his
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.
*/
#ifndef OOK_MESSAGE_DISPATCHER_H_
#define OOK_MESSAGE_DISPATCHER_H_
#include "ookLibs/ookCore/typedefs.h"
#include "ookLibs/ookCore/ookMsgObserverAbs.h"
//Define the ookMsgObserver function pointer
class ookMsgDispatcher
{
public:
ookMsgDispatcher();
virtual ~ookMsgDispatcher();
void RegisterObserver(ookMsgObserverAbs* obs);
void PostMsg(ookMessage* msg);
protected:
private:
vector<ookMsgObserverAbs*> _vObservers;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
65
]
]
]
|
22b0662e5bc0e6ad43def28dca0feea597c68908 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/QuestScripts/ArathiHighlands.cpp | 9c30d69f824506e89c83d499fb58499d2985ec96 | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,919 | cpp | /*
* WEmu Scripts for WEmu MMORPG Server
* Copyright (C) 2008 WEmu Team
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
#include "EAS/EasyFunctions.h"
class SunkenTreasure : public QuestScript
{
public:
void OnQuestStart( Player * mTarget, QuestLogEntry * qLogEntry)
{
if( mTarget == NULL || mTarget->GetMapMgr() == NULL || mTarget->GetMapMgr()->GetInterface() == NULL )
return;
float SSX = mTarget->GetPositionX();
float SSY = mTarget->GetPositionY();
float SSZ = mTarget->GetPositionZ();
Creature* creat = mTarget->GetMapMgr()->GetInterface()->GetCreatureNearestCoords(SSX, SSY, SSZ, 2768);
if(creat == NULL)
return;
creat->m_escorter = mTarget;
creat->GetAIInterface()->setMoveType(11);
creat->GetAIInterface()->StopMovement(3000);
creat->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Defens Me!");
creat->SetUInt32Value(UNIT_NPC_FLAGS, 0);
sEAS.CreateCustomWaypointMap(creat);
sEAS.WaypointCreate(creat,-2078.054443f, -2091.207764f, 9.526212f, 4.770276f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2076.626465f, -2109.960449f, 14.320494f, 4.821321f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2072.851074f, -2123.574219f, 18.482662f, 5.623996f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2063.878906f, -2132.617920f, 21.430487f, 5.512474f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2051.495117f, -2145.205811f, 20.500065f, 5.481060f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2044.748291f, -2152.411377f, 20.158432f, 5.437863f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2044.748291f, -2152.411377f, 20.158432f, 5.437863f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2044.748291f, -2152.411377f, 20.158432f, 5.437863f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2044.748291f, -2152.411377f, 20.158432f, 5.437863f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2044.748291f, -2152.411377f, 20.158432f, 5.437863f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2051.495117f, -2145.205811f, 20.500065f, 5.481060f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2063.878906f, -2132.617920f, 21.430487f, 5.512474f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2072.851074f, -2123.574219f, 18.482662f, 5.623996f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2076.626465f, -2109.960449f, 14.320494f, 4.821321f, 0, 256, 4049);
sEAS.WaypointCreate(creat,-2078.054443f, -2091.207764f, 9.526212f, 4.770276f, 0, 256, 4049);
}
};
class Professor_Phizzlethorpe : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Professor_Phizzlethorpe);
Professor_Phizzlethorpe(Creature* pCreature) : CreatureAIScript(pCreature) {}
void OnReachWP(uint32 iWaypointId, bool bForwards)
{
if(iWaypointId == 15)
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_SAY, LANG_UNIVERSAL, "Thanks, I found the fact that, it searched");
_unit->Despawn(5000,1000);
sEAS.DeleteWaypoints(_unit);
if(_unit->m_escorter == NULL)
return;
Player* plr = _unit->m_escorter;
_unit->m_escorter = NULL;
plr->GetQuestLogForEntry(665)->SendQuestComplete();
}
}
};
void SetupArathiHighlands(ScriptMgr * mgr)
{
mgr->register_creature_script(2768, &Professor_Phizzlethorpe::Create);
mgr->register_quest_script(665, CREATE_QUESTSCRIPT(SunkenTreasure));
}
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
89
]
]
]
|
0003aacf9ddab597a90b519fea160f1633f75835 | b53d50ed1ac70145dc6b1b1606583ceb1b620953 | /native/ScreenLockDetector/src/lockdetect.cpp | fb345dd6ba30eed67bd50f2d93aafd4160b14cc0 | []
| no_license | stoneburner/Java-Screenlock-Detect | ada4c3b536d3948e55fcfc4b58a3c35b14242739 | 8f2e5d69a88e6f839ee34dc8340d1ad370824748 | refs/heads/master | 2020-04-04T08:48:47.899438 | 2009-09-25T16:09:15 | 2009-09-25T16:09:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | cpp | #include <windows.h>
#include <jni.h>
#include "lockdetect.h"
/*
*
*/
JNIEXPORT jboolean JNICALL Java_at_thales_ScreenLockDetect_isScreenLocked (JNIEnv *env, jobject obj)
{
HDESK desktop;
desktop=OpenInputDesktop(0,TRUE,READ_CONTROL);
if (desktop == NULL)
{
return (jboolean) TRUE;
}
else
{
return (jboolean) FALSE;
}
}
| [
"[email protected]"
]
| [
[
[
1,
22
]
]
]
|
06ca2e7059f056dc0cd019034a5c0912f227694c | 6060f9c92def1805578fe21068c193421e058278 | /src/MilVars.h | 2f6f9a2e0733e900e651d399a3dbd52e0f652755 | []
| no_license | MatthewNg3416/jaicam_test | 134150cba552a17f9fa94d678ff8a66923a0b82a | 8079fa66acde4b77023678b436891bcfe19ba8ca | refs/heads/master | 2021-05-27T00:19:23.665817 | 2011-05-12T15:53:41 | 2011-05-12T15:53:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | h | /*
*
*/
#pragma once
#include <mil.h>
#if M_MIL_CURRENT_INT_VERSION < 0x0900
typedef long MIL_INT32;
#endif
class MilVars
{
public:
MilVars();
~MilVars();
MIL_ID getApplicationID();
MIL_ID getLiveSystemID();
void releaseSystemID();
private:
MIL_ID getStaticSystemID();
MIL_ID _MilApplication;
MIL_ID _MilLiveSystem;
};
extern MilVars gMilVars;
| [
"[email protected]"
]
| [
[
[
1,
29
]
]
]
|
4fe458b4b9e3709ba8e003f188b92e3745b6161a | 51e1cf5dc3b99e8eecffcf5790ada07b2f03f39c | /SMC/src/audio.cpp | 468fbd7a4156e7b005e71b1355406aefc21935c0 | []
| no_license | jdek/jim-pspware | c3e043b59a69cf5c28daf62dc9d8dca5daf87589 | fd779e1148caac2da4c590844db7235357b47f7e | refs/heads/master | 2021-05-31T06:45:03.953631 | 2007-06-25T22:45:26 | 2007-06-25T22:45:26 | 56,973,047 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,320 | cpp | /***************************************************************************
audio.cpp - Audio Engine
-------------------
copyright : (C) 2003-2005 by FluXy
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "include/audio.h"
cAudio :: cAudio( void )
{
for( unsigned int i = 0; i < AUDIO_MAX_SOUNDS; i++ )
{
Sound[i] = NULL;
}
Music = NULL;
Sound_Volume = 110;
Music_Volume = 128;
Sounds_Played = 0;
Music_Played = 0;
bSounds = 0;
bMusic = 0;
bDebug = 0;
bInitialised = 0;
SCounter = 0;
iHz = 44800; // Ogg Samples ( never change this )
iBuffer = 4096; // ( < 2000 is choppy )
iChannels = MIX_DEFAULT_CHANNELS; // 1 = Mono , 2 = Stereo
}
cAudio :: ~cAudio( void )
{
Close();
}
bool cAudio :: Init( void )
{
if( bInitialised || ( !bMusic && !bSounds ) )
{
return 0;
}
if( bDebug )
{
printf( "Initialising Audio System ,Buffer (%i), Frequenzy (%i)\n", iBuffer, iHz );
}
/* Initialising prefered Audio System specs with Mixer Standard format (Stereo)
*
* format : Output sample format.
* channels : Number of sound channels in output.
* Set this to 2 for stereo, 1 for mono.
* chunksize : Bytes used per output sample.
*/
if( Mix_OpenAudio( iHz, MIX_DEFAULT_FORMAT , iChannels, iBuffer ) < 0 )
{
printf( "Warning : Could not init 16-bit Audio\n- Reason : %s\n", SDL_GetError() );
return 0;
}
bInitialised = 1;
SetMusicVolume( Music_Volume );
SetSoundVolume( Sound_Volume );
return 1;
}
void cAudio :: Close( void )
{
if( bInitialised )
{
if( bSounds )
{
StopSounds();
for( unsigned int i = 0; i < AUDIO_MAX_SOUNDS; i++ )
{
Sound[i] = NULL;
}
}
if( bMusic )
{
Mix_FreeMusic( Music );
Music = NULL;
}
Mix_CloseAudio();
bInitialised = 0;
}
}
int cAudio :: PlaySound( string filename, int channel /* = -1 */, int Volume /* = -1 */ )
{
if( !bSounds || !bInitialised )
{
return 0;
}
if( channel > 128 ) // new
{
printf( "PlaySound channel is out of range : %d\n", channel );
return 0;
}
if( !valid_file( filename ) )
{
printf( "Couldn't find sound file : %s\n", filename.c_str() );
return 0;
}
SCounter++;
if( SCounter == AUDIO_MAX_SOUNDS )
{
SCounter = 0;
}
if( Sound[SCounter] )
{
Mix_FreeChunk( Sound[SCounter] );
Sound[SCounter] = NULL;
}
Sound[SCounter] = Mix_LoadWAV( filename.c_str() );
int channel_used = Mix_PlayChannel( channel, Sound[SCounter], 0 );
if( channel_used == -1 )
{
if( bDebug )
{
printf( "Couldn't play sound file : %s\n", filename.c_str() );
}
return 0;
}
else
{
Sounds_Played++;
if( Volume != -1 ) // new
{
if( Volume > 128 || Volume < 0 )
{
printf( "PlaySound Volume out is of range : %d\n", Volume );
Volume = Sound_Volume;
}
Mix_Volume( channel_used, Volume );
}
else
{
Mix_Volume( channel_used, Sound_Volume );
}
}
return 1;
}
int cAudio :: PlayMusic( string filename, int loops, bool force, unsigned int FadeInms )
{
if( !bMusic || !bInitialised )
{
return 0;
}
if( !valid_file( filename ) )
{
printf( "Couldn't find music file : %s\n", filename.c_str() );
return 0;
}
ResumeMusic();
if( !isMusicPlaying() || force )
{
if( Music )
{
if( force )
{
HaltMusic();
}
Mix_FreeMusic( Music );
Music = NULL;
}
Music = Mix_LoadMUS( filename.c_str() );
if( Music )
{
Music_Played++;
if( !FadeInms ) // No Fading
{
Mix_PlayMusic( Music, loops );
}
else // Fade the Music in
{
Mix_FadeInMusic( Music, loops, FadeInms );
}
}
else
{
if( bDebug )
{
printf( "PlayMusic couldn't play music file : %s\n", filename.c_str() );
}
return 0;
}
}
else
{
Music = Mix_LoadMUS( filename.c_str() );
}
return 1;
}
void cAudio :: ToggleMusic( void )
{
bMusic = !bMusic;
if( !bMusic )
{
HaltMusic();
}
else
{
Init();
if( !pLevel->valid_music )
{
PlayMusic( MUSIC_DIR "/game/mainmenu.ogg", -1, 1, 2000 );
}
else
{
PlayMusic( pLevel->musicfile, -1, 1, 2000 );
}
}
}
void cAudio :: ToggleSounds( void )
{
bSounds = !bSounds;
if( !bSounds )
{
StopSounds();
}
else
{
Init();
PlaySound( SOUNDS_DIR "/audio_on.ogg" );
}
}
void cAudio :: PauseMusic( void )
{
if( !bMusic || !bInitialised )
{
return;
}
if( Mix_PlayingMusic() )// Check if music is currently playing
{
Mix_PauseMusic();
}
}
void cAudio :: ResumeSounds( int channel /* = -1 */ )
{
if( !bSounds || !bInitialised )
{
return;
}
// resume playback on all previously active channels
Mix_Resume( channel );
}
void cAudio :: ResumeMusic( void )
{
if( !bMusic || !bInitialised )
{
return;
}
if( Mix_PausedMusic() ) // Check if music is currently paused
{
Mix_ResumeMusic();
}
}
void cAudio :: FadeOutSounds( unsigned int ms /* = 200 */, int channel /* = -1 */, bool overwrite_fading /* = 0 */ )
{
if( !bSounds || !bInitialised )
{
return;
}
if( Mix_Playing( channel ) ) // Check the Channels
{
if( !overwrite_fading && isSoundFading( - 1 ) == 2 )
{
return; // Do not fade the Sound out again
}
Mix_FadeOutChannel( channel, ms );
}
}
void cAudio :: FadeOutMusic( unsigned int ms, bool overwrite_fading )
{
if( !bMusic || !bInitialised )
{
return;
}
if( Mix_PlayingMusic() ) // Check if music is currently playing
{
int status = isMusicFading();
if( !overwrite_fading && status == 2 )
{
return; // Do not fade the Music out again
}
else if( status == 1 )
{
HaltMusic(); // Can't stop fading in with SDL_Mixer and Fadeout is ignored when fading in
}
Mix_FadeOutMusic( ms );
}
}
void cAudio :: SetMusicPosition( double position )
{
if( !bMusic || !bInitialised || isMusicFading() == 2 )
{
return;
}
Mix_SetMusicPosition( position );
}
int cAudio :: isMusicFading( void )
{
if( !bMusic || !bInitialised )
{
return 0;
}
Mix_Fading status = Mix_FadingMusic();
if( status == MIX_NO_FADING )
{
return 0;
}
else if( status == MIX_FADING_IN )
{
return 1;
}
else if( status == MIX_FADING_OUT )
{
return 2;
}
return 0;
}
int cAudio :: isSoundFading( int SoundChannel )
{
if( !bSounds || !bInitialised )
{
return 0;
}
Mix_Fading status = Mix_FadingChannel( SoundChannel );
if( status == MIX_NO_FADING )
{
return 0;
}
else if( status == MIX_FADING_IN )
{
return 1;
}
else if( status == MIX_FADING_OUT )
{
return 2;
}
return 0;
}
bool cAudio :: isMusicPaused( void )
{
if( !bMusic || !bInitialised )
{
return 0;
}
if( Mix_PausedMusic() )
{
return 1;
}
return 0;
}
bool cAudio :: isMusicPlaying( void )
{
if( !bMusic || !bInitialised )
{
return 0;
}
if( Mix_PlayingMusic() )
{
return 1;
}
return 0;
}
void cAudio :: HaltSounds( int channel /* = -1 */ )
{
if( !bSounds || !bInitialised )
{
return;
}
if( Mix_Playing( channel ) ) // Check all Channels
{
Mix_HaltChannel( channel );
}
}
void cAudio :: HaltMusic( void )
{
if( !bInitialised )
{
return;
}
if( Mix_PlayingMusic() ) // Checks if music is playing
{
Mix_HaltMusic();
}
}
void cAudio :: StopSounds( void )
{
if( !bInitialised )
{
return;
}
if( Mix_Playing( -1 ) ) // Check all Channels
{
Mix_HaltChannel( -1 );
if( Sounds_Played > 0 )
{
for( unsigned int i = 0;i < AUDIO_MAX_SOUNDS;i++ )
{
if( Sound[i] )
{
Mix_FreeChunk( Sound[i] ); // Can be buggy
Sound[i] = NULL;
// should only be stopped not freed
}
}
}
}
}
void cAudio :: SetSoundVolume( Uint8 iVolume, int channel /* = -1 */ )
{
if( ( iVolume > 128 ) || !bSounds || !bInitialised )
{
return;
}
Mix_Volume( channel , iVolume ); // -1 for all channels
Sound_Volume = Mix_Volume( channel, -1 ); // should retrieve the current volume
}
void cAudio :: SetMusicVolume( Uint8 iVolume )
{
if( ( iVolume > 128 ) || !bMusic || !bInitialised )
{
return;
}
Mix_VolumeMusic( iVolume );
Music_Volume = iVolume;
}
void cAudio :: Update( void )
{
if( !bMusic || !bInitialised )
{
return;
}
if( !Mix_PlayingMusic() )
{
Mix_PlayMusic( Music, 0 );
Music_Played++;
}
}
| [
"rinco@ff2c0c17-07fa-0310-a4bd-d48831021cb5"
]
| [
[
[
1,
533
]
]
]
|
9313d00c00ec6fcd5ab4dcc42944ec4d981f5da8 | f89e32cc183d64db5fc4eb17c47644a15c99e104 | /pcsx2-rr/plugins/GSdx/stdafx.h | cedb514596dec63181a1bea5b5f124b1e4112146 | []
| no_license | mauzus/progenitor | f99b882a48eb47a1cdbfacd2f38505e4c87480b4 | 7b4f30eb1f022b08e6da7eaafa5d2e77634d7bae | refs/heads/master | 2021-01-10T07:24:00.383776 | 2011-04-28T11:03:43 | 2011-04-28T11:03:43 | 45,171,114 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,129 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
#pragma once
#pragma warning(disable: 4996 4995 4324 4100 4101 4201)
#ifdef _WINDOWS
// The following macros define the minimum required platform. The minimum required platform
// is the earliest version of Windows, Internet Explorer etc. that has the necessary features to run
// your application. The macros work by enabling all features available on platform versions up to and
// including the version specified.
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Specifies that the minimum required platform is Windows Vista.
#define WINVER 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINDOWS // Specifies that the minimum required platform is Windows 98.
#define _WIN32_WINDOWS 0x0410 // Change this to the appropriate value to target Windows Me or later.
#endif
#ifndef _WIN32_IE // Specifies that the minimum required platform is Internet Explorer 7.0.
#define _WIN32_IE 0x0700 // Change this to the appropriate value to target other versions of IE.
#endif
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#include <commctrl.h>
#include <commdlg.h>
#include <shellapi.h>
#include <atlbase.h>
#endif
// stdc
#include <math.h>
#include <time.h>
#include <cstring>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <hash_map>
#include <hash_set>
#include <algorithm>
// Let's take advantage of the work that's already been done on making things cross-platform by bringing this in.
#include "Pcsx2Defs.h"
using namespace std;
#ifdef _WINDOWS
using namespace stdext;
#endif
extern string format(const char* fmt, ...);
struct delete_object {template<class T> void operator()(T& p) {delete p;}};
struct delete_first {template<class T> void operator()(T& p) {delete p.first;}};
struct delete_second {template<class T> void operator()(T& p) {delete p.second;}};
struct aligned_free_object {template<class T> void operator()(T& p) {_aligned_free(p);}};
struct aligned_free_first {template<class T> void operator()(T& p) {_aligned_free(p.first);}};
struct aligned_free_second {template<class T> void operator()(T& p) {_aligned_free(p.second);}};
// syntactic sugar
// put these into vc9/common7/ide/usertype.dat to have them highlighted
typedef unsigned char uint8;
typedef signed char int8;
typedef unsigned short uint16;
typedef signed short int16;
typedef unsigned int uint32;
typedef signed int int32;
typedef unsigned long long uint64;
typedef signed long long int64;
#define countof(a) (sizeof(a) / sizeof(a[0]))
#define EXPORT_C extern "C" __declspec(dllexport) void __stdcall
#define EXPORT_C_(type) extern "C" __declspec(dllexport) type __stdcall
#define ALIGN_STACK(n) __aligned(n) int __dummy;
#ifndef RESTRICT
#ifdef __INTEL_COMPILER
#define RESTRICT restrict
#elif _MSC_VER >= 1400 // TODO: gcc
#define RESTRICT __restrict
#else
#define RESTRICT
#endif
#endif
#if defined(_DEBUG) && defined(_MSC_VER)
#include <assert.h>
#define ASSERT assert
#else
#define ASSERT(exp) ((void)0)
#endif
#ifdef __x86_64__
#define _M_AMD64
#endif
#ifdef _WINDOWS
// directx
#include <d3d11.h>
#include <d3dx11.h>
#include <d3d9.h>
#include <d3dx9.h>
#define D3DCOLORWRITEENABLE_RGBA (D3DCOLORWRITEENABLE_RED | D3DCOLORWRITEENABLE_GREEN | D3DCOLORWRITEENABLE_BLUE | D3DCOLORWRITEENABLE_ALPHA)
#define USE_UPSCALE_HACKS //Hacks intended to fix upscaling / rendering glitches in HW renderers
// dxsdk beta missing these:
#define D3D11_SHADER_MACRO D3D10_SHADER_MACRO
#define ID3D11Blob ID3D10Blob
#endif
// sse
#if !defined(_M_SSE) && (!defined(_WINDOWS) || defined(_M_AMD64) || defined(_M_IX86_FP) && _M_IX86_FP >= 2)
#define _M_SSE 0x200
#endif
#if _M_SSE >= 0x200
#include <xmmintrin.h>
#include <emmintrin.h>
#ifndef _MM_DENORMALS_ARE_ZERO
#define _MM_DENORMALS_ARE_ZERO 0x0040
#endif
#define MXCSR (_MM_DENORMALS_ARE_ZERO | _MM_MASK_MASK | _MM_ROUND_NEAREST | _MM_FLUSH_ZERO_ON)
#if _MSC_VER < 1500
__forceinline __m128i _mm_castps_si128(__m128 a) {return *(__m128i*)&a;}
__forceinline __m128 _mm_castsi128_ps(__m128i a) {return *(__m128*)&a;}
__forceinline __m128i _mm_castpd_si128(__m128d a) {return *(__m128i*)&a;}
__forceinline __m128d _mm_castsi128_pd(__m128i a) {return *(__m128d*)&a;}
__forceinline __m128d _mm_castps_pd(__m128 a) {return *(__m128d*)&a;}
__forceinline __m128 _mm_castpd_ps(__m128d a) {return *(__m128*)&a;}
#endif
#define _MM_TRANSPOSE4_SI128(row0, row1, row2, row3) \
{ \
__m128 tmp0 = _mm_shuffle_ps(_mm_castsi128_ps(row0), _mm_castsi128_ps(row1), 0x44); \
__m128 tmp2 = _mm_shuffle_ps(_mm_castsi128_ps(row0), _mm_castsi128_ps(row1), 0xEE); \
__m128 tmp1 = _mm_shuffle_ps(_mm_castsi128_ps(row2), _mm_castsi128_ps(row3), 0x44); \
__m128 tmp3 = _mm_shuffle_ps(_mm_castsi128_ps(row2), _mm_castsi128_ps(row3), 0xEE); \
(row0) = _mm_castps_si128(_mm_shuffle_ps(tmp0, tmp1, 0x88)); \
(row1) = _mm_castps_si128(_mm_shuffle_ps(tmp0, tmp1, 0xDD)); \
(row2) = _mm_castps_si128(_mm_shuffle_ps(tmp2, tmp3, 0x88)); \
(row3) = _mm_castps_si128(_mm_shuffle_ps(tmp2, tmp3, 0xDD)); \
}
#else
#error TODO: GSVector4 and GSRasterizer needs SSE2
#endif
#if _M_SSE >= 0x301
#include <tmmintrin.h>
#endif
#if _M_SSE >= 0x401
#include <smmintrin.h>
#endif
#undef min
#undef max
| [
"koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5"
]
| [
[
[
1,
198
]
]
]
|
d5cfcda13bbd968d4554d8ba272c036a6a9fdc0c | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Common/Base/System/StackTracer/hkStackTracer.h | 356fdf2a5d66612b5840d96e5f45cdde45d17066 | []
| no_license | TheProjecter/olafurabertaymsc | 9360ad4c988d921e55b8cef9b8dcf1959e92d814 | 456d4d87699342c5459534a7992f04669e75d2e1 | refs/heads/master | 2021-01-10T15:15:49.289873 | 2010-09-20T12:58:48 | 2010-09-20T12:58:48 | 45,933,002 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,468 | h | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HKBASE_STACKTRACER_H
#define HKBASE_STACKTRACER_H
/// An object which can generate stack traces.
/// Some platforms may also be able to associate addresses to
/// function and source file information.
class hkStackTracer : public hkReferencedObject, public hkSingleton<hkStackTracer>
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE_CLASS);
/// Stores multiple callstacks in a tree to save space.
/// This works by merging trees towards their roots.
class CallTree
{
public:
struct Node
{
Node() : m_value(0), m_parent(-1), m_firstChild(-1), m_next(-1) {}
hkUlong m_value;
int m_parent;
int m_firstChild;
int m_next;
};
typedef int TraceId;
CallTree() : m_allocator(HK_NULL) {}
void init( hkMemoryAllocator* a ) { m_allocator = a; }
void quit() { m_nodes._clearAndDeallocate(*m_allocator); m_allocator = HK_NULL; }
/// Get a stack trace and insert it into the given tree.
TraceId insertCallStack( hkStackTracer& tracer );
/// Add a callstack to the tree and get its id.
TraceId insertCallStack( const hkUlong* addrs, int numAddrs );
/// Retrieve a callstack from an id.
int getCallStack( TraceId id, hkUlong* addrs, int maxAddrs ) const;
/// Read only access for traversal
const Node& node(int i) const { return m_nodes[i]; }
protected:
hkArrayBase<Node> m_nodes;
hkMemoryAllocator* m_allocator;
};
~hkStackTracer();
typedef void (HK_CALL *printFunc)(const char*, void* context);
static hkStackTracer* HK_CALL create();
/// Print the stack trace with pfunc.
/// pfunc is called may be called multiple times.
/// The output format is platform specific.
void dumpStackTrace( const hkUlong* trace, int numtrace, printFunc pfunc, void* context=HK_NULL ) const;
/// Write at most maxtrace stack entries into 'trace'.
/// Return the number of entries written.
int getStackTrace( hkUlong* trace, int maxtrace );
/// If you dynamically load DLLs then you will need to refresh the symbols
/// so that the stack tracer can see them
void refreshSymbols();
protected:
hkStackTracer();
void* m_impl;
};
#endif // HKBASE_STACKTRACER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
102
]
]
]
|
c5474c32f436ce7476910908caa763a2ecf5539d | 35dd668ff26a3dd7cd6b33643e7cb30f984c848a | /pe4constexpr.cc | 24f8fce19e7853e1741ca78c3dbf20f3eba9e599 | []
| no_license | akihiro4chawon/pe-meta | 61b7223d750aed69b4e062abd76d76c57ac2ed77 | be7b567659cd36a3ecfd862f466986b05a6b5b09 | refs/heads/master | 2016-09-11T01:55:24.427381 | 2011-07-08T12:35:30 | 2011-07-08T12:35:30 | 1,959,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,054 | cc | // one of the two numbers must be divisible by 11. Because
// (1) Any parindrome with an even number of digits are divisible by 11;
// (2) 11 is a prime number.
constexpr int reverse_digits(int in, int out)
{
return (in == 0) ? out : reverse_digits(in / 10, out * 10 + in % 10);
}
constexpr bool is_parindrome(int cand)
{
return cand == reverse_digits(cand, 0);
}
constexpr int zero_unless_parindrome(int cand)
{
return is_parindrome(cand) ? cand : 0;
}
constexpr int max(int a, int b)
{
return a > b ? a : b;
}
constexpr int search_max_parindrome(int bbeg, int rend, int a, int b, int result)
{
return
(a < rend) ? result :
(b < rend) || (a * b < result) ? search_max_parindrome(bbeg, rend, a - 1, bbeg, result) :
search_max_parindrome(bbeg, rend, a, b - 11, max(zero_unless_parindrome(a * b), result));
}
int main()
{
constexpr int answer = search_max_parindrome(990, 100, 999, 990, 0);
return answer;
}
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
6e9e32b48b080325bc2e81a37929fc25cab30fac | fbe2cbeb947664ba278ba30ce713810676a2c412 | /iptv_root/iptv_client/include/iptv_client/MediaVideoSource.h | f5dc84fd92e4b6097843738aabdb773509675b53 | []
| no_license | abhipr1/multitv | 0b3b863bfb61b83c30053b15688b070d4149ca0b | 6a93bf9122ddbcc1971dead3ab3be8faea5e53d8 | refs/heads/master | 2020-12-24T15:13:44.511555 | 2009-06-04T17:11:02 | 2009-06-04T17:11:02 | 41,107,043 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | h | #ifndef MEDIAVIDEOSOURCE_H
#define MEDIAVIDEOSOURCE_H
#include <wx/wx.h>
#include "AppInterface.h"
#include "VideoSource.h"
#define MVS_UPDATE_PERIOD 30 // 33.33 frames/second
/** @brief Provides video frames from media (collaborations).
*
* This is a VideoSource-derived class that provides frames from media collaborations. It also
* derived from wxEvtHandler and receives timer events, using them to poll the media library for
* new frames and relaying them to registered VideoSinks when appropriate.
*
*/
class MediaVideoSource: public wxEvtHandler, public VideoSource
{
private:
AppInterface *m_appInterface;
wxTimer m_timer;
unsigned long m_mediaID;
public:
MediaVideoSource(AppInterface *iface = NULL, unsigned long mediaID = 0);
virtual ~MediaVideoSource();
void SetAppInterface(AppInterface *iface);
void SetMediaID(unsigned long mediaID);
AppInterface *GetAppInterface();
unsigned long GetMediaID();
bool Init();
void Start();
void Stop();
void Close();
void OnTimer(wxTimerEvent &event);
DECLARE_EVENT_TABLE()
//unsigned char *GetFrame();
//void GetSize(int &width, int &height);
};
#endif
| [
"heineck@c016ff2c-3db2-11de-a81c-fde7d73ceb89"
]
| [
[
[
1,
46
]
]
]
|
a4c04bba959b50e245965200fb8ae291fe32376a | 9773c3304eecc308671bcfa16b5390c81ef3b23a | /MDI AIPI V.6.92 2003 ( Correct Save Fired Rules, AM =-1, g_currentLine)/AIPI/Aipi_STableNumeric.h | 6da2cef391b0f844e6aae179bf660469f78261dd | []
| no_license | 15831944/AiPI-1 | 2d09d6e6bd3fa104d0175cf562bb7826e1ac5ec4 | 9350aea6ac4c7870b43d0a9f992a1908a3c1c4a8 | refs/heads/master | 2021-12-02T20:34:03.136125 | 2011-10-27T00:07:54 | 2011-10-27T00:07:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,814 | h | // Aipi_STableNumeric.h: interface for the CAipi_STableNumeric class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AIPI_STABLENUMERIC_H__E8ED74E0_1342_4F82_B37C_EF7D941DDF48__INCLUDED_)
#define AFX_AIPI_STABLENUMERIC_H__E8ED74E0_1342_4F82_B37C_EF7D941DDF48__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Aipi_SymbolTable.h"
class CAipi_STableNumeric : public CAipi_SymbolTable
{
public:
CAipi_STableNumeric();
virtual ~CAipi_STableNumeric();
inline CAipi_STableNumeric(long iform, tstring name, int type, double value)
{
CAipi_SymbolTable::setSymbolId(iform);
CAipi_SymbolTable::setSymbolName(name);
CAipi_SymbolTable::setSymbolType(type);
m_STNumValue = value;
}
inline void CAipi_STableNumeric::setSymbolId(long iform)
{
CAipi_SymbolTable::setSymbolId(iform);
}
inline void CAipi_STableNumeric::setSymbolName(tstring name)
{
CAipi_SymbolTable::setSymbolName(name);
}
inline void CAipi_STableNumeric::setSymbolType(int type)
{
CAipi_SymbolTable::setSymbolType(type);
}
inline void CAipi_STableNumeric::setSymbolValue(double value)
{
m_STNumValue = value;
}
inline long CAipi_STableNumeric::getSymbolId()
{
return CAipi_SymbolTable::m_SymbolId;
}
inline tstring CAipi_STableNumeric::getSymbolName()
{
return CAipi_SymbolTable::m_SymbolName;
}
inline int CAipi_STableNumeric::getSymbolType()
{
return CAipi_SymbolTable::m_SymbolType;
}
inline double CAipi_STableNumeric::getSymbolValue()
{
return m_STNumValue;
}
public:
double m_STNumValue;
};
#endif // !defined(AFX_AIPI_STABLENUMERIC_H__E8ED74E0_1342_4F82_B37C_EF7D941DDF48__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
89
]
]
]
|
8f5edf8b551bc34f2640195191033bd90da7a178 | 61c263eb77eb64cf8ab42d2262fc553ac51a6399 | /src/TrailUtil.cpp | 4e579996803af0fcc9f8788552025e5ddefe1ab1 | []
| no_license | ycaihua/fingermania | 20760830f6fe7c48aa2332b67f455eef8f9246a3 | daaa470caf02169ea6533669aa511bf59f896805 | refs/heads/master | 2021-01-20T09:36:38.221802 | 2011-01-23T12:31:19 | 2011-01-23T12:31:19 | 40,102,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,677 | cpp | #include "global.h"
#include "TrailUtil.h"
#include "Trail.h"
#include "Course.h"
#include "XmlFile.h"
#include "GameManager.h"
#include "Song.h"
int TrailUtil::GetNumSongs( const Trail *pTrail )
{
return pTrail->m_vEntries.size();
}
float TrailUtil::GetTotalSeconds( const Trail *pTrail )
{
float fSecs = 0;
FOREACH_CONST( TrailEntry, pTrail->m_vEntries, e )
fSecs += e->pSong->m_fMusicLengthSeconds;
return fSecs;
}
void TrailID::FromTrail( const Trail *p )
{
if( p == NULL )
{
st = StepsType_Invalid;
cd = Difficulty_Invalid;
}
else
{
st = p->m_StepsType;
cd = p->m_CourseDifficulty;
}
m_Cache.Unset();
}
Trail *TrailID::ToTrail( const Course *p, bool bAllowNull ) const
{
ASSERT( p );
Trail *pRet = NULL;
if( !m_Cache.Get(&pRet) )
{
if( st != StepsType_Invalid && cd != Difficulty_Invalid )
pRet = p->GetTrail( st, cd );
m_Cache.Set( pRet );
}
if( !bAllowNull && pRet == NULL )
RageException::Throw( "%i, %i, \"%s\"", st, cd, p->GetDisplayFullTitle().c_str() );
return pRet;
}
XNode* TrailID::CreateNode() const
{
XNode* pNode = new XNode( "Trail" );
pNode->AppendAttr( "StepsType", GAMEMAN->GetStepsTypeInfo(st).szName );
pNode->AppendAttr( "CourseDifficulty", DifficultyToString(cd) );
return pNode;
}
void TrailID::LoadFromNode( const XNode* pNode )
{
ASSERT( pNode->GetName() == "Trail" );
RString sTemp;
pNode->GetAttrValue( "StepsType", sTemp );
st = GAMEMAN->StringToStepsType( sTemp );
pNode->GetAttrValue( "CourseDifficulty", sTemp );
cd = StringToDifficulty( sTemp );
m_Cache.Unset();
}
RString TrailID::ToString() const
{
RString s = GAMEMAN->GetStepsTypeInfo(st).szName;
s += " " + DifficultyToString( cd );
return s;
}
bool TrailID::IsValid() const
{
return st != StepsType_Invalid && cd != Difficulty_Invalid;
}
bool TrailID::operator<( const TrailID &rhs ) const
{
#define COMP(a) if(a<rhs.a) return true; if(a>rhs.a) return false;
COMP(st);
COMP(cd);
#undef COMP
return false;
}
#include "LuaBinding.h"
namespace
{
int GetNumSongs( lua_State *L )
{
Trail *pTrail = Luna<Trail>::check( L, 1, true );
int iNum = TrailUtil::GetNumSongs( pTrail );
LuaHelpers::Push( L, iNum );
return 1;
}
int GetTotalSeconds( lua_State *L )
{
Trail *pTrail = Luna<Trail>::check( L, 1, true );
float fSecs = TrailUtil::GetTotalSeconds( pTrail );
LuaHelpers::Push( L, fSecs );
return 1;
}
const luaL_Reg TrailUtilTable[] =
{
LIST_METHOD( GetNumSongs ),
LIST_METHOD( GetTotalSeconds ),
{ NULL, NULL }
};
}
LUA_REGISTER_NAMESPACE( TrailUtil )
| [
"[email protected]"
]
| [
[
[
1,
128
]
]
]
|
06e67234b0324beba6d0842b9d7ab25dc2ba7a89 | b29db0ed953e13ddcd53617326060dcc0466b76b | /plugin/ossimOpenCVSmoothFilter.h | 43c52f26e0d1930050afca1e36b64a8faa06a8e2 | []
| no_license | jartieda/opencv-ossim-plugin | 1e974fb99d3401233e8c1e7c6d427b567eff3e9c | 9cf03e0f3d0cff1e1fa11409ba5d898dd0601fca | refs/heads/master | 2021-01-23T18:12:36.361248 | 2010-11-24T12:00:53 | 2010-11-24T12:00:53 | 32,137,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,039 | h | #ifndef ossimOpenCVSmoothFilter_HEADER
#define ossimOpenCVSmoothFilter_HEADER
#include "ossim/plugin/ossimSharedObjectBridge.h"
#include "ossim/base/ossimString.h"
#include "ossim/imaging/ossimImageSourceFilter.h"
#include <ossim/imaging/ossimImageDataFactory.h>
#include <stdlib.h>
#include <cv.h>
#include <highgui.h>
/** @brief OpenCV Smooth Filter
**
** Smooths the image in one of several ways.
**
** Parameters:
** @param smooth_type Type of the smoothing:
** <ul>
** <li> <b>CV_BLUR_NO_SCALE</b> - linear convolution with param1xparam2 box kernel (all 1’s) </li>
** <li> <b>CV_BLUR</b> - linear convolution with param1xparam2 box kernel (all 1’s) with subsequent scaling by 1/param1·param2 </li>
** <li> <b>CV_GAUSSIAN</b> - linear convolution with a param1xparam2 Gaussian kernel </li>
** <li> <b>CV_MEDIAN</b> - median filter with a param1xparam1 square aperture </li>
** <li> <b>CV_BILATERAL</b> - bilateral filter with a param1xparam1 square aperture, color_sigma=param3 and spatial_sigma=param4.
** If param1=0, the aperture square side is set to cvRound(param4*1.5)*2+1.</li>
** </ul>
** @param param1 The first parameter of the smoothing operation, the aperture width. Must be a positive odd number (1, 3, 5, ...)
** @param param2 The second parameter of the smoothing operation, the aperture height. Ignored by CV_MEDIAN and CV_BILATERAL methods. In the case of
** simple scaled/non-scaled and Gaussian blur if param2 is zero, it is set to param1. Otherwise it must be a positive odd number.
** @param param3 In the case of a Gaussian parameter this parameter may specify Gaussian standard deviation.
** If it is zero, it is calculated from the kernel size: sigma = 0.3 (n/2 - 1) + 0.8, where n = param1 for horizontal kernel and param2 for
** vertical kernel
** @param param4 In case of non-square Gaussian kernel the parameter may be used to specify a different (from param3) sigma in the vertical direction.
**
**/
class ossimOpenCVSmoothFilter : public ossimImageSourceFilter
{
public:
ossimOpenCVSmoothFilter(ossimObject* owner=NULL);
ossimOpenCVSmoothFilter(ossimImageSource* inputSource);
ossimOpenCVSmoothFilter(ossimObject* owner, ossimImageSource* inputSource);
virtual ~ossimOpenCVSmoothFilter();
virtual ossimRefPtr<ossimImageData> getTile(const ossimIrect& tileRect, ossim_uint32 resLevel=0);
virtual void initialize();
virtual ossimScalarType getOutputScalarType() const;
ossim_uint32 getNumberOfOutputBands() const;
virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const;
virtual bool loadState(const ossimKeywordlist& kwl,const char* prefix=0);
ossimString getShortName()const
{
return ossimString("OpenCVSmooth");
}
ossimString getLongName()const
{
return ossimString("OpenCV Smooth Filter");
}
/*
* Methods to expose thresholds for adjustment through the GUI
*/
virtual void setProperty(ossimRefPtr<ossimProperty> property);
virtual ossimRefPtr<ossimProperty> getProperty(const ossimString& name)const;
virtual void getPropertyNames(std::vector<ossimString>& propertyNames)const;
protected:
ossimRefPtr<ossimImageData> theTile;
void runUcharTransformation(ossimImageData* tile);
int theSmoothType;///<smooth type: CV_BLUR_NO_SCALE, CV_BLUR, CV_GAUSSIAN, CV_MEDIAN, CV_BILATERAL
int theParam1;///<aperture width
int theParam2;///<aperture height
double theParam3;///<If square Gaussian kernel, the Gaussian standard desviation. If non-square Gaussian kernel, the Gaussian standard desviation in the horizontal direction
double theParam4;///<If non-square Gaussian kernel, the Gaussian standard desviation in the vertical direction
private:
void setSmoothType(const ossimString);
void getSmoothTypeList(std::vector<ossimString>&) const;
ossimString getSmoothTypeString()const;
TYPE_DATA
};
#endif
| [
"jartieda@f338cb41-fd2a-0410-a340-718c64ddaef4",
"rebeca.correo@f338cb41-fd2a-0410-a340-718c64ddaef4",
"tishampati.dhar@f338cb41-fd2a-0410-a340-718c64ddaef4",
"whatnickd@f338cb41-fd2a-0410-a340-718c64ddaef4"
]
| [
[
[
1,
3
],
[
6,
6
],
[
10,
10
],
[
13,
13
],
[
37,
41
],
[
43,
43
],
[
50,
51
],
[
53,
56
],
[
59,
59
],
[
67,
69
],
[
75,
75
],
[
81,
84
]
],
[
[
4,
5
],
[
7,
9
],
[
11,
12
],
[
14,
36
],
[
42,
42
],
[
44,
49
],
[
58,
58
],
[
70,
74
],
[
85,
90
]
],
[
[
52,
52
],
[
57,
57
]
],
[
[
60,
66
],
[
76,
80
]
]
]
|
437d9c7a3bfce6c18a324b8bd1db67f32a4d4202 | d37a1d5e50105d82427e8bf3642ba6f3e56e06b8 | /DVR/VPKServer/YuvRgbConverter.h | 218522cf08987915be86076424c50c0eb96ea1bb | []
| no_license | 080278/dvrmd-filter | 176f4406dbb437fb5e67159b6cdce8c0f48fe0ca | b9461f3bf4a07b4c16e337e9c1d5683193498227 | refs/heads/master | 2016-09-10T21:14:44.669128 | 2011-10-17T09:18:09 | 2011-10-17T09:18:09 | 32,274,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | h | // YuvRgbConverter.h: interface for the CYuvRgbConverter class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_YUVRGBCONVERTER_H__349EDDAE_F788_4238_A27C_3CDE8798F2BB__INCLUDED_)
#define AFX_YUVRGBCONVERTER_H__349EDDAE_F788_4238_A27C_3CDE8798F2BB__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//extern "C" void YUV420ToRGB32( BYTE *dst, int dstride, BYTE *y, BYTE *u , BYTE *v , int ystride, int uvstride,int width, int height);
extern "C" void YUV420ToRGB24( BYTE *dst, int dstride, BYTE *y, BYTE *u , BYTE *v , int ystride, int uvstride,int width, int height);
//extern "C" void RGB32ToYV12(BYTE * const y_out,BYTE * const u_out, BYTE * const v_out, const BYTE * const src,
// const UINT width,const UINT height,const UINT stride);
extern "C" void yv12_to_rgb32_mmx(BYTE *dst,
int dst_stride,
BYTE *y_src,
BYTE *u_src,
BYTE *v_src,
int y_stride, int uv_stride,
int width, int height);
extern "C" void _RGB32ToYV12(BYTE * const y_out,
BYTE * const u_out,
BYTE * const v_out,
const BYTE * const src,
const unsigned int width,
const unsigned int height,
const unsigned int stride);
class CYuvRgbConverter
{
public:
CYuvRgbConverter();
virtual ~CYuvRgbConverter();
static void yuv420toyuv422(BYTE* lpSrcY, int SrcPitch, BYTE* lpSrcU,BYTE* lpSrcV,
int stride_uv, BYTE* lpDst, int SrcWidth, int SrcHeight,unsigned int DstPitch);
static void yv12_to_rgb32_mmx(BYTE *dst,
int dst_stride,
BYTE *y_src,
BYTE *u_src,
BYTE *v_src,
int y_stride, int uv_stride,
int width, int height);
static void _RGB32ToYV12(BYTE * const y_out,
BYTE * const u_out,
BYTE * const v_out,
const BYTE * const src,
const unsigned int width,
const unsigned int height,
const unsigned int stride);
};
#endif // !defined(AFX_YUVRGBCONVERTER_H__349EDDAE_F788_4238_A27C_3CDE8798F2BB__INCLUDED_)
| [
"[email protected]@27769579-7047-b306-4d6f-d36f87483bb3"
]
| [
[
[
1,
61
]
]
]
|
23053fe3ba642bbf07b36b2d3aef9b3193318db3 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/addons/pa/dependencies/include/ParticleUniverse/ParticleAffectors/ParticleUniverseSphereCollider.h | cd1099f7f301666398fba1347a9312e14534517b | []
| no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,467 | h | /*
-----------------------------------------------------------------------------------------------
This source file is part of the Particle Universe product.
Copyright (c) 2010 Henry van Merode
Usage of this program is licensed under the terms of the Particle Universe Commercial License.
You can find a copy of the Commercial License in the Particle Universe package.
-----------------------------------------------------------------------------------------------
*/
#ifndef __PU_SPHERE_COLLIDER_H__
#define __PU_SPHERE_COLLIDER_H__
#include "ParticleUniversePrerequisites.h"
#include "ParticleUniverseBaseCollider.h"
#include "OgreSphere.h"
namespace ParticleUniverse
{
/** The SphereCollider is a sphere shape that collides with the particles. The SphereCollider can only collide
with particles that are created within the same ParticleTechnique as where the SphereCollider is registered.
*/
class _ParticleUniverseExport SphereCollider : public BaseCollider
{
public:
// Constants
static const Ogre::Real DEFAULT_RADIUS;
SphereCollider(void);
virtual ~SphereCollider(void){};
/** Returns the radius of the sphere
*/
const Ogre::Real getRadius(void) const;
/** Sets the radius of the sphere
*/
void setRadius(const Ogre::Real radius);
/** Returns indication whether the collision is inside or outside of the box
@remarks
If value is true, the collision is inside of the box.
*/
bool isInnerCollision(void) const;
/** Set indication whether the collision is inside or outside of the box
@remarks
If value is set to true, the collision is inside of the box.
*/
void setInnerCollision(bool innerCollision);
/**
*/
void calculateDirectionAfterCollision(Particle* particle, Ogre::Vector3 distance, Ogre::Real distanceLength);
/** @copydoc ParticleAffector::_preProcessParticles */
virtual void _preProcessParticles(ParticleTechnique* particleTechnique, Ogre::Real timeElapsed);
/** @copydoc ParticleAffector::_affect */
virtual void _affect(ParticleTechnique* particleTechnique, Particle* particle, Ogre::Real timeElapsed);
/** @copydoc ParticleAffector::copyAttributesTo */
virtual void copyAttributesTo (ParticleAffector* affector);
protected:
Ogre::Real mRadius;
Ogre::Sphere mSphere;
Ogre::Vector3 mPredictedPosition;
bool mInnerCollision;
};
}
#endif
| [
"[email protected]"
]
| [
[
[
1,
74
]
]
]
|
cccdfafb91b1c3c6f6e51de52a8ece3ca24debde | 3e69b159d352a57a48bc483cb8ca802b49679d65 | /tags/release-2006-01-13/include/gr_basic.h | 336b87e278e13921e745ee6b33dc47c398e27250 | []
| no_license | BackupTheBerlios/kicad-svn | 4b79bc0af39d6e5cb0f07556eb781a83e8a464b9 | 4c97bbde4b1b12ec5616a57c17298c77a9790398 | refs/heads/master | 2021-01-01T19:38:40.000652 | 2006-06-19T20:01:24 | 2006-06-19T20:01:24 | 40,799,911 | 0 | 0 | null | null | null | null | IBM852 | C++ | false | false | 7,298 | h | /**************/
/* gr_basic.h */
/**************/
#ifndef GR_BASIC
#define GR_BASIC
#ifndef COMMON_GLOBL
#define COMMON_GLOBL extern
#endif
#include "colors.h"
/* Constantes utiles */
#define GR_COPY 0
#define GR_OR 0x1000000
#define GR_XOR 0x2000000
#define GR_AND 0x4000000
#define GR_NXOR 0x8000000
#define GR_SURBRILL 0x80000000
#define GR_M_LEFT_DOWN 0x10000000
#define GR_M_RIGHT_DOWN 0x20000000
#define GR_M_MIDDLE_DOWN 0x40000000
#define GR_M_DCLICK 0x80000000
/* variables generales */
COMMON_GLOBL int g_XorMode // = GR_XOR ou GR_NXOR selon couleur de fond
#ifdef EDA_BASE // pour les tracÚs en mode XOR
= GR_NXOR
#endif
;
COMMON_GLOBL int g_DrawBgColor // couleur de fond de la frame de dessin
#ifdef EDA_BASE
= WHITE
#endif
;
typedef enum { /* Line styles for Get/SetLineStyle. */
GR_SOLID_LINE = 0,
GR_DOTTED_LINE = 1,
GR_DASHED_LINE = 3
} GRLineStypeType;
typedef enum { /* Line widths for Get/SetLineStyle. */
GR_NORM_WIDTH = 1,
GR_THICK_WIDTH = 3
} GRLineWidthType;
/*******************************************************/
/* Prototypage des fonctions definies dans gr_basic.cc */
/*******************************************************/
int GRMapX(int x);
int GRMapY(int y);
class WinEDA_DrawPanel;
void GRMouseWarp(WinEDA_DrawPanel * panel, const wxPoint& pos); /* positionne la souris au point de coord pos */
/* routines generales */
void GRSetDrawMode(wxDC * DC, int mode);
int GRGetDrawMode(wxDC * DC);
void GRResetPenAndBrush(wxDC * DC);
void GRSetColorPen(wxDC * DC, int Color , int width = 1);
void GRSetBrush(wxDC * DC, int Color , int fill = 0);
void GRForceBlackPen(bool flagforce );
void SetPenMinWidth(int minwidth); /* ajustage de la largeur mini de plume */
void GRLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRMixedLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRSMixedLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRDashedLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRSDashedLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRDashedLineTo(EDA_Rect * ClipBox,wxDC * DC, int x2, int y2, int Color);
void GRSDashedLineTo(EDA_Rect * ClipBox,wxDC * DC, int x2, int y2, int Color);
void GRBusLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRSBusLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRSLine(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int Color);
void GRMoveTo(int x, int y);
void GRSMoveTo(int x, int y);
void GRLineTo(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int Color);
void GRBusLineTo(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int Color);
void GRSLineTo(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int Color);
void GRMoveRel(int x, int y);
void GRSMoveRel(int x, int y);
void GRLineRel(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int Color);
void GRSLineRel(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int Color);
void GRPoly(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Fill, int Color, int BgColor);
void GRPolyLines(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Color, int BgColor, int width);
void GRClosedPoly(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Fill, int Color, int BgColor);
void GRSPoly(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Fill, int Color, int BgColor);
void GRSPolyLines(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Color, int BgColor, int width);
void GRSClosedPoly(EDA_Rect * ClipBox, wxDC * DC, int n, int *Points,
int Fill, int Color, int BgColor);
void GRCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r, int Color);
void GRCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r, int width, int Color);
void GRFilledCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r,
int Color, int BgColor);
void GRSCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r, int Color);
void GRSCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r, int width, int Color);
void GRSFilledCircle(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int r,
int Color, int BgColor);
void GRArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int StAngle, int EndAngle, int r, int Color);
void GRArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int StAngle, int EndAngle, int r, int width, int Color);
void GRArc1(EDA_Rect * ClipBox,wxDC * DC, int x1, int y1, int x2, int y2,
int xc, int yc, int Color);
void GRArc1(EDA_Rect * ClipBox,wxDC * DC, int x1, int y1, int x2, int y2,
int xc, int yc, int width, int Color);
void GRSArc1(EDA_Rect * ClipBox,wxDC * DC, int x1, int y1, int x2, int y2,
int xc, int yc, int Color);
void GRSArc1(EDA_Rect * ClipBox,wxDC * DC, int x1, int y1, int x2, int y2,
int xc, int yc, int width, int Color);
void GRSArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int StAngle, int EndAngle, int r, int Color);
void GRSArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int StAngle, int EndAngle, int r, int width, int Color);
void GRFilledArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y,
int StAngle, int EndAngle, int r, int Color, int BgColor);
void GRSFilledArc(EDA_Rect * ClipBox, wxDC * DC, int x, int y,
int StAngle, int EndAngle, int r, int Color, int BgColor);
void GRCSegm(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int width, int Color);
void GRFillCSegm(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int width, int Color);
void GRSCSegm(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1, int x2, int y2, int width, int Color);
void GRSFillCSegm(EDA_Rect * ClipBox, wxDC * DC,
int x1, int y1, int x2, int y2, int width, int Color);
void GRSetColor(int Color);
void GRSetDefaultPalette(void);
int GRGetColor(void);
void GRPutPixel(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int color);
void GRSPutPixel(EDA_Rect * ClipBox, wxDC * DC, int x, int y, int color);
int GRGetPixel(wxDC * DC, int x, int y);
void GRFilledRect(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1,
int x2, int y2, int Color, int BgColor);
void GRSFilledRect(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1,
int x2, int y2, int Color, int BgColor);
void GRSFilledRect(EDA_Rect * ClipBox,wxDC * DC, int x1, int y1, int x2, int y2,
int Color, int BgColor);
void GRRect(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1,
int x2, int y2, int Color);
void GRSRect(EDA_Rect * ClipBox, wxDC * DC, int x1, int y1,
int x2, int y2, int Color);
/* Routines relatives a l'affichage des textes */
void GRSetFont(wxDC * DC, wxFont * Font);
void GRResetTextFgColor(wxDC * DC);
void GRSetTextFgColor(wxDC * DC, int Color);
void GRSetTextFgColor(wxDC * DC, wxFont * Font, int Color);
int GRGetTextFgColor(wxDC * DC, wxFont * Font);
void GRSetTextBgColor(wxDC * DC, int Color);
void GRSetTextBgColor(wxDC * DC, wxFont * Font, int Color);
int GRGetTextBgColor(wxDC * DC, wxFont * Font);
void GRGetTextExtent(wxDC * DC, const wxChar * Text, long * width, long * height);
#endif /* define GR_BASIC */
| [
"bokeoa@244deca0-f506-0410-ab94-f4f3571dea26"
]
| [
[
[
1,
163
]
]
]
|
c4d68c3ea8479c482c2614482f464a7451cc0f4f | 11ca42d611fb189f29702da132578dfc27f27c61 | /ch12/Graph.h | 70a40d916a980a1242c57230e553d767193da04d | []
| no_license | baile320/ppp | 50c03ee08fd8e2c63ffc820c361750a800334ac9 | fdd91113e43198735bc1233117cdeeb73fda4c15 | refs/heads/master | 2021-12-23T04:34:14.214091 | 2011-10-30T23:09:03 | 2011-10-30T23:09:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,435 | h |
//
// This is a GUI support code to the chapters 12-16 of the book
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
#ifndef GRAPH_GUARD
#define GRAPH_GUARD
#include <FL/fl_draw.H>
#include <FL/Fl_Image.H>
#include "Point.h"
#include "../std_lib_facilities.h"
namespace Graph_lib {
// defense against ill-behaved Linux macros:
#undef major
#undef minor
//------------------------------------------------------------------------------
// Color is the type we use to represent color. We can use Color like this:
// grid.set_color(Color::red);
struct Color {
enum Color_type {
red=FL_RED,
blue=FL_BLUE,
green=FL_GREEN,
yellow=FL_YELLOW,
white=FL_WHITE,
black=FL_BLACK,
magenta=FL_MAGENTA,
cyan=FL_CYAN,
dark_red=FL_DARK_RED,
dark_green=FL_DARK_GREEN,
dark_yellow=FL_DARK_YELLOW,
dark_blue=FL_DARK_BLUE,
dark_magenta=FL_DARK_MAGENTA,
dark_cyan=FL_DARK_CYAN
};
enum Transparency { invisible = 0, visible=255 };
Color(Color_type cc) :c(Fl_Color(cc)), v(visible) { }
Color(Color_type cc, Transparency vv) :c(Fl_Color(cc)), v(vv) { }
Color(int cc) :c(Fl_Color(cc)), v(visible) { }
Color(Transparency vv) :c(Fl_Color()), v(vv) { } // default color
int as_int() const { return c; }
char visibility() const { return v; }
void set_visibility(Transparency vv) { v=vv; }
private:
Fl_Color c;
char v; // invisible and visible for now
};
//------------------------------------------------------------------------------
struct Line_style {
enum Line_style_type {
solid=FL_SOLID, // -------
dash=FL_DASH, // - - - -
dot=FL_DOT, // .......
dashdot=FL_DASHDOT, // - . - .
dashdotdot=FL_DASHDOTDOT, // -..-..
};
Line_style(Line_style_type ss) :s(ss), w(0) { }
Line_style(Line_style_type lst, int ww) :s(lst), w(ww) { }
Line_style(int ss) :s(ss), w(0) { }
int width() const { return w; }
int style() const { return s; }
private:
int s;
int w;
};
//------------------------------------------------------------------------------
class Font {
public:
enum Font_type {
helvetica=FL_HELVETICA,
helvetica_bold=FL_HELVETICA_BOLD,
helvetica_italic=FL_HELVETICA_ITALIC,
helvetica_bold_italic=FL_HELVETICA_BOLD_ITALIC,
courier=FL_COURIER,
courier_bold=FL_COURIER_BOLD,
courier_italic=FL_COURIER_ITALIC,
courier_bold_italic=FL_COURIER_BOLD_ITALIC,
times=FL_TIMES,
times_bold=FL_TIMES_BOLD,
times_italic=FL_TIMES_ITALIC,
times_bold_italic=FL_TIMES_BOLD_ITALIC,
symbol=FL_SYMBOL,
screen=FL_SCREEN,
screen_bold=FL_SCREEN_BOLD,
zapf_dingbats=FL_ZAPF_DINGBATS
};
Font(Font_type ff) :f(ff) { }
Font(int ff) :f(ff) { }
int as_int() const { return f; }
private:
int f;
};
//------------------------------------------------------------------------------
template<class T> class Vector_ref {
vector<T*> v;
vector<T*> owned;
public:
Vector_ref() {}
Vector_ref(T& a) { push_back(a); }
Vector_ref(T& a, T& b);
Vector_ref(T& a, T& b, T& c);
Vector_ref(T* a, T* b = 0, T* c = 0, T* d = 0)
{
if (a) push_back(a);
if (b) push_back(b);
if (c) push_back(c);
if (d) push_back(d);
}
~Vector_ref() { for (size_t i=0; i<owned.size(); ++i) delete owned[i]; }
void push_back(T& s) { v.push_back(&s); }
void push_back(T* p) { v.push_back(p); owned.push_back(p); }
T& operator[](int i) { return *v[i]; }
const T& operator[](int i) const { return *v[i]; }
int size() const { return v.size(); }
private: // prevent copying
Vector_ref(const Vector_ref&);
Vector_ref& operator=(const Vector_ref&);
};
//------------------------------------------------------------------------------
typedef double Fct(double);
class Shape { // deals with color and style, and holds sequence of lines
public:
void draw() const; // deal with color and draw lines
virtual void move(int dx, int dy); // move the shape +=dx and +=dy
void set_color(Color col) { lcolor = col; }
Color color() const { return lcolor; }
void set_style(Line_style sty) { ls = sty; }
Line_style style() const { return ls; }
void set_fill_color(Color col) { fcolor = col; }
Color fill_color() const { return fcolor; }
Point point(int i) const { return points[i]; } // read only access to points
int number_of_points() const { return int(points.size()); }
virtual ~Shape() { }
protected:
Shape();
virtual void draw_lines() const; // draw the appropriate lines
void add(Point p); // add p to points
void set_point(int i,Point p); // points[i]=p;
private:
vector<Point> points; // not used by all shapes
Color lcolor; // color for lines and characters
Line_style ls;
Color fcolor; // fill color
Shape(const Shape&); // prevent copying
Shape& operator=(const Shape&);
};
//------------------------------------------------------------------------------
struct Function : Shape {
// the function parameters are not stored
Function(Fct f, double r1, double r2, Point orig,
int count = 100, double xscale = 25, double yscale = 25);
};
//------------------------------------------------------------------------------
struct Line : Shape { // a Line is a Shape defined by two Points
Line(Point p1, Point p2); // construct a line from two points
};
//------------------------------------------------------------------------------
struct Rectangle : Shape {
Rectangle(Point xy, int ww, int hh) : w(ww), h(hh)
{
add(xy);
if (h<=0 || w<=0) error("Bad rectangle: non-positive side");
}
Rectangle(Point x, Point y) : w(y.x-x.x), h(y.y-x.y)
{
add(x);
if (h<=0 || w<=0) error("Bad rectangle: non-positive width or height");
}
void draw_lines() const;
int height() const { return h; }
int width() const { return w; }
private:
int w; // width
int h; // height
};
//------------------------------------------------------------------------------
struct Open_polyline : Shape { // open sequence of lines
void add(Point p) { Shape::add(p); }
void draw_lines() const;
};
//------------------------------------------------------------------------------
struct Closed_polyline : Open_polyline { // closed sequence of lines
void draw_lines() const;
};
//------------------------------------------------------------------------------
struct Polygon : Closed_polyline { // closed sequence of non-intersecting lines
void add(Point p);
void draw_lines() const;
};
//------------------------------------------------------------------------------
struct Lines : Shape { // related lines
void draw_lines() const;
void add(Point p1, Point p2); // add a line defined by two points
};
//------------------------------------------------------------------------------
struct Text : Shape {
// the point is the bottom left of the first letter
Text(Point x, const string& s)
: lab(s), fnt(fl_font()), fnt_sz(fl_size()) { add(x); }
void draw_lines() const;
void set_label(const string& s) { lab = s; }
string label() const { return lab; }
void set_font(Font f) { fnt = f; }
Font font() const { return Font(fnt); }
void set_font_size(int s) { fnt_sz = s; }
int font_size() const { return fnt_sz; }
private:
string lab; // label
Font fnt;
int fnt_sz;
};
//------------------------------------------------------------------------------
struct Axis : Shape {
enum Orientation { x, y, z };
Axis(Orientation d, Point xy, int length,
int number_of_notches=0, string label = "");
void draw_lines() const;
void move(int dx, int dy);
void set_color(Color c);
Text label;
Lines notches;
};
//------------------------------------------------------------------------------
struct Circle : Shape {
Circle(Point p, int rr) // center and radius
:r(rr) { add(Point(p.x-r,p.y-r)); }
void draw_lines() const;
Point center() const { return Point(point(0).x+r, point(0).y+r); }
void set_radius(int rr) { set_point(0,Point(center().x-rr,center().y-rr)); r=rr; }
int radius() const { return r; }
private:
int r;
};
//------------------------------------------------------------------------------
struct Ellipse : Shape {
Ellipse(Point p, int ww, int hh) // center, min, and max distance from center
:w(ww), h(hh) { add(Point(p.x-ww,p.y-hh)); }
void draw_lines() const;
Point center() const { return Point(point(0).x+w,point(0).y+h); }
Point focus1() const {
if (h<=w)// foci are on the x-axis:
return Point(center().x+int(sqrt(double(w*w-h*h))),center().y);
else // foci are on the y-axis:
return Point(center().x,center().y+int(sqrt(double(h*h-w*w))));
}
Point focus2() const {
if (h<=w)
return Point(center().x-int(sqrt(double(w*w-h*h))),center().y);
else
return Point(center().x,center().y-int(sqrt(double(h*h-w*w))));
}
//Point focus2() const { return Point(center().x-int(sqrt(double(abs(w*w-h*h)))),center().y); }
void set_major(int ww) { set_point(0,Point(center().x-ww,center().y-h)); w=ww; }
int major() const { return w; }
void set_minor(int hh) { set_point(0,Point(center().x-w,center().y-hh)); h=hh; }
int minor() const { return h; }
private:
int w;
int h;
};
//------------------------------------------------------------------------------
struct Marked_polyline : Open_polyline {
Marked_polyline(const string& m) :mark(m) { }
void draw_lines() const;
private:
string mark;
};
//------------------------------------------------------------------------------
struct Marks : Marked_polyline {
Marks(const string& m) :Marked_polyline(m)
{
set_color(Color(Color::invisible));
}
};
//------------------------------------------------------------------------------
struct Mark : Marks {
Mark(Point xy, char c) : Marks(string(1,c))
{
add(xy);
}
};
//------------------------------------------------------------------------------
struct Suffix {
enum Encoding { none, jpg, gif };
};
Suffix::Encoding get_encoding(const string& s);
//------------------------------------------------------------------------------
struct Image : Shape {
Image(Point xy, string file_name, Suffix::Encoding e = Suffix::none);
~Image() { delete p; }
void draw_lines() const;
void set_mask(Point xy, int ww, int hh) { w=ww; h=hh; cx=xy.x; cy=xy.y; }
private:
int w,h; // define "masking box" within image relative to position (cx,cy)
int cx,cy;
Fl_Image* p;
Text fn;
};
//------------------------------------------------------------------------------
struct Bad_image : Fl_Image {
Bad_image(int h, int w) : Fl_Image(h,w,0) { }
void draw(int x,int y, int, int, int, int) { draw_empty(x,y); }
};
//------------------------------------------------------------------------------
} // of namespace Graph_lib
#endif
| [
"[email protected]"
]
| [
[
[
1,
393
]
]
]
|
2b99e28143d87960b3f2f58c08eef3a54bfd89aa | 6e563096253fe45a51956dde69e96c73c5ed3c18 | /dhplay/dhplay/decode/FifoBuffer.h | 7136f948592c4bc0e49e02f80e29676733e458a4 | []
| no_license | 15831944/phoebemail | 0931b76a5c52324669f902176c8477e3bd69f9b1 | e10140c36153aa00d0251f94bde576c16cab61bd | refs/heads/master | 2023-03-16T00:47:40.484758 | 2010-10-11T02:31:02 | 2010-10-11T02:31:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,835 | h | #ifndef FIFOBUFFER_H
#define FIFOBUFFER_H
#include <windows.h>
#include "decode.h"
// 只要用于内部记录更多信息
struct DhAVFrame
{
DhAVFrame *prev;
DhAVFrame *next;
unsigned char *context; // 数据指针
int width ;
int height ;
int size;
//Frame bit rate
int frameLen;
int frameType;
//IVS
int ivsobjnum;
DH_IVS_OBJ* ivsObjList;
DH_IVS_PREPOS tIvsPrePos;
};
class FifoBuffer
{
public:
FifoBuffer();
~FifoBuffer();
int init(int count,int chunksize);
int reset();
int resize(int chunksize);
int clear();
bool write(DhAVFrame* vframe) ;
bool read(DhAVFrame* vframe) ;
int chunkCount();//有效数据 块数
void setlock(bool iflock) ;
bool getlock();
BYTE* GetLastFrame();
BYTE* GetNextWritePos();
void SetbReadNull(bool ifReadNull){m_bReadNull = ifReadNull;}
bool GetIfReadNull(){return m_bReadNull;}
void GetLastFrameBuf(unsigned char* pBuf){m_dataFrame.context = pBuf;}
private:
bool createFreeList();
void cleanFreeList();
void cleanDataList();
DhAVFrame *getFreeNode();
DhAVFrame *getDataNode();
void appendToFreeList(DhAVFrame *item);
void appendToDataList(DhAVFrame *item);
private:
unsigned char *m_mempool;//内存池
bool m_ifLock ;//如果锁定,则write函数中一直等待有空的缓冲块,在定位操作时,将它置为False,以使write函数尽快返回
bool m_inited; // 初始化成功标志
int m_count; // 节点总数
int m_chunksize;
DhAVFrame *m_freeQueueFirst;
DhAVFrame *m_freeQueueLast;
int m_freeCount;//空的块的数
DhAVFrame *m_outQueueFirst;
DhAVFrame *m_outQueueLast;
int m_outCount;//有效数据块数
DhAVFrame m_dataFrame;
CRITICAL_SECTION m_DataAccessLock ;
bool m_bReadNull;
};
#endif
| [
"guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd"
]
| [
[
[
1,
99
]
]
]
|
070dd7d6afb4e897d520f65d78eac038aafd5dca | 51003f6af36ce7adaa753eb910d1bc33354be26a | /menu.cpp | dce1a16deaec5250eac5c38f01b6a48b874a2ca5 | []
| no_license | bluegr/scummvm-picture | c58d45273180b593980fbcd04d6856e5f105e3ce | 3b73be498868b2983a7387c04a51a9b2c4feda2b | refs/heads/master | 2020-05-17T17:14:31.683213 | 2011-11-03T21:30:54 | 2011-11-03T21:30:54 | 2,769,341 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,107 | cpp | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
* $URL: https://www.switchlink.se/svn/picture/resource.cpp $
* $Id: resource.cpp 2 2008-08-04 12:18:15Z johndoe $
*
*/
#include "common/savefile.h"
#include "picture/picture.h"
#include "picture/menu.h"
#include "picture/palette.h"
#include "picture/render.h"
#include "picture/resource.h"
namespace Picture {
MenuSystem::MenuSystem(PictureEngine *vm) : _vm(vm) {
}
MenuSystem::~MenuSystem() {
}
int MenuSystem::run() {
//debug("MenuSystem::run()");
_background = new Graphics::Surface();
_background->create(640, 400, Graphics::PixelFormat::createFormatCLUT8());
// Save original background
Graphics::Surface backgroundOrig;
backgroundOrig.create(640, 400, Graphics::PixelFormat::createFormatCLUT8());
memcpy(backgroundOrig.getBasePtr(0,0), _vm->_screen->_frontScreen, 640 * 400);
_currMenuID = kMenuIdNone;
_newMenuID = kMenuIdMain;
_currItemID = kItemIdNone;
_editingDescription = false;
_cfgText = true;
_cfgVoices = true;
_cfgMasterVolume = 10;
_cfgVoicesVolume = 10;
_cfgMusicVolume = 10;
_cfgSoundFXVolume = 10;
_cfgBackgroundVolume = 10;
_running = true;
_top = 30 - _vm->_guiHeight / 2;
_needRedraw = false;
// TODO: buildColorTransTable2
_vm->_palette->buildColorTransTable(0, 16, 7);
_vm->_screen->_renderQueue->clear();
// Draw the menu background and frame
_vm->_screen->blastSprite(0x140 + _vm->_cameraX, 0x175 + _vm->_cameraY, 0, 1, 0x4000);
shadeRect(60, 39, 520, 246, 30, 94);
memcpy(_background->pixels, _vm->_screen->_frontScreen, 640 * 400);
while (_running) {
update();
_vm->_system->updateScreen();
}
// Restore original background
memcpy(_vm->_screen->_frontScreen, backgroundOrig.getBasePtr(0,0), 640 * 400);
_vm->_system->copyRectToScreen((const byte *)_vm->_screen->_frontScreen, 640, 0, 0, 640, 400);
_vm->_system->updateScreen();
// Cleanup
backgroundOrig.free();
_background->free();
delete _background;
return 0;
}
void MenuSystem::update() {
if (_currMenuID != _newMenuID) {
_currMenuID = _newMenuID;
//debug("_currMenuID = %d", _currMenuID);
initMenu(_currMenuID);
}
handleEvents();
if (_needRedraw) {
//_vm->_system->copyRectToScreen((const byte *)_vm->_screen->_frontScreen + 39 * 640 + 60, 640, 60, 39, 520, 247);
_vm->_system->copyRectToScreen((const byte *)_vm->_screen->_frontScreen, 640, 0, 0, 640, 400);
//debug("redraw");
_needRedraw = false;
}
_vm->_system->delayMillis(5);
}
void MenuSystem::handleEvents() {
Common::Event event;
Common::EventManager *eventMan = _vm->_system->getEventManager();
while (eventMan->pollEvent(event)) {
switch (event.type) {
case Common::EVENT_KEYDOWN:
handleKeyDown(event.kbd);
break;
case Common::EVENT_QUIT:
_running = false;
break;
case Common::EVENT_MOUSEMOVE:
handleMouseMove(event.mouse.x, event.mouse.y);
break;
case Common::EVENT_LBUTTONDOWN:
handleMouseClick(event.mouse.x, event.mouse.y);
break;
default:
break;
}
}
}
void MenuSystem::addClickTextItem(ItemID id, int x, int y, int w, uint fontNum, const char *caption, byte defaultColor, byte activeColor) {
Item item;
item.id = id;
item.defaultColor = defaultColor;
item.activeColor = activeColor;
item.x = x;
item.y = y;
item.w = w;
item.fontNum = fontNum;
setItemCaption(&item, caption);
_items.push_back(item);
}
void MenuSystem::drawItem(ItemID itemID, bool active) {
Item *item = getItem(itemID);
if (item) {
byte color = active ? item->activeColor : item->defaultColor;
drawString(item->rect.left, item->y, 0, item->fontNum, color, item->caption.c_str());
}
}
void MenuSystem::handleMouseMove(int x, int y) {
if (!_editingDescription) {
ItemID newItemID = findItemAt(x, y);
if (_currItemID != newItemID) {
leaveItem(_currItemID);
_currItemID = newItemID;
enterItem(newItemID);
}
}
}
void MenuSystem::handleMouseClick(int x, int y) {
if (!_editingDescription) {
ItemID id = findItemAt(x, y);
clickItem(id);
}
}
void MenuSystem::handleKeyDown(const Common::KeyState& kbd) {
if (_editingDescription) {
if (kbd.keycode >= Common::KEYCODE_SPACE && kbd.keycode <= Common::KEYCODE_z) {
_editingDescriptionItem->caption += kbd.ascii;
restoreRect(_editingDescriptionItem->rect.left, _editingDescriptionItem->rect.top,
_editingDescriptionItem->rect.width() + 1, _editingDescriptionItem->rect.height() - 2);
setItemCaption(_editingDescriptionItem, _editingDescriptionItem->caption.c_str());
drawItem(_editingDescriptionID, true);
} else if (kbd.keycode == Common::KEYCODE_BACKSPACE) {
_editingDescriptionItem->caption.deleteLastChar();
restoreRect(_editingDescriptionItem->rect.left, _editingDescriptionItem->rect.top,
_editingDescriptionItem->rect.width() + 1, _editingDescriptionItem->rect.height() - 2);
setItemCaption(_editingDescriptionItem, _editingDescriptionItem->caption.c_str());
drawItem(_editingDescriptionID, true);
} else if (kbd.keycode == Common::KEYCODE_RETURN) {
SavegameItem *savegameItem = getSavegameItemByID(_editingDescriptionID);
_editingDescription = false;
_vm->requestSavegame(savegameItem->_slotNum, _editingDescriptionItem->caption);
_running = false;
} else if (kbd.keycode == Common::KEYCODE_ESCAPE) {
_editingDescription = false;
}
}
}
ItemID MenuSystem::findItemAt(int x, int y) {
for (Common::Array<Item>::iterator iter = _items.begin(); iter != _items.end(); iter++) {
if ((*iter).rect.contains(x, y))
return (*iter).id;
}
return kItemIdNone;
}
MenuSystem::Item *MenuSystem::getItem(ItemID id) {
for (Common::Array<Item>::iterator iter = _items.begin(); iter != _items.end(); iter++) {
if ((*iter).id == id)
return &(*iter);
}
return NULL;
}
void MenuSystem::setItemCaption(Item *item, const char *caption) {
Font font(_vm->_res->load(_vm->_screen->getFontResIndex(item->fontNum))->data);
int width = font.getTextWidth((const byte*)caption);
int height = font.getHeight();
item->rect = Common::Rect(item->x, item->y - height, item->x + width, item->y);
if (item->w) {
item->rect.translate(item->w - width / 2, 0);
}
item->caption = caption;
}
void MenuSystem::initMenu(MenuID menuID) {
int newSlotNum;
_items.clear();
memcpy(_vm->_screen->_frontScreen, _background->pixels, 640 * 400);
switch (menuID) {
case kMenuIdMain:
drawString(0, 74, 320, 1, 229, _vm->getSysString(kStrWhatCanIDoForYou));
addClickTextItem(kItemIdLoad, 0, 115, 320, 0, _vm->getSysString(kStrLoad), 229, 255);
addClickTextItem(kItemIdSave, 0, 135, 320, 0, _vm->getSysString(kStrSave), 229, 255);
addClickTextItem(kItemIdToggleText, 0, 165, 320, 0, _vm->getSysString(kStrTextOn), 229, 255);
addClickTextItem(kItemIdToggleVoices, 0, 185, 320, 0, _vm->getSysString(kStrVoicesOn), 229, 255);
addClickTextItem(kItemIdVolumesMenu, 0, 215, 320, 0, _vm->getSysString(kStrVolume), 229, 255);
addClickTextItem(kItemIdPlay, 0, 245, 320, 0, _vm->getSysString(kStrPlay), 229, 255);
addClickTextItem(kItemIdQuit, 0, 275, 320, 0, _vm->getSysString(kStrQuit), 229, 255);
break;
case kMenuIdLoad:
drawString(0, 74, 320, 1, 229, _vm->getSysString(kStrLoadGame));
addClickTextItem(kItemIdSavegameUp, 0, 155, 545, 1, "^", 255, 253);
addClickTextItem(kItemIdSavegameDown, 0, 195, 545, 1, "\\", 255, 253);
addClickTextItem(kItemIdCancel, 0, 275, 320, 0, _vm->getSysString(kStrCancel), 255, 253);
addClickTextItem(kItemIdSavegame1, 0, 115 + 20 * 0, 300, 0, "SAVEGAME 1", 231, 234);
addClickTextItem(kItemIdSavegame2, 0, 115 + 20 * 1, 300, 0, "SAVEGAME 2", 231, 234);
addClickTextItem(kItemIdSavegame3, 0, 115 + 20 * 2, 300, 0, "SAVEGAME 3", 231, 234);
addClickTextItem(kItemIdSavegame4, 0, 115 + 20 * 3, 300, 0, "SAVEGAME 4", 231, 234);
addClickTextItem(kItemIdSavegame5, 0, 115 + 20 * 4, 300, 0, "SAVEGAME 5", 231, 234);
addClickTextItem(kItemIdSavegame6, 0, 115 + 20 * 5, 300, 0, "SAVEGAME 6", 231, 234);
addClickTextItem(kItemIdSavegame7, 0, 115 + 20 * 6, 300, 0, "SAVEGAME 7", 231, 234);
loadSavegamesList();
setSavegameCaptions();
break;
case kMenuIdSave:
drawString(0, 74, 320, 1, 229, _vm->getSysString(kStrSaveGame));
addClickTextItem(kItemIdSavegameUp, 0, 155, 545, 1, "^", 255, 253);
addClickTextItem(kItemIdSavegameDown, 0, 195, 545, 1, "\\", 255, 253);
addClickTextItem(kItemIdCancel, 0, 275, 320, 0, _vm->getSysString(kStrCancel), 255, 253);
addClickTextItem(kItemIdSavegame1, 0, 115 + 20 * 0, 300, 0, "SAVEGAME 1", 231, 234);
addClickTextItem(kItemIdSavegame2, 0, 115 + 20 * 1, 300, 0, "SAVEGAME 2", 231, 234);
addClickTextItem(kItemIdSavegame3, 0, 115 + 20 * 2, 300, 0, "SAVEGAME 3", 231, 234);
addClickTextItem(kItemIdSavegame4, 0, 115 + 20 * 3, 300, 0, "SAVEGAME 4", 231, 234);
addClickTextItem(kItemIdSavegame5, 0, 115 + 20 * 4, 300, 0, "SAVEGAME 5", 231, 234);
addClickTextItem(kItemIdSavegame6, 0, 115 + 20 * 5, 300, 0, "SAVEGAME 6", 231, 234);
addClickTextItem(kItemIdSavegame7, 0, 115 + 20 * 6, 300, 0, "SAVEGAME 7", 231, 234);
newSlotNum = loadSavegamesList() + 1;
_savegames.push_back(SavegameItem(newSlotNum, Common::String::format("GAME %03d", _savegames.size() + 1)));
setSavegameCaptions();
break;
case kMenuIdVolumes:
drawString(0, 74, 320, 1, 229, _vm->getSysString(kStrAdjustVolume));
drawString(0, 130, 200, 0, 246, _vm->getSysString(kStrMaster));
drawString(0, 155, 200, 0, 244, _vm->getSysString(kStrVoices));
drawString(0, 180, 200, 0, 244, _vm->getSysString(kStrMusic));
drawString(0, 205, 200, 0, 244, _vm->getSysString(kStrSoundFx));
drawString(0, 230, 200, 0, 244, _vm->getSysString(kStrBackground));
addClickTextItem(kItemIdDone, 0, 275, 200, 0, _vm->getSysString(kStrDone), 229, 253);
addClickTextItem(kItemIdCancel, 0, 275, 440, 0, _vm->getSysString(kStrCancel), 229, 253);
addClickTextItem(kItemIdMasterDown, 0, 130 + 25 * 0, 348, 1, "[", 229, 253);
addClickTextItem(kItemIdVoicesDown, 0, 130 + 25 * 1, 348, 1, "[", 229, 253);
addClickTextItem(kItemIdMusicDown, 0, 130 + 25 * 2, 348, 1, "[", 229, 253);
addClickTextItem(kItemIdSoundFXDown, 0, 130 + 25 * 3, 348, 1, "[", 229, 253);
addClickTextItem(kItemIdBackgroundDown, 0, 130 + 25 * 4, 348, 1, "[", 229, 253);
addClickTextItem(kItemIdMasterUp, 0, 130 + 25 * 0, 372, 1, "]", 229, 253);
addClickTextItem(kItemIdVoicesUp, 0, 130 + 25 * 1, 372, 1, "]", 229, 253);
addClickTextItem(kItemIdMusicUp, 0, 130 + 25 * 2, 372, 1, "]", 229, 253);
addClickTextItem(kItemIdSoundFXUp, 0, 130 + 25 * 3, 372, 1, "]", 229, 253);
addClickTextItem(kItemIdBackgroundUp, 0, 130 + 25 * 4, 372, 1, "]", 229, 253);
drawVolumeBar(kItemIdMaster);
drawVolumeBar(kItemIdVoices);
drawVolumeBar(kItemIdMusic);
drawVolumeBar(kItemIdSoundFX);
drawVolumeBar(kItemIdBackground);
break;
default:
break;
}
for (Common::Array<Item>::iterator iter = _items.begin(); iter != _items.end(); iter++) {
drawItem((*iter).id, false);
}
}
void MenuSystem::enterItem(ItemID id) {
drawItem(id, true);
}
void MenuSystem::leaveItem(ItemID id) {
drawItem(id, false);
}
void MenuSystem::clickItem(ItemID id) {
//Item *item = getItem(id);
switch (id) {
// Main menu
case kItemIdSave:
_newMenuID = kMenuIdSave;
break;
case kItemIdLoad:
_newMenuID = kMenuIdLoad;
break;
case kItemIdToggleText:
setCfgText(!_cfgText, true);
if (!_cfgVoices && !_cfgText)
setCfgVoices(true, false);
break;
case kItemIdToggleVoices:
setCfgVoices(!_cfgVoices, true);
if (!_cfgVoices && !_cfgText)
setCfgText(true, false);
break;
case kItemIdVolumesMenu:
//debug("kItemIdVolumesMenu");
_newMenuID = kMenuIdVolumes;
break;
case kItemIdPlay:
//debug("kItemIdPlay");
_running = false;
break;
case kItemIdQuit:
_running = false;
_vm->quitGame();
break;
// Volumes menu
case kItemIdMasterUp:
changeVolumeBar(kItemIdMaster, +1);
break;
case kItemIdVoicesUp:
changeVolumeBar(kItemIdVoices, +1);
break;
case kItemIdMusicUp:
changeVolumeBar(kItemIdMusic, +1);
break;
case kItemIdSoundFXUp:
changeVolumeBar(kItemIdSoundFX, +1);
break;
case kItemIdBackgroundUp:
changeVolumeBar(kItemIdBackground, +1);
break;
case kItemIdMasterDown:
changeVolumeBar(kItemIdMaster, -1);
break;
case kItemIdVoicesDown:
changeVolumeBar(kItemIdVoices, -1);
break;
case kItemIdMusicDown:
changeVolumeBar(kItemIdMusic, -1);
break;
case kItemIdSoundFXDown:
changeVolumeBar(kItemIdSoundFX, -1);
break;
case kItemIdBackgroundDown:
changeVolumeBar(kItemIdBackground, -1);
break;
case kItemIdCancel:
_newMenuID = kMenuIdMain;
break;
// Save/Load menu
case kItemIdSavegame1:
case kItemIdSavegame2:
case kItemIdSavegame3:
case kItemIdSavegame4:
case kItemIdSavegame5:
case kItemIdSavegame6:
case kItemIdSavegame7:
clickSavegameItem(id);
break;
case kItemIdDone:
_newMenuID = kMenuIdMain;
break;
case kItemIdSavegameUp:
scrollSavegames(-6);
break;
case kItemIdSavegameDown:
scrollSavegames(+6);
break;
default:
break;
}
}
void MenuSystem::restoreRect(int x, int y, int w, int h) {
byte *src = (byte*)_background->getBasePtr(x, y);
byte *dst = _vm->_screen->_frontScreen + x + y * 640;
while (h--) {
memcpy(dst, src, w);
src += 640;
dst += 640;
}
}
void MenuSystem::shadeRect(int x, int y, int w, int h, byte color1, byte color2) {
byte *src = (byte*)_background->getBasePtr(x, y);
for (int xc = 0; xc < w; xc++) {
src[xc] = color2;
src[xc + h * 640] = color1;
}
src += 640;
w -= 1;
h -= 1;
while (h--) {
src[0] = color2;
src[w] = color1;
src += 640;
}
}
void MenuSystem::drawString(int16 x, int16 y, int w, uint fontNum, byte color, const char *text) {
fontNum = _vm->_screen->getFontResIndex(fontNum);
Font font(_vm->_res->load(fontNum)->data);
if (w) {
x = x + w - font.getTextWidth((const byte*)text) / 2;
}
_vm->_screen->drawString(x, y - font.getHeight(), color, fontNum, (const byte*)text, -1, NULL, true);
_needRedraw = true;
}
int MenuSystem::loadSavegamesList() {
int maxSlotNum = -1;
_savegameListTopIndex = 0;
_savegames.clear();
Common::SaveFileManager *saveFileMan = g_system->getSavefileManager();
Picture::PictureEngine::SaveHeader header;
Common::String pattern = _vm->getTargetName();
pattern += ".???";
Common::StringArray filenames;
filenames = saveFileMan->listSavefiles(pattern.c_str());
Common::sort(filenames.begin(), filenames.end()); // Sort (hopefully ensuring we are sorted numerically..)
for (Common::StringArray::const_iterator file = filenames.begin(); file != filenames.end(); file++) {
// Obtain the last 3 digits of the filename, since they correspond to the save slot
int slotNum = atoi(file->c_str() + file->size() - 3);
if (slotNum > maxSlotNum)
maxSlotNum = slotNum;
if (slotNum >= 0 && slotNum <= 999) {
Common::InSaveFile *in = saveFileMan->openForLoading(file->c_str());
if (in) {
if (Picture::PictureEngine::readSaveHeader(in, false, header) == Picture::PictureEngine::kRSHENoError) {
_savegames.push_back(SavegameItem(slotNum, header.description));
//debug("%s -> %s", file->c_str(), header.description.c_str());
}
delete in;
}
}
}
return maxSlotNum;
}
MenuSystem::SavegameItem *MenuSystem::getSavegameItemByID(ItemID id) {
switch (id) {
case kItemIdSavegame1:
case kItemIdSavegame2:
case kItemIdSavegame3:
case kItemIdSavegame4:
case kItemIdSavegame5:
case kItemIdSavegame6:
case kItemIdSavegame7:
return &_savegames[_savegameListTopIndex + id - kItemIdSavegame1];
default:
return NULL;
}
}
void MenuSystem::setSavegameCaptions() {
uint index = _savegameListTopIndex;
setItemCaption(getItem(kItemIdSavegame1), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame2), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame3), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame4), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame5), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame6), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
setItemCaption(getItem(kItemIdSavegame7), index < _savegames.size() ? _savegames[index++]._description.c_str() : "");
}
void MenuSystem::scrollSavegames(int delta) {
int newPos = CLIP<int>(_savegameListTopIndex + delta, 0, _savegames.size() - 1);
_savegameListTopIndex = newPos;
restoreRect(80, 92, 440, 140);
setSavegameCaptions();
drawItem(kItemIdSavegame1, false);
drawItem(kItemIdSavegame2, false);
drawItem(kItemIdSavegame3, false);
drawItem(kItemIdSavegame4, false);
drawItem(kItemIdSavegame5, false);
drawItem(kItemIdSavegame6, false);
drawItem(kItemIdSavegame7, false);
}
void MenuSystem::clickSavegameItem(ItemID id) {
if (_currMenuID == kMenuIdLoad) {
SavegameItem *savegameItem = getSavegameItemByID(id);
//debug("slotNum = [%d]; description = [%s]", savegameItem->_slotNum, savegameItem->_description.c_str());
//_vm->loadgame(savegameItem->_filename.c_str());
_vm->requestLoadgame(savegameItem->_slotNum);
_running = false;
} else {
_editingDescription = true;
_editingDescriptionItem = getItem(id);
_editingDescriptionID = id;
_editingDescriptionItem->activeColor = 249;
_editingDescriptionItem->defaultColor = 249;
drawItem(_editingDescriptionID, true);
}
}
void MenuSystem::setCfgText(bool value, bool active) {
if (_cfgText != value) {
Item *item = getItem(kItemIdToggleText);
_cfgText = value;
restoreRect(item->rect.left, item->rect.top, item->rect.width() + 1, item->rect.height() - 2);
setItemCaption(item, _vm->getSysString(_cfgText ? kStrTextOn : kStrTextOff));
drawItem(kItemIdToggleText, true);
}
}
void MenuSystem::setCfgVoices(bool value, bool active) {
if (_cfgVoices != value) {
Item *item = getItem(kItemIdToggleVoices);
_cfgVoices = value;
restoreRect(item->rect.left, item->rect.top, item->rect.width() + 1, item->rect.height() - 2);
setItemCaption(item, _vm->getSysString(_cfgVoices ? kStrVoicesOn : kStrVoicesOff));
drawItem(kItemIdToggleVoices, true);
}
}
void MenuSystem::drawVolumeBar(ItemID itemID) {
int w = 440, y, volume;
char text[21];
switch (itemID) {
case kItemIdMaster:
y = 130 + 25 * 0;
volume = _cfgMasterVolume;
break;
case kItemIdVoices:
y = 130 + 25 * 1;
volume = _cfgVoicesVolume;
break;
case kItemIdMusic:
y = 130 + 25 * 2;
volume = _cfgMusicVolume;
break;
case kItemIdSoundFX:
y = 130 + 25 * 3;
volume = _cfgSoundFXVolume;
break;
case kItemIdBackground:
y = 130 + 25 * 4;
volume = _cfgBackgroundVolume;
break;
default:
return;
}
Font font(_vm->_res->load(_vm->_screen->getFontResIndex(1))->data);
restoreRect(390, y - font.getHeight(), 100, 25);
for (int i = 0; i < volume; i++)
text[i] = '|';
text[volume] = 0;
drawString(0, y, w, 0, 246, text);
}
void MenuSystem::changeVolumeBar(ItemID itemID, int delta) {
int *volume, newVolume;
switch (itemID) {
case kItemIdMaster:
volume = &_cfgMasterVolume;
break;
case kItemIdVoices:
volume = &_cfgVoicesVolume;
break;
case kItemIdMusic:
volume = &_cfgMusicVolume;
break;
case kItemIdSoundFX:
volume = &_cfgSoundFXVolume;
break;
case kItemIdBackground:
volume = &_cfgBackgroundVolume;
break;
default:
return;
}
newVolume = CLIP(*volume + delta, 0, 20);
if (newVolume != *volume) {
*volume = newVolume;
drawVolumeBar(itemID);
}
}
} // End of namespace Picture
| [
"[email protected]",
"[email protected]",
"[email protected]"
]
| [
[
[
1,
43
],
[
45,
46
],
[
48,
48
],
[
54,
72
],
[
74,
74
],
[
76,
83
],
[
92,
100
],
[
102,
109
],
[
111,
327
],
[
329,
347
],
[
349,
351
],
[
353,
355
],
[
358,
479
],
[
481,
498
],
[
500,
532
],
[
534,
640
]
],
[
[
44,
44
],
[
49,
53
],
[
73,
73
],
[
75,
75
],
[
84,
91
],
[
101,
101
],
[
110,
110
],
[
328,
328
],
[
348,
348
],
[
352,
352
],
[
356,
357
],
[
480,
480
],
[
499,
499
],
[
533,
533
]
],
[
[
47,
47
]
]
]
|
9190427ffcf9ac9adf14bcf9075a626fef7f8eb6 | 35f23e4f6a24dbcb0d2382f42c1246635b98a1a5 | /source/Collectors/IIS7/nativesyslogmodulefactory.h | 71bea9cdec71124d09aca8497f2573bec33da635 | [
"BSD-2-Clause",
"BSD-3-Clause"
]
| permissive | Cloudxtreme/Realtime-Web-Monitoring | d53c1f22e7de6d74499a56852985f6231b7fb211 | 6fcf2bcee10ce6567b972c153f66233c1e0cf6b5 | refs/heads/master | 2021-06-01T07:49:13.134965 | 2011-09-19T21:03:21 | 2011-09-19T21:03:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,714 | h | #ifndef __MODULE_FACTORY_H__
#define __MODULE_FACTORY_H__
// Factory class for CNativeSyslogModule.
// This class is responsible for creating instances
// of CNativeSyslogModule for each request.
class CNativeSyslogModuleFactory : public IHttpModuleFactory
{
public:
CNativeSyslogModuleFactory() {
IAppHostAdminManager * pMgr = NULL;
IAppHostElement * pModuleConfig = NULL;
IAppHostProperty* configProperty = NULL;
BSTR bstrSectionName = SysAllocString(L"system.webServer/nativeSyslogPublisher");
BSTR bstrConfigPath = SysAllocString(L"MACHINE/WEBROOT/APPHOST");
BSTR bstrServerPropName = SysAllocString(L"logServer");
BSTR bstrPortPropName = SysAllocString(L"port");
BSTR bstrMessageSizePropName = SysAllocString(L"maxMessageLength");
BSTR bstrFacilityPropName = SysAllocString(L"facility");
HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
if (SUCCEEDED(hr)) {
hr = CoCreateInstance( __uuidof( AppHostAdminManager ), NULL, CLSCTX_INPROC_SERVER, __uuidof( IAppHostAdminManager ), (void**) &pMgr );
if((SUCCEEDED(hr)) && (pMgr != NULL))
{
hr = pMgr->GetAdminSection(bstrSectionName, bstrConfigPath, &pModuleConfig);
if(SUCCEEDED(hr) && (&pModuleConfig != NULL))
{
VARIANT variantValue;
hr = pModuleConfig->GetPropertyByName(bstrServerPropName, &configProperty);
if (SUCCEEDED(hr) && configProperty) {
hr = configProperty->get_Value(&variantValue);
if (SUCCEEDED(hr)) bstrServerName = SysAllocString(variantValue.bstrVal);
}
VariantClear(&variantValue);
hr = pModuleConfig->GetPropertyByName(bstrPortPropName, &configProperty);
if (SUCCEEDED(hr) && configProperty) {
hr = configProperty->get_Value(&variantValue);
if (SUCCEEDED(hr)) bstrPort = SysAllocString(variantValue.bstrVal);
}
VariantClear(&variantValue);
hr = pModuleConfig->GetPropertyByName(bstrMessageSizePropName, &configProperty);
if (SUCCEEDED(hr) && configProperty) {
hr = configProperty->get_Value(&variantValue);
if (SUCCEEDED(hr)) uiMaxMessageSize = variantValue.uiVal;
}
VariantClear(&variantValue);
hr = pModuleConfig->GetPropertyByName(bstrFacilityPropName, &configProperty);
if (SUCCEEDED(hr) && configProperty) {
hr = configProperty->get_Value(&variantValue);
if (SUCCEEDED(hr)) uiFacility = variantValue.uiVal;
}
}
}
}
if (pMgr != NULL) pMgr->Release();
if (pModuleConfig != NULL) pModuleConfig->Release();
SysFreeString(bstrSectionName);
SysFreeString(bstrConfigPath);
SysFreeString(bstrServerPropName);
SysFreeString(bstrPortPropName);
SysFreeString(bstrMessageSizePropName);
SysFreeString(bstrFacilityPropName);
}
~CNativeSyslogModuleFactory()
{
if (!bstrServerName)
SysFreeString(bstrServerName);
if (!bstrPort)
SysFreeString(bstrPort);
}
virtual HRESULT GetHttpModule(OUT CHttpModule **ppModule, IN IModuleAllocator*)
{
HRESULT hr = S_OK;
CNativeSyslogModule *pModule = new CNativeSyslogModule();
if (!pModule)
{
hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY );
}
else
{
// Load in our settings to override the defaults.
pModule->bstrServerName = SysAllocString(bstrServerName);
pModule->uiMaxMessageSize = uiMaxMessageSize;
pModule->uiFacility = uiFacility;
pModule->bstrPort = SysAllocString(bstrPort);
*ppModule = pModule;
pModule = NULL;
}
return hr;
}
virtual void Terminate()
{
delete this;
}
private:
// syslog server name
BSTR bstrServerName;
// syslog server port
BSTR bstrPort;
// syslog Max Message Size
USHORT uiMaxMessageSize;
// syslog facility
USHORT uiFacility;
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
118
]
]
]
|
804ba377124a2bdc68bcd0bd9c446afe18d9e0f4 | 444a151706abb7bbc8abeb1f2194a768ed03f171 | /trunk/ENIGMAsystem/SHELL/Universal_System/motion_planning_struct.h | f6e5f1fc4daa4022411a66e823080023c9fbdf58 | []
| 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 | ISO-8859-13 | C++ | false | false | 3,082 | h | /********************************************************************************\
** **
** Copyright (C) 2011 Harijs Grīnbergs **
** **
** 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 <vector>
#include <map>
using std::vector;
using std::multimap;
#ifdef INCLUDED_FROM_SHELLMAIN
# error This file includes non-ENIGMA STL headers and should not be included from SHELLmain.
#endif
namespace enigma
{
struct node
{
unsigned x, y, F, H, G, cost;
node* came_from;
vector<node*> neighbor_nodes;
};
struct grid
{
unsigned int id;
int left, top;
unsigned int hcells, vcells, cellwidth, cellheight;
unsigned threshold;
double speed_modifier;
vector<node> nodearray;
grid(unsigned int id,int left,int top,unsigned int hcells,unsigned int vcells,unsigned int cellwidth,unsigned int cellheight, unsigned int threshold, double speed_modifier);
~grid();
};
extern grid** gridstructarray;
void gridstructarray_reallocate();
multimap<unsigned,node*> find_path(unsigned id, node* n0, node* n1, bool allow_diag, bool &status);
}
| [
"[email protected]"
]
| [
[
[
1,
58
]
]
]
|
cb8e5fcfa96b576bd9bdb74f84f8b244a86961a9 | 8cf9b251e0f4a23a6ef979c33ee96ff4bdb829ab | /src-ginga-editing/wac-editing-cpp/src/EditingCommand.cpp | 289d3c29503a1903452229b80103117e8d4841b2 | []
| no_license | BrunoSSts/ginga-wac | 7436a9815427a74032c9d58028394ccaac45cbf9 | ea4c5ab349b971bd7f4f2b0940f2f595e6475d6c | refs/heads/master | 2020-05-20T22:21:33.645904 | 2011-10-17T12:34:32 | 2011-10-17T12:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,282 | cpp | /******************************************************************************
Este arquivo eh parte da implementacao do ambiente declarativo do middleware
Ginga (Ginga-NCL).
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
Este programa eh software livre; voce pode redistribui-lo e/ou modificah-lo sob
os termos da Licenca Publica Geral GNU versao 2 conforme publicada pela Free
Software Foundation.
Este programa eh distribuido na expectativa de que seja util, porem, SEM
NENHUMA GARANTIA; nem mesmo a garantia implicita de COMERCIABILIDADE OU
ADEQUACAO A UMA FINALIDADE ESPECIFICA. Consulte a Licenca Publica Geral do
GNU versao 2 para mais detalhes.
Voce deve ter recebido uma copia da Licenca Publica Geral do GNU versao 2 junto
com este programa; se nao, escreva para a Free Software Foundation, Inc., no
endereco 59 Temple Street, Suite 330, Boston, MA 02111-1307 USA.
Para maiores informacoes:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
******************************************************************************
This file is part of the declarative environment of middleware Ginga (Ginga-NCL)
Copyright (C) 2009 UFSCar/Lince, Todos os Direitos Reservados.
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 version 2 for more
details.
You should have received a copy of the GNU General Public License version 2
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
For further information contact:
[email protected]
http://www.ncl.org.br
http://www.ginga.org.br
http://lince.dc.ufscar.br
*******************************************************************************/
/**
* @file EditingCommand.h
* @author Caio Viel
* @date 29-01-10
*/
#include "../include/EditingCommand.h"
namespace br {
namespace ufscar {
namespace lince {
namespace ginga {
namespace wac {
namespace editing {
EditingCommand::EditingCommand() {
entity = NULL;
type = NONE;
commandId = "";
}
EditingCommand::EditingCommand(Entity* e, string id) {
this->entity = e;
commandId = id;
setEntity(e);
}
EditingCommand::EditingCommand(string id, int t) {
entity = NULL;
commandId = id;
this->type = t;
}
EditingCommand::~EditingCommand() {
//não faz nada
}
void EditingCommand::setEntity(Entity* e){
this->entity = e;
if (entity->instanceOf("Node")) {
type = ADD_NODE;
} else if (entity->instanceOf("Rule")) {
type = ADD_RULE;
} else if (entity->instanceOf("Transition")) {
type = ADD_TRANSITION;
} else if (entity->instanceOf("Connector")) {
type = ADD_CONNECTOR;
} else if (entity->instanceOf("GenericDescriptor")) {
type = ADD_DESCRIPTOR;
} else if (entity->instanceOf("InterfacePoint")) {
type = ADD_INTERFACE;
} else if (entity->instanceOf("Link")) {
type = ADD_LINK;
} else {
type = NONE;
}
}
Entity* EditingCommand::getEntity() {
return entity;
}
int EditingCommand::getEntityType() {
return type;
}
void EditingCommand::setCommandId(string id) {
this->commandId = id;
}
string EditingCommand::getCommandId() {
return commandId;
}
const int EditingCommand::NONE=-1;
const int EditingCommand::ADD_RULE=1;
const int EditingCommand::REMOVE_RULE=2;
const int EditingCommand::ADD_TRANSITION=3;
const int EditingCommand::REMOVE_TRANSITION=4;
const int EditingCommand::ADD_CONNECTOR=5;
const int EditingCommand::REMOVE_CONNECTOR=6;
const int EditingCommand::ADD_DESCRIPTOR=7;
const int EditingCommand::REMOVE_DESCRIPTOR=8;
const int EditingCommand::ADD_NODE=9;
const int EditingCommand::REMOVE_NODE=10;
const int EditingCommand::ADD_INTERFACE=11;
const int EditingCommand::REMOVE_INTERFACE=12;
const int EditingCommand::ADD_LINK=13;
const int EditingCommand::REMOVE_LINK=14;
const int EditingCommand::ADD_REGION=15;
const int EditingCommand::REMOVE_REGION=16;
}
}
}
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
147
]
]
]
|
54820af66ccb36ed1d6f609135b12e563f4ce225 | 1caba14ec096b36815b587f719dda8c963d60134 | /tags/start/smx/libsmx/strx.cpp | 3512fcbaa6e3a77e43db7ae99c8c93d81188a9f9 | []
| no_license | BackupTheBerlios/smx-svn | 0502dff1e494cffeb1c4a79ae8eaa5db647e5056 | 7955bd611e88b76851987338b12e47a97a327eaf | refs/heads/master | 2021-01-10T19:54:39.450497 | 2009-03-01T12:24:56 | 2009-03-01T12:24:56 | 40,749,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,100 | cpp | /* COPYRIGHT 1998 Prime Data Corp.
All Rights Reserved. Use of this file without prior written
authorization is strictly prohibited.
*/
#include <stdio.h>
#include <stdarg.h>
#include "qlib.h"
#include "str.h"
#include "map.h"
char *CStr::s_empty = "";
CStr &operator <<(CStr &left, float right)
{
return operator <<(left, (double) right);
}
CStr &operator <<(CStr &left, double right)
{
int l = left.Length();
int r = strlen(_gcvt(right, 10, left.Grow(l + 32) + l));
left.Grow(l + r);
return left;
}
CStr operator <<(CStr left, int right)
{
int l = left.Length();
int r = strlen(_itoa(right, left.Grow(l + 32) + l, 10));
left.Grow(l + r);
return left;
}
CStr &operator <<(CStr &left, long right)
{
int l = left.Length();
int r = strlen(_itoa(right, left.Grow(l + 32) + l, 10));
left.Grow(l + r);
return left;
}
CStr operator <<(const char *left, const CStr &right)
{
return CStr(left) << right;
}
CStr CStr::Null = 0;
CStr CStr::Empty = CStr("", 0);
// string conversion helpers
void strcln(const char *p, char *t, char *e)
{
while (*p && t < e) {
if (!(*p == '$' || *p == ','))
*t++ = *p++;
++p;
}
}
double strtodx(const char *str)
{
const char *base, *p; char *endp;
p = base = str;
while (*p) {
if (*p == '$' || *p == ',') {
char buf[256];
int len = MIN(128,p - base);
char *t = buf + len;
char *e = buf + 256;
memcpy(buf, base, len);
++p;
strcln(p, t, e);
return strtod(buf, &endp);
}
++p;
}
return strtod(base, &endp);
}
int strlenx(const char *b)
{
const char *p = b;
while (*p)
if (*p == '<')
return p - b;
else
++p;
return p - b;
}
double strtolx(const char *str)
{
const char *base, *p; char *endp;
p = base = str;
while (*p) {
if (*p == '$' || *p == ',') {
char buf[128];
int len = MIN(64,p - base);
char *t = buf + len;
char *e = buf + 128;
memcpy(buf, base, len);
++p;
strcln(p, t, e);
return strtol(buf, &endp, 0);
}
++p;
}
return strtol(base, &endp, 0);
}
| [
"(no author)@407f561b-fe63-0410-8234-8332a1beff53"
]
| [
[
[
1,
107
]
]
]
|
75b7b2f8780564d662e5a33a2bfc9da87e9ae771 | 3bf3c2da2fd334599a80aa09420dbe4c187e71a0 | /FreezeTower.cpp | ea6a6ab5fb5291919d725704ad933b0d8921cebd | []
| no_license | xiongchiamiov/virus-td | 31b88f6a5d156a7b7ee076df55ddce4e1c65ca4f | a7b24ce50d07388018f82d00469cb331275f429b | refs/heads/master | 2020-12-24T16:50:11.991795 | 2010-06-10T05:05:48 | 2010-06-10T05:05:48 | 668,821 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,993 | cpp | #include "FreezeTower.h"
#include "constants.h"
#include "models.h"
#include "Particles.h"
#include "shadow.h"
namespace f_tower{
const int MAX_UPGRADES = 3;
const int MAX_HP[MAX_UPGRADES] = {8, 12, 16};
const int ATK[MAX_UPGRADES] = {4, 8, 16};
const int ATK_DT[MAX_UPGRADES] = {3000, 3000, 3000}; //Milleseconds between attacks
const float RANGE[MAX_UPGRADES] = {2.5, 2.5, 3.0};
const int BUILD_TIME = 3000;
char* SOUND = "media/sounds/whoosh.wav";
}
using namespace f_tower;
FreezeTower::FreezeTower(float inx, float iny, float inz, int gx, int gy):
Tower(inx, iny, inz, gx, gy)
{
hp = MAX_HP[0];
max_hp = MAX_HP[0];
ai.atk_dmg = ATK[0];
ai.atk_dt = ATK_DT[0];
ai.range = RANGE[0];
type = T_FREEZE;
build_time = BUILD_TIME;
stage = 0;
sound = SOUND;
weapon = new Particles(0.3);
weapon->setWeaponType(particle_texture[2]);
weapon->setSpeed(1.75);
weapon->setSpread(2.0);
animateSpeed = 5;
}
FreezeTower::~FreezeTower(void)
{
delete weapon;
}
void FreezeTower::draw(GLuint id, GLenum mode){
glPushMatrix();
glTranslatef(x, y, z);
glPushMatrix();
// glPushMatrix();
// // Scale and orient animation to fit grid
// glTranslatef(0.0, 0.25, 0.0);
// glScaled(0.15, 0.15, 0.15);
// if(ai.hasTarget){
// if(ai.last_atk < ai.atk_dt) {
// weapon->setDirection(ai.target->getX() - x, 0.0, ai.target->getZ() - z, true);
// weapon->drawParticles();
// }
// } else {
// weapon->reset();
// }
// glPopMatrix();
// Scale and orient model to fit grid
glTranslatef(0.0, 0.4, 0.0);
// Mini Tower Defense TBQH
glScaled(0.035, 0.035, 0.035);
glTranslatef(0.0, 2.0, 0.0);
// glCallList(vtd_dl::fanDL);
if (animateSpeed >= 360) {
animateSpeed = 0;
}
double dist = sqrt((getX() - cam.getCamX()) * (getX() - cam.getCamX())
+ (getY() - cam.getCamY()) * (getY() - cam.getCamY())
+ (getZ() - cam.getCamZ()) * (getZ() - cam.getCamZ()));
if(mode == GL_SELECT)
glLoadName(id);
if (dist <= 8) {
drawFanDLAnimated(animateSpeed+=5, 3);
} else if (dist <= 11) {
drawFanDLAnimated(animateSpeed+=5, 2);
} else {
drawFanDLAnimated(animateSpeed+=5, 1);
}
glPopMatrix();
glPushMatrix();
if(mode == GL_RENDER)
draw_shadow(4);
glPopMatrix();
glPopMatrix();
}
void FreezeTower::step(float dt){
}
bool FreezeTower::shoot(){
bool ret = Tower::shoot();
if(ret){
ai.target->slow();
}
return ret;
}
bool FreezeTower::upgrade(){
if(stage < MAX_UPGRADES){
hp = MAX_HP[stage++];
max_hp = MAX_HP[stage];
ai.atk_dmg = ATK[stage];
ai.atk_dt = ATK_DT[stage];
ai.range = RANGE[stage];
return true;
}
return false;
} | [
"agonza40@05766cc9-4f33-4ba7-801d-bd015708efd9",
"kehung@05766cc9-4f33-4ba7-801d-bd015708efd9",
"jlangloi@05766cc9-4f33-4ba7-801d-bd015708efd9",
"tcasella@05766cc9-4f33-4ba7-801d-bd015708efd9"
]
| [
[
[
1,
2
],
[
6,
30
],
[
36,
42
],
[
44,
44
],
[
46,
46
],
[
48,
60
],
[
93,
118
]
],
[
[
3,
4
],
[
31,
35
],
[
45,
45
],
[
47,
47
],
[
61,
76
],
[
80,
88
]
],
[
[
5,
5
],
[
89,
89
],
[
92,
92
]
],
[
[
43,
43
],
[
77,
79
],
[
90,
91
]
]
]
|
f22f6b8fea6b589d5e1e1458675000c6d9fe078c | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/InPlaceList.h | 4785bdb49d416e93d58d61b4b4614d0a793a9c76 | []
| no_license | wgwang/yinhustock | 1c57275b4bca093e344a430eeef59386e7439d15 | 382ed2c324a0a657ddef269ebfcd84634bd03c3a | refs/heads/master | 2021-01-15T17:07:15.833611 | 2010-11-27T07:06:40 | 2010-11-27T07:06:40 | 37,531,026 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,141 | h | #if !defined(AFX_INPLACELIST_H__ECD42822_16DF_11D1_992F_895E185F9C72__INCLUDED_)
#define AFX_INPLACELIST_H__ECD42822_16DF_11D1_992F_895E185F9C72__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// InPlaceList.h : header file
//
//
// Written by Chris Maunder ([email protected])
// Copyright (c) 1998.
//
// The code contained in this file is based on the original
//
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included. If
// the source code in this file is used in any commercial application
// then acknowledgement must be made to the author of this file
// (in whatever form you wish).
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// Expect bugs!
//
// Please use and enjoy. Please let me know of any bugs/mods/improvements
// that you have found/implemented and I will fix/incorporate them into this
// file.
//
/////////////////////////////////////////////////////////////////////////////
#define IDC_COMBOEDIT 1001
class CComboEdit : public CEdit
{
public:
CComboEdit();
public:
public:
//{{AFX_VIRTUAL(CComboEdit)
virtual BOOL PreTranslateMessage(MSG* pMsg);
//}}AFX_VIRTUAL
public:
virtual ~CComboEdit();
protected:
//{{AFX_MSG(CComboEdit)
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
class CInPlaceList : public CComboBox
{
friend class CComboEdit;
public:
CInPlaceList(CWnd* pParent,
CRect& rect,
DWORD dwStyle,
UINT nID,
int nRow, int nColumn,
CStringArray& Items,
CString sInitText,
UINT nFirstChar);
public:
CComboEdit m_edit;
public:
//{{AFX_VIRTUAL(CInPlaceList)
protected:
virtual void PostNcDestroy();
//}}AFX_VIRTUAL
public:
virtual ~CInPlaceList();
protected:
void EndEdit();
protected:
//{{AFX_MSG(CInPlaceList)
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
afx_msg void OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
int m_nNumLines;
CString m_sInitText;
int m_nRow;
int m_nCol;
UINT m_nLastChar;
BOOL m_bExitOnArrows;
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_INPLACELIST_H__ECD42822_16DF_11D1_992F_895E185F9C72__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
129
]
]
]
|
eb79f57123393290b03b9b155dd5decc28b32f01 | d504537dae74273428d3aacd03b89357215f3d11 | /src/Script/Meshifier.cpp | 3adb05516038b2d35e54c960764ac08dfa5270f6 | []
| no_license | h0MER247/e6 | 1026bf9aabd5c11b84e358222d103aee829f62d7 | f92546fd1fc53ba783d84e9edf5660fe19b739cc | refs/heads/master | 2020-12-23T05:42:42.373786 | 2011-02-18T16:16:24 | 2011-02-18T16:16:24 | 237,055,477 | 1 | 0 | null | 2020-01-29T18:39:15 | 2020-01-29T18:39:14 | null | UTF-8 | C++ | false | false | 5,985 | cpp |
#include "Script.h"
#include "e6_impl.h"
#include "e6_container.h"
#include "../Core/Core.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // system call & varargs
#include <stdarg.h> // system call & varargs
namespace Meshifier
{
struct CInterpreter
: public e6::Class< e6::CName<Script::Interpreter>, CInterpreter>
{
char _konsole[8192];
char _kinput[8192];
bool _selAll;
CInterpreter()
{
memset( _konsole, 0, 8192 );
memset( _kinput, 0, 8192 );
_selAll = 0;
$1("CInterpreter()");
}
~CInterpreter()
{
$1("~CInterpreter()");
}
virtual bool exec( e6::Engine * engine, const char *buffer )// load & run
{
Core::World * world = (Core::World *)engine->createInterface( "Core", "Core.World" );
print_konsole("<< Meshifier %s >>\n", __DATE__ );
E_RELEASE( world );
return false;
}
virtual const char * getOutput() const // virtual console
{
return _konsole;
}
virtual void clearOutput() // clear virtual console
{
_konsole[0]=0;
return ;
}
/***
bool process( Core::Node *node, int what, float x, float y, float z )
{
switch( what ) {
case 0:
print_konsole( "scale %s %f %f %f\r\n", s->getName(), x,y,z );
Meshify::scale(node, x,y,z);
break;
case 1:
print_konsole( "rot %s %f %f %f\r\n", s->getName(), x,y,z );
Meshify::rot(node, x,y,z);
break;
case 2:
print_konsole( "move %s %f %f %f\r\n", s->getName(), x,y,z );
Meshify::move(node, x,y,z);
break;
case 3:
print_konsole( "yz %s \r\n", s->getName() );
Meshify::yz(node);
break;
case 4:
print_konsole( "norms %s\r\n", s->getName() );
Meshify::normals(node);
break;
case 5:
print_konsole( "share %s\r\n", s->getName() );
Meshify::share(node,_konsole);
break;
case 6:
print_konsole( "world %s\r\n", s->getName() );
Meshify::world(node,m->getFrame()->getComposite());
m->getFrame()->reset();
break;
default : return 0;
}
m->getBox()->clear();
return 1;
}
bool Meshifier::run()
{
if ( _kinput[0] == 0 ) return 0;
int what=0;
float x=0,y=0,z=0;
char str[300];
str[0]=0;
IScene *scn = engine->activeScene();
if ( ! scn ) {
print_konsole("no scene active !\r\n");
return 0;
}
if ( sscanf(_kinput, "lmap %d", &what ) == 1 )
{
ILightMapper *lm = createLightMapper();
lm->setOptions( what, (what!=0), _konsole );
lm->lightScene( engine, scn );
delete lm;
return 1;
}
else
if ( sscanf(_kinput, "sel %s", str ) ) {
_selAll=0;
if ( !strcmp(str,"all") )
return (_selAll=1);
IBase *base=0;
const char *t = engine->deepSearch(str, &base);
if (base){
mdl = dynamic_cast<IModel*>(base);
if ( mdl ) {
print_konsole("selected %s %s!\r\n", t, str);
return 1;
}
else print_konsole("err :%s %s is not Model !\r\n", t, str );
}
else print_konsole("err :%s %s not found !\r\n", t, str );
return 0;
}
else
if ( sscanf(_kinput, "load %s", str ) ) {
return engine->loadScene(str);
}
else
if ( sscanf(_kinput, "save %s", str ) ) {
return engine->saveScene(str);
}
else
if ( sscanf(_kinput, "scale %f %f %f", &x,&y,&z ) ) what = 0;
else
if ( sscanf(_kinput, "rot %f %f %f", &x,&y,&z ) ) what = 1;
else
if ( sscanf(_kinput, "move %f %f %f", &x,&y,&z ) ) what = 2;
else
if ( !strncmp(_kinput, "swapyz",6 ) ) what = 3;
else
if ( !strncmp(_kinput, "norms",5 ) ) what = 4;
else
if ( !strncmp(_kinput, "share",5 ) ) what = 5;
else
if ( !strncmp(_kinput, "world",5 ) ) what = 6;
else {
print_konsole("could not eval your input ('%s')\r\ntry one of those:\r\n",_kinput);
print_konsole("load sc-name -- load a scene\r\n");
print_konsole("save sc-name -- save a scene\r\n");
print_konsole("sel m-name -- select model\r\n");
print_konsole("world -- transform to world-coords\r\n");
print_konsole("share -- try to share verz (active modl)\r\n");
print_konsole("norms -- generate shared face-norms(active modl)\r\n");
print_konsole("swapyz -- swap active Model's y-z verts\r\n");
print_konsole("scale x y z -- scale active model\r\n");
print_konsole("rot x y z -- rotate active model (world-space)\r\n");
print_konsole("move x y z -- move active Model (world-space)\r\n");
return 0;
}
if ( selAll )
{
for ( IModel *m = scn->getModel(); m; m=m->next() )
process( m, what, x,y,z );
return 1;
}
else
return process( mdl, what, x,y,z );
if ( mdl )
print_konsole("no model active !\r\n");
return 0;
}
***/
void print_konsole( const char *fmt, ... )
{
if ( ! fmt || !fmt[0] ) return;
static char buffer[2048] = {0};
buffer[0] = 0;
va_list args;
va_start( args, fmt );
vsprintf( buffer, fmt, args );
va_end( args );
int len = strlen(buffer);
buffer[len] = 0;
if ( (strlen(_konsole) + len) > 8190 )
_konsole[0] = 0; // sorry, we've got to clear the buffer
strcat( _konsole, buffer );
}
};
};
extern "C"
uint getClassInfo( e6::ClassInfo ** ptr )
{
const static e6::ClassInfo _ci[] =
{
{ "Script.Interpreter", "Meshifier", Meshifier::CInterpreter::createInterface },
{ 0, 0, 0 }
};
*ptr = (e6::ClassInfo *)_ci;
return 1; // classses
}
#include "../e6/version.h"
extern "C"
uint getVersion( e6::ModVersion * mv )
{
mv->modVersion = ("MyScript 00.000.0001 (" __DATE__ ")");
mv->e6Version = e6::e6_version;
return 1;
}
| [
"[email protected]"
]
| [
[
[
1,
228
]
]
]
|
25e7673e42aedba08c376a9f36bc2e1f117aa6bd | 871585f3c45603024488cabd14184610af7a081f | /conv_inc_i/main.cpp | b4891ea8129f53bf89d74ba0802cc4ef564c99b6 | []
| no_license | davideanastasia/ORIP | 9ac6fb8c490d64da355d34804d949b85ea17dbff | 54c180b442a02a202076b8072ceb573f5e345871 | refs/heads/master | 2016-09-06T14:17:22.765343 | 2011-11-05T16:23:23 | 2011-11-05T16:23:23 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 9,912 | cpp | /* ORIP_v2 –> Op Ref Im Proc -> Oper Refin Imag Process -> Operational Refinement of Image Processing
*
* Copyright Davide Anastasia and Yiannis Andreopoulos, University College London
*
* http://www.ee.ucl.ac.uk/~iandreop/ORIP.html
* If you have not retrieved this source code via the above link, please contact [email protected] and [email protected]
*
*/
#define _CRT_SECURE_NO_DEPRECATE
#include <iostream>
#include <fstream>
#include <functional>
#include <algorithm>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include "commandlineparser.h"
#include "common_lib.h"
#include "library.h"
#include "timing.h"
// boolean for threading cooperation
#ifdef _OPENMP
#include <omp.h>
#include "sleep_t.h"
extern bool flag_int;
extern bool flag_scheduler;
#endif
// ---
using namespace std;
int main(int ac, char* av[])
{
#ifdef _OPENMP
cout << " 2D Conv w/ Loose Packing & Scheduling: Two Threads (Main Loop + Scheduler)" << endl;
cout << " OpenMP Enabled: " << _OPENMP << endl;
#else
cout << " 2D Conv w/ Loose Packing" << endl;
#endif
// TIMER -----
My_Timer perf_timer;
My_Timer perf_timer_f;
// -----------
#ifdef _OPENMP
Sleep_T sleep_timer;
int num_incomplete_frame = 0;
#endif
// input file
FILE *ifile;
FILE *ofile;
// ----
command_line_parser* parser = new command_line_parser();
parser->parse_line(ac, av);
if (parser->is_set_help())
{
parser->get_help();
return 1;
}
if ( !(parser->check_constrains()) )
{
parser->get_help();
return 1; // 1: error
}
if ( (ifile = fopen(parser->get_input_filename().c_str(), "rb")) == NULL )
{
cerr << "[!] Binary image doesn't exist or there's possibly a wrong path" << endl;
exit(1);
}
if ( parser->get_output_filename() != DEFAULT_OUT_FILE )
{
if ( (ofile = fopen(parser->get_output_filename().c_str(), "wb")) == NULL )
{
cerr << "[!] Output file cannot be opened" << endl;
exit(1);
}
}
parser->print_progression_pattern();
#ifdef _OPENMP
// Setting Thread timer variables
int time = parser->get_time();
int jitter = parser->get_time_jitter();
time -= jitter;
if ( time < 0 ) time = 0;
jitter *= 2;
cout << " Clock Timer Configuration: (" << time << "," << time+jitter << ")" << endl;
// END ---
#endif
// -----------------------------------------------------------------------------
double wrk_time = 0;
int last_bitplane = NUM_BITPLANE + 1 - parser->get_bitplane();
int const width = parser->get_width();
int const height = parser->get_height();
int width_c = parser->get_width_conv();
int height_c = parser->get_height_conv();
matrix conv_matrix;
switch ( parser->get_mode() )
{
case 1: {
// 12x12 gaussian
height_c = width_c = 12;
conv_matrix = create_matrix<my_t>(width_c, width_c);
setup_conv_gaussian_12x12(conv_matrix);
break;
}
case 2: {
// 18x18 gaussian
height_c = width_c = 18;
conv_matrix = create_matrix<my_t>(width_c, width_c);
setup_conv_gaussian_18x18(conv_matrix);
break;
}
case 3: {
// 6x6 gaussian
height_c = width_c = 6;
conv_matrix = create_matrix<my_t>(width_c, width_c);
setup_conv_gaussian_6x6(conv_matrix);
break;
}
case 4: {
conv_matrix = read_matrix_from_file<my_t>(parser->get_kernel_filename(), width_c, height_c);
break;
}
default:
conv_matrix = create_matrix<my_t>(width_c, height_c);
setup_conv_matrix(conv_matrix, width_c, height_c, parser->get_kernel_max_value());
}
cout << "CONV =" << endl;
print_matrix(conv_matrix, width_c, height_c);
// -----------------------------------------------------------------------------
// --- calculate max value for packing ----
setup_env(conv_matrix, width_c, height_c, parser->get_max_progression_step());
show_env_status();
// --------------------
// -----------------------------------------------------------------------------
double last_step_perc = parser->get_last_step_percentage();
int width_e = width;
int width_p = width;
int height_e = height;
if ( (height%__num_pack) != 0 )
{
height_e = height + (__num_pack - (height%__num_pack));
}
int height_p = height_e/__num_pack + height_c - 1;
// -----------------------------------------------------------------------------
// -- buffers ------------------------------------------------------------------
matrix input_f = create_matrix<my_t>(width_e, height_e);
matrix input_b = create_matrix<my_t>(width_e, height_e);
my_t** input_p = create_matrix<my_t>(width_p, height_p); // different sizes
my_t** output_p = create_matrix<my_t>(width_p, height_p);
matrix output_f = create_matrix<my_t>(width_e, height_e);
// -----------------------------------------------------------------------------
vector<int> bitplane = parser->get_progression_pattern();
vector<int> indexes = parser->get_progression_indexes();
start_high_priority();
#pragma omp parallel sections num_threads(2)
{
#pragma omp section
// thread 1
{
perf_timer_f.start();
for ( int frames = 0; frames < parser->get_frame_num() ; frames++ )
{
// reset accumulation buffers
reset_matrix(output_f, width_e, height_e);
// read frames
fill_matrix(input_f, width_e, height, ifile);
// --- handling correctly parsing progression
int bits, b;
// ---
for ( int dx = 0; dx < parser->get_progression_steps(); dx++ ) // prog steps
{
bits = bitplane[dx];
b = indexes[dx];
if ( (dx + 1) == parser->get_progression_steps() ) // last step
{
width_p = int(width*last_step_perc);
width_e = int(width*last_step_perc);
}
// extract bitplane
extract_bitplane_matrix_i(input_f, input_b, width_e, height_e, b, bits);
perf_timer.start(); // ---- timer!
pack_matrix(input_b, width_e, height_e, input_p, width_p, height_p, __num_pack);
switch ( parser->get_mode() )
{
case 1:
case 2:
case 3: {
conv2_symmetric(input_p, height_p, width_p, conv_matrix, height_c, width_c, output_p);
}
break;
default: {
conv2(input_p, height_p, width_p, conv_matrix, height_c, width_c, output_p);
}
break;
}
unpack_matrix_and_store_i(output_p, width_p, height_p, output_f, width_e, height_e, __num_pack, b, bits);
perf_timer.stop_and_update();
// --- handling correctly parsing progression
if ( (dx + 1) == parser->get_progression_steps() ) // last step
{
width_p = width;
width_e = width;
}
// ---
#ifdef _OPENMP
//#pragma omp atomic
if ( flag_int == true )
{
cout << "(" << (NUM_BITPLANE - b) << ")";
num_incomplete_frame++;
break;
}
#endif
}
if ( parser->get_output_filename() != DEFAULT_OUT_FILE )
{
write_matrix_full(output_f, width, height, ofile);
}
#ifdef _OPENMP
#pragma omp critical
{
flag_int = false;
sleep_timer.restart();
}
#endif
}
perf_timer_f.stop_and_update();
#ifdef _OPENMP
flag_scheduler = false;
sleep_timer.stop(); // stop timer
#endif
} // thread 1 ----- #pragma omp section
#ifdef _OPENMP
#pragma omp section
// thread 2
{
int susp_t = time;
if ( jitter == 0 ) {
while (flag_scheduler)
{
sleep_timer.set_and_go(susp_t);
flag_int = true;
}
} else {
srand ( 0 );
while (flag_scheduler)
{
#pragma omp critical
{
susp_t = (rand() % jitter) + time;
}
sleep_timer.set_and_go(susp_t);
flag_int = true;
}
}
} // end thread 2
#endif
} // #pragma omp parallel sections num_threads(2)
cout << endl;
exit_high_priority();
//cout << "IN (example output for debug purposes) =" << endl;
//print_matrix(input_f, width, height, PRINT, PRINT);
//print_matrix(input_f, PRINT, PRINT);
//cout << "OUT =" << endl;
//print_matrix(output_f, width, height, PRINT, PRINT);
//print_matrix(output_f, PRINT, PRINT);
cout << endl;
cout << " Execution time (msec): " << perf_timer.get_time() << endl;
cout << " Execution time (msec) + I/O: " << perf_timer_f.get_time() << endl;
cout << " Average execution time per frame (msec): " << perf_timer.get_time()/parser->get_frame_num() << endl;
cout << " Average execution time per frame w/ I/O (msec): " << perf_timer_f.get_time()/parser->get_frame_num() << endl;
#ifdef _OPENMP
cout << " Number of incomplete frame: " << num_incomplete_frame << " / " << parser->get_frame_num() << " ( " << ((double)(num_incomplete_frame)/parser->get_frame_num())*100 <<" % )" <<endl;
#endif
// ------------ clean up -------------------------------------------------------
free_matrix(conv_matrix, width_c, height_c);
free_matrix(input_f, width, height);
free_matrix(input_b, width, height);
free_matrix(input_p, width_p, height_p);
free_matrix(output_p, width_p, height_p);
free_matrix(output_f, width, height);
// -----------------------------------------------------------------------------
return 0; // 0: ok!
}
| [
"[email protected]"
]
| [
[
[
1,
341
]
]
]
|
7f06cea87bd31cd56df71458751954d20d83c4a5 | 978eeebf47d01b62d3223a9aa62f78b0afd1ad19 | /addons/scriptbuilder/scriptbuilder.cpp | 756e1fd3d12fff748b49fec394a49d773f638b05 | [
"MIT"
]
| permissive | kennyzhong/ogre-angelscript | 228bbb6ecd6a4cc77deae25d94ef8316de36cd3a | 9bc9d0cf918dca8d4b23b4eec05130a4b0f109c5 | refs/heads/master | 2021-01-10T08:47:58.931787 | 2011-07-31T20:51:37 | 2011-07-31T20:51:37 | 51,088,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,170 | cpp | #include "scriptbuilder.h"
#include <vector>
using namespace std;
#include <stdio.h>
#if defined(_MSC_VER) && !defined(_WIN32_WCE)
#include <direct.h>
#endif
#ifdef _WIN32_WCE
#include <windows.h> // For GetModuleFileName
#endif
BEGIN_AS_NAMESPACE
// Helper functions
static const char *GetCurrentDir(char *buf, size_t size);
CScriptBuilder::CScriptBuilder()
{
engine = 0;
module = 0;
includeCallback = 0;
callbackParam = 0;
}
void CScriptBuilder::SetIncludeCallback(INCLUDECALLBACK_t callback, void *userParam)
{
includeCallback = callback;
callbackParam = userParam;
}
int CScriptBuilder::StartNewModule(asIScriptEngine *engine, const char *moduleName)
{
if( engine == 0 ) return -1;
this->engine = engine;
module = engine->GetModule(moduleName, asGM_ALWAYS_CREATE);
if( module == 0 )
return -1;
ClearAll();
return 0;
}
int CScriptBuilder::AddSectionFromFile(const char *filename)
{
// TODO: The file name stored in the set should be the fully resolved name because
// it is possible to name the same file in multiple ways using relative paths.
if( IncludeIfNotAlreadyIncluded(filename) )
{
int r = LoadScriptSection(filename);
if( r < 0 )
return r;
}
return 0;
}
int CScriptBuilder::AddSectionFromMemory(const char *scriptCode, const char *sectionName)
{
if( IncludeIfNotAlreadyIncluded(sectionName) )
{
int r = ProcessScriptSection(scriptCode, sectionName);
if( r < 0 )
return r;
}
return 0;
}
int CScriptBuilder::BuildModule()
{
return Build();
}
void CScriptBuilder::DefineWord(const char *word)
{
string sword = word;
if( definedWords.find(sword) == definedWords.end() )
{
definedWords.insert(sword);
}
}
void CScriptBuilder::ClearAll()
{
includedScripts.clear();
#if AS_PROCESS_METADATA == 1
foundDeclarations.clear();
typeMetadataMap.clear();
funcMetadataMap.clear();
varMetadataMap.clear();
#endif
}
bool CScriptBuilder::IncludeIfNotAlreadyIncluded(const char *filename)
{
string scriptFile = filename;
if( includedScripts.find(scriptFile) != includedScripts.end() )
{
// Already included
return false;
}
// Add the file to the set of included sections
includedScripts.insert(scriptFile);
return true;
}
int CScriptBuilder::ProcessScriptSection(const char *script, const char *sectionname)
{
vector<string> includes;
// Perform a superficial parsing of the script first to store the metadata
modifiedScript = script;
// First perform the checks for #if directives to exclude code that shouldn't be compiled
int pos = 0;
int nested = 0;
while( pos < (int)modifiedScript.size() )
{
int len;
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_UNKNOWN && modifiedScript[pos] == '#' )
{
int start = pos++;
// Is this an #if directive?
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
string token;
token.assign(&modifiedScript[pos], len);
pos += len;
if( token == "if" )
{
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_WHITESPACE )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
}
if( t == asTC_IDENTIFIER )
{
string word;
word.assign(&modifiedScript[pos], len);
// Overwrite the #if directive with space characters to avoid compiler error
pos += len;
OverwriteCode(start, pos-start);
// Has this identifier been defined by the application or not?
if( definedWords.find(word) == definedWords.end() )
{
// Exclude all the code until and including the #endif
pos = ExcludeCode(pos);
}
else
{
nested++;
}
}
}
else if( token == "endif" )
{
// Only remove the #endif if there was a matching #if
if( nested > 0 )
{
OverwriteCode(start, pos-start);
nested--;
}
}
}
else
pos += len;
}
#if AS_PROCESS_METADATA == 1
// Preallocate memory
string metadata, declaration;
metadata.reserve(500);
declaration.reserve(100);
#endif
// Then check for meta data and #include directives
pos = 0;
while( pos < (int)modifiedScript.size() )
{
int len;
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_COMMENT || t == asTC_WHITESPACE )
{
pos += len;
continue;
}
#if AS_PROCESS_METADATA == 1
// Is this the start of metadata?
if( modifiedScript[pos] == '[' )
{
// Get the metadata string
pos = ExtractMetadataString(pos, metadata);
// Determine what this metadata is for
int type;
pos = ExtractDeclaration(pos, declaration, type);
// Store away the declaration in a map for lookup after the build has completed
if( type > 0 )
{
SMetadataDecl decl(metadata, declaration, type);
foundDeclarations.push_back(decl);
}
}
else
#endif
// Is this a preprocessor directive?
if( modifiedScript[pos] == '#' )
{
int start = pos++;
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_IDENTIFIER )
{
string token;
token.assign(&modifiedScript[pos], len);
if( token == "include" )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_WHITESPACE )
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
}
if( t == asTC_VALUE && len > 2 && modifiedScript[pos] == '"' )
{
// Get the include file
string includefile;
includefile.assign(&modifiedScript[pos+1], len-2);
pos += len;
// Store it for later processing
includes.push_back(includefile);
// Overwrite the include directive with space characters to avoid compiler error
OverwriteCode(start, pos-start);
}
}
}
}
// Don't search for metadata/includes within statement blocks or between tokens in statements
else
pos = SkipStatement(pos);
}
// Build the actual script
engine->SetEngineProperty(asEP_COPY_SCRIPT_SECTIONS, true);
module->AddScriptSection(sectionname, modifiedScript.c_str(), modifiedScript.size());
if( includes.size() > 0 )
{
// If the callback has been set, then call it for each included file
if( includeCallback )
{
for( int n = 0; n < (int)includes.size(); n++ )
{
int r = includeCallback(includes[n].c_str(), sectionname, this, callbackParam);
if( r < 0 )
return r;
}
}
else
{
// By default we try to load the included file from the relative directory of the current file
// Determine the path of the current script so that we can resolve relative paths for includes
string path = sectionname;
size_t posOfSlash = path.find_last_of("/\\");
if( posOfSlash != string::npos )
path.resize(posOfSlash+1);
else
path = "";
// Load the included scripts
for( int n = 0; n < (int)includes.size(); n++ )
{
// If the include is a relative path, then prepend the path of the originating script
if( includes[n].find_first_of("/\\") != 0 &&
includes[n].find_first_of(":") == string::npos )
{
includes[n] = path + includes[n];
}
// Include the script section
int r = AddSectionFromFile(includes[n].c_str());
if( r < 0 )
return r;
}
}
}
return 0;
}
int CScriptBuilder::Build()
{
int r = module->Build();
if( r < 0 )
return r;
#if AS_PROCESS_METADATA == 1
// After the script has been built, the metadata strings should be
// stored for later lookup by function id, type id, and variable index
for( int n = 0; n < (int)foundDeclarations.size(); n++ )
{
SMetadataDecl *decl = &foundDeclarations[n];
if( decl->type == 1 )
{
// Find the type id
int typeId = module->GetTypeIdByDecl(decl->declaration.c_str());
if( typeId >= 0 )
typeMetadataMap.insert(map<int, string>::value_type(typeId, decl->metadata));
}
else if( decl->type == 2 )
{
// Find the function id
int funcId = module->GetFunctionIdByDecl(decl->declaration.c_str());
if( funcId >= 0 )
funcMetadataMap.insert(map<int, string>::value_type(funcId, decl->metadata));
}
else if( decl->type == 3 )
{
// Find the global variable index
int varIdx = module->GetGlobalVarIndexByDecl(decl->declaration.c_str());
if( varIdx >= 0 )
varMetadataMap.insert(map<int, string>::value_type(varIdx, decl->metadata));
}
}
#endif
return 0;
}
int CScriptBuilder::SkipStatement(int pos)
{
int len;
// Skip until ; or { whichever comes first
while( pos < (int)modifiedScript.length() && modifiedScript[pos] != ';' && modifiedScript[pos] != '{' )
{
engine->ParseToken(&modifiedScript[pos], 0, &len);
pos += len;
}
// Skip entire statement block
if( pos < (int)modifiedScript.length() && modifiedScript[pos] == '{' )
{
pos += 1;
// Find the end of the statement block
int level = 1;
while( level > 0 && pos < (int)modifiedScript.size() )
{
asETokenClass t = engine->ParseToken(&modifiedScript[pos], 0, &len);
if( t == asTC_KEYWORD )
{
if( modifiedScript[pos] == '{' )
level++;
else if( modifiedScript[pos] == '}' )
level--;
}
pos += len;
}
}
else
pos += 1;
return pos;
}
// Overwrite all code with blanks until the matching #endif
int CScriptBuilder::ExcludeCode(int pos)
{
int len;
int nested = 0;
while( pos < (int)modifiedScript.size() )
{
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( modifiedScript[pos] == '#' )
{
modifiedScript[pos] = ' ';
pos++;
// Is it an #if or #endif directive?
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
string token;
token.assign(&modifiedScript[pos], len);
OverwriteCode(pos, len);
if( token == "if" )
{
nested++;
}
else if( token == "endif" )
{
if( nested-- == 0 )
{
pos += len;
break;
}
}
}
else if( modifiedScript[pos] != '\n' )
{
OverwriteCode(pos, len);
}
pos += len;
}
return pos;
}
// Overwrite all characters except line breaks with blanks
void CScriptBuilder::OverwriteCode(int start, int len)
{
char *code = &modifiedScript[start];
for( int n = 0; n < len; n++ )
{
if( *code != '\n' )
*code = ' ';
code++;
}
}
#if AS_PROCESS_METADATA == 1
int CScriptBuilder::ExtractMetadataString(int pos, string &metadata)
{
metadata = "";
// Overwrite the metadata with space characters to allow compilation
modifiedScript[pos] = ' ';
// Skip opening brackets
pos += 1;
int level = 1;
int len;
while( level > 0 && pos < (int)modifiedScript.size() )
{
asETokenClass t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_KEYWORD )
{
if( modifiedScript[pos] == '[' )
level++;
else if( modifiedScript[pos] == ']' )
level--;
}
// Copy the metadata to our buffer
if( level > 0 )
metadata.append(&modifiedScript[pos], len);
// Overwrite the metadata with space characters to allow compilation
if( t != asTC_WHITESPACE )
OverwriteCode(pos, len);
pos += len;
}
return pos;
}
int CScriptBuilder::ExtractDeclaration(int pos, string &declaration, int &type)
{
declaration = "";
type = 0;
int start = pos;
std::string token;
int len = 0;
asETokenClass t = asTC_WHITESPACE;
// Skip white spaces and comments
do
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
} while ( t == asTC_WHITESPACE || t == asTC_COMMENT );
// We're expecting, either a class, interface, function, or variable declaration
if( t == asTC_KEYWORD || t == asTC_IDENTIFIER )
{
token.assign(&modifiedScript[pos], len);
if( token == "interface" || token == "class" )
{
// Skip white spaces and comments
do
{
pos += len;
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
} while ( t == asTC_WHITESPACE || t == asTC_COMMENT );
if( t == asTC_IDENTIFIER )
{
type = 1;
declaration.assign(&modifiedScript[pos], len);
pos += len;
return pos;
}
}
else
{
// For function declarations, store everything up to the start of the statement block
// For variable declaration store everything up until the first parenthesis, assignment, or end statement.
// We'll only know if the declaration is a variable or function declaration when we see the statement block, or absense of a statement block.
int varLength = 0;
declaration.append(&modifiedScript[pos], len);
pos += len;
for(; pos < (int)modifiedScript.size();)
{
t = engine->ParseToken(&modifiedScript[pos], modifiedScript.size() - pos, &len);
if( t == asTC_KEYWORD )
{
token.assign(&modifiedScript[pos], len);
if( token == "{" )
{
// We've found the end of a function signature
type = 2;
return pos;
}
if( token == "=" || token == ";" )
{
// We've found the end of a variable declaration.
if( varLength != 0 )
declaration.resize(varLength);
type = 3;
return pos;
}
else if( token == "(" && varLength == 0 )
{
// This is the first parenthesis we encounter. If the parenthesis isn't followed
// by a statement block, then this is a variable declaration, in which case we
// should only store the type and name of the variable, not the initialization parameters.
varLength = (int)declaration.size();
}
}
declaration.append(&modifiedScript[pos], len);
pos += len;
}
}
}
return start;
}
const char *CScriptBuilder::GetMetadataStringForType(int typeId)
{
map<int,string>::iterator it = typeMetadataMap.find(typeId);
if( it != typeMetadataMap.end() )
return it->second.c_str();
return "";
}
const char *CScriptBuilder::GetMetadataStringForFunc(int funcId)
{
map<int,string>::iterator it = funcMetadataMap.find(funcId);
if( it != funcMetadataMap.end() )
return it->second.c_str();
return "";
}
const char *CScriptBuilder::GetMetadataStringForVar(int varIdx)
{
map<int,string>::iterator it = varMetadataMap.find(varIdx);
if( it != varMetadataMap.end() )
return it->second.c_str();
return "";
}
#endif
static const char *GetCurrentDir(char *buf, size_t size)
{
#ifdef _MSC_VER
#ifdef _WIN32_WCE
static TCHAR apppath[MAX_PATH] = TEXT("");
if (!apppath[0])
{
GetModuleFileName(NULL, apppath, MAX_PATH);
int appLen = _tcslen(apppath);
// Look for the last backslash in the path, which would be the end
// of the path itself and the start of the filename. We only want
// the path part of the exe's full-path filename
// Safety is that we make sure not to walk off the front of the
// array (in case the path is nothing more than a filename)
while (appLen > 1)
{
if (apppath[appLen-1] == TEXT('\\'))
break;
appLen--;
}
// Terminate the string after the trailing backslash
apppath[appLen] = TEXT('\0');
}
#ifdef _UNICODE
wcstombs(buf, apppath, min(size, wcslen(apppath)*sizeof(wchar_t)));
#else
memcpy(buf, apppath, min(size, strlen(apppath)));
#endif
return buf;
#else
return _getcwd(buf, (int)size);
#endif
#elif defined(__APPLE__)
return getcwd(buf, size);
#else
return "";
#endif
}
END_AS_NAMESPACE
| [
"[email protected]_W_722V_Typ_B"
]
| [
[
[
1,
645
]
]
]
|
aa6c002ab5d85749622fbcd38b1597a4c4550dcb | 3eae1d8c99d08bca129aceb7c2269bd70e106ff0 | /trunk/Codes/CLR/Libraries/CorLib/corlib_native_System_Resources_ResourceManager.cpp | 155d2d0b21229d7967871acb2d51ee5c6e4bb686 | []
| no_license | yuaom/miniclr | 9bfd263e96b0d418f6f6ba08cfe4c7e2a8854082 | 4d41d3d5fb0feb572f28cf71e0ba02acb9b95dc1 | refs/heads/master | 2023-06-07T09:10:33.703929 | 2010-12-27T14:41:18 | 2010-12-27T14:41:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,269 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "CorLib.h"
HRESULT Library_corlib_native_System_Resources_ResourceManager::FindResource___STATIC__I4__STRING__SystemReflectionAssembly( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_Assembly_Instance assm;
CLR_INT32 resourceFileId;
CLR_RT_HeapBlock* pArgs = &stack.Arg0();
LPCSTR szText = pArgs[ 0 ].RecoverString(); FAULT_ON_NULL(szText);
TINYCLR_CHECK_HRESULT(Library_corlib_native_System_Reflection_Assembly::GetTypeDescriptor( pArgs[ 1 ], assm ));
TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.LocateResourceFile( assm, szText, resourceFileId ));
stack.SetResult_I4( resourceFileId );
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Resources_ResourceManager::GetObjectInternal___OBJECT__I2( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_Assembly_Instance assm;
CLR_UINT32 size;
const CLR_RECORD_RESOURCE* resource;
CLR_RT_Assembly* pAssm;
const CLR_UINT8* buf;
CLR_RT_HeapBlock* pThis = stack.This();
CLR_RT_HeapBlock* pArgs = &(stack.Arg1());
CLR_UINT32 resourceFileId = pThis[ FIELD__m_resourceFileId ].NumericByRefConst().s4;
CLR_RT_HeapBlock& top = stack.PushValueAndClear();
//
// Set up for restart on out of memory.
//
if(stack.m_customState == 0)
{
stack.m_customState = 1;
stack.m_flags |= CLR_RT_StackFrame::c_CompactAndRestartOnOutOfMemory;
}
TINYCLR_CHECK_HRESULT(Library_corlib_native_System_Reflection_Assembly::GetTypeDescriptor( pThis[ FIELD__m_assembly ], assm ));
TINYCLR_CHECK_HRESULT(g_CLR_RT_TypeSystem.LocateResource( assm, resourceFileId, pArgs[ 0 ].NumericByRefConst().s2, resource, size ));
if(resource != NULL) //otherwise NULL is returned
{
pAssm = assm.m_assm;
buf = pAssm->GetResourceData( resource->offset );
switch(resource->kind)
{
case CLR_RECORD_RESOURCE::RESOURCE_String:
{
TINYCLR_SET_AND_LEAVE(CLR_RT_HeapBlock_String::CreateInstance( top, (LPCSTR)buf, pAssm ));
}
break;
case CLR_RECORD_RESOURCE::RESOURCE_Bitmap:
{
CLR_RT_HeapBlock* ptr;
TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Bitmap ));
ptr = top.Dereference();
//TINYCLR_SET_AND_LEAVE(CLR_GFX_Bitmap::CreateInstance( ptr[ CLR_GFX_Bitmap::FIELD__m_bitmap ], buf, size, pAssm ));
}
break;
case CLR_RECORD_RESOURCE::RESOURCE_Font:
{
CLR_RT_HeapBlock* ptr;
TINYCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex( top, g_CLR_RT_WellKnownTypes.m_Font ));
ptr = top.Dereference();
//TINYCLR_SET_AND_LEAVE(CLR_GFX_Font::CreateInstance( ptr[ CLR_GFX_Font::FIELD__m_font ], buf, pAssm ));
}
break;
case CLR_RECORD_RESOURCE::RESOURCE_Binary:
{
TINYCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Array::CreateInstance( top, size, g_CLR_RT_WellKnownTypes.m_UInt8 ));
memcpy( top.DereferenceArray()->GetFirstElement(), buf, size );
}
break;
default:
_ASSERTE(false);
break;
}
}
TINYCLR_NOCLEANUP();
}
HRESULT Library_corlib_native_System_Resources_ResourceManager::GetObject___STATIC__OBJECT__SystemResourcesResourceManager__SystemEnum( CLR_RT_StackFrame& stack )
{
NATIVE_PROFILE_CLR_CORE();
TINYCLR_HEADER();
CLR_RT_HeapBlock& blkResourceManager = stack.Arg0();
CLR_RT_HeapBlock& blkEnumObj = stack.Arg1();
CLR_RT_HeapBlock* blkVT = blkEnumObj.Dereference();
CLR_RT_HeapBlock* blkEnum = blkVT + 1;
CLR_RT_MethodDef_Instance md;
if(stack.m_customState == 0)
{
stack.m_customState = 1;
FAULT_ON_NULL(blkVT);
if(blkEnum->DataType() != DATATYPE_I2 && blkEnum->DataType() != DATATYPE_U2) TINYCLR_SET_AND_LEAVE( CLR_E_INVALID_PARAMETER );
//call back into ResourceManager.GetObjectFromId(short id);
_SIDE_ASSERTE(md.InitializeFromIndex( g_CLR_RT_WellKnownMethods.m_ResourceManager_GetObjectFromId ));
TINYCLR_CHECK_HRESULT( stack.MakeCall( md, &blkResourceManager, blkEnum, 1 ));
}
TINYCLR_NOCLEANUP();
}
| [
"[email protected]"
]
| [
[
[
1,
135
]
]
]
|
d45112bb82558142a527c83ba38b1c46c29b4f11 | b3f6e84f764d13d5bd49fadb00171f7cd191e2b8 | /src/player.cpp | b1779130aa0f1695e6f526f41220cb9114618324 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
]
| permissive | youngj/cranea | f55a93d2c7b97479a2f9c7f63ac72f1dd419e9f6 | 5411a9374a7dc29dd33e4445ef9277ed2b72c835 | refs/heads/master | 2020-05-18T15:13:03.623874 | 2008-04-23T08:50:20 | 2008-04-23T08:50:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | cpp | // player.cpp : Defines the entry point for the console application.
//
#include "cranea.h"
#include "GameBase.h"
#include "GameInput.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 0)
{
cerr << "Need at least 1 argument to main!" << endl;
return 1;
}
string executableName = baseFileName(argv[0]);
size_t extPos = executableName.rfind('.');
if (extPos != string::npos)
{
executableName = executableName.substr(0, extPos);
}
string encryptedFilename = executableName + ENCRYPTED_EXT;
while (true)
{
GameInput in(encryptedFilename);
if (in.fail())
{
cerr << "Error opening data file " << encryptedFilename << "." << endl;
cout << "Enter another file (blank to quit):";
getline(cin, encryptedFilename);
if (encryptedFilename.empty())
break;
else
continue;
}
GameContext ctx(in);
ctx.playGame();
break;
}
return 0;
}
| [
"adunar@1d512d32-bd3c-0410-8fef-f7bcb4ce661b"
]
| [
[
[
1,
50
]
]
]
|
b70958b8c73f5a5153a8c0a3fc0c461c3f9bde01 | ba9730136fe9cb54b4949ddad93d25cda2ed4a71 | /code/tools/editor/MainFrm.h | 15e4f140f7fc0a932c30abfee791f8532ebfafc5 | []
| no_license | davidfoxhu/nebula3-engine | 0fe6b7b015d839fcc38d7cb100059dc2d729de86 | ead4dca7f82569baa2e69e7c18e53fea8d75468a | refs/heads/master | 2021-01-25T05:34:49.353997 | 2011-06-02T13:19:36 | 2011-06-02T13:19:36 | 34,825,948 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,747 | h | // MainFrm.h : interface of the CMainFrame class
//
#pragma once
#include "ChildView.h"
//#include "MyThread.h"
#include "n3viewerapp.h"
#include "PaneDialog.h"
#include "ExplorerView.h"
class CMainFrame : public CXTPFrameWnd
{
public:
CMainFrame();
protected:
DECLARE_DYNAMIC(CMainFrame)
// Attributes
public:
// Operations
public:
BOOL OnIdle(LONG lCount);
//CXTPDockingPane* GetActivePane();
//CWnd* GetActivePaneView();
void SetActive(BOOL bActive) { m_bIsActive = bActive; m_bRedrawScreen = bActive; };
CPaneDialog& GetPanelDialog();
// Overrides
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo);
// Implementation
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // control bar embedded members
CXTPStatusBar m_wndStatusBar;
CChildView m_wndView;
CXTPDockingPaneManager m_paneManager;
CXTPOfficeBorder<CStatic> m_wndOptions;
CXTPOfficeBorder<CEdit> m_wndProperties;
//CWinThread* m_wndThread;
BOOL m_bIsActive;
BOOL m_bRedrawScreen;
CPaneDialog m_dlgPane;
CExplorerView m_wndExplorerView;
public:
Editor::N3ViewerApp m_gameApp;
// Generated message map functions
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSetFocus(CWnd *pOldWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnClose();
afx_msg void OnCustomize();
afx_msg LRESULT OnDockingPaneNotify(WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnFileOpen();
afx_msg void OnImportCollada();
};
| [
"[email protected]@7e8db568-2a23-3793-81a9-aaa2aa97450b"
]
| [
[
[
1,
74
]
]
]
|
dcf11e3584d482c705bdb852838b05748ba7c9d6 | ea12fed4c32e9c7992956419eb3e2bace91f063a | /zombie/code/renaissance/rnsgameplay/src/ncgameplayliving/ncgameplaylivingclass_cmds.cc | 0a07e9df2129f32c50203e4464f5e4a7770dd3b2 | []
| no_license | ugozapad/TheZombieEngine | 832492930df28c28cd349673f79f3609b1fe7190 | 8e8c3e6225c2ed93e07287356def9fbdeacf3d6a | refs/heads/master | 2020-04-30T11:35:36.258363 | 2011-02-24T14:18:43 | 2011-02-24T14:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,749 | cc | #include "precompiled/pchrnsgameplay.h"
//------------------------------------------------------------------------------
// ncgameplaylivingclass_cmds.cc
// (C) 2005 Conjurer Services, S.A.
//------------------------------------------------------------------------------
#include "ncgameplayliving/ncgameplaylivingclass.h"
//-----------------------------------------------------------------------------
NSCRIPT_INITCMDS_BEGIN(ncGameplayLivingClass)
NSCRIPT_ADDCMD_COMPCLASS('ISXX', void, SetBaseSpeed, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGXX', float, GetBaseSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F001', void, SetMultSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F002', int, GetMultSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGSP', float, GetSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F004', void, SetMultRunSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F005', int, GetMultRunSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGRS', float, GetRunSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F006', void, SetMultIronsightSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F007', int, GetMultIronsightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RGIS', float, GetIronsightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F008', void, SetMultRunIronsightSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F009', int, GetMultRunIronsightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGIR', float, GetRunIronsightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F010', void, SetMultCrouchSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F011', int, GetMultCrouchSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGCH', float, GetCrouchSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F012', void, SetMultProneSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F013', int, GetMultProneSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGCL', float, GetProneSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F014', void, SetMultCrouchIronSightSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F015', int, GetMultCrouchIronSightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGHI', float, GetCrouchIronSightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F016', void, SetMultProneIronSightSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F017', int, GetMultProneIronSightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGLI', float, GetProneIronSightSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F018', void, SetMultSwimSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('F019', int, GetMultSwimSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGWE', float, GetSwimSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RSTS', void, SetTurnSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RGTS', float, GetTurnSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISTR', void, SetTurnRadius, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGTR', float, GetTurnRadius, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ESMT', void, SetMaxAngularVelocityInDegrees, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('EGMT', float, GetMaxAngularVelocityInDegrees, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISJH', void, SetJumpHeight, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGJH', float, GetJumpHeight, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RSJS', void, SetJumpSpeed, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RGJS', float, GetJumpSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISSZ', void, SetSize, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGSZ', float, GetSize, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISMC', void, SetMaxClimbSlope, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGMC', float, GetMaxClimbSlope, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISFD', void, SetFallingDamageRatio, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGFD', float, GetFallingDamageRatio, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISEH', void, SetEyeHeight, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGEH', float, GetEyeHeight, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISUR', void, SetUseRange, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGUR', float, GetUseRange, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('JSSC', void, SetStepsAnimCycle, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('JGSC', int, GetStepsAnimCycle, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISCC', void, SetCanBeCarried, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ICBC', bool, CanBeCarried, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISPU', void, SetPickUp, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGPU', bool, GetPickUp, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISIS', void, SetInventorySize, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGIS', int, GetInventorySize, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISMH', void, SetMaxHealth, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGMH', int, GetMaxHealth, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISRT', void, SetRegenThreshold, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGRT', float, GetRegenThreshold, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISRA', void, SetRegenAmount, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGRA', float, GetRegenAmount, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISGS', void, SetGameplayLivingState, 1, (unsigned int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGST', unsigned int, GetGameplayLivingState, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISCS', void, SetCanBeStunned, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ICBS', bool, CanBeStunned, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISCB', void, SetCanBeIncapacitated, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ICBI', bool, CanBeIncapacitated, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISBK', void, SetCanBeKilled, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ICCK', bool, CanBeKilled, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISNA', void, SetNeedsAir, 1, (bool), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGNA', bool, GetNeedsAir, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISBM', void, SetBreathMax, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGBM', float, GetBreathMax, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISLA', void, SetBreathLossAmount, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGLA', float, GetBreathLossAmount, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISLS', void, SetBreathLossSpeed, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGLS', float, GetBreathLossSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISBR', void, SetBreathRecoverySpeed, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGBR', float, GetBreathRecoverySpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISSR', void, SetSightRadius, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGSR', float, GetSightRadius, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISFA', void, SetFOVAngle, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGFA', float, GetFOVAngle, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISER', void, SetHearingRadius, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGER', float, GetHearingRadius, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISFR', void, SetFeelingRadius, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGFR', float, GetFeelingRadius, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISMT', void, SetMemoryTime, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGMT', int, GetMemoryTime, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISCR', void, SetCommRadius, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGCR', float, GetCommRadius, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISCI', void, SetCommIntensity, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGCI', float, GetCommIntensity, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISMR', void, SetMeleeRange, 1, (float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGMR', float, GetMeleeRange, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('ISAS', void, SetAttackSpeed, 1, (int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('IGAS', float, GetAttackSpeed, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RSDM', void, SetDamageModification, 2, (ncGameplayLivingClass::BodyPart, float), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RGDM', float, GetDamageModification, 1, (ncGameplayLivingClass::BodyPart), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RRSR', void, ResetRingsInfo, 0, (), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RAFR', void, AddFightRing, 2, (float, int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RRFR', void, RemoveFightRing, 2, (float, int), 0, ());
NSCRIPT_ADDCMD_COMPCLASS('RRRI', void, RemoveFightRingIndex, 1, (int), 0, ());
NSCRIPT_INITCMDS_END()
//------------------------------------------------------------------------------
/**
SaveCmds
*/
bool
ncGameplayLivingClass::SaveCmds (nPersistServer* ps)
{
if ( ncGameplayClass::SaveCmds(ps) )
{
// -- baseSpeed
ps->Put (this->entityClass, 'ISXX', this->baseSpeed);
// -- speed
ps->Put (this->entityClass, 'F001', this->multSpeed);
// -- runSpeed
ps->Put (this->entityClass, 'F004', this->multRunSpeed);
// -- ironsightSpeed
if (!ps->Put (this->entityClass, 'F006', this->multIronsightSpeed))
{
return false;
}
// -- runIronsightSpeed
ps->Put (this->entityClass, 'F008', this->multRunIronsightSpeed);
// -- crouchSpeed
ps->Put (this->entityClass, 'F010', this->multCrouchSpeed);
// -- proneSpeed
ps->Put (this->entityClass, 'F012', this->multProneSpeed);
// -- crouchIronsightSpeed
ps->Put (this->entityClass, 'F014', this->multCrouchIronsightSpeed);
// -- proneIronSightSpeed
ps->Put (this->entityClass, 'F016', this->multProneIronSightSpeed);
// -- swimSpeed
ps->Put (this->entityClass, 'F018', this->multSwimSpeed);
// -- turnSpeed
if (!ps->Put (this->entityClass, 'RSTS', this->turnSpeed))
{
return false;
}
// -- turnRadius
ps->Put (this->entityClass, 'ISTR', this->turnRadius);
// -- maxAngularVelocity
ps->Put (this->entityClass, 'ESMT', this->GetMaxAngularVelocityInDegrees());
// -- jumpHeight
ps->Put (this->entityClass, 'ISJH', this->jumpHeight);
// -- jumpSpeed
if (!ps->Put (this->entityClass, 'RSJS', this->jumpSpeed))
{
return false;
}
// -- size
ps->Put (this->entityClass, 'ISSZ', this->size);
// -- maxClimbSlope
ps->Put (this->entityClass, 'ISMC', this->maxClimbSlope);
// -- fallingDamageRatio
ps->Put (this->entityClass, 'ISFD', this->fallingDamageRatio);
// -- eyeHeight
ps->Put (this->entityClass, 'ISEH', this->eyeHeight);
// -- useRange
ps->Put (this->entityClass, 'ISUR', this->useRange);
// ---------------------------------- Inventory attributes --
// -- inventorySize
ps->Put (this->entityClass, 'ISIS', this->inventorySize);
// ------------------------------------- Health attributes --
// -- maxHealth
ps->Put (this->entityClass, 'ISMH', this->maxHealth);
// -- regenThreshold
ps->Put (this->entityClass, 'ISRT', this->regenThreshold);
// -- regenAmount
ps->Put (this->entityClass, 'ISRA', this->regenAmount);
// ------------------------------------- Breath attributes --
// -- breathMax
ps->Put (this->entityClass, 'ISBM', this->breathMax);
// -- breathLossAmount
ps->Put (this->entityClass, 'ISLA', this->breathLossAmount);
// -- breathLossSpeed
ps->Put (this->entityClass, 'ISLS', this->breathLossSpeed);
// -- breathRecoverySpeed
ps->Put (this->entityClass, 'ISBR', this->breathRecoverySpeed);
// --------------------------------- Perception attributes --
// -- sightRadius
ps->Put (this->entityClass, 'ISSR', this->sightRadius);
// -- FOVAngle
ps->Put (this->entityClass, 'ISFA', this->FOVAngle);
// -- hearingRadius
ps->Put (this->entityClass, 'ISER', this->hearingRadius);
// -- feelingRadius
ps->Put (this->entityClass, 'ISFR', this->feelingRadius);
// -- memoryTime
ps->Put (this->entityClass, 'ISMT', this->memoryTime);
// ------------------------------ Communication attributes --
// -- commRadius
ps->Put (this->entityClass, 'ISCR', this->commRadius);
// -- commIntensity
ps->Put (this->entityClass, 'ISCI', this->commIntensity);
// ------------------------------------------- Class state --
// -- state
ps->Put (this->entityClass, 'ISGS', this->state);
// ------------------------------------- Combat attributes --
// -- meleeRange
ps->Put (this->entityClass, 'ISMR', this->meleeRange);
// -- attackSpeed
ps->Put (this->entityClass, 'ISAS', this->attackSpeed);
// reset rings information
if (!ps->Put(this->entityClass, 'RRSR'))
{
return false;
}
// -- rings information
for (int i = 0; i < this->ringsInfo->Size(); i++)
{
if (!ps->Put(this->entityClass, 'RAFR', this->ringsInfo->At(i).radius, this->ringsInfo->At(i).size))
{
return false;
}
}
}
return true;
} | [
"magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91"
]
| [
[
[
1,
245
]
]
]
|
e582c6404e566c4923d5c1f3a56ba25b082b70f0 | 16052d8fae72cecb6249372b80fe633251685e1d | /unknown_val/unknown_handler_factory.cpp | 7b3635eba0ff6c65c4b8a07f3c2d16658201a55c | []
| no_license | istrandjev/hierarhical-clustering | 7a9876c5c6124488162f4089d7888452a53595a6 | adad22cce42d68b04cca747352d94df039e614a2 | refs/heads/master | 2021-01-19T14:59:08.593414 | 2011-06-29T06:07:41 | 2011-06-29T06:07:41 | 32,250,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | cpp | #include "unknown_handler_factory.h"
#include "unknown_values_handler.h"
#include "ignore_unknown_elements_handler.h"
#include "average_unknown_handler.h"
#include "no_unknown_handler.h"
#include <vector>
#include <string>
std::vector<const UnkownHandler*> UnknownHandlerFactory::unkownHandlers;
std::string UnknownHandlerFactory::unknownHandlerName;
bool UnknownHandlerFactory::initialized = false;
// static
void UnknownHandlerFactory::InitUnkownHandlers() {
unkownHandlers.push_back(new NoUnkownHandler());
unkownHandlers.push_back(new AverageUnkownHandler());
unkownHandlers.push_back(new IgnoreUnkownHandler());
initialized = true;
}
// static
const UnkownHandler* UnknownHandlerFactory::getUnkownHandler() {
if (!initialized) {
InitUnkownHandlers();
}
for (size_t index = 0; index < unkownHandlers.size(); ++index) {
if (unkownHandlers[index]->getName() == unknownHandlerName) {
return unkownHandlers[index];
}
}
throw new UnsupportedUnknownHandlerException();
return NULL;
}
// static
const std::vector<const UnkownHandler*> UnknownHandlerFactory::getAllUnkownHandlers() {
if (!initialized) {
InitUnkownHandlers();
}
return unkownHandlers;
}
//static
void UnknownHandlerFactory::setUnknownHandlerName(const std::string& name)
{
unknownHandlerName = name;
}
| [
"[email protected]@c0cadd32-5dbd-3e50-b098-144b922aa411"
]
| [
[
[
1,
51
]
]
]
|
4802c7621ccf41b32d3b46c4d95df86056be39dc | 00b979f12f13ace4e98e75a9528033636dab021d | /branches/ziis/src/core/ziafs_request_header_validation.cc | 7a447a3101793a254e9122d298d630c05eefae53 | []
| no_license | BackupTheBerlios/ziahttpd-svn | 812e4278555fdd346b643534d175546bef32afd5 | 8c0b930d3f4a86f0622987776b5220564e89b7c8 | refs/heads/master | 2016-09-09T20:39:16.760554 | 2006-04-13T08:44:28 | 2006-04-13T08:44:28 | 40,819,288 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,799 | cc | #include <ziafs_http.hh>
#include <ziafs_debug.hh>
#include <zia_stringmanager.hh>
#include <sstream>
#ifndef _WIN32
extern int stricmp(const char*, const char*);
extern int strnicmp(const char*, const char*, int);
#endif // ! _WIN32
bool net::http::valid_method()
{
std::string valid_method[] = {"get", "post", "head", ""};
std::string method_str(m_method);
int flag = 0;
stringmanager::normalize(method_str);
for (int i = 0; !valid_method[i].empty(); i++)
{
if (valid_method[i] == method_str)
flag = 1;
}
if (!flag)
{
// Perhaps a module is using another method
//m_uri.status_code() = 405;
//return false;
}
return true;
}
bool net::http::valid_uri()
{
std::string host;
std::string wwwname(m_uri.wwwname());
std::string tmp;
if (!strncmp("http://", wwwname.c_str(), 7))
{
tmp = wwwname.substr(7, wwwname.length());
size_t i = tmp.find("/", 0);
if (i != std::string::npos)
{
std::string tmmp;
tmmp = tmp.substr(i, tmp.length() - i);
tmp = tmmp;
}
else
{
tmp = "/";
}
m_uri.wwwname() = tmp;
}
//if (wwwname[0] != '/')
//{
// host = "http://";
//if (strncmp(wwwname.c_str(), host.c_str(), host.size()))
//{
// m_uri.status_code() = 400;
// return false;
//}
//}
char *str;
str = (char *)m_uri.wwwname().c_str();
while ((str[0] == '/') && (str[1] == '/'))
str++;
m_uri.wwwname() = str;
if (m_uri.wwwname().empty() || (m_uri.wwwname()[0] != '/'))
{
m_uri.status_code() = 400;
return false;
}
return true;
}
bool net::http::valid_version()
{
if (!strnicmp("http/", request.m_version.c_str(), 5))
{
if (stricmp("http/1.1", request.m_version.c_str()) && stricmp("http/1.0", request.m_version.c_str()))
{
m_uri.status_code() = 505;
return false;
}
}
else
{
m_uri.status_code() = 501;
return false;
}
return true;
}
bool net::http::valid_host()
{
if ((!stricmp("http/1.1", request.m_version.c_str())) && (request["host"].empty()))
{
m_uri.status_code() = 400;
return false;
}
return true;
}
bool net::http::valid_root()
{
// root is valid ?
std::vector<std::string> vec;
std::string str;
str = m_uri.wwwname();
str += "lala";
stringmanager::split(str, "/", vec);
std::vector<std::string>::iterator iter;
int i = 0;
for(iter = vec.begin(); iter != vec.end(); iter++)
{
if ((*iter) == "..")
i--;
else
i++;
}
i--;
if (i < 0)
{
m_uri.status_code() = 403;
return false;
}
return true;
}
bool net::http::request_header_validation()
{
if (!valid_method()) return false;
if (!valid_uri()) return false;
if (!valid_version()) return false;
if (!valid_host()) return false;
if (!valid_root()) return false;
return true;
}
| [
"texane@754ce95b-6e01-0410-81d0-8774ba66fe44",
"zapoutix@754ce95b-6e01-0410-81d0-8774ba66fe44"
]
| [
[
[
1,
38
],
[
40,
40
],
[
52,
52
],
[
54,
56
],
[
68,
74
],
[
80,
84
],
[
99,
103
],
[
109,
130
],
[
132,
132
],
[
135,
146
]
],
[
[
39,
39
],
[
41,
51
],
[
53,
53
],
[
57,
67
],
[
75,
79
],
[
85,
98
],
[
104,
108
],
[
131,
131
],
[
133,
134
]
]
]
|
778130d12a1753973bd10c367b1d9d9f7aa2e003 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/app/contacts/phonebook_fetch_ui_api/ExtraCodes/BCTContactWrapper.cpp | d1340524ec84de3b0236c634a905167639ce5b6f | []
| no_license | SymbianSource/oss.FCL.sftools.ana.compatanamdw | a6a8abf9ef7ad71021d43b7f2b2076b504d4445e | 1169475bbf82ebb763de36686d144336fcf9d93b | refs/heads/master | 2020-12-24T12:29:44.646072 | 2010-11-11T14:03:20 | 2010-11-11T14:03:20 | 72,994,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,702 | cpp | /*
* Copyright (c) 2002 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// INCLUDE FILES
#include <CPbkContactEngine.h>
#include <CPbkContactItem.h>
#include <CPbkFieldsInfo.h>
#include "BCTContactWrapper.h"
#include "BCTBCardData.h"
// LOCAL CONSTANTS AND MACROS
_LIT(KSubfieldDelimiter, "|");
_LIT(KDefaulPhoneTag, "<DEFAULTPHONE>");
_LIT(KLabelStartTag, "<LABEL>");
_LIT(KLabelEndTag, "</LABEL>");
// ---------------------------------------------------------
// Constructor
// ---------------------------------------------------------
//
CBCTContactWrapper::CBCTContactWrapper(
CPbkContactItem& aContact,
CPbkContactEngine& aContactEngine,
const TBool aForVCard)
:iContact(aContact),
iContactEngine(aContactEngine),
iForVCard(aForVCard)
{
}
// ---------------------------------------------------------
// ConstructL
// ---------------------------------------------------------
//
void CBCTContactWrapper::ConstructL()
{
}
// ---------------------------------------------------------
// Two-phased constructor.
// ---------------------------------------------------------
//
CBCTContactWrapper* CBCTContactWrapper::NewL(
CPbkContactItem& aContact,
CPbkContactEngine& aContactEngine,
const TBool aForVCard)
{
CBCTContactWrapper* self = new (ELeave) CBCTContactWrapper(aContact,
aContactEngine,aForVCard);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
// ---------------------------------------------------------
// Destructor
// ---------------------------------------------------------
//
CBCTContactWrapper::~CBCTContactWrapper()
{
}
/**
* Get the contact data.
*/
void CBCTContactWrapper::GetContactDataL(CBCTBCardData& aData)
{
aData.ResetData();
aData.iLastName = GetDataFieldContentsL(EPbkFieldIdLastName);
aData.iFirstName = GetDataFieldContentsL(EPbkFieldIdFirstName);
aData.iPhoneNumberStandard = GetDataFieldContentsL(EPbkFieldIdPhoneNumberStandard);
aData.iPhoneNumberHome = GetDataFieldContentsL(EPbkFieldIdPhoneNumberHome,EPbkFieldLocationHome);
aData.iPhoneNumberWork = GetDataFieldContentsL(EPbkFieldIdPhoneNumberWork,EPbkFieldLocationWork);
aData.iPagerNumber = GetDataFieldContentsL(EPbkFieldIdPagerNumber);
aData.iPhoneNumberMobile = GetDataFieldContentsL(EPbkFieldIdPhoneNumberMobile);
aData.iPhoneNumberMobileHome = GetDataFieldContentsL(EPbkFieldIdPhoneNumberMobile,EPbkFieldLocationHome);
aData.iPhoneNumberMobileWork = GetDataFieldContentsL(EPbkFieldIdPhoneNumberMobile,EPbkFieldLocationWork);
aData.iFaxNumber = GetDataFieldContentsL(EPbkFieldIdFaxNumber);
aData.iFaxNumberHome = GetDataFieldContentsL(EPbkFieldIdFaxNumber,EPbkFieldLocationHome);
aData.iFaxNumberWork = GetDataFieldContentsL(EPbkFieldIdFaxNumber,EPbkFieldLocationWork);
aData.iEmailAddress = GetDataFieldContentsL(EPbkFieldIdEmailAddress);
aData.iEmailAddressHome = GetDataFieldContentsL(EPbkFieldIdEmailAddress,EPbkFieldLocationHome);
aData.iEmailAddressWork = GetDataFieldContentsL(EPbkFieldIdEmailAddress,EPbkFieldLocationWork);
aData.iPostalAddress = GetDataFieldContentsL(EPbkFieldIdPostalAddress);
aData.iPostalAddressHome = GetDataFieldContentsL(EPbkFieldIdPostalAddress,EPbkFieldLocationHome);
aData.iCompanyAddress = GetDataFieldContentsL(EPbkFieldIdPostalAddress,EPbkFieldLocationWork);
aData.iURL = GetDataFieldContentsL(EPbkFieldIdURL);
aData.iURLWork = GetDataFieldContentsL(EPbkFieldIdURL,EPbkFieldLocationWork);
aData.iURLHome = GetDataFieldContentsL(EPbkFieldIdURL,EPbkFieldLocationHome);
aData.iJobTitle = GetDataFieldContentsL(EPbkFieldIdJobTitle);
aData.iCompanyName = GetDataFieldContentsL(EPbkFieldIdCompanyName);
aData.iDate = GetDateL(EPbkFieldIdDate);
aData.iNote = GetDataFieldContentsL(EPbkFieldIdNote);
aData.iPicture = GetDataFieldContentsL(EPbkFieldIdPicture);
// this kind of thumbnail retrieving is not in use any more
//aData.iThumbnailImage = GetDataFieldContentsL(EPbkFieldIdThumbnailImage);
// ADR general
aData.iPOBox = GetDataFieldContentsL(EPbkFieldIdPOBox);
aData.iExtensonAdr = GetDataFieldContentsL(EPbkFieldIdExtendedAddress);
aData.iStreet = GetDataFieldContentsL(EPbkFieldIdStreetAddress);
aData.iPostalCode = GetDataFieldContentsL(EPbkFieldIdPostalCode);
aData.iCity = GetDataFieldContentsL(EPbkFieldIdCity);
aData.iState = GetDataFieldContentsL(EPbkFieldIdState);
aData.iCountry = GetDataFieldContentsL(EPbkFieldIdCountry);
// ADR home
aData.iPOBoxHome = GetDataFieldContentsL(EPbkFieldIdPOBox,EPbkFieldLocationHome);
aData.iExtensonAdrHome = GetDataFieldContentsL(EPbkFieldIdExtendedAddress,EPbkFieldLocationHome);
aData.iStreetHome = GetDataFieldContentsL(EPbkFieldIdStreetAddress,EPbkFieldLocationHome);
aData.iPostalCodeHome = GetDataFieldContentsL(EPbkFieldIdPostalCode,EPbkFieldLocationHome);
aData.iCityHome = GetDataFieldContentsL(EPbkFieldIdCity,EPbkFieldLocationHome);
aData.iStateHome = GetDataFieldContentsL(EPbkFieldIdState,EPbkFieldLocationHome);
aData.iCountryHome = GetDataFieldContentsL(EPbkFieldIdCountry,EPbkFieldLocationHome);
// ADR work
aData.iPOBoxWork = GetDataFieldContentsL(EPbkFieldIdPOBox,EPbkFieldLocationWork);
aData.iExtensonAdrWork = GetDataFieldContentsL(EPbkFieldIdExtendedAddress,EPbkFieldLocationWork);
aData.iStreetWork = GetDataFieldContentsL(EPbkFieldIdStreetAddress,EPbkFieldLocationWork);
aData.iPostalCodeWork = GetDataFieldContentsL(EPbkFieldIdPostalCode,EPbkFieldLocationWork);
aData.iCityWork = GetDataFieldContentsL(EPbkFieldIdCity,EPbkFieldLocationWork);
aData.iStateWork = GetDataFieldContentsL(EPbkFieldIdState,EPbkFieldLocationWork);
aData.iCountryWork = GetDataFieldContentsL(EPbkFieldIdCountry,EPbkFieldLocationWork);
}
/**
* Set the contact data.
*/
void CBCTContactWrapper::SetContactDataL(CBCTBCardData& aData)
{
AddDataFieldsL(EPbkFieldIdLastName,aData.iLastName,NULL);
AddDataFieldsL(EPbkFieldIdFirstName,aData.iFirstName,NULL);
AddDataFieldsL(EPbkFieldIdPhoneNumberStandard,aData.iPhoneNumberStandard,NULL);
AddDataFieldsL(EPbkFieldIdPhoneNumberHome,aData.iPhoneNumberHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdPhoneNumberWork,aData.iPhoneNumberWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdPagerNumber,aData.iPagerNumber,NULL);
AddDataFieldsL(EPbkFieldIdPhoneNumberMobile,aData.iPhoneNumberMobile,NULL);
AddDataFieldsL(EPbkFieldIdPhoneNumberMobile,aData.iPhoneNumberMobileHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdPhoneNumberMobile,aData.iPhoneNumberMobileWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdFaxNumber,aData.iFaxNumber,NULL);
AddDataFieldsL(EPbkFieldIdFaxNumber,aData.iFaxNumberHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdFaxNumber,aData.iFaxNumberWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdEmailAddress,aData.iEmailAddress,NULL);
AddDataFieldsL(EPbkFieldIdEmailAddress,aData.iEmailAddressWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdEmailAddress,aData.iEmailAddressHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdPostalAddress,aData.iPostalAddress,NULL);
AddDataFieldsL(EPbkFieldIdPostalAddress,aData.iPostalAddressHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdPostalAddress,aData.iCompanyAddress,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdURL,aData.iURL,NULL);
AddDataFieldsL(EPbkFieldIdURL,aData.iURLHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdURL,aData.iURLWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdJobTitle,aData.iJobTitle,NULL);
AddDataFieldsL(EPbkFieldIdCompanyName,aData.iCompanyName,NULL);
SetDateL(EPbkFieldIdDate,aData.iDate);
AddDataFieldsL(EPbkFieldIdNote,aData.iNote,NULL);
SetThumbnailValueL(aData.iThumbnailImage);
// ADR general
AddDataFieldsL(EPbkFieldIdPOBox,aData.iPOBox,NULL);
AddDataFieldsL(EPbkFieldIdExtendedAddress,aData.iExtensonAdr,NULL);
AddDataFieldsL(EPbkFieldIdStreetAddress,aData.iStreet,NULL);
AddDataFieldsL(EPbkFieldIdPostalCode,aData.iPostalCode,NULL);
AddDataFieldsL(EPbkFieldIdCity,aData.iCity,NULL);
AddDataFieldsL(EPbkFieldIdState,aData.iState,NULL);
AddDataFieldsL(EPbkFieldIdCountry,aData.iCountry,NULL);
// ADR home
AddDataFieldsL(EPbkFieldIdPOBox,aData.iPOBoxHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdExtendedAddress,aData.iExtensonAdrHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdStreetAddress,aData.iStreetHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdPostalCode,aData.iPostalCodeHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdCity,aData.iCityHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdState,aData.iStateHome,NULL,EPbkFieldLocationHome);
AddDataFieldsL(EPbkFieldIdCountry,aData.iCountryHome,NULL,EPbkFieldLocationHome);
// ADR work
AddDataFieldsL(EPbkFieldIdPOBox,aData.iPOBoxWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdExtendedAddress,aData.iExtensonAdrWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdStreetAddress,aData.iStreetWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdPostalCode,aData.iPostalCodeWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdCity,aData.iCityWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdState,aData.iStateWork,NULL,EPbkFieldLocationWork);
AddDataFieldsL(EPbkFieldIdCountry,aData.iCountryWork,NULL,EPbkFieldLocationWork);
}
void CBCTContactWrapper::SetThumbnailValueL(const HBufC* aImageFileName)
{
if (aImageFileName)
{
SaveImageFileToContactL(iContact,*aImageFileName);
}
}
TBool CBCTContactWrapper::SaveImageFileToContactL(CPbkContactItem& aItem, const TDesC& aFilename)
{
CPbkFieldInfo* field = iContactEngine.FieldsInfo().Find(EPbkFieldIdThumbnailImage);
if (field)
{
switch (field->FieldStorageType())
{
case KStorageTypeText:
{
// store imagename as link
TPbkContactItemField* itemField = aItem.AddOrReturnUnusedFieldL(*field);
CContactTextField* tf = itemField->ItemField().TextStorage();
tf->SetTextL(aFilename);
break;
}
case KStorageTypeStore:
{
// store image using manager
SaveEmbeddedImageToContactL(*field, aItem, aFilename);
break;
}
default:
{
return EFalse;
break;
}
}
}
return ETrue;
}
void CBCTContactWrapper::SaveEmbeddedImageToContactL(
CPbkFieldInfo& aFieldInfo,
CPbkContactItem& aItem,
const TDesC& aFilename)
{
// read imagefile to buffer
HBufC8* buffer = ReadImageFileToDescL(aFilename);
CleanupStack::PushL(buffer);
TPbkContactItemField* field = aItem.AddOrReturnUnusedFieldL(aFieldInfo);
if (!field)
{
User::Leave(KErrNotFound);
}
CContactStoreField* store = field->ItemField().StoreStorage();
store->SetThingL(*buffer);
CleanupStack::PopAndDestroy(buffer);
}
HBufC8* CBCTContactWrapper::ReadImageFileToDescL(const TDesC& aFilename)
{
RFs fs;
User::LeaveIfError(fs.Connect());
CleanupClosePushL(fs);
RFile file;
TInt err = file.Open(fs, aFilename, EFileRead);
if (err != KErrNone)
{
if (err == KErrNotFound)
{
//
HBufC8* empty = HBufC8::NewL(1);
CleanupStack::PopAndDestroy(); // fs
return empty;
}
else
{
User::Leave(err);
}
}
CleanupClosePushL(file);
TInt filelen;
file.Size(filelen);
HBufC8* imageBuffer = HBufC8::NewL(filelen);
CleanupStack::PushL(imageBuffer);
TPtr8 imabeBufferPtr = imageBuffer->Des();
User::LeaveIfError(file.Read(imabeBufferPtr));
CleanupStack::Pop(imageBuffer);
CleanupStack::PopAndDestroy(2); // fs, file
return imageBuffer;
}
/**
* Find the given contact item.
*/
TPbkContactItemField* CBCTContactWrapper::FindFieldForModificationL(
CPbkContactItem& aItem,
const TPbkFieldId aFieldId,
const TPbkFieldLocation aLocation)
{
CPbkFieldInfo* info = iContactEngine.FieldsInfo().Find(aFieldId,aLocation);
if (info)
{
return aItem.AddOrReturnUnusedFieldL(*info);
}
else
{
return NULL;
}
}
/**
* Get the maxlength of field.
*/
TInt CBCTContactWrapper::FindFieldMaximumLength(TPbkFieldId aFieldId)
{
CPbkFieldInfo *fi = iContactEngine.FieldsInfo().Find(aFieldId);
if(fi)
{
return fi->MaxLength();
}
else
{
return 0;
}
}
/**
* Add data fields.
*/
void CBCTContactWrapper::AddDataFieldsL(
TPbkFieldId aFieldId,
const TDesC* aDataLine,
const TDesC* aLabel,
const TPbkFieldLocation aLocation)
{
if (!aDataLine)
{
return;
}
HBufC* line = HBufC::NewLC(aDataLine->Length());
*line = *aDataLine;
TInt pos = 0;
TInt length;
TInt startPos = 0;
do
{
pos = line->Find(KSubfieldDelimiter);
if (pos > 0)
{
length = pos;
}
else
{
length = line->Length();
}
HBufC* tmpHeap = HBufC::NewLC(length);
*tmpHeap = line->Mid(startPos,length);
TPtr tmp = tmpHeap->Des();
// Check if defined as default phone number
TBool defaultPhone =EFalse;
TInt tagPos = tmp.Find(KDefaulPhoneTag);
if (tagPos > 0)
{
tmp.Replace(tagPos,KDefaulPhoneTag().Length(),KNullDesC );
defaultPhone = ETrue;
}
AddFieldWithValueL(aFieldId,aLocation,tmpHeap,defaultPhone,aLabel);
CleanupStack::PopAndDestroy(tmpHeap);
if (pos > 0)
{
*line = line->Mid(pos + KSubfieldDelimiter().Length());
}
}
while (pos > 0);
CleanupStack::PopAndDestroy(line);
}
/**
* Add datafield with value.
*/
TBool CBCTContactWrapper::AddFieldWithValueL(
TPbkFieldId aFieldId,
const TPbkFieldLocation aLocation,
HBufC* aValue,
TBool aPhoneNumber,
const TDesC* aLabel)
{
TPbkContactItemField* f;
if (!aValue)
{
return EFalse;
}
f = FindFieldForModificationL(iContact, aFieldId,aLocation);
if(f)
{
// Copy the property value
HBufC *buf = HBufC::NewL(aValue->Length());
CleanupStack::PushL(buf);
TPtr buffer = buf->Des();
buffer = *aValue;
// Clip the property value if it does not fit the field
TInt maxlen = FindFieldMaximumLength(f->FieldInfo().FieldId());
if(maxlen)
{
if(maxlen < aValue->Length())
buffer.SetLength(maxlen);
}
CContactTextField* tf = f->ItemField().TextStorage();
tf->SetTextL(buffer);
if(aPhoneNumber)
{
// If this is a preferred phone number set field as DefaultPhoneNumber
if(!iContact.DefaultPhoneNumberField())
iContact.SetDefaultPhoneNumberFieldL(f);
}
if(aLabel)
{
f->SetLabelL(*aLabel);
}
CleanupStack::PopAndDestroy(); // buf
return ETrue;
}
return EFalse;
}
/**
* Check if given field is defaultphonefield.
*/
TBool CBCTContactWrapper::IsDefaultPhone(const TPbkContactItemField* aField) const
{
if (!aField)
{
return EFalse;
}
TPbkContactItemField* defPhone = iContact.DefaultPhoneNumberField();
if (defPhone)
{
if (defPhone == aField)
{
return ETrue;
}
else
{
return EFalse;
}
}
else
{
return EFalse;
}
}
/**
* Get the value of the defaultphone.
*/
HBufC* CBCTContactWrapper::GetDefaultPhoneL()
{
TPbkContactItemField* defPhone = iContact.DefaultPhoneNumberField();
if (defPhone)
{
return GetFieldTextL(defPhone);
}
else
{
return NULL;
}
}
/**
* Get date value.
*/
HBufC* CBCTContactWrapper::GetDateL(const TPbkFieldId aId)
{
TPbkContactItemField* field;
field= iContact.FindField(aId);
if (!field)
{
return NULL;
}
TVersitDateTime* vdt =
new (ELeave) TVersitDateTime(field->ItemField().DateTimeStorage()->Time().DateTime(),
TVersitDateTime::EIsMachineLocal);
CleanupStack::PushL(vdt);
TDateTime dateval = vdt->iDateTime;
CleanupStack::PopAndDestroy(vdt);
TInt year = dateval.Year();
TInt month = MonthToNumber(dateval.Month());
// Note: 'day' is zero based, must add 1
TInt day = dateval.Day() + 1;
TInt KMaxLen = 8;
HBufC* textHeap = HBufC::NewLC(KMaxLen);
TPtr text = textHeap->Des();
text.Num(year);
if (month < 10)
{
text.AppendNum(0);
}
text.AppendNum(month);
if (day < 10)
{
text.AppendNum(0);
}
text.AppendNum(day);
CleanupStack::Pop(textHeap);
return textHeap;
}
/**
* Set datefield.
*/
void CBCTContactWrapper::SetDateL(const TPbkFieldId aId, const TDesC* aDataLine)
{
if (!aDataLine)
{
return;
}
TPbkContactItemField* f;
f = FindFieldForModificationL(iContact, aId, EPbkFieldLocationNone);
if(f)
{
TVersitDateTime* date = GetVersitDateTimeL(aDataLine);
if (date)
{
f->ItemField().DateTimeStorage()->SetTime(date->iDateTime);
delete date;
}
}
}
/**
* Get versit datetime from the given text.
*/
TVersitDateTime* CBCTContactWrapper::GetVersitDateTimeL(const TDesC* aDataText)
{
if (!aDataText)
{
return NULL;
}
TBuf<4> year;
TBuf<2> month;
TBuf<2> day;
year = aDataText->Left(4);
month = aDataText->Mid(4,2);
day = aDataText->Mid(6,2);
TLex yearlex(year);
TInt yearint;
if (yearlex.Val(yearint) != KErrNone )
{
return NULL;
}
TLex monthlex(month);
TInt monthint;
if (monthlex.Val(monthint) != KErrNone )
{
return NULL;
}
TLex daylex(day);
TInt dayint;
if (daylex.Val(dayint) != KErrNone )
{
return NULL;
}
// Note: 'day' is zero based, must decrease 1
dayint = dayint - 1;
TDateTime dateTime(yearint,NumberToMonth(monthint),dayint,00,00,00,000000);
TVersitDateTime* vdt =
new (ELeave) TVersitDateTime(dateTime,TVersitDateTime::EIsMachineLocal);
return vdt;
}
/**
* Confert number to month.
*/
TMonth CBCTContactWrapper::NumberToMonth(const TInt aNumber) const
{
switch (aNumber)
{
case 1:
{
return EJanuary;
}
case 2:
{
return EFebruary;
}
case 3:
{
return EMarch;
}
case 4:
{
return EApril;
}
case 5:
{
return EMay;
}
case 6:
{
return EJune;
}
case 7:
{
return EJuly;
}
case 8:
{
return EAugust;
}
case 9:
{
return ESeptember;
}
case 10:
{
return EOctober;
}
case 11:
{
return ENovember;
}
case 12:
{
return EDecember;
}
default:
{
_LIT(KPanicText, "CBCTContactWrapper::MonthToNumber");
const TInt KPanicCode = 1;
User::Panic(KPanicText, KPanicCode);
return EDecember;
}
}
}
/**
* Convert month to number.
*/
TInt CBCTContactWrapper::MonthToNumber(const TMonth aMonth) const
{
switch (aMonth)
{
case EJanuary:
{
return 1;
}
case EFebruary:
{
return 2;
}
case EMarch:
{
return 3;
}
case EApril:
{
return 4;
}
case EMay:
{
return 5;
}
case EJune:
{
return 6;
}
case EJuly:
{
return 7;
}
case EAugust:
{
return 8;
}
case ESeptember:
{
return 9;
}
case EOctober:
{
return 10;
}
case ENovember:
{
return 11;
}
case EDecember:
{
return 12;
}
default:
{
return 0;
}
}
}
/**
* Get the fieldtext of given field.
*/
HBufC* CBCTContactWrapper::GetFieldTextL(const TPbkContactItemField* aField)
{
if(!aField)
{
return NULL;
}
TBool addDefaultPhone = EFalse;
TBool addLabel = EFalse;
TInt textLength = aField->Text().Length();
if (textLength > 0)
{
// check if default phone
if (IsDefaultPhone(aField))
{
addDefaultPhone = ETrue;
textLength += KDefaulPhoneTag().Length();
}
// Add labels only if dealing with Compact business cards
if (!iForVCard)
{
TInt labelLength = aField->Label().Length();
if (labelLength > 0 )
{
addLabel = ETrue;
textLength += labelLength + KLabelStartTag().Length()
+ KLabelEndTag().Length();
}
}
}
HBufC* textHeap = HBufC::NewL(textLength);
CleanupStack::PushL(textHeap);
TPtr text = textHeap->Des();
text.Copy(aField->Text());
// add labeltext
if (addLabel)
{
text.Append(KLabelStartTag);
text.Append(aField->Label());
text.Append(KLabelEndTag);
}
// process possible default phone number
if (addDefaultPhone)
{
text.Append(KDefaulPhoneTag);
}
CleanupStack::Pop(textHeap);
return textHeap;
}
/**
* Get datafield contents.
*/
HBufC* CBCTContactWrapper::GetDataFieldContentsL(
const TPbkFieldId aId, const TPbkFieldLocation aLocation)
{
TInt index = 0;
const TInt KMaxLen = 1000;
CPbkFieldInfo* fieldInfo = iContactEngine.FieldsInfo().Find(aId, aLocation);
if (!fieldInfo)
{
return NULL;
}
TPbkContactItemField* field;
field= iContact.FindField(*fieldInfo,index);
HBufC* mainfield = GetFieldTextL(field);
if (mainfield)
{
CleanupStack::PushL(mainfield);
HBufC* tmpHeap = HBufC::NewLC(KMaxLen);
TPtr tmp = tmpHeap->Des();
tmp = *mainfield;
HBufC* addText;
while (index >= 0)
{
index++;
field = iContact.FindField(*fieldInfo,index);
addText = GetFieldTextL(field);
if (addText)
{
tmp.Append(KSubfieldDelimiter);
tmp.Append(*addText);
delete addText;
addText = NULL;
}
}
HBufC* data = HBufC::NewL(tmpHeap->Length());
*data = *tmpHeap;
CleanupStack::PopAndDestroy(tmpHeap);
CleanupStack::PopAndDestroy(mainfield);
return data;
}
else
{
return mainfield;
}
}
| [
"none@none"
]
| [
[
[
1,
871
]
]
]
|
3d736b5183ad781b59d019d020cc72fbeb1810e7 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src/MtlCom.cpp | bdaa857dd132d8f8c8b8cbfe1639d5ae5fcc7264 | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | MacCentralEurope | C++ | false | false | 16,951 | cpp | /**
* @file MtlCom.cpp
* @brief MTL : COMä÷ĆW
*/
#include "stdafx.h"
#include "MtlCom.h"
#if defined USE_ATLDBGMEM
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
namespace MTL {
/// Helper for creating default FORMATETC from cfFormat
LPFORMATETC _MtlFillFormatEtc(LPFORMATETC lpFormatEtc, CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtcFill)
{
ATLASSERT(lpFormatEtcFill != NULL);
if (lpFormatEtc == NULL && cfFormat != 0) {
lpFormatEtc = lpFormatEtcFill;
lpFormatEtc->cfFormat = cfFormat;
lpFormatEtc->ptd = NULL;
lpFormatEtc->dwAspect = DVASPECT_CONTENT;
lpFormatEtc->lindex = -1;
lpFormatEtc->tymed = (DWORD) -1;
}
return lpFormatEtc;
}
bool MtlIsDataAvailable(IDataObject *pDataObject, CLIPFORMAT cfFormat, LPFORMATETC lpFormatEtc)
{
ATLASSERT(pDataObject != NULL);
// fill in FORMATETC struct
FORMATETC formatEtc;
lpFormatEtc = MTL::_MtlFillFormatEtc(lpFormatEtc, cfFormat, &formatEtc);
// attempt to get the data
return pDataObject->QueryGetData(lpFormatEtc) == S_OK;
}
bool MtlGetDropFileName(IDataObject *pDataObject, CSimpleArray<CString> &arrFileNames)
{
if ( !MTL::MtlIsDataAvailable(pDataObject, CF_HDROP) )
return false;
FORMATETC formatetc = { CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stgmedium;
HRESULT hr = pDataObject->GetData(&formatetc, &stgmedium);
if (FAILED(hr) || stgmedium.hGlobal == NULL) {
return false;
}
HDROP hDropInfo = (HDROP) stgmedium.hGlobal;
UINT nFiles = ::DragQueryFile(hDropInfo, (UINT) -1, NULL, 0);
for (UINT iFile = 0; iFile < nFiles; iFile++) {
TCHAR szFileName[_MAX_PATH];
szFileName[0] = 0;
::DragQueryFile(hDropInfo, iFile, szFileName, _MAX_PATH);
arrFileNames.Add( CString(szFileName) );
}
::DragFinish(hDropInfo); // required?
::ReleaseStgMedium(&stgmedium);
if (arrFileNames.GetSize() > 0)
return true;
else
return false;
}
// Implementation
bool MtlGetHGlobalText(IDataObject *pDataObject, CString &strText, CLIPFORMAT cfFormat)
{
bool bResult = false;
if ( !MTL::MtlIsDataAvailable(pDataObject, cfFormat) )
return false;
FORMATETC formatetc = { cfFormat, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
STGMEDIUM stgmedium = { 0 };
HRESULT hr = pDataObject->GetData(&formatetc, &stgmedium);
if ( SUCCEEDED(hr) ) {
if (stgmedium.hGlobal != NULL) {
HGLOBAL hText = stgmedium.hGlobal;
strText = reinterpret_cast<LPTSTR>( ::GlobalLock(hText) ); //+++ LPSTR Ā® LPTSTR
::GlobalUnlock(hText);
bResult = true;
}
::ReleaseStgMedium(&stgmedium);
}
return bResult;
}
HDROP MtlCreateDropFile(CSimpleArray<CString> &arrFiles)
{
if (arrFiles.GetSize() == 0)
return NULL;
//filename\0...\0filename\0...\0filename\0\0
int nLen = 0;
int i;
for (i = 0; i < arrFiles.GetSize(); ++i) {
nLen += arrFiles[i].GetLength();
nLen += 1; // for '\0' separator
}
nLen += 1; // for the last '\0'
HDROP hDrop = (HDROP) ::GlobalAlloc( GHND, sizeof (DROPFILES) + nLen * sizeof (TCHAR) );
if (hDrop == NULL)
return NULL;
LPDROPFILES lpDropFiles;
lpDropFiles = (LPDROPFILES) ::GlobalLock(hDrop);
lpDropFiles->pFiles = sizeof (DROPFILES);
lpDropFiles->pt.x = 0;
lpDropFiles->pt.y = 0;
lpDropFiles->fNC = FALSE;
#ifdef _UNICODE
lpDropFiles->fWide = TRUE;
#else
lpDropFiles->fWide = FALSE;
#endif
TCHAR * psz = (TCHAR *) (lpDropFiles + 1);
for (i = 0; i < arrFiles.GetSize(); ++i) {
::lstrcpy(psz, arrFiles[i]);
psz += arrFiles[i].GetLength() + 1; // skip a '\0' separator
}
::GlobalUnlock(hDrop);
return hDrop;
}
// Helper for initializing CComSafeArray
bool _MtlCompareSafeArrays(SAFEARRAY *parray1, SAFEARRAY *parray2)
{
bool bCompare = false;
// If one is NULL they must both be NULL to compare
if (parray1 == NULL || parray2 == NULL) {
return parray1 == parray2;
}
// Dimension must match and if 0, then arrays compare
DWORD dwDim1 = ::SafeArrayGetDim(parray1);
DWORD dwDim2 = ::SafeArrayGetDim(parray2);
if (dwDim1 != dwDim2)
return false;
else if (dwDim1 == 0)
return true;
// Element size must match
DWORD dwSize1 = ::SafeArrayGetElemsize(parray1);
DWORD dwSize2 = ::SafeArrayGetElemsize(parray2);
if (dwSize1 != dwSize2)
return false;
long* pLBound1 = NULL;
long* pLBound2 = NULL;
long* pUBound1 = NULL;
long* pUBound2 = NULL;
void* pData1 = NULL;
void* pData2 = NULL;
// Bounds must match
ATLTRY(pLBound1 = new long[dwDim1]);
ATLTRY(pLBound2 = new long[dwDim2]);
ATLTRY(pUBound1 = new long[dwDim1]);
ATLTRY(pUBound2 = new long[dwDim2]);
size_t nTotalElements = 1;
// Get and compare bounds
for (DWORD dwIndex = 0; dwIndex < dwDim1; dwIndex++) {
MtlCheckError( ::SafeArrayGetLBound(parray1, dwIndex + 1, &pLBound1[dwIndex]) );
MtlCheckError( ::SafeArrayGetLBound(parray2, dwIndex + 1, &pLBound2[dwIndex]) );
MtlCheckError( ::SafeArrayGetUBound(parray1, dwIndex + 1, &pUBound1[dwIndex]) );
MtlCheckError( ::SafeArrayGetUBound(parray2, dwIndex + 1, &pUBound2[dwIndex]) );
// Check the magnitude of each bound
if ( pUBound1[dwIndex] - pLBound1[dwIndex]
!= pUBound2[dwIndex] - pLBound2[dwIndex])
{
delete[] pLBound1;
delete[] pLBound2;
delete[] pUBound1;
delete[] pUBound2;
return false;
}
// Increment the element count
nTotalElements *= pUBound1[dwIndex] - pLBound1[dwIndex] + 1;
}
// Access the data
MtlCheckError( ::SafeArrayAccessData(parray1, &pData1) );
MtlCheckError( ::SafeArrayAccessData(parray2, &pData2) );
// Calculate the number of bytes of data and compare
size_t nSize = nTotalElements * dwSize1;
int nOffset = memcmp(pData1, pData2, nSize);
bCompare = (nOffset == 0);
// Release the array locks
MtlCheckError( ::SafeArrayUnaccessData(parray1) );
MtlCheckError( ::SafeArrayUnaccessData(parray2) );
// Clean up bounds arrays
delete[] pLBound1;
delete[] pLBound2;
delete[] pUBound1;
delete[] pUBound2;
return bCompare;
}
/////////////////////////////////////////////////////////////////////////////
// CComSafeArray class
///Constructors
CComSafeArray::CComSafeArray()
{
_SafeArrayInit(this);
vt = VT_EMPTY;
}
CComSafeArray::~CComSafeArray()
{
Clear();
}
CComSafeArray::CComSafeArray(const SAFEARRAY &saSrc, VARTYPE vtSrc)
{
_SafeArrayInit(this);
vt = (VARTYPE) (vtSrc | VT_ARRAY);
MtlCheckError( ::SafeArrayCopy( (LPSAFEARRAY) &saSrc, &parray ) );
m_dwDims = GetDim();
m_dwElementSize = GetElemSize();
}
CComSafeArray::CComSafeArray(LPCSAFEARRAY pSrc, VARTYPE vtSrc)
{
_SafeArrayInit(this);
vt = (VARTYPE) (vtSrc | VT_ARRAY);
MtlCheckError( ::SafeArrayCopy( (LPSAFEARRAY) pSrc, &parray ) );
m_dwDims = GetDim();
m_dwElementSize = GetElemSize();
}
CComSafeArray::CComSafeArray(const CComSafeArray &saSrc)
{
_SafeArrayInit(this);
*this = saSrc;
m_dwDims = GetDim();
m_dwElementSize = GetElemSize();
}
CComSafeArray::CComSafeArray(const VARIANT &varSrc)
{
_SafeArrayInit(this);
*this = varSrc;
m_dwDims = GetDim();
m_dwElementSize = GetElemSize();
}
CComSafeArray::CComSafeArray(LPCVARIANT pSrc)
{
_SafeArrayInit(this);
*this = pSrc;
m_dwDims = GetDim();
m_dwElementSize = GetElemSize();
}
void CComSafeArray::_SafeArrayInit(CComSafeArray *psa)
{
::memset( psa, 0, sizeof (*psa) );
}
void CComSafeArray::Clear()
{
MTLVERIFY(::VariantClear(this) == NOERROR);
}
CComSafeArray::operator LPVARIANT()
{
return this;
}
CComSafeArray::operator LPCVARIANT() const
{
return this;
}
DWORD CComSafeArray::GetDim()
{
return ::SafeArrayGetDim(parray);
}
DWORD CComSafeArray::GetElemSize()
{
return ::SafeArrayGetElemsize(parray);
}
/// Operations
void CComSafeArray::Attach(VARIANT &varSrc)
{
ATLASSERT(varSrc.vt & VT_ARRAY);
// Free up previous safe array if necessary
Clear();
// give control of data to CComSafeArray
::memcpy( this, &varSrc, sizeof (varSrc) );
varSrc.vt = VT_EMPTY;
}
VARIANT CComSafeArray::Detach()
{
VARIANT varResult = *this;
vt = VT_EMPTY;
return varResult;
}
/// Assignment operators
CComSafeArray &CComSafeArray::operator =(const CComSafeArray &saSrc)
{
ATLASSERT(saSrc.vt & VT_ARRAY);
MtlCheckError( ::VariantCopy(this, (LPVARIANT) &saSrc) );
return *this;
}
CComSafeArray &CComSafeArray::operator =(const VARIANT &varSrc)
{
ATLASSERT(varSrc.vt & VT_ARRAY);
MtlCheckError( ::VariantCopy(this, (LPVARIANT) &varSrc) );
return *this;
}
CComSafeArray &CComSafeArray::operator =(LPCVARIANT pSrc)
{
ATLASSERT(pSrc->vt & VT_ARRAY);
MtlCheckError( ::VariantCopy(this, (LPVARIANT) pSrc) );
return *this;
}
CComSafeArray &CComSafeArray::operator =(const CComVariant &varSrc)
{
ATLASSERT(varSrc.vt & VT_ARRAY);
MtlCheckError( ::VariantCopy(this, (LPVARIANT) &varSrc) );
return *this;
}
// Comparison operators
bool CComSafeArray::operator ==(const SAFEARRAY &saSrc) const
{
return _MtlCompareSafeArrays(parray, (LPSAFEARRAY) &saSrc);
}
bool CComSafeArray::operator ==(LPCSAFEARRAY pSrc) const
{
return _MtlCompareSafeArrays(parray, (LPSAFEARRAY) pSrc);
}
bool CComSafeArray::operator ==(const CComSafeArray &saSrc) const
{
if (vt != saSrc.vt)
return false;
return _MtlCompareSafeArrays(parray, saSrc.parray);
}
bool CComSafeArray::operator ==(const VARIANT &varSrc) const
{
if (vt != varSrc.vt)
return false;
return _MtlCompareSafeArrays(parray, varSrc.parray);
}
bool CComSafeArray::operator ==(LPCVARIANT pSrc) const
{
if (vt != pSrc->vt)
return false;
return _MtlCompareSafeArrays(parray, pSrc->parray);
}
bool CComSafeArray::operator ==(const CComVariant &varSrc) const
{
if (vt != varSrc.vt)
return false;
return _MtlCompareSafeArrays(parray, varSrc.parray);
}
void CComSafeArray::CreateOneDim(VARTYPE vtSrc, DWORD dwElements, const void *pvSrcData, long nLBound)
{
ATLASSERT(dwElements > 0);
// Setup the bounds and create the array
SAFEARRAYBOUND rgsabound;
rgsabound.cElements = dwElements;
rgsabound.lLbound = nLBound;
Create(vtSrc, 1, &rgsabound);
// Copy over the data if neccessary
if (pvSrcData != NULL) {
void *pvDestData;
AccessData(&pvDestData);
memcpy(pvDestData, pvSrcData, GetElemSize() * dwElements);
UnaccessData();
}
}
DWORD CComSafeArray::GetOneDimSize()
{
ATLASSERT(GetDim() == 1);
long nUBound, nLBound;
GetUBound(1, &nUBound);
GetLBound(1, &nLBound);
return nUBound + 1 - nLBound;
}
void CComSafeArray::ResizeOneDim(DWORD dwElements)
{
ATLASSERT(GetDim() == 1);
SAFEARRAYBOUND rgsabound;
rgsabound.cElements = dwElements;
rgsabound.lLbound = 0;
Redim(&rgsabound);
}
void CComSafeArray::Create(VARTYPE vtSrc, DWORD dwDims, DWORD *rgElements)
{
ATLASSERT(rgElements != NULL);
// Allocate and fill proxy array of bounds (with lower bound of zero)
SAFEARRAYBOUND *rgsaBounds = new SAFEARRAYBOUND[dwDims];
for (DWORD dwIndex = 0; dwIndex < dwDims; dwIndex++) {
// Assume lower bound is 0 and fill in element count
rgsaBounds[dwIndex].lLbound = 0;
rgsaBounds[dwIndex].cElements = rgElements[dwIndex];
}
Create(vtSrc, dwDims, rgsaBounds);
delete[] rgsaBounds;
}
void CComSafeArray::Create(VARTYPE vtSrc, DWORD dwDims, SAFEARRAYBOUND *rgsabound)
{
ATLASSERT(dwDims > 0);
ATLASSERT(rgsabound != NULL);
// Validate the VARTYPE for SafeArrayCreate call
ATLASSERT( !(vtSrc & VT_ARRAY) );
ATLASSERT( !(vtSrc & VT_BYREF) );
ATLASSERT( !(vtSrc & VT_VECTOR) );
ATLASSERT(vtSrc != VT_EMPTY);
ATLASSERT(vtSrc != VT_NULL);
// Free up old safe array if necessary
Clear();
ATLTRY( parray = ::SafeArrayCreate(vtSrc, dwDims, rgsabound) );
if (parray == NULL) {
ATLTRACE2(atlTraceDBProvider, 0, "CComSafeArray::Create Error : OOM\n");
return;
}
vt = unsigned short (vtSrc | VT_ARRAY);
m_dwDims = dwDims;
m_dwElementSize = GetElemSize();
}
void CComSafeArray::AccessData(void **ppvData)
{
MtlCheckError( ::SafeArrayAccessData(parray, ppvData) );
}
void CComSafeArray::UnaccessData()
{
MtlCheckError( ::SafeArrayUnaccessData(parray) );
}
void CComSafeArray::AllocData()
{
MtlCheckError( ::SafeArrayAllocData(parray) );
}
void CComSafeArray::AllocDescriptor(DWORD dwDims)
{
MtlCheckError( ::SafeArrayAllocDescriptor(dwDims, &parray) );
}
void CComSafeArray::Copy(LPSAFEARRAY *ppsa)
{
MtlCheckError( ::SafeArrayCopy(parray, ppsa) );
}
void CComSafeArray::GetLBound(DWORD dwDim, long *pLbound)
{
MtlCheckError( ::SafeArrayGetLBound(parray, dwDim, pLbound) );
}
void CComSafeArray::GetUBound(DWORD dwDim, long *pUbound)
{
MtlCheckError( ::SafeArrayGetUBound(parray, dwDim, pUbound) );
}
void CComSafeArray::GetElement(long *rgIndices, void *pvData)
{
MtlCheckError( ::SafeArrayGetElement(parray, rgIndices, pvData) );
}
void CComSafeArray::PtrOfIndex(long *rgIndices, void **ppvData)
{
MtlCheckError( ::SafeArrayPtrOfIndex(parray, rgIndices, ppvData) );
}
void CComSafeArray::PutElement(long *rgIndices, void *pvData)
{
MtlCheckError( ::SafeArrayPutElement(parray, rgIndices, pvData) );
}
void CComSafeArray::Redim(SAFEARRAYBOUND *psaboundNew)
{
MtlCheckError( ::SafeArrayRedim(parray, psaboundNew) );
}
void CComSafeArray::Lock()
{
MtlCheckError( ::SafeArrayLock(parray) );
}
void CComSafeArray::Unlock()
{
MtlCheckError( ::SafeArrayUnlock(parray) );
}
void CComSafeArray::Destroy()
{
MtlCheckError( ::SafeArrayDestroy(parray) );
}
void CComSafeArray::DestroyData()
{
MtlCheckError( ::SafeArrayDestroyData(parray) );
}
void CComSafeArray::DestroyDescriptor()
{
MtlCheckError( ::SafeArrayDestroyDescriptor(parray) );
}
/////////////////////////////////////////////////////////////////////////////
// Helper for iter to CComSafeArray
void _MtlCreateOneDimArray(VARIANT &varSrc, DWORD dwSize)
{
UINT nDim;
// Clear VARIANT and re-create SafeArray if necessary
if (varSrc.vt != (VT_UI1 | VT_ARRAY)
|| ( nDim = ::SafeArrayGetDim(varSrc.parray) ) != 1)
{
MTLVERIFY(::VariantClear(&varSrc) == NOERROR);
varSrc.vt = VT_UI1 | VT_ARRAY;
SAFEARRAYBOUND bound;
bound.cElements = dwSize;
bound.lLbound = 0;
ATLTRY( varSrc.parray = ::SafeArrayCreate(VT_UI1, 1, &bound) );
if (varSrc.parray == NULL)
ATLTRACE2(atlTraceDBProvider, 0, "MtlCheckError Error : OOM\n");
} else {
// Must redimension array if necessary
long lLower, lUpper;
MtlCheckError( ::SafeArrayGetLBound(varSrc.parray, 1, &lLower) );
MtlCheckError( ::SafeArrayGetUBound(varSrc.parray, 1, &lUpper) );
// Upper bound should always be greater than lower bound
long lSize = lUpper - lLower;
if (lSize < 0) {
ATLASSERT(FALSE);
lSize = 0;
}
if ( (DWORD) lSize != dwSize ) {
SAFEARRAYBOUND bound;
bound.cElements = dwSize;
bound.lLbound = lLower;
MtlCheckError( ::SafeArrayRedim(varSrc.parray, &bound) );
}
}
}
void _MtlCopyBinaryData(SAFEARRAY *parray, const void *pvSrc, DWORD dwSize)
{
// Access the data, copy it and unaccess it.
void *pDest;
MtlCheckError( ::SafeArrayAccessData(parray, &pDest) );
::memcpy(pDest, pvSrc, dwSize);
MtlCheckError( ::SafeArrayUnaccessData(parray) );
}
void MtlInitVariantFromArray(CComVariant &v, CSimpleArray<BYTE> &arrSrc)
{
int nSize = arrSrc.GetSize();
// Set the correct type and make sure SafeArray can hold data
_MtlCreateOneDimArray(v, (DWORD) nSize);
// Copy the data into the SafeArray
_MtlCopyBinaryData(v.parray, arrSrc.GetData(), (DWORD) nSize);
}
void MtlInitVariantFromItemIDList(CComVariant &v, LPCITEMIDLIST pidl)
{
if (pidl != NULL) {
// walk through entries in the list and accumulate their size
UINT cbTotal = 0;
SAFEARRAY * psa = NULL;
LPCITEMIDLIST pidlWalker = pidl;
while (pidlWalker->mkid.cb) {
cbTotal += pidlWalker->mkid.cb;
pidlWalker = (LPCITEMIDLIST) ( ( (LPBYTE) pidlWalker ) + pidlWalker->mkid.cb );
}
// add the base structure size
cbTotal += sizeof (ITEMIDLIST);
// get a safe array for them
psa = ::SafeArrayCreateVector(VT_UI1, 0, cbTotal);
// copy it and set members
if (psa != NULL) {
::memcpy(psa->pvData, (LPBYTE) pidl, cbTotal);
v.vt = VT_ARRAY | VT_UI1;
v.parray = psa;
}
}
}
////////////////////////////////////////////////////////////////////////////
} // namespace MTL
| [
"[email protected]"
]
| [
[
[
1,
799
]
]
]
|
a57c68003d80472f3c8357695ab4e598f704f44d | c034a6ffa81773a279c4cd25bdbd3b23a999d4b7 | /GMFGUI/GMFGUI/GMFDec/decSceneFunctions.cpp | 4148d802ab5845aee7ec43dce712616652efe808 | []
| no_license | Shima33/gmftoolkit | 08ee92bb5700af984286c71dd54dbfd1ffecd35a | 0e602d27b9b8cce83942f9624cbb892b0fd44b6b | refs/heads/master | 2021-01-10T15:45:10.838305 | 2010-06-20T19:09:19 | 2010-06-20T19:09:19 | 50,957,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | cpp | // Open Source C GMF Compiler
// Copyright (c) 2008 Sergiusz Bazanski
// http://www.q3k.org/
// GPL License
#include "stdafx.h"
#include "../mystdio.h"
#include <string.h>
#include <memory.h>
#include <stdlib.h>
#include "byteFunctions.h"
#include "helperFunctions.h"
extern FILE *source;
extern FILE *output;
#ifdef _BIG_ENDIAN
#define endian_swap32(x) ((((x) & 0xff000000) >> 24) | \
(((x) & 0x00ff0000) >> 8) | \
(((x) & 0x0000ff00) << 8) | \
(((x) & 0x000000ff) << 24))
#else
#define endian_swap32(x) (x)
#endif
void readSceneInfo()
{
free(getBytes(8));
unsigned int sceneLength = getInteger();
char* sceneName = getString();
myprintf("Decompiling SCENE %s...\n\n", sceneName);
unsigned int sceneFirstFrame = getInteger();
unsigned int sceneLastFrame = getInteger();
unsigned int sceneFrameSpeed = getInteger();
unsigned int sceneTicksPerFrame = getInteger();
char* sceneBackgroundStatic = getRGB();
char* sceneAmbientStatic = getRGB();
fprintf(output, "*SCENE\n");
fprintf(output, "{\n");
fprintf(output, "\t*SCENE_FILENAME\t%s\n", sceneName);
fprintf(output, "\t*SCENE_FIRSTFRAME\t%i\n", sceneFirstFrame);
fprintf(output, "\t*SCENE_LASTFRAME\t%i\n", sceneLastFrame);
fprintf(output, "\t*SCENE_FRAMESPEED\t%i\n", sceneFrameSpeed);
fprintf(output, "\t*SCENE_TICKSPERFRAME\t%i\n", sceneTicksPerFrame);
fprintf(output, "\t*SCENE_BACKGROUND_STATIC\t%s\n", sceneBackgroundStatic);
fprintf(output, "\t*SCENE_AMBIENT_STATIC\t%s\n", sceneAmbientStatic);
fprintf(output, "}\n");
free(sceneName);
free(sceneBackgroundStatic);
free(sceneAmbientStatic);
} | [
"Bazanski@1d10bff2-9961-11dd-bd51-a78b85c98fae"
]
| [
[
[
1,
54
]
]
]
|
11645dc9aa8ba004042a346d8c009822781cc658 | 974a20e0f85d6ac74c6d7e16be463565c637d135 | /trunk/coreLibrary_200/source/physics/dgCollisionSphere.cpp | d38ef6ca331c3a57776fa35db638b730725c29b9 | []
| no_license | Naddiseo/Newton-Dynamics-fork | cb0b8429943b9faca9a83126280aa4f2e6944f7f | 91ac59c9687258c3e653f592c32a57b61dc62fb6 | refs/heads/master | 2021-01-15T13:45:04.651163 | 2011-11-12T04:02:33 | 2011-11-12T04:02:33 | 2,759,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,989 | cpp | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "dgPhysicsStdafx.h"
#include "dgBody.h"
#include "dgWorld.h"
#include "dgContact.h"
#include "dgCollisionSphere.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define EDGE_COUNT 96
dgInt32 dgCollisionSphere::m_shapeRefCount = 0;
dgVector dgCollisionSphere::m_unitSphere[DG_SPHERE_VERTEX_COUNT];
dgConvexSimplexEdge dgCollisionSphere::m_edgeArray[EDGE_COUNT];
dgCollisionSphere::dgCollisionSphere(dgMemoryAllocator* const allocator,
dgUnsigned32 signature, dgFloat32 radii, const dgMatrix& offsetMatrix) :
dgCollisionConvex(allocator, signature, offsetMatrix, m_sphereCollision)
{
Init(radii, allocator);
}
dgCollisionSphere::dgCollisionSphere(dgWorld* const world,
dgDeserialize deserialization, void* const userData) :
dgCollisionConvex(world, deserialization, userData)
{
dgVector size;
deserialization(userData, &size, sizeof(dgVector));
Init(size.m_x, world->GetAllocator());
}
dgCollisionSphere::~dgCollisionSphere()
{
m_shapeRefCount--;
_ASSERTE(m_shapeRefCount >= 0);
dgCollisionConvex::m_simplex = NULL;
dgCollisionConvex::m_vertex = NULL;
}
void dgCollisionSphere::Init(dgFloat32 radius, dgMemoryAllocator* allocator)
{
m_rtti |= dgCollisionSphere_RTTI;
m_radius = radius;
m_edgeCount = EDGE_COUNT;
m_vertexCount = DG_SPHERE_VERTEX_COUNT;
dgCollisionConvex::m_vertex = m_vertex;
if (!m_shapeRefCount)
{
dgInt32 indexList[256];
dgVector tmpVectex[256];
dgVector p0(dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p1(-dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p2(dgFloat32(0.0f), dgFloat32(1.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p3(dgFloat32(0.0f), -dgFloat32(1.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p4(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(1.0f),
dgFloat32(0.0f));
dgVector p5(dgFloat32(0.0f), dgFloat32(0.0f), -dgFloat32(1.0f),
dgFloat32(0.0f));
dgInt32 i = 1;
dgInt32 count = 0;
TesselateTriangle(i, p4, p0, p2, count, tmpVectex);
TesselateTriangle(i, p4, p2, p1, count, tmpVectex);
TesselateTriangle(i, p4, p1, p3, count, tmpVectex);
TesselateTriangle(i, p4, p3, p0, count, tmpVectex);
TesselateTriangle(i, p5, p2, p0, count, tmpVectex);
TesselateTriangle(i, p5, p1, p2, count, tmpVectex);
TesselateTriangle(i, p5, p3, p1, count, tmpVectex);
TesselateTriangle(i, p5, p0, p3, count, tmpVectex);
//_ASSERTE (count == EDGE_COUNT);
dgInt32 vertexCount = dgVertexListToIndexList(&tmpVectex[0].m_x,
sizeof(dgVector), 3 * sizeof(dgFloat32), 0, count, indexList, 0.001f);
_ASSERTE(vertexCount == DG_SPHERE_VERTEX_COUNT);
for (dgInt32 i = 0; i < vertexCount; i++)
{
m_unitSphere[i] = tmpVectex[i];
}
dgPolyhedra polyhedra(m_allocator);
polyhedra.BeginFace();
for (dgInt32 i = 0; i < count; i += 3)
{
#ifdef _DEBUG
dgEdge* const edge = polyhedra.AddFace(indexList[i], indexList[i + 1],
indexList[i + 2]);
_ASSERTE(edge);
#else
polyhedra.AddFace (indexList[i], indexList[i + 1], indexList[i + 2]);
#endif
}
polyhedra.EndFace();
dgUnsigned64 i1 = 0;
dgPolyhedra::Iterator iter(polyhedra);
for (iter.Begin(); iter; iter++)
{
dgEdge* const edge = &(*iter);
edge->m_userData = i1;
i1++;
}
for (iter.Begin(); iter; iter++)
{
dgEdge* const edge = &(*iter);
dgConvexSimplexEdge* const ptr = &m_edgeArray[edge->m_userData];
ptr->m_vertex = edge->m_incidentVertex;
ptr->m_next = &m_edgeArray[edge->m_next->m_userData];
ptr->m_prev = &m_edgeArray[edge->m_prev->m_userData];
ptr->m_twin = &m_edgeArray[edge->m_twin->m_userData];
}
}
for (dgInt32 i = 0; i < DG_SPHERE_VERTEX_COUNT; i++)
{
m_vertex[i] = m_unitSphere[i].Scale(m_radius);
}
m_shapeRefCount++;
dgCollisionConvex::m_simplex = m_edgeArray;
SetVolumeAndCG();
dgVector inertia;
dgVector centerOfMass;
dgVector crossInertia;
m_volume.m_w = CalculateMassProperties(inertia, crossInertia, centerOfMass);
}
dgVector dgCollisionSphere::SupportVertexSimd(const dgVector& dir) const
{
_ASSERTE(dgAbsf(dir % dir - dgFloat32 (1.0f)) < dgFloat32 (1.0e-3f));
// return SupportVertex (dir);
return dir.Scale(m_radius);
}
dgVector dgCollisionSphere::SupportVertex(const dgVector& dir) const
{
_ASSERTE(dgAbsf(dir % dir - dgFloat32 (1.0f)) < dgFloat32 (1.0e-3f));
return dir.Scale(m_radius);
}
void dgCollisionSphere::TesselateTriangle(dgInt32 level, const dgVector& p0,
const dgVector& p1, const dgVector& p2, dgInt32& count,
dgVector* ouput) const
{
if (level)
{
_ASSERTE(dgAbsf (p0 % p0 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
_ASSERTE(dgAbsf (p1 % p1 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
_ASSERTE(dgAbsf (p2 % p2 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
dgVector p01(p0 + p1);
dgVector p12(p1 + p2);
dgVector p20(p2 + p0);
p01 = p01.Scale(dgFloat32(1.0f) / dgSqrt(p01 % p01));
p12 = p12.Scale(dgFloat32(1.0f) / dgSqrt(p12 % p12));
p20 = p20.Scale(dgFloat32(1.0f) / dgSqrt(p20 % p20));
_ASSERTE(dgAbsf (p01 % p01 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
_ASSERTE(dgAbsf (p12 % p12 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
_ASSERTE(dgAbsf (p20 % p20 - dgFloat32 (1.0f)) < dgFloat32 (1.0e-4f));
TesselateTriangle(level - 1, p0, p01, p20, count, ouput);
TesselateTriangle(level - 1, p1, p12, p01, count, ouput);
TesselateTriangle(level - 1, p2, p20, p12, count, ouput);
TesselateTriangle(level - 1, p01, p12, p20, count, ouput);
}
else
{
ouput[count++] = p0;
ouput[count++] = p1;
ouput[count++] = p2;
}
}
void dgCollisionSphere::SetCollisionBBox(const dgVector& p0__,
const dgVector& p1__)
{
_ASSERTE(0);
}
dgInt32 dgCollisionSphere::CalculateSignature() const
{
dgUnsigned32 buffer[2 * sizeof(dgMatrix) / sizeof(dgInt32)];
memset(buffer, 0, sizeof(buffer));
buffer[0] = m_sphereCollision;
buffer[1] = Quantize(m_radius);
memcpy(&buffer[2], &m_offset, sizeof(dgMatrix));
return dgInt32(MakeCRC(buffer, sizeof(buffer)));
}
void dgCollisionSphere::CalcAABB(const dgMatrix &matrix, dgVector &p0,
dgVector &p1) const
{
dgFloat32 radius = m_radius + DG_MAX_COLLISION_PADDING;
p0.m_x = matrix[3][0] - radius;
p1.m_x = matrix[3][0] + radius;
p0.m_y = matrix[3][1] - radius;
p1.m_y = matrix[3][1] + radius;
p0.m_z = matrix[3][2] - radius;
p1.m_z = matrix[3][2] + radius;
p0.m_w = dgFloat32(1.0f);
p1.m_w = dgFloat32(1.0f);
}
dgInt32 dgCollisionSphere::CalculatePlaneIntersection(const dgVector& normal,
const dgVector& point, dgVector* const contactsOut) const
{
_ASSERTE((normal % normal) > dgFloat32 (0.999f));
// contactsOut[0] = point;
contactsOut[0] = normal.Scale(normal % point);
return 1;
}
dgInt32 dgCollisionSphere::CalculatePlaneIntersectionSimd(
const dgVector& normal, const dgVector& point,
dgVector* const contactsOut) const
{
#ifdef DG_BUILD_SIMD_CODE
_ASSERTE((normal % normal) > dgFloat32 (0.999f));
// contactsOut[0] = point;
contactsOut[0] = normal.Scale(normal % point);
return 1;
#else
return 0;
#endif
}
void dgCollisionSphere::DebugCollision(const dgMatrix& matrixPtr,
OnDebugCollisionMeshCallback callback, void* const userData) const
{
dgInt32 i;
dgInt32 count;
dgTriplex pool[1024 * 2];
dgVector tmpVectex[1024 * 2];
dgVector p0(dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p1(-dgFloat32(1.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p2(dgFloat32(0.0f), dgFloat32(1.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p3(dgFloat32(0.0f), -dgFloat32(1.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector p4(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(1.0f),
dgFloat32(0.0f));
dgVector p5(dgFloat32(0.0f), dgFloat32(0.0f), -dgFloat32(1.0f),
dgFloat32(0.0f));
i = 3;
count = 0;
TesselateTriangle(i, p4, p0, p2, count, tmpVectex);
TesselateTriangle(i, p4, p2, p1, count, tmpVectex);
TesselateTriangle(i, p4, p1, p3, count, tmpVectex);
TesselateTriangle(i, p4, p3, p0, count, tmpVectex);
TesselateTriangle(i, p5, p2, p0, count, tmpVectex);
TesselateTriangle(i, p5, p1, p2, count, tmpVectex);
TesselateTriangle(i, p5, p3, p1, count, tmpVectex);
TesselateTriangle(i, p5, p0, p3, count, tmpVectex);
for (i = 0; i < count; i++)
{
tmpVectex[i] = tmpVectex[i].Scale(m_radius);
}
// const dgMatrix &matrix = myBody.GetCollisionMatrix();
dgMatrix matrix(GetOffsetMatrix() * matrixPtr);
matrix.TransformTriplex(&pool[0].m_x, sizeof(dgTriplex), &tmpVectex[0].m_x,
sizeof(dgVector), count);
for (i = 0; i < count; i += 3)
{
callback(userData, 3, &pool[i].m_x, 0);
}
}
dgFloat32 dgCollisionPoint::GetVolume() const
{
_ASSERTE(0);
return dgFloat32(0.0f);
}
void dgCollisionPoint::CalculateInertia(dgVector& inertia,
dgVector& origin) const
{
_ASSERTE(0);
// matrix = dgGetIdentityMatrix();
inertia.m_x = dgFloat32(0.0f);
inertia.m_y = dgFloat32(0.0f);
inertia.m_z = dgFloat32(0.0f);
origin.m_x = dgFloat32(0.0f);
origin.m_y = dgFloat32(0.0f);
origin.m_z = dgFloat32(0.0f);
}
dgVector dgCollisionPoint::SupportVertex(const dgVector& dir) const
{
return dgVector(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
}
dgVector dgCollisionPoint::SupportVertexSimd(const dgVector& dir) const
{
_ASSERTE(0);
return dgVector(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
}
dgFloat32 dgCollisionSphere::RayCast(const dgVector& p0, const dgVector& p1,
dgContactPoint& contactOut, OnRayPrecastAction preFilter,
const dgBody* const body, void* const userData) const
{
dgFloat32 t;
dgFloat32 a;
dgFloat32 b;
dgFloat32 c;
dgFloat32 desc;
if (PREFILTER_RAYCAST (preFilter, body, this, userData))
{
return dgFloat32(1.2f);
}
dgVector dp(p1 - p0);
a = dp % dp;
b = dgFloat32(2.0f) * (p0 % dp);
c = (p0 % p0) - m_radius * m_radius;
t = dgFloat32(1.2f);
desc = b * b - 4.0f * a * c;
if (desc > dgFloat32(0.0f))
{
desc = dgSqrt (desc);
a = dgFloat32(1.0f) / (dgFloat32(2.0f) * a);
t = GetMin((-b + desc) * a, (-b - desc) * a);
if (t < dgFloat32(0.0f))
{
t = dgFloat32(1.2f);
}
if (t < dgFloat32(1.0f))
{
dgVector contact(p0 + dp.Scale(t));
contactOut.m_normal = contact.Scale(dgRsqrt (contact % contact));
contactOut.m_userId = SetUserDataID();
}
}
return t;
}
dgFloat32 dgCollisionSphere::RayCastSimd(const dgVector& p0, const dgVector& p1,
dgContactPoint& contactOut, OnRayPrecastAction preFilter,
const dgBody* const body, void* const userData) const
{
return RayCast(p0, p1, contactOut, preFilter, body, userData);
}
dgFloat32 dgCollisionSphere::CalculateMassProperties(dgVector& inertia,
dgVector& crossInertia, dgVector& centerOfMass) const
{
dgFloat32 volume;
dgFloat32 inerta;
//volume = dgCollisionConvex::CalculateMassProperties (inertia, crossInertia, centerOfMass);
centerOfMass = GetOffsetMatrix().m_posit;
volume = dgFloat32(4.0f * 3.141592f / 3.0f) * m_radius * m_radius * m_radius;
inerta = dgFloat32(2.0f / 5.0f) * m_radius * m_radius * volume;
crossInertia.m_x = -volume * centerOfMass.m_y * centerOfMass.m_z;
crossInertia.m_y = -volume * centerOfMass.m_z * centerOfMass.m_x;
crossInertia.m_z = -volume * centerOfMass.m_x * centerOfMass.m_y;
dgVector central(centerOfMass.CompProduct(centerOfMass));
inertia.m_x = inerta + volume * (central.m_y + central.m_z);
inertia.m_y = inerta + volume * (central.m_z + central.m_x);
inertia.m_z = inerta + volume * (central.m_x + central.m_y);
centerOfMass = centerOfMass.Scale(volume);
return volume;
}
void dgCollisionSphere::GetCollisionInfo(dgCollisionInfo* info) const
{
dgCollisionConvex::GetCollisionInfo(info);
info->m_sphere.m_r0 = m_radius;
info->m_sphere.m_r1 = m_radius;
info->m_sphere.m_r2 = m_radius;
info->m_offsetMatrix = GetOffsetMatrix();
// strcpy (info->m_collisionType, "sphere");
info->m_collisionType = m_collsionId;
}
void dgCollisionSphere::Serialize(dgSerialize callback,
void* const userData) const
{
dgVector size(m_radius, m_radius, m_radius, dgFloat32(0.0f));
SerializeLow(callback, userData);
callback(userData, &size, sizeof(dgVector));
}
| [
"[email protected]@b7a2f1d6-d59d-a8fe-1e9e-8d4888b32692"
]
| [
[
[
1,
443
]
]
]
|
029ec1c6438004c2790a7c366460ef228d444d0c | b5ad65ebe6a1148716115e1faab31b5f0de1b493 | /maxsdk2008/include/icustattribcontainer.h | cd016f148ac7616f88796ea4c88f7131bdb01035 | []
| no_license | gasbank/aran | 4360e3536185dcc0b364d8de84b34ae3a5f0855c | 01908cd36612379ade220cc09783bc7366c80961 | refs/heads/master | 2021-05-01T01:16:19.815088 | 2011-03-01T05:21:38 | 2011-03-01T05:21:38 | 1,051,010 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,407 | h | /**********************************************************************
*<
FILE: ICustAttribContainer.h
DESCRIPTION: Defines ICustAttribContainer class
CREATED BY: Nikolai Sander
HISTORY: created 5/22/00
*> Copyright (c) 2000, All Rights Reserved.
**********************************************************************/
#ifndef _ICUSTATTRIBCONTAINER_H_
#define _ICUSTATTRIBCONTAINER_H_
class CustAttrib;
/*! \sa Class CustAttrib , Class RemapDir, Class ReferenceTarget\n\n
\par Description:
This class is available in release 4.0 and later only.\n\n
This class represents the interface class to a custom attributes container.
*/
class ICustAttribContainer : public ReferenceTarget
{
public:
/*! \remarks This method returns the number of custom attributes. */
virtual int GetNumCustAttribs()=0;
/*! \remarks This method allows you to retrieve the custom attribute by
its specified index.
\par Parameters:
<b>int i</b>\n\n
The index of the custom attribute you with to obtain. */
virtual CustAttrib *GetCustAttrib(int i)=0;
/*! \remarks This method allows you to append a custom attribute.
\par Parameters:
<b>CustAttrib *attribute</b>\n\n
A pointer to the custom attribute you wish to add. */
virtual void AppendCustAttrib(CustAttrib *attribute)=0;
/*! \remarks This method allows you to set the custom attribute at the
specified index.
\par Parameters:
<b>int i</b>\n\n
The index for which to set the custom attribute.\n\n
<b>CustAttrib *attribute</b>\n\n
A pointer to the custom attribute you wish to set. */
virtual void SetCustAttrib(int i, CustAttrib *attribute)=0;
/*! \remarks This method allows you to insert a custom attribute at the
specified index.
\par Parameters:
<b>int i</b>\n\n
The index at which to insert the custom attribute.\n\n
<b>CustAttrib *attribute</b>\n\n
A pointer to the custom attribute you wish to insert.\n\n
\return */
virtual void InsertCustAttrib(int i, CustAttrib *attribute)=0;
/*! \remarks This method allows you to remove a custom attribute.
\par Parameters:
<b>int i</b>\n\n
The index of the custom attribute to remove. */
virtual void RemoveCustAttrib(int i)=0;
/*! \remarks This method gets called when the material or texture is to be
displayed in the material editor parameters area. The plug-in should
allocate a new instance of a class derived from ParamDlg to manage the user
interface.
\par Parameters:
<b>HWND hwMtlEdit</b>\n\n
The window handle of the materials editor.\n\n
<b>IMtlParams *imp</b>\n\n
The interface pointer for calling methods in 3ds Max.
\return A pointer to the created instance of a class derived from
<b>ParamDlg</b>. */
virtual ParamDlg* CreateParamDlg(HWND hwMtlEdit, IMtlParams *imp)=0;
/*! \remarks This method will copy the parameters from a specified
reference maker.
\par Parameters:
<b>ReferenceMaker *from</b>\n\n
A pointer to the reference maker to copy the parameters from.\n\n
<b>RemapDir \&remap</b>\n\n
This class is used for remapping references during a Clone. See
Class RemapDir. */
virtual void CopyParametersFrom(ReferenceMaker *from, RemapDir &remap)=0;
/*! \remarks This method returns a pointer to the owner of the custom
attributes. */
virtual Animatable *GetOwner()=0;
/*! \remarks Self deletion. */
virtual void DeleteThis()=0;
};
#endif | [
"[email protected]"
]
| [
[
[
1,
91
]
]
]
|
1e70824029b0032706ea8f46ce05c8e582edc996 | e192bb584e8051905fc9822e152792e9f0620034 | /tags/sources_0_1/noyau/implantation/affichable.cpp | b87955fd1b4bd3692fc1f95e383dc71a1e41a18e | []
| no_license | BackupTheBerlios/projet-univers-svn | 708ffadce21f1b6c83e3b20eb68903439cf71d0f | c9488d7566db51505adca2bc858dab5604b3c866 | refs/heads/master | 2020-05-27T00:07:41.261961 | 2011-07-31T20:55:09 | 2011-07-31T20:55:09 | 40,817,685 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 1,961 | cpp | /***************************************************************************
* Copyright (C) 2004 by Equipe Projet Univers *
* [email protected] *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "affichable.h"
namespace ProjetUnivers {
namespace Noyau {
using namespace ProjetUnivers::Base ;
//////////////////
// Classe abstraite donc destructeur virtuel.
Affichable::~Affichable()
{}
//////////////////////
// Classe abstraite donc constructeur protégé.
// On indique le nom du mesh Ogre.
Affichable::Affichable(const Chaine& _nomDuMesh)
: nomDuMesh(_nomDuMesh)
{}
}
}
| [
"rogma@fb75c231-3be1-0310-9bb4-c95e2f850c73"
]
| [
[
[
1,
44
]
]
]
|
143f037389a83d27ef108ea3a5eacf570068b325 | 4aadb120c23f44519fbd5254e56fc91c0eb3772c | /Source/EduNetGames/ModNetSoccer/NetSoccerPlugin.h | dd5014e0f0e4db90fda0a19a00b0b42b3400069e | []
| no_license | janfietz/edunetgames | d06cfb021d8f24cdcf3848a59cab694fbfd9c0ba | 04d787b0afca7c99b0f4c0692002b4abb8eea410 | refs/heads/master | 2016-09-10T19:24:04.051842 | 2011-04-17T11:00:09 | 2011-04-17T11:00:09 | 33,568,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,615 | h | #ifndef __NETSOCCERPLUGIN_H__
#define __NETSOCCERPLUGIN_H__
//-----------------------------------------------------------------------------
// Copyright (c) 2009, Jan Fietz, Cyrus Preuss
// 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 EduNetGames nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#include "EduNetCommon/EduNetCommon.h"
#include "NetSoccerBall.h"
#include "NetSoccerPlayer.h"
#include "OpenSteerUT/CameraPlugin.h"
//-----------------------------------------------------------------------------
class NetSoccerPlugin : public OpenSteer::Plugin
{
ET_DECLARE_BASE ( OpenSteer::Plugin );
public:
NetSoccerPlugin ( bool bAddToRegistry = true );
virtual ~NetSoccerPlugin() {} // be more "nice" to avoid a compiler warning
OS_IMPLEMENT_CLASSNAME ( NetSoccerPlugin )
//-------------------------------------------------------------------------
// OpenSteer::Plugin interface
virtual const char* name() const
{
return this->getClassName();
};
virtual float selectionOrderSortKey ( void ) const
{
return 0.01f;
}
virtual void open ( void );
virtual void update ( const float currentTime, const float elapsedTime );
virtual void redraw ( OpenSteer::AbstractRenderer* pRenderer, const float currentTime, const float elapsedTime) OS_OVERRIDE;
virtual void close ( void );
virtual void reset ( void );
virtual void handleFunctionKeys ( int keyNumber ){};
virtual void printMiniHelpForFunctionKeys ( void ) const{};
virtual const osAVGroup& allVehicles ( void ) const
{
return ( const osAVGroup& ) all;
}
virtual osAVGroup& allVehicles ( void )
{
return ( osAVGroup& ) all;
}
// implement to create a vehicle of the specified class
virtual osAbstractVehicle* createVehicle ( osEntityClassId ) const;
virtual void addVehicle ( osAbstractVehicle* pkVehicle );
virtual void removeVehicle ( osAbstractVehicle* pkVehicle);
virtual void addPlayer (OpenSteer::AbstractPlayer* pkPlayer);
virtual void removePlayer (OpenSteer::AbstractPlayer* pkPlayer);
// a group (STL vector) of all vehicles in the Plugin
std::vector<osAbstractVehicle*> all;
int resetCount;
unsigned int m_PlayerCountA;
unsigned int m_PlayerCountB;
NetSoccerPlayer::Group m_kTeamA;
NetSoccerPlayer::Group m_kTeamB;
NetSoccerPlayer::Group m_AllPlayers;
NetSoccerBall *m_Ball;
OpenSteer::AABBox *m_bbox;
OpenSteer::AABBox *m_TeamAGoal;
OpenSteer::AABBox *m_TeamBGoal;
int junk;
int m_redScore;
int m_blueScore;
private:
void createTeam(unsigned int uiTeamMemberCount,
NetSoccerPlayer::Group& kPlayerGroup, bool bTeamId);
NetSoccerPlayer* findUncontrolledSoccer( NetSoccerPlayer::Group& kTeam );
bool checkForGoal( void );
OpenSteer::CameraPlugin* m_pCameraPlugin;
};
#endif // __NETSOCCERPLUGIN_H__
| [
"janfietz@localhost"
]
| [
[
[
1,
118
]
]
]
|
eeaff3034a28ce646948d8f5df73bad2bd5b5913 | d57f646dc96686ef496054d073d4d495b6036b9b | /NetPipe.NET/NetPipe.NET.h | 5d00a2e533f478c7f80c0b2ac4f2285e07c9ea5b | [
"BSD-2-Clause"
]
| permissive | limura/netpipe | 00d65fd542d3bab833acf24a1a27ac7fd767503a | 1e363a21e299bc2bab4f902c8e70c66786ea8e5b | refs/heads/master | 2021-01-19T13:50:41.041736 | 2007-10-02T10:25:13 | 2007-10-02T10:25:13 | 32,438,427 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,923 | h | /*
* Copyright (c) 2007 IIMURA Takuji. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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$
*/
// NetPipe.NET.h
#pragma once
namespace NetPipe {
class MainLoop;
class ServiceManager;
class ServiceCreator;
class PipeManager;
class Kicker;
};
namespace NetPipeDotNET {
public ref class Initializer {
public:
static void Initialize();
};
public ref class Kicker {
private:
NetPipe::Kicker *original;
public:
Kicker();
~Kicker();
!Kicker();
void kick(System::String ^pipePath);
};
public ref class PipeManager {
private:
NetPipe::PipeManager *original;
public:
PipeManager(NetPipe::PipeManager *Original);
// void addReadFD(int fd, size_t bufSize = 4096);
bool write(System::String ^portName, array<System::Byte> ^buf);
bool write(System::String ^portName, array<System::Byte> ^buf, int length);
bool write(System::String ^portName, System::String ^str);
bool commit(System::String ^portName);
void exit();
};
public ref class Service abstract {
public:
enum class EVENT_TYPE {
RECV,
RECV_DOWN,
FD_INPUT,
FD_DOWN,
TIMER,
};
virtual void onEvent(NetPipeDotNET::PipeManager ^pipeManager,
System::String ^portName, System::String ^arg,
EVENT_TYPE type, array<System::Byte> ^buf) = 0;
};
public ref class ServiceCreator abstract {
public:
virtual Service ^createNewService(System::IntPtr userData) = 0;
};
public ref class ServiceManager {
private:
NetPipe::ServiceManager *UmServiceManager;
public:
ServiceManager(System::String ^serviceName);
~ServiceManager();
!ServiceManager();
NetPipe::ServiceManager *getUnmanagedObject();
System::String ^getServiceName();
void addReadPort(System::String ^portName, System::String ^description);
void addReadPort(System::String ^portName);
void addWritePort(System::String ^portName, System::String ^description);
void addWritePort(System::String ^portName);
//void addReadFD(int fd, string description = "UNDEFINED", size_t bufSize = 4096);
// void addTimer(int usec, string description = "UNDEFINED");
void addServiceCreator(NetPipeDotNET::ServiceCreator ^serviceCreator, System::IntPtr userData);
void addServiceCreator(NetPipeDotNET::ServiceCreator ^serviceCreator);
};
public ref class MainLoop
{
private:
NetPipe::MainLoop *UmMainLoop;
public:
MainLoop();
~MainLoop();
!MainLoop();
void addServiceManager(NetPipeDotNET::ServiceManager ^sm);
void run(int usec);
void run();
};
}
| [
"uirou.j@b085bb30-bf34-0410-99c5-0750ab6b8f60"
]
| [
[
[
1,
123
]
]
]
|
ff6709dab9bd14738292635ad85b05fc8ffb39b0 | 7cf0bc0c3120c2040c3ed534421082cd93f0242f | /ab_mfc/ab_mfc/Page1.h | f310d3adb6c9c50e3c79625a31dd358b9e908493 | []
| no_license | zephyrer/ab-mfc | 3d7be0283fa3fff3dcb7120fc1544e60a3811d88 | f228b27a6fdbcb55f481155e9e9d77302335336a | refs/heads/master | 2021-01-13T02:15:55.470629 | 2010-12-10T12:16:23 | 2010-12-10T12:16:23 | 40,066,957 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,531 | h | #pragma once
#include "afxwin.h"
#include "afxcmn.h"
#include "afxdtctl.h"
// CPage1 对话框
class CPage1 : public CDialog
{
DECLARE_DYNAMIC(CPage1)
public:
CPage1(CWnd* pParent = NULL); // 标准构造函数
virtual ~CPage1();
virtual BOOL OnInitDialog();
// 对话框数据
enum { IDD = IDD_TAB_DLG1 };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CString m_spinval;
CString m_comb_add;
CString m_list_add;
CComboBox m_comb;
CListBox m_list;
CListCtrl m_list_ctrl;
CString m_list_ctrl_add;
CProgressCtrl m_progress;
CSliderCtrl m_slider;
CSpinButtonCtrl m_spin;
CDateTimeCtrl m_datetime;
CIPAddressCtrl m_ipaddress;
afx_msg void OnBnClickedButtonCombDel();
afx_msg void OnBnClickedIdcButtonListAdd();
afx_msg void OnBnClickedButton4();
afx_msg void OnBnClickedButtonCombAdd();
afx_msg void OnBnClickedIdcButtonListCtrlAdd();
afx_msg void OnNMRclickList2(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedIdcButtonListCtrlDel();
afx_msg void OnAdd();
afx_msg void OnDel();
afx_msg void OnOK();
afx_msg void OnNMCustomdrawSlider1(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnDeltaposSpin1(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedButtonGettime();
afx_msg void OnBnClickedButtonGetip();
afx_msg void OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
afx_msg void OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar);
};
| [
"superkiki1989@ce34bfc1-e555-5f21-4a2b-332ae8037cd2",
"[email protected]"
]
| [
[
[
1,
6
],
[
8,
24
],
[
26,
29
],
[
38,
40
],
[
42,
46
],
[
48,
51
],
[
54,
54
]
],
[
[
7,
7
],
[
25,
25
],
[
30,
37
],
[
41,
41
],
[
47,
47
],
[
52,
53
]
]
]
|
7c52973884fef75112d0ea6f2445cea920066a76 | f7cbfb0c72bc3c979bf8dc156b9815b7bffa683e | /recipes/freenote/files/FreeNote/FreeNote/FNCanvas.cpp | 6e7f615600d2b8b3ec81a8407469e29e36a3e288 | [
"MIT"
]
| permissive | overo/overo-oe-natty | a2e77dd6f37ca7ba2a7049488c0790de5dadc5d4 | 695d932b8f25e31b9ae9a3c3ee310331b9c93051 | HEAD | 2016-09-05T16:49:01.171341 | 2011-04-24T11:26:33 | 2011-04-24T11:26:33 | 1,678,549 | 2 | 1 | null | null | null | null | SHIFT_JIS | C++ | false | false | 56,512 | cpp | /* FreeNote for Sharp SLA300, B500, C7x0, C860 Linux PDA
Copyright (C) 2003-2005 Joe Kanemori.<[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
2005/06/04 FreeNote 1.11.12pre
・グリッドの枠線を実際の選択範囲よりも大きく表示するように変更。
・範囲選択、グリッド、ガイド、罫線カラーのカスタマイズを可能に。
・カラーピッカーモードの追加
2005/06/02 FreeNote 1.11.11Apre
・テキスト移動枠の不具合修正
・罫線をグリッドの2倍で表示するように変更
・消しゴム時の範囲指定時に、ペンオフしてワンテンポおいてから範囲確定するように変更
2005/03/18 FreeNote 1.11.10Bpre
・描画の最適化
2005/02/27 FreeNote 1.11.10pre
・PDFの出力形式を一部変更
・インポート時のバグfix
2005/01/04 FreeNote 1.11.6pre
・カーブモードで8の字がかけるように整形エンジンを改善
2005/01/04 FreeNote 1.11.5Apre
・バグフィックス
2004/12/25 FreeNote 1.11.5pre
・レイヤー機能追加
2004/11/24 FreeNote 1.11.0pre
・テキストペースト機能
2004/10/17 FreeNote 1.10.0リリース
2004/08/26 ver 1.9.3pre
・罫線機能を追加
2004/05/23 ver 1.9.1Apre
・欧文環境対応
2004/02/16 ver 1.7.3pre
・編集機能強化
2004/02/14 ver 1.7.2pre
・検索機能追加
2004/02/12 ver 1.7.1pre
・フォント仕様の変更
・テキスト処理の高速化
・テキストボックスの多機能化
2003/02/10 ver 1.7.0pre
・文字入力
2003/12/23 ver 1.6.1
・保存情報のサイズ縮小
2003/12/16-19 ver 1.5.5pre
・ペンサイズの追加(1-8)
・アンドゥ・リドゥの実装
2003/12/14 ver 1.5.4pre
・ペンサイズを選択可能に。
2003/12/05 ver 1.5.3Apre
・グリッドの色を修正
2003/12/04 ver 1.5.3pre
・グリッドの描画を一部修正
2003/11/10 ver 1.5.1pre
・曲線整形モード追加
2003/11/09 ver 1.5.0pre
・自動整形モード追加
2003/09/03 ver 1.3.4pre
・Use all quadrant OFF時に表示位置がリセットされる場合があるバグ対応。
2003/09/01-03 ver 1.3.3pre
・スクロールの改良
・Use all quadrant(全象限を使用する)メニューを追加
2003/08/31 FreeNote 1.3.2pre
・全方向スクロール
2003/08/23 FreeNote 1.3.0pre
・CR動作の修正
2003/08/15 FreeNote 1.2.1を公開
・保存時のバグ修正
・完了ダイアログの自動消去
・PNGファイルへの出力
2003/08/15 FreeNote 1.2を公開
・オプション追加
・スクロールガイド
・Freeファイル関連付け
・アイコンの変更
2003/08/05 FreeNote 1.1.1preを公開
・高速起動時に閉じた状態を保持
・描画モード切替え時に消しゴム表示
・保存時間短縮
・Viewモードの挙動を変更
・メニューの見た目を変更
*/
#include "fncanvas.h"
#include <qsjiscodec.h>
#include <stdio.h>
#include <qfile.h>
#include <qmessagebox.h>
#include <qtextstream.h>
#include <qpen.h>
#include <qcolor.h>
#include <qpoint.h>
#include <qthread.h>
#include <qimage.h>
#include <math.h>
#include <qtextcodec.h>
#include <qmultilineedit.h>
#include <qbitmap.h>
#include "fnmessagebox.h"
#include "fmtengine.h"
#include "fntextdialog.h"
#include <qfont.h>
#include <qapplication.h>
#include <qclipboard.h>
#include "frmmain.h"
#include "fnlayerdlg.h"
#include <stdlib.h>
int snap(int v) {
int tv = abs(v);
tv = ((int)(tv + SNAP_SIZE / 2) / SNAP_SIZE) * SNAP_SIZE;
if (0 > v) {
return -tv;
} else {
return tv;
}
}
FNCanvas::FNCanvas(FNColorDialog* dlg, QWidget* parent, const char* name, WFlags f)
:QWidget(parent, name, f),
_txtTmp(NULL),
_pen(black, 1, SolidLine, RoundCap, RoundJoin),
_asMode(AS_NONE),
_drawMode(MODE_DRAW),
_prevMode(MODE_DRAW),
_eraser_l(50),
_eraser_s(10),
_h_step(100),
_v_step(100),
_margin(5),
_scrollTiming(800),
_selIdx(0),
_viewMode(false),
_isWaiting(false),
_isDragging(false),
_isDrawing(false),
_isHeadingEnables(false),
_isShowGuide(false),
_isUseAllQuadrant(false),
_showRuler(false),
_isTinyPaging(false),
_scale_x(1.0),
_scale_y(1.0),
_tboxRect(0, 50, 220, 240),
_isEraseWaiting(false),
_colorSelector(dlg),
_isColorRevision(true)
{
_tracks.setAutoDelete(true);
_clipboard.setAutoDelete(true);
_current = new FNLayer();
_layers.append(_current);
_layers.setAutoDelete(true);
_undobuf.setAutoDelete(true);
_current->Name = "Layer0";
this->setBackgroundMode(NoBackground);
_timer = new QTimer(this);
connect(_timer, SIGNAL(timeout()), this, SLOT(autoScroll()));
_dlgFind = new FNFindDialog(this, "Find");
connect(_dlgFind, SIGNAL(originChanged(int, int)), this, SLOT(setOrigin(int, int)));
connect(_dlgFind, SIGNAL(resetOrigin()), this, SLOT(resetOrigin()));
}
FNCanvas::~FNCanvas()
{
_timer->stop();
delete _timer;
_tracks.clear();
_layers.clear();
//clearList(_draws);
delete _dlgFind;
}
void FNCanvas::addLayer()
{
FNLayer* layer = new FNLayer();
_current=layer;
uint cnt = _layers.count();
while (1) {
QString name = "Layer";
name += QString::number(cnt);
bool nameExists = false;
for (uint i = 0; i < _layers.count(); ++i) {
if (_layers.at(i)->Name == name) {
nameExists = true;
break;
}
}
if (false == nameExists) {
layer->Name = name;
break;
}
++cnt;
}
_layers.append(layer);
_selIdx = _layers.count() - 1;
redraw();
}
//表示レイヤーを下に移動する
void FNCanvas::moveAboveLayer()
{
--_selIdx;
if (0 > _selIdx) {
_selIdx = 0;
}
_current = _layers.at(_selIdx);
redraw();
}
//表示レイヤーを上に移動する
void FNCanvas::moveBelowLayer()
{
++_selIdx;
if (_layers.count() - 1 <= (uint)_selIdx) {
_selIdx = _layers.count() - 1;
}
_current = _layers.at(_selIdx);
redraw();
}
void FNCanvas::setScrollTiming(int v)
{
_scrollTiming = v;
}
void FNCanvas::setVStep(int v)
{
_v_step = v;
}
void FNCanvas::setHStep(int v)
{
_h_step = v;
}
void FNCanvas::setSEraser(int v)
{
_eraser_s = v;
}
void FNCanvas::setLEraser(int v)
{
_eraser_l = v;
}
void FNCanvas::setMargin(int v)
{
if (v < 3) {
v = 3;
}
_margin = v;
}
void FNCanvas::find()
{
if (_viewMode) {
return;
}
_dlgFind->setElements(_layers);
_dlgFind->show();
_dlgFind->exec();
}
void FNCanvas::setScrollMode(int as)
{
_asMode = as;
redraw();
}
void FNCanvas::autoScroll()
{
if (MODE_ERASE == _drawMode) {
if (0 < _selection.width()) {
int hsn = SNAP_SIZE / 2;
int qsn = hsn / 2;
int x = ((_selection.x() - qsn) / hsn) * hsn;
int y = ((_selection.y() - qsn) / hsn) * hsn;
int dx = _selection.x() - x;
int dy = _selection.y() - y;
int w = ((_selection.width() + dx + hsn) / hsn) * hsn;
int h = ((_selection.height() + dy + hsn) / hsn) * hsn;
_selection.setRect(x, y, w, h);
_isSelected = true;
}
_last = QPoint(-1, -1);
_tracks.clear();
_isHeadingEnables = false;
_isEraseWaiting = false;
redraw();
} else {
if (AS_NONE == _asMode) {
setOrigin(_origin.x(), _origin.y(), false);
redraw();
return;
}
bool tmp = _isHeadingEnables;
int dx = 0;
int dy = 0;
if (AS_BOTH == _asMode || AS_HORIZONTAL == _asMode) {
if (_last.x() > width() * (_margin - 1) / _margin) {
dx = _h_step;
} else if (_last.x() < width() / _margin) {
dx = -_h_step;
}
}
if (AS_BOTH == _asMode || AS_VERTICAL == _asMode) {
if (_last.y() > height() * (_margin - 1) / _margin) {
dy = _v_step;
} else if (_last.y() < height() / _margin) {
dy = -_v_step;
}
}
setOrigin(_origin.x() + dx, _origin.y() + dy, false);
_isHeadingEnables = tmp;
redraw();
}
}
void FNCanvas::drawRect(QPainter& pa, const QRect& r)
{
int w = width();
int h = height();
int sx = r.left();
int sy = r.top();
int ex = r.right();
int ey = r.bottom();
if (0 > sx) {
sx = 0;
}
if (0 > sy) {
sy = 0;
}
if (h < ey) {
ey = h;
}
if (w < ex) {
ex = w;
}
if (0 <= r.left()) {
pa.drawLine(sx, sy, sx, ey);
}
if (0 <= r.top()) {
pa.drawLine(sx, sy, ex, sy);
}
if (w >= r.right()) {
pa.drawLine(ex, sy, ex, ey);
}
if (h >= r.bottom()) {
pa.drawLine(sx, ey, ex, ey);
}
}
void FNCanvas::mousePressEvent(QMouseEvent* evt)
{
if (!_current->IsShow) {
return;
}
setFocus();
_timer->stop();
_tracks.clear();
_txtwait = 10;
if (_viewMode) {
_isWaiting = true;
_viewMode = false;
setOrigin((int)((evt->x()) / _scale_x) - width() / 2, (int)((evt->y()) / _scale_y) - height() / 2, false);
//redraw();
emit resetViewMode();
} else if (MODE_CPICK == _drawMode) {
QRgb c = _buffer.convertToImage().pixel(evt->pos().x(), evt->pos().y());
emit pickColor(c);
return;
} else if (MODE_TEXT == _drawMode) {
_txtTmp = NULL;
// _last = evt->pos();
_last = SnapPoint(evt->pos(), SNAP_SIZE / 4);
int x = _last.x();
int y = _last.y();
for (int i = _current->draws.count() - _current->disp_offset() - 1; i >= 0; --i) {
FNPolygon* p = _current->draws.at((uint)i);
if (FN_TEXT == p->type()) {
QRect r = p->boundingRect();
if (r.contains(x, y)) {
_txtTmp = (FNText*)p;
_selection.setRect(0, 0, -1, -1);
_tdx = _last.x() - r.x();
_tdy = _last.y() - r.y();
break;
}
}
}
} else if (MODE_ERASE == _drawMode) {
if (_isEraseWaiting) {
return;
}
_last = evt->pos();
if (0 >= _selection.width() || !_selection.contains(_last)) {
_isSelected = false;
}
if (!_isSelected) {
_selection = QRect(0, 0, -1, -1);
_selected.clear();
redraw();
int w = _eraser_s;
if (PENWIDTH_MAX / 2 < _pen.width()) {
w = _eraser_l;
}
// 大バグ対策:
// 0 > xの座標に、縦150位の四角形を書くと、C系ザウのパフォーマンスが激落ちします。
// 以降同様のロジックはこの対策のためです。
QPainter pwin;
pwin.begin(this);
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
_preRect.setRect(_last.x() - w / 2, _last.y() - w / 2, w, w);
drawRect(pwin, _preRect);
pwin.flush();
pwin.end();
_selection = QRect(0, 0, -1, -1);
_selected.clear();
} else {
QPainter pwin;
pwin.begin(this);
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
_preRect.setRect(_selection.x(), _selection.y(), _selection.width(), _selection.height());
drawRect(pwin, _preRect);
pwin.flush();
pwin.end();
QPoint t = SnapPoint(QPoint(_selection.x(), _selection.y()));
_last = SnapPoint(_last);
_tdx = _last.x() - t.x();
_tdy = _last.y() - t.y();
}
} else {
_last = evt->pos();
_tracks.append(new QPoint(_last));
}
_isDragging = true;
}
void FNCanvas::mouseMoveEvent(QMouseEvent* evt)
{
if (!_current->IsShow) {
return;
}
if (_isWaiting) {
return;
}
if (MODE_TEXT == _drawMode) {
if (NULL == _txtTmp) {
return;
}
if (0 < _txtwait) {
--_txtwait;
return;
}
QPainter pwin;
pwin.begin(this);
if (-1 != _selection.width()) {
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
drawRect(pwin, _selection);
} else {
_selection = _txtTmp->boundingRect();
}
QPoint tmp = SnapPoint(evt->pos(), SNAP_SIZE / 4);
tmp.setX(tmp.x() - _tdx);
tmp.setY(tmp.y() - _tdy);
if (tmp != _last) {
_selection.moveTopLeft(tmp);
_last = tmp;
}
drawRect(pwin, _selection);
pwin.flush();
pwin.end();
} else if (MODE_CPICK == _drawMode) {
QRgb c = _buffer.convertToImage().pixel(evt->pos().x(), evt->pos().y());
emit pickColor(c);
return;
} else if (MODE_ERASE == _drawMode) {
//redraw();
if (_last.x() == -1) {
return;
}
if (!_isSelected) {
int w = _eraser_s;
if (PENWIDTH_MAX / 2 < _pen.width()) {
w = _eraser_l;
}
QPainter pwin;
pwin.begin(this);
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
drawRect(pwin, _preRect);
_last = evt->pos();
_preRect.setRect(_last.x() - w / 2, _last.y() - w / 2, w, w);
pwin.setRasterOp(CopyROP);
QRect r = QRect(0, 0, width(), height());
for (uint i = 0; i < _current->draws.count() - _current->disp_offset(); ++i) {
FNPolygon* p = _current->draws.at(i);
QRect bounds = p->boundingRect();
if (r.intersects(bounds)) {
bool f = false;
QRect& selected = _preRect;
for (uint j = 0; j < p->points().count(); ++j) {
QPoint& pts = p->points().at(j);
if (selected.contains(pts)) {
f = true;
if (-1 == _selection.width()) {
_selection = bounds;
} else {
if (bounds.x() < _selection.x()) {
_selection.setX(bounds.x());
}
if (bounds.y() < _selection.y()) {
_selection.setY(bounds.y());
}
if (bounds.right() > _selection.right()) {
_selection.setRight(bounds.right());
}
if (bounds.bottom() > _selection.bottom()) {
_selection.setBottom(bounds.bottom());
}
}
break;
}
}
if (f) {
if (0 == _selected.contains(p)) {
_selected.append(p);
}
p->drawShape(pwin, f);
}
}
}
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
drawRect(pwin, _preRect);
pwin.flush();
pwin.end();
} else {
if (0 >= _selection.width()) {
return;
}
//選択中(移動処理)
QPainter pwin;
pwin.begin(this);
pwin.setRasterOp(XorROP);
pwin.setPen(QPen(white, 1));
drawRect(pwin, _preRect);
_last = SnapPoint(evt->pos(), SNAP_SIZE / 4);
_preRect.setRect(_last.x() - _tdx, _last.y() - _tdy, _selection.width(), _selection.height());
drawRect(pwin, _preRect);
pwin.flush();
pwin.end();
}
} else {
QPainter pwin;
pwin.begin(this);
pwin.setPen(_pen);
pwin.drawLine(_last, evt->pos());
pwin.flush();
pwin.end();
_last = evt->pos();
_tracks.append(new QPoint(_last));
}
}
void FNCanvas::mouseReleaseEvent(QMouseEvent* evt)
{
if (!_current->IsShow) {
return;
}
_isDragging = false;
if (_isWaiting) {
_isWaiting = false;
return;
}
if (MODE_ERASE == _drawMode) {
if (_isSelected) {
//_lastへ移動
_last = SnapPoint(evt->pos(), SNAP_SIZE / 4);
int dx = _last.x() - _tdx - _selection.x();
int dy = _last.y() - _tdy - _selection.y();
for (uint i = 0; i < _selected.count(); ++i) {
FNPolygon* p = _selected.at(i);
p->translate(dx, dy);
}
_selection.moveBy(dx, dy);
redraw();
} else {
if (false == _isEraseWaiting) {
_isEraseWaiting = true;
}
redraw();
_timer->start(_scrollTiming, true);
}
} else if (MODE_CPICK == _drawMode) {
QRgb c = _buffer.convertToImage().pixel(evt->pos().x(), evt->pos().y());
emit pickColor(c);
emit changeMode(_prevMode);
return;
} else {
if (1 < _tracks.count()) {
_last = evt->pos();
FNPolygon* p = NULL;
if (MODE_FORMAT == _drawMode) {
p = new FNPolygon(_pen);
_tracks = AutoFormat(_tracks);
} else if (MODE_CURVE == _drawMode) {
QPoint sp = SnapPoint(*_tracks.at(0));
QPoint ep = SnapPoint(*_tracks.at(_tracks.count()-1));
FNPointList tracks;
tracks.setAutoDelete(true);
for (uint i = 0; i < _tracks.count(); ++i) {
QPoint t = *_tracks.at(i);
tracks.append(new QPoint(t.x(), t.y()));
}
_tracks = AutoCurve(_tracks);
bool isEllipse = false;
if (sp == ep) {
if (0 < _tracks.count()) {
int vdconv = 0; //縦方向転換
int vdir = 0;
int svdir = 0;
int hdconv = 0; //横方向転換
int hdir = 0;
int shdir = 0;
QPoint* st = _tracks.at(0);
QPoint* l = st;
for (uint i = 1; i < _tracks.count(); ++i) {
QPoint* p = _tracks.at(i);
int thdir = sign(p->x() - l->x());
if (l->x() != p->x()) {
//水平方向転換
if (0 != thdir) {
if (0 == hdir) {
shdir = thdir;
} else if (thdir != hdir) {
++hdconv;
}
hdir = thdir;
}
}
int tvdir = sign(p->y() - l->y());
if (l->y() != p->y()) {
//垂直方向転換
if (0 != tvdir) {
if (0 == vdir) {
svdir = tvdir;
} else if (tvdir != vdir) {
++vdconv;
}
vdir = tvdir;
}
}
l = p;
}
if (shdir == hdir) {
--hdconv;
}
if (svdir == vdir) {
--vdconv;
}
if (1 >= hdconv && 1 >= vdconv) {
isEllipse = true;
int dircnt = 0;
//もう1判定
tracks = AutoFormat(tracks);
if (2 < tracks.count()) {
int phdir = sign(tracks.at(1)->x() - tracks.at(0)->x());
int pvdir = sign(tracks.at(1)->y() - tracks.at(0)->y());
l = tracks.at(1);
for (uint i = 2; i < tracks.count(); ++i) {
QPoint* p = tracks.at(i);
int thdir = sign(p->x() - l->x());
int tvdir = sign(p->y() - l->y());
if ((0 == pvdir && 0 != tvdir && 0 != phdir && 0 == thdir) ||
(0 != pvdir && 0 == tvdir && 0 == phdir && 0 != thdir))
{
if (3 < dircnt) {
isEllipse = false;
break;
}
++dircnt;
}
l = p;
phdir = thdir;
pvdir = tvdir;
}
}
}
}
}
if (isEllipse) {
QRect r = GetBounds(_tracks);
_tracks.clear();
sp = SnapPoint(QPoint(r.x(), r.y()));
ep = SnapPoint(QPoint(r.x() + r.width(), r.y() + r.height()));
_tracks.append(new QPoint(sp.x(), sp.y()));
_tracks.append(new QPoint(ep.x(), ep.y()));
p = new FNEllipse(_pen);
} else if (2 < _tracks.count()) {
p = new FNBezier(_pen);
} else {
p = new FNPolygon(_pen);
}
} else if (MODE_SMOOTH == _drawMode) {
_tracks = Smoothing(_tracks);
if (2 < _tracks.count()) {
p = new FNBezier(_pen);
} else {
p = new FNPolygon(_pen);
}
} else {
_tracks = Reduce(_tracks);
p = new FNPolygon(_pen);
}
if (NULL != p) {
p->setFill(_fill);
if (1 < _tracks.count()) {
p->setPoints(_tracks);
redobuf_flush();
_current->draws.append(p);
}
}
} else if (MODE_TEXT == _drawMode) {
if (NULL == _txtTmp) {
textEdit(_last.x(), _last.y());
} else {
QRect r = _txtTmp->boundingRect();
if (_selection == r || 0 < _txtwait) {
textEdit(r.x(), r.y(), _txtTmp);
} else {
if (-1 != _selection.width()) {
_txtTmp->translate(_last.x() - r.x(), _last.y() - r.y());
}
}
}
_txtTmp = NULL;
}
_tracks.clear();
_isHeadingEnables = true;
_timer->start(_scrollTiming, true);
}
}
void FNCanvas::textEdit(int x, int y, FNText* obj)
{
FNTextDialog dlg(fontname, _colorSelector, this);
dlg.show();
/*
if (width() < _tboxRect.x()) {
_tboxRect.setX(0);
}
if (50 > _tboxRect.y()) {
_tboxRect.setY(50);
}
if (height() < _tboxRect.height()) {
_tboxRect.setHeight(height());
}
if (width() < _tboxRect.width()) {
_tboxRect.setWidth(width());
}
dlg.move(_tboxRect.x(), _tboxRect.y());
dlg.resize(_tboxRect.width(), _tboxRect.height());
*/
dlg.move(width() / 8, height() / 8);
dlg.resize(width() * 6 / 8, height() * 6 / 8);
QPen pen = _pen;
if (NULL != obj) {
for (uint i = 0; i < obj->lines.count(); ++i) {
dlg.lines->append(obj->lines[i]);
}
pen = obj->pen();
}
dlg.setPen(pen);
int mx = x;
int my = y;
if (dlg.exec()) {
pen = dlg.pen();
if (0 < dlg.lines->text().length()) {
FNText* p = obj;
if (NULL == obj) {
p = new FNText(pen);
_current->draws.append((FNPolygon*)p);
}
p->pen() = pen;
p->lines.clear();
FNPointList l;
l.append(new QPoint(x, y));
QFont font(fontname);
font.setPointSize(FONTSIZE[pen.width()]);
QFontMetrics fm(font);
int h = fm.height();
for (int i = 0; i < dlg.lines->numLines(); ++i) {
p->lines.append(dlg.lines->textLine(i));
int w = fm.width(dlg.lines->textLine(i)) + x;
l.append(new QPoint(w, my));
my += h;
l.append(new QPoint(w, my));
l.append(new QPoint(x, my));
if (mx < w) {
mx = w;
}
}
p->setPoints(l);
redobuf_flush();
redraw();
} else {
if (NULL != obj) {
_current->draws.remove(obj);
}
}
}
_tboxRect = QRect(dlg.x(), dlg.y(), dlg.width(), dlg.height());
}
void FNCanvas::paintEvent(QPaintEvent*)
{
bitBlt(this, 0, 0, &_buffer);
}
void FNCanvas::resizeEvent(QResizeEvent* evt)
{
QPixmap save(_buffer);
_buffer.resize(evt->size());
_buffer.fill(white);
bitBlt(&_buffer, 0, 0, &save);
redraw();
}
void FNCanvas::setOrigin(QPoint& o)
{
this->setOrigin(o.x(), o.y());
}
QPoint FNCanvas::getTopLeft()
{
bool hasValue = false;
int dx = 0;
int dy = 0;
if (0 < _current->draws.count()) {
dx = ((FNPolygon*)_current->draws.at(0))->boundingRect().x();
dy = ((FNPolygon*)_current->draws.at(0))->boundingRect().y();
}
for (uint j = 0; j < _layers.count(); ++j) {
FNPolygonList& draws = _layers.at(j)->draws;
for (uint i = 0; i < draws.count(); ++i) {
FNPolygon* p = draws.at(i);
hasValue = true;
if (dx > p->boundingRect().x()) {
dx = p->boundingRect().x();
}
if (dy > p->boundingRect().y()) {
dy = p->boundingRect().y();
}
}
}
if (!hasValue || !_isUseAllQuadrant) {
return _origin;
}
return QPoint(snap(dx), snap(dy));
}
void FNCanvas::rebuild()
{
if (!_isUseAllQuadrant) {
return;
}
QPoint d = getTopLeft();
d.setX(d.x() - SNAP_SIZE);
d.setY(d.y() - SNAP_SIZE);
for (uint j = 0; j < _layers.count(); ++j) {
FNPolygonList& draws = _layers.at(j)->draws;
for (uint i = 0; i < draws.count(); ++i) {
FNPolygon* p = draws.at(i);
p->translate(-d.x(), -d.y());
}
}
_origin = QPoint(0, 0);
}
void FNCanvas::resetOrigin()
{
int ox = 0;
int oy = 0;
_isHeadingEnables = false;
_timer->stop();
int dx = 0;
int dy = 0;
if (!_isUseAllQuadrant) {
if (0 > ox) {
ox = 0;
}
if (0 > oy) {
oy = 0;
}
dx = _origin.x() - ox;
dy = _origin.y() - oy;
} else {
dx = _origin.x() - ox;
dy = _origin.y() - oy;
if (0 > ox) {
ox = 0;
}
if (0 > oy) {
oy = 0;
}
}
for (uint i = 0; i < _tracks.count(); ++i) {
QPoint* p = _tracks.at(i);
p->setX(p->x() + dx);
p->setY(p->y() + dy);
}
for (uint i = 0; i < _layers.count(); ++i) {
FNPolygonList& draws = _layers.at(i)->draws;
for (uint j = 0; j < draws.count(); ++j) {
FNPolygon* p = draws.at(j);
p->translate(dx, dy);
}
}
_origin = QPoint(ox, oy);
}
void FNCanvas::setOrigin(int ox, int oy, bool isRedrawEnabled)
{
ox = snap(ox);
oy = snap(oy);
_isHeadingEnables = false;
_timer->stop();
int dx = 0;
int dy = 0;
if (!_isUseAllQuadrant) {
if (0 > ox) {
ox = 0;
}
if (0 > oy) {
oy = 0;
}
dx = _origin.x() - ox;
dy = _origin.y() - oy;
} else {
dx = _origin.x() - ox;
dy = _origin.y() - oy;
if (0 > ox) {
ox = 0;
}
if (0 > oy) {
oy = 0;
}
}
if (dx == 0 && dy == 0) {
return;
}
for (uint i = 0; i < _tracks.count(); ++i) {
QPoint* p = _tracks.at(i);
p->setX(p->x() + dx);
p->setY(p->y() + dy);
}
for (uint j = 0; j < _layers.count(); ++j) {
FNPolygonList& draws = _layers.at(j)->draws;
for (uint i = 0; i < draws.count(); ++i) {
FNPolygon* p = draws.at(i);
p->translate(dx, dy);
}
}
if (-1 != _selection.width()) {
_selection.moveBy(dx, dy);
}
_origin = QPoint(ox, oy);
emit originChanged(ox, oy);
if (isRedrawEnabled) {
redraw();
}
}
void FNCanvas::redraw()
{
if (_isDrawing) {
return;
}
if (_isDragging) {
return;
}
if (!this->isVisible()) {
return;
}
_isDrawing = true;
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (_isTinyPaging) {
if (_current == &layer) {
layer.IsShow = true;
} else {
layer.IsShow = false;
}
}
}
int h = height(); //(height() / 40) * 40;
_buffer.fill(white);
QRect r = QRect(0, 0, width(), height());
QPainter pbuf;
pbuf.begin(&_buffer);
pbuf.setFont(QFont(fontname));
pbuf.setClipRect(0, 0, width(), height());
if (_viewMode) {
float wx = 0;
float wy = 0;
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (layer.IsShow) {
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon* p = draws.at(i);
QRect r = p->boundingRect();
if (wx < r.right()) {
wx = r.right();
}
if (wy < r.bottom()) {
wy = r.bottom();
}
}
}
}
wx += SNAP_SIZE;
wy += SNAP_SIZE;
wx = snap((int)wx);
wy = snap((int)wy);
wx = wx + _origin.x();
wy = wy + _origin.y();
_scale_x = (float)width() / wx;
_scale_y = (float)height() / wy;
if (1.0f < _scale_x) {
_scale_x = 1.0f;
}
if (1.0f < _scale_y) {
_scale_y = 1.0f;
}
if (_scale_x > _scale_y) {
_scale_x = _scale_y;
} else if (_scale_x < _scale_y) {
_scale_y = _scale_x;
}
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (!layer.IsShow) {
continue;
}
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon* p = draws.at(i);
FNPolygon* t = NULL;
if (p->type() == FN_BEZIER) {
t = new FNBezier(*(FNBezier*)p);
} else if (p->type() == FN_ELLIPSE) {
t = new FNEllipse(*(FNEllipse*)p);
} else if (p->type() == FN_TEXT) {
t = new FNText(*(FNText*)p);
} else {
t = new FNPolygon(*p);
}
t->translate(-_origin.x(), -_origin.y());
for (uint j = 0; j < t->points().count(); ++j) {
QPoint& pts = t->points().at(j);
int x = (int)(pts.x() * _scale_x);
int y = (int)(pts.y() * _scale_y);
pts.setX(x);
pts.setY(y);
}
double pensize = t->pen().width();
if (_scale_x > _scale_y) {
pensize = pensize * _scale_y;
} else {
pensize = pensize * _scale_x;
}
if (0 >= pensize) {
pensize = 1;
}
if (p->type() == FN_TEXT) {
FNText* tp = (FNText*)t;
QPoint& sp = t->points().at(0);
//default font size checking...
QFont f(fontname, FONTSIZE[p->pen().width()]);
QFontMetrics fm(f);
int h = fm.height();
int wx = 0;
int wy = 0;
for (uint i = 0; i < tp->lines.count(); ++i) {
int tw = fm.width(tp->lines[i]);
if (tw > wx) {
wx = tw;
}
wy += h;
}
//create default font image...
QRect r = tp->boundingRect();
QPixmap tmp(wx + 1, wy + 1);
tmp.fill(Qt::white);
QPainter pt;
pt.begin(&tmp);
pt.setFont(f);
pt.setPen(p->pen());
int y = h + 1;
for (uint i = 0; i < tp->lines.count(); ++i) {
pt.drawText(1, y, tp->lines[i]);
y += h;
}
pt.flush();
pt.end();
//draw to font image
tmp = tmp.convertToImage().smoothScale(r.width(), r.height());
tmp.setMask(tmp.createHeuristicMask());
pbuf.drawPixmap(sp.x(), sp.y(), tmp);
pbuf.flush();
} else {
t->pen().setWidth(pensize);
t->drawShape(pbuf);
}
delete t;
}
}
} else {
if (MODE_ERASE == _drawMode || MODE_FORMAT == _drawMode || MODE_CURVE == _drawMode || MODE_TEXT == _drawMode) {
//グリッド描画
//QPen pen2(QColor(0, 0, 0), 1);
//pbuf.setPen(QPen(QColor(50, 240, 240), 1));
pbuf.setPen(QPen(GridColor));
for (int x = 0; x < width() + SNAP_SIZE; x += SNAP_SIZE) {
pbuf.drawLine(x - SNAP_SIZE / 2, 0, x - SNAP_SIZE / 2, h);
for (int y = 0; y < h + SNAP_SIZE; y += SNAP_SIZE) {
pbuf.drawLine(0, y - SNAP_SIZE / 2, width(), y - SNAP_SIZE / 2);
pbuf.drawRect(x-1,y-1,2,2);
}
}
}
if (MODE_ERASE != _drawMode) {
if (!(MODE_FORMAT == _drawMode || MODE_CURVE == _drawMode || MODE_TEXT == _drawMode)) {
if (_showRuler) {
//罫線
pbuf.setPen(QPen(RulerColor, 1, SolidLine));
int step = SNAP_SIZE * 2; //SNAP_SIZEの2倍に。
for (int i = 0; i < height(); i += step) {
pbuf.drawLine(0, i, width(), i);
}
}
}
if (_isShowGuide) {
pbuf.setPen(QPen(GuideColor, 1, DashLine));
if (AS_HORIZONTAL == _asMode || AS_BOTH == _asMode) {
if (0 != _origin.x() || _isUseAllQuadrant) {
pbuf.drawLine(width() / _margin, 0, width() / _margin, h);
}
pbuf.drawLine(width() * (_margin - 1) / _margin, 0, width() * (_margin - 1) / _margin, h);
}
if (AS_VERTICAL == _asMode || AS_BOTH == _asMode) {
if (0 != _origin.y() || _isUseAllQuadrant) {
pbuf.drawLine(0, h / _margin, width(), h / _margin);
}
pbuf.drawLine(0, h * (_margin - 1) / _margin, width(), h * (_margin - 1) / _margin);
}
}
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (layer.IsShow) {
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon* p = draws.at(i);
if (r.intersects(p->boundingRect())) {
p->drawShape(pbuf);
}
}
}
}
} else {
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (layer.IsShow) {
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon* p = draws.at(i);
if (!_selected.contains(p)) {
if (r.intersects(p->boundingRect())) {
p->drawShape(pbuf);
}
}
}
}
}
for (uint i = 0; i < _selected.count(); ++i) {
_selected.at(i)->drawShape(pbuf, true);
}
if (_isSelected) {
pbuf.setPen(QPen(SelectionFrameColor, 1, DashLine));
pbuf.setBrush(NoBrush);
pbuf.drawRect(_selection);
}
}
}
pbuf.end();
_isDrawing = false;
repaint();
}
void FNCanvas::changeColor(QRgb c)
{
_pen.setColor(QColor(c));
if (_isSelected && _drawMode == MODE_ERASE) {
for (uint i = 0; i < _selected.count(); ++i) {
_selected.at(i)->pen().setColor(QColor(c));
}
}
}
void FNCanvas::selectionMoveTo(int dx, int dy)
{
if (_isSelected) {
for (uint i = 0; i < _selected.count(); ++i) {
_selected.at(i)->translate(dx, dy);
}
_selection.moveBy(dx, dy);
}
redraw();
}
void FNCanvas::copy()
{
if (MODE_ERASE != _drawMode || _viewMode) {
return;
}
_clipboard.clear();
int size = _selected.count();
int a1[size];
int a2[size];
for (int i = 0; i < size; ++i) {
a1[i] = _current->draws.findRef(_selected.at(i));
a2[i] = i;
}
//ソート
FNPolygonList tmp;
for (int i = 0; i < size; ++i) {
int min = i;
for (int j = i + 1; j < size; ++j) {
if (a1[min] > a1[j]) {
min = j;
}
}
tmp.append(_selected.at(a2[min]));
a1[min] = a1[i];
a2[min] = a2[i];
}
//並び順を保証してコピー
tmp.clone(_clipboard);
tmp.clear();
}
void FNCanvas::paste()
{
if (_viewMode) {
return;
}
if (MODE_ERASE == _drawMode) {
_selected.clear();
_clipboard.clone(_selected);
_selection = QRect(0, 0, -1, -1);
for (uint i = 0; i < _selected.count(); ++i) {
FNPolygon* o = _selected.at(i);
o->translate(10, 10);
QRect bounds = o->boundingRect();
if (-1 == _selection.width()) {
_selection = bounds;
} else {
if (bounds.x() < _selection.x()) {
_selection.setX(bounds.x());
}
if (bounds.y() < _selection.y()) {
_selection.setY(bounds.y());
}
if (bounds.right() > _selection.right()) {
_selection.setRight(bounds.right());
}
if (bounds.bottom() > _selection.bottom()) {
_selection.setBottom(bounds.bottom());
}
}
}
_selected.copy(_current->draws);
_isSelected = true;
} else {
int my = 10;
int mx = 10;
int x = 10;
QStringList lines = QStringList::split("\n", QApplication::clipboard()->text());
if (0 < lines.count()) {
FNText* p = new FNText(_pen);
_current->draws.append((FNPolygon*)p);
p->lines.clear();
FNPointList l;
l.append(new QPoint(0, 0));
QFont font(fontname);
font.setPointSize(FONTSIZE[_pen.width()]);
QFontMetrics fm(font);
int h = fm.height();
for (uint i = 0; i < lines.count(); ++i) {
p->lines.append(lines[i]);
int w = fm.width(lines[i]) + x;
l.append(new QPoint(w, my));
my += h;
l.append(new QPoint(w, my));
l.append(new QPoint(x, my));
if (mx < w) {
mx = w;
}
}
p->setPoints(l);
}
}
redraw();
}
void FNCanvas::redo()
{
if (MODE_ERASE != _drawMode) {
_current->redo();
}
redraw();
}
void FNCanvas::clearList(FNPolygonList& list)
{
list.setAutoDelete(true);
list.clear();
list.setAutoDelete(false);
}
void FNCanvas::resetSelection()
{
_selection = QRect(0, 0, -1, -1);
_selected.clear();
_isSelected = false;
}
void FNCanvas::clear()
{
resetSelection();
_layers.clear();
_current = new FNLayer();
_layers.append(_current);
_current->Name = "Layer0";
_selIdx = 0;
_isTinyPaging = false;
//_undobuf.clear();
setOrigin(0, 0);
redraw();
}
void FNCanvas::undo()
{
_timer->stop();
if (MODE_ERASE != _drawMode) {
_current->undo();
} else {
_selected.clear();
_isSelected = false;
_layers.clear();
for (uint i = 0; i < _undobuf.count(); ++i) {
_layers.append(new FNLayer(*_undobuf.at(i)));
}
_current = _layers.at(0);
_selIdx = 0;
}
redraw();
}
void FNCanvas::viewChanged(bool flg)
{
_tracks.clear();
_viewMode = flg;
if (_viewMode) {
if (_isUseAllQuadrant) {
rebuild();
}
setOrigin(0, 0, false);
}
redraw();
}
void FNCanvas::redobuf_flush()
{
_current->redobuf_flush();
}
void FNCanvas::modeChanged(int mode)
{
_tracks.clear();
resetSelection();
_drawMode = mode;
for (uint i = 0; i < _layers.count(); ++i) {
FNLayer* p = _layers.at(i);
p->modeChanged();
}
_undobuf.clear();
if (MODE_ERASE == mode) {
_isEraseWaiting = false;
for (uint i = 0; i < _layers.count(); ++i) {
_undobuf.append(new FNLayer(*_layers.at(i)));
}
}
if (MODE_CPICK != mode) {
_prevMode = mode;
}
redraw();
}
QRect FNCanvas::getMatrix(const QRect& r) const
{
int ox = _origin.x();
int oy = _origin.y();
const int wide = 100;
int left = r.left() + ox;
int top = r.top() + oy;
int right = r.right() + ox;
int bottom = r.bottom() + oy;
left = (int)(left / wide) * wide;
top = (int)(top / wide) * wide;
right = (right % wide == 0 && left != right) ? right : (int)((right + wide) / wide) * wide;
bottom = (bottom % wide == 0 && top != bottom) ? bottom : (int)((bottom + wide) / wide) * wide;
return QRect(left - ox, top - oy, right - left, bottom - top);
}
void FNCanvas::CR()
{
if (MODE_ERASE == _drawMode) {
return;
}
int h = height(); //(height() / 40) * 40;
int step = snap(h) / _margin;
if (_isHeadingEnables) {
//lastから、左方向に向けて探索する。
QRect r = getMatrix(_current->draws.last()->boundingRect());
bool isSearching = true;
r.moveBy(-100, 0);
while (isSearching) {
isSearching = false;
for (uint i = 0; i < _current->draws.count(); ++i) {
FNPolygon* p = _current->draws.at(i);
const QRect& r2 = p->boundingRect();
if (r.intersects(r2)) {
if (r.left() + 100 > r2.left()) {
r = getMatrix(r2);
r.moveBy(-100, 0);
isSearching = true;
break;
}
}
}
}
r.moveBy(100, 0);
//lastが画面の4/5以下ならば、スクロールアップする。
//そうでなければ、ヘッディングのみ。
if (_last.y() > h * 4 / 5) {
setOrigin(_origin.x() + r.x(), _origin.y() + step);
} else {
setOrigin(_origin.x() + r.x(), _origin.y());
}
_isHeadingEnables = false;
} else {
//lastの周囲に何も無い場合は、縦にスクロールする。
setOrigin(_origin.x(), _origin.y() + step);
}
}
void FNCanvas::erase()
{
if (MODE_ERASE != _drawMode) {
return;
}
FNPolygonList temp;
int w = _eraser_s;
if (PENWIDTH_MAX / 2 < _pen.width()) {
w = _eraser_l;
}
for (uint i = 0; i < _selected.count(); ++i) {
_current->draws.remove(_selected.at(i));
//_marks.append(_selected.at(i));
}
resetSelection();
_tracks.clear();
_isEraseWaiting = false;
redraw();
}
void FNCanvas::setPensize(int sz)
{
_pen.setWidth(sz);
if (_isSelected) {
for (uint i = 0; i < _selected.count(); ++i) {
if (FN_TEXT != _selected.at(i)->type()) {
_selected.at(i)->pen().setWidth(sz);
}
}
}
}
bool FNCanvas::exportPNG(const QFileInfo& info, QPixmap& buf)
{
if (0 == info.fileName().length()) {
QMessageBox::warning(0,"FreeNoteQt", "file name is empty.");
return false;
}
if (info.extension(false) != "png") {
QMessageBox::warning(0,"FreeNoteQt", "extension '.png' expected.");
return false;
}
bool ret;
if (_isColorRevision) {
QImage img = buf.convertToImage();
int wd = buf.width();
int ht = buf.height();
for (int i = 0; i < ht; ++i) {
for (int j = 0; j < wd; ++j) {
QRgb c = img.pixel(j, i);
int r = qRed(c) >> 3;
int g = qGreen(c) >> 2;
int b = qBlue(c) >> 3;
r = (r << 3) | (r >> 2);
b = (b << 3) | (b >> 2);
g = (g << 2) | (g >> 4);
//float f1 = 248f / 255f;
//float f2 = 252f / 255f;
//img.setPixel(qRed(c) * f1, qGreen(c) * f2, qBlue(c) * f1);
img.setPixel(j, i, qRgb(r, g, b));
}
}
ret = img.save(info.absFilePath(), "PNG");
} else {
ret = buf.save(info.absFilePath(), "PNG");
}
if (ret) {
FNMessageBox::information(0,"FreeNoteQt", "export PNG complete.");
} else {
QMessageBox::warning(0,"FreeNoteQt", "could not export file.");
}
return ret;
}
QString FNCanvas::mkPDFscript(FNPolygon* elm, int wy)
{
QString s ="";
char buf[1024];
float r;
float g;
float b;
if (_isColorRevision) {
r = (float)elm->pen().color().red() / 248.0f;
g = (float)elm->pen().color().green() / 252.0f;
b = (float)elm->pen().color().blue() / 248.0f;
} else {
r = (float)elm->pen().color().red() / 255.0f;
g = (float)elm->pen().color().green() / 255.0f;
b = (float)elm->pen().color().blue() / 255.0f;
}
if (elm->type() == FN_TEXT) {
FNText* t = (FNText*)elm;
sprintf(buf, "BT\r\n/F1 %d Tf\r\n", FONTSIZE[elm->pen().width()]);
s += buf;
sprintf(buf, "0 Tr\r\n%f %f %f rg\r\n", r, g, b);
s += buf;
QRect r = t->boundingRect();
r.moveBy(_origin.x(), _origin.y());
QFont font(fontname);
font.setPointSize(FONTSIZE[elm->pen().width()]);
QFontMetrics fm(font);
int h = fm.height();
int y = r.y() + h;
for (uint i = 0; i < t->lines.count(); ++i) {
sprintf(buf, "1 0 0 1 %d %d Tm\r\n", r.x() + 3, wy - y);
s += buf;
y = y + h;
s += "<";
for (uint j = 0; j < t->lines[i].length(); ++j) {
sprintf(buf, "%04X", (t->lines[i].at(j).unicode() & 0x0ffff));
s += buf;
}
s += "> Tj\r\n";
}
s += "ET\r\n";
} else {
s += "q\r\n";
if (elm->fill()) {
sprintf(buf, "%f %f %f rg\r\n", r, g, b);
} else {
sprintf(buf, "%f %f %f RG\r\n", r, g, b);
}
s += buf;
QPointArray points = elm->points().copy();
points.translate(_origin.x(), _origin.y());
if (elm->type() == FN_BEZIER) {
sprintf(buf, "%d %d m\r\n", points[0].x(), wy - points[0].y());
s += buf;
for (uint j = 1; j < points.count(); j += 3) {
sprintf(buf, "%d %d %d %d %d %d c\r\n",
points[j].x(), wy - points[j].y(),
points[j + 1].x(), wy - points[j + 1].y(),
points[j + 2].x(), wy - points[j + 2].y()
);
s += buf;
}
} else if (elm->type() == FN_ELLIPSE) {
int x = points[0].x();
int y = points[0].y();
int ex = points[1].x();
int ey = points[1].y();
int w = ex - x;
int h = ey - y;
int cx = x + w/2;
int cy = y;
int x1 = x + 3*w/4;
int y1 = y;
int x2 = x + w;
int y2 = y + h/4;
int x3 = x + w;
int y3 = y + h/2;
sprintf(buf, "%d %d m\r\n%d %d %d %d %d %d c\r\n", cx, wy - cy, x1, wy - y1, x2, wy - y2, x3, wy - y3);
s += buf;
x1 = x + w;
y1 = y + 3 * h / 4;
x2 = x + 3 * w / 4;
y2 = y + h;
x3 = x + w/2;
y3 = y + h;
sprintf(buf, "%d %d %d %d %d %d c\r\n", x1, wy - y1, x2, wy - y2, x3, wy - y3);
s += buf;
x1 = x + w / 4;
y1 = y + h;
x2 = x;
y2 = y + 3 * h / 4;
x3 = x;
y3 = y + h / 2;
sprintf(buf, "%d %d %d %d %d %d c\r\n", x1, wy - y1, x2, wy - y2, x3, wy - y3);
s += buf;
x1 = x;
y1 = y + h / 4;
x2 = x + w / 4;
y2 = y;
x3 = x + w / 2;
y3 = y;
sprintf(buf, "%d %d %d %d %d %d c\r\n", x1, wy - y1, x2, wy - y2, x3, wy - y3);
s += buf;
} else {
sprintf(buf, "%d %d m\r\n", points[0].x(), wy - points[0].y());
s += buf;
for (uint j = 1; j < points.count(); ++j) {
sprintf(buf, "%d %d l\r\n", points[j].x(), wy - points[j].y());
s += buf;
}
}
sprintf(buf, "%d w\r\n", elm->pen().width());
s += buf;
if (elm->fill()) {
s += "f*\r\n";
} else {
s += "S\r\n";
}
s += "Q\r\n";
}
return s;
}
bool FNCanvas::exportPDF(const QFileInfo& info)
{
if (0 == info.fileName().length()) {
QMessageBox::warning(0,"FreeNoteQt", "file name is empty.");
return false;
}
if (info.extension(false) != "pdf") {
QMessageBox::warning(0,"FreeNoteQt", "extension '.pdf' expected.");
return false;
}
FILE* fp = NULL;
if (!(fp = fopen(info.absFilePath().utf8(), "wt"))) {
QMessageBox::warning(0,"FreeNoteQt", "could not export file.");
return false;
}
QPoint o = getTopLeft();
rebuild();
int wx = 595;
int wy = 842;
char buf[1024];
int bias = 0;
if (_isUseAllQuadrant) {
bias = SNAP_SIZE;
}
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon* p = draws.at(i);
QRect r = p->boundingRect();
r.moveBy(_origin.x(), _origin.y());
if (wx < r.right() + bias) {
wx = r.right() + bias;
}
if (wy < r.bottom() + bias) {
wy = r.bottom() + bias;
}
}
}
int len = 0;
/*
sprintf(buf, "1 0 0 -1 0 %d cm\r\n", wy);
QString cm = buf;
len += cm.length();
*/
QString cm = "";
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (layer.IsShow) {
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
QString s = mkPDFscript(draws.at(i), wy);
len += s.length();
}
}
}
//int ref = 0;
QString header = "";
QStringList xref;
xref.append("0000000000 65535 f\r\n");
header += "%PDF-1.3\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
header += "1 0 obj<</Type/Catalog/Outlines 2 0 R/Pages 3 0 R>>\r\n";
header += "endobj\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
header += "2 0 obj<</Type/Outlines/Count 0>>\r\n";
header += "endobj\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
header += "3 0 obj<</Type/Pages/Kids[4 0 R]/Count 1>>\r\n";
header += "endobj\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
header += "4 0 obj<</Type/Page/Parent 3 0 R";
sprintf(buf, "/MediaBox[0 0 %d %d]", wx, wy);
header += buf;
header += "/Contents 6 0 R/Resources<</Font<</F1 5 0 R>>/ProcSet[/PDF/Text]>>>>\r\n";
header += "endobj\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
if (encode == QString("WinAnsiEncoding")) {
header += "5 0 obj<</Type/Font/Subtype/Type1/BaseFont/Helvetica/FirstChar 0/LastChar 255/Encoding/WinAnsiEncoding>>\r\n";
} else if (encode == QString("UniJIS-UCS2-H")) {
header += "5 0 obj<</Type/Font/Encoding/UniJIS-UCS2-H/BaseFont/MSGothic/Subtype/Type0/DescendantFonts[<</W[0[1000] 1 94 500 231 324 500 327 389 500 631 [500] 668 [500]]/Type/Font/BaseFont/MSGothic/Subtype/CIDFontType2/CIDSystemInfo<</Ordering(Japan1)/Registry(Adobe)/Supplement 2>>/FontDescriptor<</Type/FontDescriptor/FontBBox[0 -137 1000 859]/FontName/MSGothic/Flags 32/StemV 92/CapHeight 770/XHeight 543/Ascent 859/Descent -137/ItalicAngle 0>>/DW 1000>>]>>\r\n";
}
header += "endobj\r\n";
sprintf(buf, "%010d 00000 n\r\n", header.length());
xref.append(buf);
sprintf(buf, "6 0 obj<</Length %d>>\r\n", len);
header += buf;
header += "stream\r\n";
QString footer = "";
footer += "xref\r\n";
sprintf(buf, "0 %d\r\n", xref.count());
footer += buf;
for (uint i = 0; i < xref.count(); ++i) {
footer += xref[i];
}
footer += "trailer\r\n";
sprintf(buf, "<</Size %d/Root 1 0 R>>\r\n", xref.count());
footer += buf;
footer += "startxref\r\n";
len = cm.length();
len += header.length();
fputs(header, fp);
fputs(cm, fp);
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
if (layer.IsShow) {
FNPolygonList& draws = layer.draws;
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
QString s = mkPDFscript(draws.at(i), wy);
len += s.length();
fputs(s, fp);
}
}
}
QString streamfooter = "endstream\r\nendobj\r\n";
len += streamfooter.length();
fputs(streamfooter, fp);
fputs(footer, fp);
sprintf(buf, "%d\r\n", len);
fputs(buf, fp);
fputs("%%EOF\r\n", fp);
fclose(fp);
if (_isUseAllQuadrant) {
setOrigin(-o.x(), -o.y());
}
FNMessageBox::information(0,"FreeNoteQt", "export PDF complete.");
return true;
}
bool FNCanvas::save(const QFileInfo& info)
{
if (0 == info.fileName().length()) {
QMessageBox::warning(0,"FreeNoteQt", "file name is empty.");
return false;
}
if (info.extension(false) != "free") {
QMessageBox::warning(0,"FreeNoteQt", "extension '.free' expected.");
return false;
}
FILE* fp = NULL;
if (!(fp = fopen(info.absFilePath().utf8(), "wt"))) {
QMessageBox::warning(0,"FreeNoteQt", "could not save file.");
return false;
}
QPoint o = getTopLeft();
rebuild();
fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", fp);
char buf[1024];
sprintf(buf, "<freenote version=\"4.1\" pg=%d idx=\"%d\">\n", _isTinyPaging, _selIdx);
fputs(buf, fp);
for (uint l = 0; l < _layers.count(); ++l) {
FNLayer& layer = *_layers.at(l);
FNPolygonList& draws = layer.draws;
QString s = "<layer v=";
if (layer.IsShow) {
s += "1 name=\"";
} else {
s += "0 name=\"";
}
s += layer.Name;
s += "\">\n";
fputs(s.utf8(), fp);
for (uint i = 0; i < draws.count() - layer.disp_offset(); ++i) {
FNPolygon p(*draws.at(i));
p.translate(_origin.x(), _origin.y());
if (p.type() == FN_BEZIER) {
sprintf(buf, "\t<bz color=\"%x\" width=\"%d\" f=\"%d\">\n", (uint)p.pen().color().rgb(), p.pen().width(), p.fill());
} else if (p.type() == FN_ELLIPSE) {
sprintf(buf, "\t<el color=\"%x\" width=\"%d\" f=\"%d\">\n", (uint)p.pen().color().rgb(), p.pen().width(), p.fill());
} else if (p.type() == FN_TEXT) {
sprintf(buf, "\t<tx color=\"%x\" width=\"%d\">\n", (uint)p.pen().color().rgb(), p.pen().width());
} else {
sprintf(buf, "\t<po color=\"%x\" width=\"%d\" f=\"%d\">\n", (uint)p.pen().color().rgb(), p.pen().width(), p.fill());
}
fputs(buf, fp);
QPointArray& points = p.points();
for (uint j = 0; j < points.count(); ++j) {
QPoint point = points.point(j);
sprintf(buf, "\t\t<p x=\"%d\" y=\"%d\"/>\n", point.x(), point.y());
fputs(buf, fp);
}
if (p.type() == FN_BEZIER) {
fputs("\t</bz>\n", fp);
} else if (p.type() == FN_ELLIPSE) {
fputs("\t</el>\n", fp);
} else if (p.type() == FN_TEXT) {
FNText* tp = (FNText*)draws.at(i);
for (uint j = 0; j < tp->lines.count(); ++j) {
s = "\t\t<t v=\"";
s += tp->lines[j];
s += "\"/>\n";
fputs(s.utf8(), fp);
}
fputs("\t</tx>\n", fp);
} else {
fputs("\t</po>\n", fp);
}
}
fputs("</layer>\n", fp);
}
fputs("</freenote>\n", fp);
fclose(fp);
if (_isUseAllQuadrant) {
setOrigin(-o.x()+SNAP_SIZE, -o.y()+SNAP_SIZE);
}
FNMessageBox::information(0, "FreeNoteQt", "save complete.");
return true;
}
bool FNCanvas::load(const QFileInfo& info)
{
if (0 == info.fileName().length()) {
QMessageBox::warning(0,"FreeNoteQt", "file name is empty.");
return false;
}
if (!info.exists()) {
QMessageBox::warning(0,"FreeNoteQt", "file not exists.");
return false;
}
FILE* fp = NULL;
if (!(fp = fopen(info.absFilePath().utf8(), "rt"))) {
QMessageBox::warning(0,"FreeNoteQt", "could not open file.");
return false;
}
clear();
open(_layers, fp);
if ((uint)_selIdx >= _layers.count()) {
_selIdx = 0;
}
_current = _layers.at(_selIdx);
fclose(fp);
redraw();
FNMessageBox::information(0,"FreeNoteQt", "load complete.");
return true;
}
bool FNCanvas::import(const QFileInfo& info)
{
if (0 == info.fileName().length()) {
QMessageBox::warning(0,"FreeNoteQt", "file name is empty.");
return false;
}
if (!info.exists()) {
QMessageBox::warning(0,"FreeNoteQt", "file not exists.");
return false;
}
FILE* fp = NULL;
if (!(fp = fopen(info.absFilePath().utf8(), "rt"))) {
QMessageBox::warning(0,"FreeNoteQt", "could not open file.");
return false;
}
clearList(_clipboard);
open(_clipboard, fp);
fclose(fp);
if (0 < _clipboard.count()) {
int x = _clipboard.at(0)->boundingRect().left();
int y = _clipboard.at(0)->boundingRect().top();
for (uint i = 1; i < _clipboard.count(); ++i) {
if (y > _clipboard.at(i)->boundingRect().top()) {
y = _clipboard.at(i)->boundingRect().top();
}
if (x > _clipboard.at(i)->boundingRect().left()) {
x = _clipboard.at(i)->boundingRect().left();
}
}
for (uint i = 0; i < _clipboard.count(); ++i) {
_clipboard.at(i)->translate(-x, -y);
}
}
FNMessageBox::information(0,"FreeNoteQt", "import complete.");
return true;
}
void FNCanvas::open(FNPolygonList& list, FILE* fp)
{
clearList(list);
FNLayerList layers;
open(layers, fp);
for (uint i = 0; i < layers.count(); ++i) {
FNLayer& layer = *layers.at(i);
if (layer.IsShow) {
layer.draws.clone(list);
/*
FNPolygonList& elmlst = layer.draws;
for (uint j = 0; j < elmlst.count(); ++j) {
list.append(elmlst.at(j));
}
elmlst.clear();
*/
}
}
layers.clear();
}
void FNCanvas::open(FNLayerList& layers, FILE* fp)
{
QString line;
FNPointList points;
points.setAutoDelete(true);
int c;
int w;
QPen pen(Qt::black, 1);
FNPolygon* polygon;
char rdbuf[1024];
char buf[1024];
QString type = "";
QStringList lines;
layers.setAutoDelete(true);
layers.clear();
layers.setAutoDelete(false);
FNLayer* layer = new FNLayer();
layer->IsShow = true;
layer->Name = "Layer0";
//_current = layer;
layers.append(layer);
FNPolygonList* list = &layer->draws;
bool isFirstLayer = true;
bool fill = false;
while (!feof(fp)) {
fgets(rdbuf, sizeof(rdbuf), fp);
line = rdbuf;
if (-1 != line.find("<freenote")) {
if (-1 != line.find("pg=1")) {
_isTinyPaging = true;
} else {
_isTinyPaging = false;
}
int st = line.find("idx=") + 5;
int ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
sscanf(buf, "%d", &_selIdx);
} else if (-1 != line.find("<layer ")) {
if (false == isFirstLayer) {
layer = new FNLayer();
list = &layer->draws;
layers.append(layer);
}
isFirstLayer = false;
if (-1 != line.find("v=0")) {
layer->IsShow = false;
} else if (-1 != line.find("v=1")) {
layer->IsShow = true;
}
int st = line.find("name=") + 6;
int ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
QTextCodec *codec = QTextCodec::codecForName("utf8");
layer->Name = codec->toUnicode(buf);
} else if (-1 != line.find("<fnpolygon ") ||
-1 != line.find("<po ") ||
-1 != line.find("<bz ") ||
-1 != line.find("<el ") ||
-1 != line.find("<tx ")
) {
if (-1 != line.find("<el ")) {
type = "Ellipse";
} else if (-1 != line.find("<bz ")) {
type = "Bezier";
} else if (-1 != line.find("<tx ")) {
type = "Text";
lines.clear();
} else {
type = "Polygon";
}
fill = false;
points.clear();
int st = line.find("color") + 7;
int ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
sscanf(buf, "%x", &c);
st = line.find("width") + 7;
ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
sscanf(buf, "%d", &w);
if (-1 != line.find(" f=\"1\"")) {
fill = true;
}
} else if (-1 != line.find("<point ") ||
-1 != line.find("<p ")
) {
int st = line.find("x=") + 3;
int ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
int x;
sscanf(buf, "%d", &x);
st = line.find("y=") + 3;
ed = line.find("\"", st);
strcpy(buf, line.mid(st, ed - st));
int y;
sscanf(buf, "%d", &y);
points.append(createPts(x, y)); //バグ対策
} else if (-1 != line.find("<t ")) {
int st = line.find("v=") + 3;
int ed = line.findRev("\"");
strcpy(buf, line.mid(st, ed - st));
QTextCodec *codec = QTextCodec::codecForName("utf8");
lines.append(codec->toUnicode(buf));
} else if (-1 != line.find("</fnpolygon") ||
-1 != line.find("</bz") ||
-1 != line.find("</el") ||
-1 != line.find("</po") ||
-1 != line.find("</tx")) {
pen.setColor((QRgb)c);
pen.setWidth(w);
if (type == "Bezier") {
list->append(polygon = createBezier(pen)); //バグ対策
} else if (type == "Ellipse") {
list->append(polygon = createEllipse(pen)); //バグ対策
} else if (type == "Text") {
list->append(polygon = createText(pen, lines));
} else {
list->append(polygon = createPolygon(pen)); //バグ対策
}
polygon->setFill(fill);
polygon->setPoints(points);
points.clear();
}
}
}
FNPolygon* FNCanvas::createPolygon(QPen& pen)
{
return new FNPolygon(pen);
}
FNPolygon* FNCanvas::createBezier(QPen& pen)
{
return new FNBezier(pen);
}
FNPolygon* FNCanvas::createEllipse(QPen& pen)
{
return new FNEllipse(pen);
}
FNPolygon* FNCanvas::createText(QPen& pen, QStringList& lines)
{
FNText* p = new FNText(pen);
p->lines = lines;
return p;
}
QPoint* FNCanvas::createPts(int x, int y)
{
return new QPoint(x, y);
}
void FNCanvas::setGuide(bool f)
{
_isShowGuide = f;
redraw();
}
void FNCanvas::fillChanged(bool f) {
_fill = f;
if (_isSelected) {
for (uint i = 0; i < _selected.count(); ++i) {
_selected.at(i)->setFill(f);
}
}
}
| [
"[email protected]"
]
| [
[
[
1,
2244
]
]
]
|
abb4bfed4d2d32bf7474f5d9b93f4d3d6bb212f3 | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/AppMonitor.cpp | 04a47683b01e9c91d9808ec54b538f2c31f668ef | []
| 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,821 | cpp | // /*
// *
// * 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
// *
// */
#include "stdafx.h"
#include "AppMonitor.h"
#include "atlenc.h"
#ifdef _UNITTESTING
BOOL AppMonitor::UnitTest()
{
TRACE(_T("===> AppMonitor::UnitTest\r\n"));
TCHAR state[500];
{
AppMonitor ap;
ap.StartMonitoring();
ap.IncreaseAppCount();
ap.IncreaseAppCount();
ap.IncreaseCrashCount();
UNITTEST(ap.GetState().Runs == 2);
UNITTEST(ap.GetState().TotalRuns == 2);
UNITTEST(ap.GetState().Crashes == 1);
UNITTEST(ap.GetState().TotalCrashes == 1);
UNITTEST(ap.IsAfterCrash() == FALSE);
UNITTEST(ap.GetState().AppUniqueID != 0);
UNITTEST(ap.GetState().InstallationDate.wYear > 0);
UNITTEST(ap.GetState().RunningTimeInMinutes == 0);
ap.StopMonitoring();
UNITTEST(ap.Save(state, 500));
}
{
AppMonitor ap;
ap.Load(state);
ap.StartMonitoring();
UNITTEST(ap.GetState().Runs == 2);
UNITTEST(ap.GetState().TotalRuns == 2);
UNITTEST(ap.GetState().Crashes == 1);
UNITTEST(ap.GetState().TotalCrashes == 1);
UNITTEST(ap.IsAfterCrash() == FALSE);
UNITTEST(ap.GetState().AppUniqueID != 0);
UNITTEST(ap.GetState().InstallationDate.wYear > 0);
UNITTEST(ap.GetState().RunningTimeInMinutes == 0);
UNITTEST(ap.Save(state, 500));
}
{
AppMonitor ap;
ap.Load(state);
ap.StartMonitoring();
UNITTEST(ap.IsAfterCrash() == TRUE);
}
return TRUE;
}
#endif
AppMonitor::AppMonitor():
m_bIsAfterCrash(FALSE)
{
memset(&m_startTime, 0, sizeof(SYSTEMTIME));
}
AppMonitor::~AppMonitor()
{
}
//GetLocalTime(&m_startTime);
//=== Start Monitoring
// 1. Resets the RunningTime Counter
// 2. Sets the bRunning to TRUE
// 3. If the AppUniqueID is 0 then it sets the InstallationDate and creates a new UID
// Usually use it after Load(...)
void AppMonitor::StartMonitoring()
{
GetLocalTime(&m_startTime);
m_state.bRunning = TRUE;
if (m_state.AppUniqueID == 0)
{
GetLocalTime(&m_state.InstallationDate);
m_state.AppUniqueID = MAKELPARAM(m_state.InstallationDate.wMilliseconds + m_state.InstallationDate.wSecond * 1000, GetTickCount());
}
}
//=== Start Monitoring
// 1. Updates the "Running Minutes" state value
// 2. Sets the bRunning to FALSE
// Usually use it before Save(...)
void AppMonitor::StopMonitoring()
{
m_state.RunningTimeInMinutes = GetRunningTimeInMinutes();
m_state.bRunning = FALSE;
}
// 1. Calculates The IsAfterCrash Flag from the bRunning Flag
BOOL AppMonitor::Load(LPCTSTR stateString)
{
CHAR bf[2 * sizeof(State)];
INT i = 0;
for (; i < 2 * sizeof(State); i++)
{
bf[i] = (CHAR)stateString[i];
if (stateString[i] == 0)
break;
}
State tmpState;
INT len = sizeof(State);
if (!Base64Decode(bf, i, (BYTE*)&tmpState, &len))
return FALSE;
if (len != sizeof(State))
return FALSE;
//BYTE b[sizeof(State)];
//TCHAR tmp[3];
//tmp[2] = 0;
//for (INT i = 0; i < sizeof(State); i++)
//{
// tmp[0] = stateString[2*i];
// tmp[1] = stateString[2*i+1];
// if (tmp[0] == 0 || tmp[1] == 0)
// return FALSE;
// LPTSTR endPtr = 0;
// b[i] = (BYTE)_tcstoul(tmp, &endPtr, 16);
//}
//State* pState = (State*) &b;
//===Make some sane tests here.
if (tmpState.InstallationDate.wYear < 2000)
return FALSE;
if (tmpState.InstallationDate.wHour >= 24)
return FALSE;
if (tmpState.InstallationDate.wMinute >= 60)
return FALSE;
if (tmpState.InstallationDate.wSecond >= 60)
return FALSE;
m_state = tmpState;
m_bIsAfterCrash = (m_state.bRunning == TRUE);
return TRUE;
}
BOOL AppMonitor::Save(LPTSTR bf, UINT bfLen)
{
if (bfLen < ((sizeof(State) * 2) + 1))
return FALSE;
CHAR base64Data[2 * sizeof(State)];
INT base64DataLen = 2 * sizeof(State);
if (!Base64Encode((BYTE*)&m_state, sizeof(State), base64Data, &base64DataLen, ATL_BASE64_FLAG_NOCRLF))
return FALSE;
INT i = 0;
for (; i < base64DataLen; i++)
bf[i] = base64Data[i];
bf[i] = 0;
return TRUE;
//BYTE* pState = (BYTE*) &m_state;
//for (INT i = 0; i < sizeof(State); i++)
// _sntprintf(&bf[i*2], 3, _T("%02X"), pState[i]);
//return TRUE;
}
DOUBLE AppMonitor::GetInstalledTime() const
{
return GetTimeFromNow(&m_state.InstallationDate);
}
UINT AppMonitor::GetRunningTimeInMinutes() const
{
if (m_startTime.wYear == 0)
return m_state.RunningTimeInMinutes;
return m_state.RunningTimeInMinutes + INT(GetTimeFromNow(&m_startTime) / 60);
}
DOUBLE AppMonitor::GetTimeFromNow(const SYSTEMTIME* time)
{
SYSTEMTIME st;
GetLocalTime(&st);
DOUBLE curTime = 0.0;
SystemTimeToVariantTime(&st, &curTime);
DOUBLE instTime = 0.0;
SystemTimeToVariantTime((LPSYSTEMTIME)time, &instTime);
return curTime - instTime;
}
void AppMonitor::IncreaseCrashCount()
{
m_state.Crashes++;
m_state.TotalCrashes++;
}
void AppMonitor::IncreaseAppCount()
{
m_state.Runs++;
m_state.TotalRuns++;
}
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
232
]
]
]
|
5143232c34c0d793acaaa2fce22a9abd54dff29e | 340f8c7e48059a93b16b8c5a2499f3a352f92fe3 | /wloo/XmppClient.h | 4c3191384a9d091834b6040e5aeb70015d03fffb | [
"BSD-2-Clause"
]
| permissive | silphire/wloo | c93073c6487f0c09e14b5f54206e78e4cb89da1b | 7a9b3e2f8cff6e39b8b3416a98e014daebf33800 | refs/heads/master | 2020-12-30T14:55:44.233574 | 2011-05-15T22:05:37 | 2011-05-15T22:05:37 | 1,686,466 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #pragma once
class XmppClient
{
public:
static const int DefaultPort;
XmppClient(void);
virtual ~XmppClient(void);
protected:
int Connect(const std::string &hostname, int port);
int Resolve(const std::string &hostname, int port);
int Establish(const std::string &hostname, int port);
int OpenStream(void);
int StartTLS(void);
int Authenticate(void);
int BindResource(void);
int CloseStream(void);
int Shutdown(void);
};
| [
"[email protected]"
]
| [
[
[
1,
21
]
]
]
|
f8f5b858e44b448659c19a752a58fa32bfdaea40 | 88f4b257863d50044212e6036dd09a25ec65a1ff | /src/jingxian/networks/IOCPServer.cpp | 98a93b2e10233df552e9259adc79efff264ed8ef | []
| no_license | mei-rune/jx-proxy | bb1ee92f6b76fb21fdf2f4d8a907823efd05e17b | d24117ab62b10410f2ad05769165130a9f591bfb | refs/heads/master | 2022-08-20T08:56:54.222821 | 2009-11-14T07:01:08 | 2009-11-14T07:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,081 | cpp |
# include "pro_config.h"
# include "jingxian/exception.h"
# include "jingxian/directory.h"
# include "jingxian/networks/IOCPServer.h"
# include "jingxian/networks/TCPAcceptor.h"
# include "jingxian/networks/TCPConnector.h"
# include "jingxian/networks/commands/RunCommand.h"
# include "jingxian/networks/commands/command_queue.h"
_jingxian_begin
IOCPServer::IOCPServer(void)
: completion_port_(null_ptr)
, isRunning_(false)
, logger_(_T("jingxian.system"))
, toString_(_T("IOCPServer"))
{
resolver_.initialize(this);
acceptorFactories_[_T("tcp")] = new TCPAcceptorFactory(this);
connectionBuilders_[_T("tcp")] = new TCPConnector(this);
path_ = simplify(getApplicationDirectory());
tstring logPath = simplify(combinePath(path_, _T("log")));
if (!existDirectory(logPath))
createDirectory(logPath);
}
IOCPServer::~IOCPServer(void)
{
for (stdext::hash_map<tstring, IAcceptorFactory* >::iterator it = acceptorFactories_.begin()
; it != acceptorFactories_.end()
; ++ it)
{
delete(it->second);
}
for (stdext::hash_map<tstring, IConnectionBuilder* >::iterator it = connectionBuilders_.begin()
; it != connectionBuilders_.end()
; ++ it)
{
delete(it->second);
}
close();
for (stdext::hash_map<tstring, ListenPort*>::iterator it = listenPorts_.begin()
; it != listenPorts_.end(); ++it)
{
delete(it->second);
}
}
bool IOCPServer::initialize(size_t number_of_threads)
{
if (!is_null(completion_port_))
return false;
number_of_threads_ = number_of_threads;
completion_port_ = ::CreateIoCompletionPort(INVALID_HANDLE_VALUE,
0,
0,
number_of_threads_);
return !is_null(completion_port_);
}
bool IOCPServer::isPending()
{
for (stdext::hash_map<tstring, ListenPort*>::iterator it = listenPorts_.begin()
; it != listenPorts_.end(); ++it)
{
if (it->second->isPending())
return true;
}
return false;
}
void IOCPServer::wait(time_t seconds)
{
time_t old = time(NULL);
while ((time(NULL) - old) < 3*60)
{
if (sessions_.empty() // 没有连接了
&& !isPending()) // 没有未完成的请求了
break;
if (-1 == handle_events(1000))
break;
}
}
void IOCPServer::close(void)
{
interrupt();
if (is_null(completion_port_))
return ;
wait(3*60);
::CloseHandle(completion_port_);
completion_port_ = null_ptr;
}
/// If the function dequeues a completion packet for a successful I/O operation
/// from the completion port, the return value is nonzero. The function stores
/// information in the variables pointed to by the lpNumberOfBytesTransferred,
/// lpCompletionKey, and lpOverlapped parameters
///
/// 如果函数从端口取出一个完成包,且完成操作是成功的,则返回非0值。上下文数据
/// 保存在lpNumberOfBytesTransferred,lpCompletionKey,lpOverlapped中
///
/// If *lpOverlapped is NULL and the function does not dequeue a completion packet
/// from the completion port, the return value is zero. The function does not
/// store information in the variables pointed to by the lpNumberOfBytes and
/// lpCompletionKey parameters. To get extended error information, call GetLastError.
/// If the function did not dequeue a completion packet because the wait timed out,
/// GetLastError returns WAIT_TIMEOUT.
///
/// 如lpOverlapped 是NULL,没有从端口取出一个完成包,则返回0值。lpNumberOfBytesTransferred
/// ,lpCompletionKey,lpOverlapped也没有保存上下文数据,可以用GetLastError取
/// 得详细错误。如果没有从端口取出一个完成包,可能是超时,GetLastError返回WAIT_TIMEOUT
///
/// If *lpOverlapped is not NULL and the function dequeues a completion packet for
/// a failed I/O operation from the completion port, the return value is zero.
/// The function stores information in the variables pointed to by lpNumberOfBytes,
/// lpCompletionKey, and lpOverlapped. To get extended error information, call GetLastError.
///
/// 如果 lpOverlapped 不是NULL,但完成操作是失败的,则返回0值。上下文数据保存在
/// lpNumberOfBytesTransferred,lpCompletionKey,lpOverlapped中,可以用GetLastError
/// 取得详细错误。
///
/// If a socket handle associated with a completion port is closed, GetQueuedCompletionStatus
/// returns ERROR_SUCCESS, with *lpOverlapped non-NULL and lpNumberOfBytes equal zero.
///
/// 如一个socket句柄被关闭了,GetQueuedCompletionStatus返回ERROR_SUCCESS, lpOverlapped
/// 不是NULL,lpNumberOfBytes等于0。
///
/// </summary>
int IOCPServer::handle_events(uint32_t milli_seconds)
{
OVERLAPPED *overlapped = 0;
u_long bytes_transferred = 0;
ULONG_PTR completion_key = 0;
BOOL result = ::GetQueuedCompletionStatus(completion_port_,
&bytes_transferred,
&completion_key,
&overlapped,
milli_seconds);
if (FALSE == result && is_null(overlapped))
{
switch (GetLastError())
{
case WAIT_TIMEOUT:
return 1;
case ERROR_SUCCESS:
return 0;
default:
return -1;
}
}
else
{
ICommand *asynch_result = (ICommand *) overlapped;
errcode_t error = 0;
if (!result)
error = GetLastError();
this->application_specific_code(asynch_result,
bytes_transferred,
(void *) completion_key,
error);
}
return 0;
}
void IOCPServer::application_specific_code(ICommand *asynch_result,
size_t bytes_transferred,
const void *completion_key,
errcode_t error)
{
try
{
asynch_result->on_complete(bytes_transferred,
error == 0,
(void *) completion_key,
error);
}
catch (std::exception& e)
{
LOG_FATAL(logger_ , "error :" << e.what());
}
catch (...)
{
LOG_FATAL(logger_ , "unkown error!");
}
command_queue::release(asynch_result);
}
bool IOCPServer::post(ICommand *result)
{
if (is_null(result))
return false;
DWORD bytes_transferred = 0;
ULONG_PTR comp_key = 0;
return TRUE == ::PostQueuedCompletionStatus(completion_port_, // completion port
bytes_transferred , // xfer count
comp_key, // completion key
result // overlapped
);
}
//HANDLE IOCPServer::handle()
//{
// return completion_port_;
//}
bool IOCPServer::bind(HANDLE handle, void *completion_key)
{
ULONG_PTR comp_key = reinterpret_cast < ULONG_PTR >(completion_key);
return 0 != ::CreateIoCompletionPort(handle,
this->completion_port_,
comp_key,
this->number_of_threads_);
}
void IOCPServer::connectWith(const tchar* endPoint
, OnBuildConnectionComplete onComplete
, OnBuildConnectionError onError
, void* context)
{
StringArray<tchar> sa = split_with_string(endPoint, _T("://"));
if (2 != sa.size())
{
LOG_ERROR(logger_, _T("尝试连接到 '") << endPoint
<< _T("' 时发生错误 - 地址格式不正确"));
ErrorCode error(_T("地址格式不正确!"));
onError(error, context);
return ;
}
stdext::hash_map<tstring, IConnectionBuilder*>::iterator it =
connectionBuilders_.find(to_lower<tstring>(sa.ptr(0)));
if (it == connectionBuilders_.end())
{
LOG_ERROR(logger_, _T("尝试连接到 '") << endPoint
<< _T("' 时发生错误 - 不能识别的协议‘") << sa.ptr(0)
<< _T("’"));
tstring err = _T("不能识别的协议 - ");
err += sa.ptr(0);
err += _T("!");
ErrorCode error(err.c_str());
onError(error, context);
return ;
}
it->second->connect(endPoint, onComplete, onError, context);
}
bool IOCPServer::listenWith(const tchar* endPoint, IProtocolFactory* protocolFactory)
{
// NOTICE: 用字符串地址直接查找是不好的,转换成 IEndpoint 对象进行比较才更准确
tstring addr = endPoint;
stdext::hash_map<tstring, ListenPort*>::iterator acceptorIt = listenPorts_.find(to_lower<tstring>(addr));
if (listenPorts_.end() != acceptorIt)
{
LOG_TRACE(logger_, _T("已经创建过监听器 '") << endPoint
<< _T("' 了!"));
return false;
}
StringArray<tchar> sa = split_with_string(endPoint, _T("://"));
if (2 != sa.size())
{
LOG_ERROR(logger_, _T("尝试监听地址 '") << endPoint
<< _T("' 时发生错误 - 地址格式不正确!"));
return false;
}
stdext::hash_map<tstring, IAcceptorFactory*>::iterator it =
acceptorFactories_.find(to_lower<tstring>(sa.ptr(0)));
if (it == acceptorFactories_.end())
{
LOG_ERROR(logger_, _T("尝试监听地址 '") << endPoint
<< _T("' 时发生错误 - 不能识别的协议‘") << sa.ptr(0)
<< _T("’"));
return false;
}
listenPorts_[endPoint] = new ListenPort(this, protocolFactory
, it->second->createAcceptor(sa.ptr(1)));
return false;
}
bool IOCPServer::send(IRunnable* runnable)
{
std::auto_ptr< ICommand > ptr(new RunCommand(completion_port_, runnable));
if (ptr->execute())
{
ptr.release();
return true;
}
return false;
}
void IOCPServer::runForever()
{
LOG_CRITICAL(logger_, _T("服务开始运行!"));
isRunning_ = true;
std::list<ListenPort*> instances;
for (stdext::hash_map<tstring, ListenPort*>::iterator it = listenPorts_.begin()
; it != listenPorts_.end();)
{
stdext::hash_map<tstring, ListenPort* >::iterator current = it++;
if (!current->second->start())
{
isRunning_ = false;
LOG_CRITICAL(logger_, _T("启动 '") << current->first << _T("' 组件失败!"));
break;
}
instances.push_back(current->second);
}
if (!isRunning_)
{
/// 启动服务失败,将已启动成功的停止
for (std::list<ListenPort*>::iterator it = instances.begin()
; it != instances.end(); ++it)
{
(*it)->stop();
}
LOG_CRITICAL(logger_, _T("服务启动失败,退出!"));
return;
}
while (isRunning_)
{
if (1 == handle_events(5*1000))
onIdle();
}
LOG_CRITICAL(logger_, _T("服务停止,开始清理工作!"));
for (stdext::hash_map<tstring, ListenPort*>::iterator it = listenPorts_.begin()
; it != listenPorts_.end();)
{
stdext::hash_map<tstring, ListenPort* >::iterator current = it++;
current->second->stop();
}
tstring reason = _T("系统停止");
for (SessionList::iterator it = sessions_.begin()
; it != sessions_.end();)
{
SessionList::iterator current = it++;
(*current)->transport()->disconnection(reason);
}
wait(3*60);
LOG_CRITICAL(logger_, _T("清理工作完成,退出服务!"));
}
void IOCPServer::interrupt()
{
LOG_CRITICAL(logger_, _T("服务收到停止请求!"));
isRunning_ = false;
}
bool IOCPServer::isRunning() const
{
return isRunning_;
}
IDNSResolver& IOCPServer::resolver()
{
return resolver_;
}
const tstring& IOCPServer::basePath() const
{
return path_;
}
void IOCPServer::onIdle()
{
}
SessionList::iterator IOCPServer::addSession(ISession* session)
{
return sessions_.insert(sessions_.end(), session);
}
void IOCPServer::removeSession(SessionList::iterator& it)
{
sessions_.erase(it);
}
void IOCPServer::onExeception(int errCode, const tstring& description)
{
LOG_ERROR(logger_, _T("发生错误 - '") << errCode << _T("' ")
<< description);
}
const tstring& IOCPServer::toString() const
{
return toString_;
}
_jingxian_end
| [
"[email protected]@53e742d2-d0ea-11de-97bf-6350044336de"
]
| [
[
[
1,
434
]
]
]
|
ce9c29950cb5121ea4cca776a222b0f6c6fe8b29 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Source/Direct3D9Plugin/Video/Direct3D9VideoDriver.cpp | f69c0b90ef0a4ac59a4796fb2ab85e61437441d6 | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,637 | cpp | // //
// # # ### # # -= Nuclex Project =- //
// ## # # # ## ## Direct3D9VideoDriver.cpp - Direct3D9 video device //
// ### # # ### //
// # ### # ### A video device using Direct3D9 for rendering //
// # ## # # ## ## //
// # # ### # # R8 (C)2002 Markus Ewald -> License.txt //
// //
#include "Direct3D9Plugin/Video/Direct3D9VideoDriver.h"
#include "Direct3D9Plugin/Video/Direct3D9VideoDevice.h"
#include "DirectX/DXErr9.h"
//#include <multimon.h>
using namespace Nuclex;
using namespace Nuclex::Video;
namespace {
const D3DFORMAT SupportedD3DFormats[] = {
// D3DFMT_R3G3B2,
D3DFMT_R5G6B5,
D3DFMT_R8G8B8,
D3DFMT_X1R5G5B5,
D3DFMT_X8R8G8B8,
D3DFMT_A1R5G5B5,
D3DFMT_A4R4G4B4,
D3DFMT_A8R8G8B8
};
const size_t NumSupportedD3DFormats =
sizeof(SupportedD3DFormats) / sizeof(*SupportedD3DFormats);
}
// //
// Direct3D9DisplayModeEnumerator //
// //
/// Enumerator for display modes
/** Enumerates over all display modes available on a video device
*/
class Direct3D9DisplayModeEnumerator :
public VideoDriver::DisplayModeEnumerator {
public:
/// Constructor
/** Initializes an instance of Direct3D9DisplayModeEnumerator
*/
Direct3D9DisplayModeEnumerator(unsigned long nAdapter) :
m_nAdapter(nAdapter),
m_nCurrentFormat(0),
m_nCurrentMode(0),
m_nNumModes(0) {
return;
}
/// Destructor
/** Destroys an instance of Direct3D9DisplayModeEnumerator
*/
virtual ~Direct3D9DisplayModeEnumerator() {}
/// Cycle through renderers
/** Returns the current renderer being enumerated and advances
to the next. If no more renderers are remaning, NULL is returned
@return The currently enumerated renderer
*/
const VideoDriver::DisplayMode &get() const {
return m_DisplayMode;
}
/// Cycle through renderers
/** Returns the current renderer being enumerated and advances
to the next. If no more renderers are remaning, NULL is returned
@return The currently enumerated renderer
*/
bool next() {
D3DDISPLAYMODE DisplayMode;
getDirect3D9()->GetAdapterDisplayMode(m_nAdapter, &DisplayMode);
while(m_nCurrentMode >= m_nNumModes) {
m_nCurrentFormat++;
if(m_nCurrentFormat > NumSupportedD3DFormats)
return false;
m_nCurrentMode = 0;
m_nNumModes = getDirect3D9()->GetAdapterModeCount(m_nAdapter, SupportedD3DFormats[m_nCurrentFormat - 1]);
}
D3DCheck("Nuclex::Direct3D9DisplayModeEnumerator::cycle()", "IDirect3D9::EnumAdapterModes()",
getDirect3D9()->EnumAdapterModes(m_nAdapter, SupportedD3DFormats[m_nCurrentFormat - 1],
m_nCurrentMode, &DisplayMode));
m_DisplayMode.Resolution.X = DisplayMode.Width;
m_DisplayMode.Resolution.Y = DisplayMode.Height;
m_DisplayMode.nRefreshRate = DisplayMode.RefreshRate;
m_DisplayMode.eFormat = PixelFormatFromD3DFORMAT(DisplayMode.Format);
m_DisplayMode.bFullscreen = true;
m_nCurrentMode++;
return true;
}
private:
VideoDriver::DisplayMode m_DisplayMode; ///< Currently enumerated display mode
unsigned long m_nAdapter; ///< Direct3D video adapter id
unsigned long m_nCurrentMode; ///< Current video mode
unsigned long m_nNumModes; ///< Total number of video modes
unsigned long m_nCurrentFormat; ///< Current format being enumerated
};
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::Direct3D9VideoDriver() Constructor # //
// ####################################################################### //
/** Initializes an instance of Direct3D9VideoDriver
@param pKernel Kernel to which the device belongs
@param nAdapter Direct3D Adapter number of the device
@bug Does not display the monitor's name correctly
*/
Direct3D9VideoDriver::Direct3D9VideoDriver(Kernel *pKernel, unsigned long nAdapter) :
m_nAdapter(nAdapter),
m_pKernel(pKernel) {
IDirect3D9 *pDirect3D9 = getDirect3D9();
// Query the device's capabilities
D3DCheck("Nuclex::Direct3D9VideoDriver::Direct3D9VideoDriver", "IDirect3D9::GetDeviceCaps()",
pDirect3D9->GetDeviceCaps(m_nAdapter, D3DDEVTYPE_HAL, &m_DeviceCaps));
// Build a string uniquely describing the device
D3DADAPTER_IDENTIFIER9 AdapterIdentifier;
D3DCheck("Nuclex::Direct3D9VideoDriver::Direct3D9VideoDriver", "IDirect3D9::GetDeviceCaps()",
pDirect3D9->GetAdapterIdentifier(m_nAdapter, 0, &AdapterIdentifier));
HMONITOR hMonitor = pDirect3D9->GetAdapterMonitor(m_nAdapter);
MONITORINFOEX MonitorInfoEx;
memset(&MonitorInfoEx, 0, sizeof(MonitorInfoEx));
MonitorInfoEx.cbSize = sizeof(MonitorInfoEx);
GetMonitorInfo(hMonitor, &MonitorInfoEx);
string MonitorName = MonitorInfoEx.szDevice;
string::size_type Pos = MonitorName.find_first_of("0123456789");
if(Pos == string::npos) {
Pos = MonitorName.find_last_of("\\/");
if(Pos == string::npos)
Pos = 0;
else
++Pos;
}
m_sName = string("Direct3D9 ") + AdapterIdentifier.Description +
" on Monitor " + MonitorName.substr(Pos);
if(MonitorName.substr(Pos) == "1")
m_sName += " (primary)";
D3DDISPLAYMODE D3DDisplayMode;
pDirect3D9->GetAdapterDisplayMode(nAdapter, &D3DDisplayMode);
m_DesktopDisplayMode.Resolution.X = D3DDisplayMode.Width;
m_DesktopDisplayMode.Resolution.Y = D3DDisplayMode.Height;
m_DesktopDisplayMode.eFormat = PixelFormatFromD3DFORMAT(D3DDisplayMode.Format);
m_DesktopDisplayMode.nRefreshRate = D3DDisplayMode.RefreshRate;
m_DesktopDisplayMode.bFullscreen = false;
}
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::getMaxTextureSize() # //
// ####################################################################### //
/** Returns the maximum texture size supported by the device
@return The maximum texture size of the device
*/
Point2<size_t> Direct3D9VideoDriver::getMaxTextureSize() const {
return Point2<size_t>(m_DeviceCaps.MaxTextureWidth, m_DeviceCaps.MaxTextureHeight);
}
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::supportsScissorTest() # //
// ####################################################################### //
/** Returns true if the device supports scissor testing
@return True, if scissor testing is supported
*/
bool Direct3D9VideoDriver::supportsScissorTest() const {
return (m_DeviceCaps.RasterCaps & D3DPRASTERCAPS_SCISSORTEST) != 0;
}
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::createDevice() # //
// ####################################################################### //
/** Creates a renderer on this device. The renderer is an instance
of the device with an output window. So the device manages vertex
buffers, textures and other resources, while the renderer performs
the actual drawing using these resources and handles the output
window. This allows multiple windows to share the same resources.
@return The created device
*/
shared_ptr<VideoDevice> Direct3D9VideoDriver::createDevice(const DisplayMode &Mode) {
return shared_ptr<VideoDevice>(new Direct3D9VideoDevice(m_pKernel, m_nAdapter, Mode));
}
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::enumDisplayModes() # //
// ####################################################################### //
/** Can be used to enumerate all display modes the device supports
@return A new display mode enumerator
*/
shared_ptr<VideoDriver::DisplayModeEnumerator> Direct3D9VideoDriver::enumDisplayModes() const {
return shared_ptr<VideoDriver::DisplayModeEnumerator>(new Direct3D9DisplayModeEnumerator(m_nAdapter));
}
// ####################################################################### //
// # Nuclex::Direct3D9VideoDriver::getName() # //
// ####################################################################### //
/** Returns a human readable name uniquely describing the
device. Should include the graphics card and monitor used.
@return The device's name
*/
const string &Direct3D9VideoDriver::getName() const {
return m_sName;
}
BOOL CALLBACK Direct3D9VideoDriver::MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT, LPARAM dwData) {
Direct3D9VideoDriver *pThis = reinterpret_cast<Direct3D9VideoDriver *>(dwData);
/*
++pThis->m_MonitorIndex;
if(hMonitor == pThis->m_hSearchedMonitor)
return FALSE;
else
*/
return TRUE;
}
| [
"[email protected]"
]
| [
[
[
1,
238
]
]
]
|
e99db91cc2f039e95dbd2e181c3042b8d07e83b2 | 83c85d3cae31e27285ca07e192cc9bbad8081736 | /POIViewDlg.h | 3519010a09ff11b39324c8601b7cd05314d24ba1 | []
| no_license | yjfcool/poitool | 0768d7299a453335cbd1ae1045440285b3295801 | 1068837ab32dbb9c6df18bbab1ea64bc70942cbf | refs/heads/master | 2016-09-05T11:37:18.585724 | 2010-04-09T06:16:14 | 2010-04-09T06:16:14 | 42,576,080 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,391 | h | // POIViewDlg.h : header file
//
#if !defined(AFX_POIVIEWDLG_H__C5282BDD_A2C6_4035_9FB5_61B54C5C24F7__INCLUDED_)
#define AFX_POIVIEWDLG_H__C5282BDD_A2C6_4035_9FB5_61B54C5C24F7__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//#include "dump\xstring.h"
//#include "dump\filelogger.h"
#include "poiinfo.h"
#include "TreeDlg.h"
#include "SetArea.h"
#include "SetAssort.h"
/////////////////////////////////////////////////////////////////////////////
// CPOIViewDlg dialog
class CPOIViewDlg : public CDialog
{
// Construction
public:
CPOIViewDlg(CWnd* pParent = NULL); // standard constructor
CString m_csFilePath;
CPOIInfo m_poi;
// Dialog Data
//{{AFX_DATA(CPOIViewDlg)
enum { IDD = IDD_POIVIEW_DIALOG };
CListCtrl m_lsPoiList;
CComboBox m_cbAssort3;
CComboBox m_cbAssort2;
CComboBox m_cbAssort1;
CComboBox m_cbCity;
CComboBox m_cbCountry;
CComboBox m_cbProvince;
BOOL m_bPoi;
BOOL m_bSight;
BOOL m_bStreet;
BOOL m_bAcross;
CString m_csStatus;
int m_iModeIndex;
CString m_csSearchStr;
CString m_csCurArea;
CString m_csCurAssor;
//}}AFX_DATA
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CPOIViewDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
CTreeDlg m_TreeDlg;
CSetArea m_AreaSelDlg;
CSetAssort m_AssortSelDlg;
// Implementation
protected:
void UpdateCurAreaInfo(void);
// void UpdateAdmin(int pro, int city, int country = -1);
HICON m_hIcon;
// Generated message map functions
//{{AFX_MSG(CPOIViewDlg)
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
virtual void OnOK();
afx_msg void OnOpenfile();
afx_msg void OnAdcode();
afx_msg void OnAssort();
afx_msg void OnSel();
afx_msg void OnSelchangeCbcity();
afx_msg void OnEditchangeCbprovince();
afx_msg void OnSelchangeCbprovince();
afx_msg void OnOk();
afx_msg void OnCurrentarea();
afx_msg void OnCurrentassort();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_POIVIEWDLG_H__C5282BDD_A2C6_4035_9FB5_61B54C5C24F7__INCLUDED_)
| [
"dulton@370d939e-410d-02cf-1e1d-9a5f4ca5de21"
]
| [
[
[
1,
108
]
]
]
|
5723bc0a00522a3a5300ef75c00a7e4ae140411b | 61679165892c5487e2c6244267e78e30e37b6a17 | /include/gl.hh | ffe67e0e178cd555909c2792232cf99703338ed7 | []
| no_license | jenshz/3dproject | 292b5c303562adfef4d5c9513c5b69dab606b68c | 03609a2a0dd3851445e4a7b6ab9d01ff93df5e77 | refs/heads/master | 2021-01-01T17:56:17.536235 | 2010-12-07T21:21:26 | 2010-12-07T21:21:26 | 1,111,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | hh | #ifndef _GL_HH_
#define _GL_HH_
#ifdef _WIN32
#include <Windows.h>
#endif
#include <GL/glut.h>
#include <vector>
#include <string>
#include "draw.hh"
void initGL();
void reshape(int w, int h);
void display();
void motion(int x, int y);
void mouse(int button, int state, int x, int y);
void keyboard(unsigned char key, int x, int y);
class Screen {
public:
static void toggleFullScreen();
static void setSize(int width, int height);
static int getWidth();
static int getHeight();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
37
]
]
]
|
4353479660852c256dcd4a249569369d1fa1af91 | 9152cb31fbe4e82c22092bb3071b2ec8c6ae86ab | /face/popoface/CNIcqDlg.cpp | decaa6195dda0587aa2c79e96c45eb077ed885ff | []
| no_license | zzjs2001702/sfsipua-svn | ca3051b53549066494f6264e8f3bf300b8090d17 | e8768338340254aa287bf37cf620e2c68e4ff844 | refs/heads/master | 2022-01-09T20:02:20.777586 | 2006-03-29T13:24:02 | 2006-03-29T13:24:02 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,728 | cpp | // CNIcqDlg.cpp : implementation file
//
#include "stdafx.h"
#include "CNIcq.h"
#include "CNIcqDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define WM_ICON_NOTIFY WM_USER+200
/////////////////////////////////////////////////////////////////////////////
// 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)
virtual void OnOK();
//}}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)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCNIcqDlg dialog
CCNIcqDlg::CCNIcqDlg(CWnd* pParent /*=NULL*/)
: CDialog(CCNIcqDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CCNIcqDlg)
//}}AFX_DATA_INIT
// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_pGif = new CGif89a;
}
CCNIcqDlg::~CCNIcqDlg()
{
delete m_pGif;
}
void CCNIcqDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CCNIcqDlg)
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CCNIcqDlg, CDialog)
//{{AFX_MSG_MAP(CCNIcqDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_LBUTTONDOWN()
ON_COMMAND(ID_FILE_EXIT, OnFileExit)
ON_COMMAND(ID_HELP_ABOUT, OnHelpAbout)
ON_WM_SIZE()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CCNIcqDlg message handlers
BOOL CCNIcqDlg::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
// Create the tray icon
if (!m_TrayIcon.Create(NULL, // Parent window
WM_ICON_NOTIFY, // Icon notify message to use
_T("CN即时通讯"), // tooltip
::LoadIcon(NULL, IDI_ASTERISK), // Icon to use
IDR_POPUP_MENU)
) // ID of tray icon
return -1;
m_TrayIcon.SetMenuDefaultItem(0, TRUE);
//取控件对象
//CButton *pButton = (CButton *)GetDlgItem(IDC_BUTTON1);
//pButton->EnableWindow(FALSE);
/*
pButton = new CButton;
ASSERT_VALID (pButton);
pButton->Create(_T("OK"),WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,
CRect(20,20,100,44),this,100);
*/
m_pGif->Load("2.gif");
m_pGif->Pause(TRUE);
CRect rc;
GetClientRect(&rc);
m_ImTab.CreateEx(WS_EX_TRANSPARENT, NULL, NULL, WS_VISIBLE | WS_CHILD,
CRect(0, 0, rc.Width(), rc.Height()-m_pGif->GetHeight()-5), this,NULL);
return TRUE; // return TRUE unless you set the focus to a control
}
void CCNIcqDlg::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 CCNIcqDlg::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
{
CPaintDC dc(this); // device context for painting
CDialog::OnPaint();
CRect rect;
GetClientRect(&rect);
dc.FillSolidRect(rect, RGB(255,255,255));
}
}
// The system calls this to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CCNIcqDlg::OnQueryDragIcon()
{
return (HCURSOR) m_hIcon;
}
BOOL CCNIcqDlg::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Add your specialized code here and/or call the base class
//窗口居中
cs.x = cs.y = 0;
cs.cx=GetSystemMetrics(SM_CXSCREEN/2);
cs.cy=GetSystemMetrics(SM_CYSCREEN/2);
return CDialog::PreCreateWindow(cs);
}
void CCNIcqDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CDialog::OnLButtonDown(nFlags, point);
//Fool dialog into thinking simeone clicked on its caption bar .
//点任意位置移动窗口
PostMessage (WM_NCLBUTTONDOWN , HTCAPTION ,MAKELPARAM(point.x , point. y ));
}
/*
void CCNIcqDlg::GetTadkList(CListBox &list)
{
CString strCaption; //Caption of window.
list.ResetContent (); //Clear list box.
//Get first Window in window list.
ASSERT_VALID (AfxGetMainWnd ());
CWnd* pWnd=AfxGetMainWnd () ->GetWindow (GW_HWNDFIRST);
//Walk window list.
while (pWnd)
{
// I window visible, has a caption, and does not have an owner?
if (pWnd ->IsWindowVisible () &&
pWnd ->GetWindowTextLength () &&!
pWnd ->GetOwner ())
{
//Add caption o window to list box.
pWnd ->GetWindowText (strCaption);
list.AddString (strCaption);
}
//Get next window in window list.
pWnd=pWnd->GetWindow (GW_HWNDNEXT);
}
}
*/
void CCNIcqDlg::OnFileExit()
{
// TODO: Add your command handler code here
if( MessageBox("你确定要退出系统吗?","提示",MB_YESNO | MB_ICONQUESTION) == IDYES)
{
EndDialog(0);
}
}
void CCNIcqDlg::OnHelpAbout()
{
// TODO: Add your command handler code here
CAboutDlg AboutDlg;
AboutDlg.DoModal();
}
void CCNIcqDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CRect rc;
int iWidth,iHeight;
GetClientRect(&rc);
iWidth = m_pGif->GetWidth();
iHeight = m_pGif->GetHeight();
m_pGif->Play(m_hWnd, CRect((cx-iWidth)/2,cy-iHeight-1,(cx-iWidth)/2 + iWidth,cy-1));
m_pGif->Pause(FALSE);
InvalidateRect(CRect(0,cy-iHeight-1,cx,cy-1));
m_ImTab.MoveWindow(CRect(0, 0, rc.Width(), rc.Height()-iHeight-2),TRUE);
}
void CAboutDlg::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}
LRESULT CCNIcqDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
// TODO: Add your specialized code here and/or call the base class
return CDialog::WindowProc(message, wParam, lParam);
}
| [
"yippeesoft@5dda88da-d10c-0410-ac74-cc18da35fedd"
]
| [
[
[
1,
324
]
]
]
|
179f1f799e0819dcf306831a6b769deff14addc1 | 24adabaec8e7b0c8bb71366fea2b02e4e8b34203 | /db-builder/lib/src/operator.cpp | 81aa33c369b21ac9712f66320ec2bf2631d33780 | []
| no_license | weimingtom/db-verkstan | 246fb8ce2890b3833a2a84f2369e8e0e5495390f | 9101195975ec48f4eed33e65e33c83b2dd9ba8c0 | refs/heads/master | 2021-01-10T01:36:39.787220 | 2009-02-23T22:36:09 | 2009-02-23T22:36:09 | 43,455,399 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,231 | cpp | #include "db-util.hpp"
#include "operator.hpp"
#include "texture.hpp"
#include "mesh.hpp"
#include "filters.hpp"
#include <string.h>
Operator* operators[DB_MAX_OPERATORS];
short numberOfOperators;
Operator::Operator(unsigned int filterType_) :
mesh(0),
texture(0),
renderable(0),
numberOfInputs(0),
numberOfOutputs(0),
dirty(true),
filterType(filterType_)
{
for (int i = 0; i < DB_MAX_OPERATOR_CONNECTIONS; i++)
inputs[i] = -1;
}
#ifdef DB_EDITOR
Operator::~Operator()
{
deviceLost();
}
#endif
void Operator::cascadeProcess()
{
if (!isDirty())
return;
/*
for (int i = 0; i < numberOfInputs; i++)
operators[inputs[i]]->cascadeProcess();
*/
process();
dirty = false;
}
void Operator::process()
{
if (texture != 0)
{
delete texture;
texture = 0;
}
if (mesh != 0)
{
delete mesh;
// The mesh can also be the renderable, don't delete twice
if (renderable == mesh)
renderable = 0;
mesh = 0;
}
if (renderable != 0)
{
delete renderable;
renderable = 0;
}
switch (filterType)
{
case BlurTextureFilter:
texture = TextureFilters::blur(getInput(0)->texture,
getByteProperty(0),
getByteProperty(2),
getByteProperty(3),
getByteProperty(1) + 1);
break;
case PixelsTextureFilter:
{
Texture* inputTexture = 0;
if (getInput(0) != 0)
inputTexture = getInput(0)->texture;
texture = TextureFilters::pixels(inputTexture,
getColorProperty(0),
getColorProperty(1),
getByteProperty(2),
getByteProperty(3));
break;
}
}
if (mesh != 0 && renderable == 0)
{
// Use mesh as renderable
renderable = mesh;
}
}
unsigned char Operator::getByteProperty(int index)
{
return properties[index].byteValue;
}
int Operator::getIntProperty(int index)
{
return properties[index].intValue;
}
float Operator::getFloatProperty(int index)
{
return properties[index].floatValue;
}
const char* Operator::getStringProperty(int index)
{
return properties[index].stringValue;
}
D3DXCOLOR Operator::getColorProperty(int index)
{
return properties[index].colorValue;
}
D3DXVECTOR3 Operator::getVectorProperty(int index)
{
return properties[index].vectorValue;
}
bool Operator::isDirty()
{
return dirty;
}
void Operator::setDirty(bool dirty)
{
for (int i = 0; i < numberOfOutputs; i++)
operators[outputs[i]]->setDirty(dirty);
this->dirty = dirty;
}
Operator* Operator::getInput(int index)
{
if (inputs[index] == -1)
return 0;
return operators[inputs[index]];
}
#ifdef DB_EDITOR
void Operator::deviceLost()
{
if (texture != 0)
texture->setDirty();
if (mesh != 0)
mesh->setDirty();
}
#endif
| [
"finalman@75511648-93a4-11dd-b566-b74dd1c53f51"
]
| [
[
[
1,
160
]
]
]
|
baeeade90655b19e0ffb8ab0a167eabe1049435f | 4d5ee0b6f7be0c3841c050ed1dda88ec128ae7b4 | /src/nvimage/openexr/src/IlmImf/ImfTiledInputFile.cpp | 432aecb8a18ca414e69f9a34b73afc1fb25f64dd | []
| no_license | saggita/nvidia-mesh-tools | 9df27d41b65b9742a9d45dc67af5f6835709f0c2 | a9b7fdd808e6719be88520e14bc60d58ea57e0bd | refs/heads/master | 2020-12-24T21:37:11.053752 | 2010-09-03T01:39:02 | 2010-09-03T01:39:02 | 56,893,300 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 33,711 | cpp | ///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// 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 Industrial Light & Magic 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.
//
///////////////////////////////////////////////////////////////////////////
//-----------------------------------------------------------------------------
//
// class TiledInputFile
//
//-----------------------------------------------------------------------------
#include <ImfTiledInputFile.h>
#include <ImfTileDescriptionAttribute.h>
#include <ImfChannelList.h>
#include <ImfMisc.h>
#include <ImfTiledMisc.h>
#include <ImfStdIO.h>
#include <ImfCompressor.h>
#include "ImathBox.h"
#include <ImfXdr.h>
#include <ImfConvert.h>
#include <ImfVersion.h>
#include <ImfTileOffsets.h>
#include <ImfThreading.h>
#include "IlmThreadPool.h"
#include "IlmThreadSemaphore.h"
#include "IlmThreadMutex.h"
#include "ImathVec.h"
#include "Iex.h"
#include <string>
#include <vector>
#include <algorithm>
#include <assert.h>
namespace Imf {
using Imath::Box2i;
using Imath::V2i;
using std::string;
using std::vector;
using std::min;
using std::max;
using IlmThread::Mutex;
using IlmThread::Lock;
using IlmThread::Semaphore;
using IlmThread::Task;
using IlmThread::TaskGroup;
using IlmThread::ThreadPool;
namespace {
struct TInSliceInfo
{
PixelType typeInFrameBuffer;
PixelType typeInFile;
char * base;
size_t xStride;
size_t yStride;
bool fill;
bool skip;
double fillValue;
int xTileCoords;
int yTileCoords;
TInSliceInfo (PixelType typeInFrameBuffer = HALF,
PixelType typeInFile = HALF,
char *base = 0,
size_t xStride = 0,
size_t yStride = 0,
bool fill = false,
bool skip = false,
double fillValue = 0.0,
int xTileCoords = 0,
int yTileCoords = 0);
};
TInSliceInfo::TInSliceInfo (PixelType tifb,
PixelType tifl,
char *b,
size_t xs, size_t ys,
bool f, bool s,
double fv,
int xtc,
int ytc)
:
typeInFrameBuffer (tifb),
typeInFile (tifl),
base (b),
xStride (xs),
yStride (ys),
fill (f),
skip (s),
fillValue (fv),
xTileCoords (xtc),
yTileCoords (ytc)
{
// empty
}
struct TileBuffer
{
const char * uncompressedData;
char * buffer;
int dataSize;
Compressor * compressor;
Compressor::Format format;
int dx;
int dy;
int lx;
int ly;
bool hasException;
string exception;
TileBuffer (Compressor * const comp);
~TileBuffer ();
inline void wait () {_sem.wait();}
inline void post () {_sem.post();}
protected:
Semaphore _sem;
};
TileBuffer::TileBuffer (Compressor *comp):
uncompressedData (0),
dataSize (0),
compressor (comp),
format (defaultFormat (compressor)),
dx (-1),
dy (-1),
lx (-1),
ly (-1),
hasException (false),
exception (),
_sem (1)
{
// empty
}
TileBuffer::~TileBuffer ()
{
delete compressor;
}
} // namespace
//
// struct TiledInputFile::Data stores things that will be
// needed between calls to readTile()
//
struct TiledInputFile::Data: public Mutex
{
Header header; // the image header
TileDescription tileDesc; // describes the tile layout
int version; // file's version
FrameBuffer frameBuffer; // framebuffer to write into
LineOrder lineOrder; // the file's lineorder
int minX; // data window's min x coord
int maxX; // data window's max x coord
int minY; // data window's min y coord
int maxY; // data window's max x coord
int numXLevels; // number of x levels
int numYLevels; // number of y levels
int * numXTiles; // number of x tiles at a level
int * numYTiles; // number of y tiles at a level
TileOffsets tileOffsets; // stores offsets in file for
// each tile
bool fileIsComplete; // True if no tiles are missing
// in the file
Int64 currentPosition; // file offset for current tile,
// used to prevent unnecessary
// seeking
vector<TInSliceInfo> slices; // info about channels in file
IStream * is; // file stream to read from
bool deleteStream; // should we delete the stream
// ourselves? or does someone
// else do it?
size_t bytesPerPixel; // size of an uncompressed pixel
size_t maxBytesPerTileLine; // combined size of a line
// over all channels
vector<TileBuffer*> tileBuffers; // each holds a single tile
size_t tileBufferSize; // size of the tile buffers
Data (bool deleteStream, int numThreads);
~Data ();
inline TileBuffer * getTileBuffer (int number);
// hash function from tile indices
// into our vector of tile buffers
};
TiledInputFile::Data::Data (bool del, int numThreads):
numXTiles (0),
numYTiles (0),
is (0),
deleteStream (del)
{
//
// We need at least one tileBuffer, but if threading is used,
// to keep n threads busy we need 2*n tileBuffers
//
tileBuffers.resize (max (1, 2 * numThreads));
}
TiledInputFile::Data::~Data ()
{
delete [] numXTiles;
delete [] numYTiles;
if (deleteStream)
delete is;
for (size_t i = 0; i < tileBuffers.size(); i++)
delete tileBuffers[i];
}
TileBuffer*
TiledInputFile::Data::getTileBuffer (int number)
{
return tileBuffers[number % tileBuffers.size()];
}
namespace {
void
readTileData (TiledInputFile::Data *ifd,
int dx, int dy,
int lx, int ly,
char *&buffer,
int &dataSize)
{
//
// Read a single tile block from the file and into the array pointed
// to by buffer. If the file is memory-mapped, then we change where
// buffer points instead of writing into the array (hence buffer needs
// to be a reference to a char *).
//
//
// Look up the location for this tile in the Index and
// seek to that position if necessary
//
Int64 tileOffset = ifd->tileOffsets (dx, dy, lx, ly);
if (tileOffset == 0)
{
THROW (Iex::InputExc, "Tile (" << dx << ", " << dy << ", " <<
lx << ", " << ly << ") is missing.");
}
if (ifd->currentPosition != tileOffset)
ifd->is->seekg (tileOffset);
//
// Read the first few bytes of the tile (the header).
// Verify that the tile coordinates and the level number
// are correct.
//
int tileXCoord, tileYCoord, levelX, levelY;
Xdr::read <StreamIO> (*ifd->is, tileXCoord);
Xdr::read <StreamIO> (*ifd->is, tileYCoord);
Xdr::read <StreamIO> (*ifd->is, levelX);
Xdr::read <StreamIO> (*ifd->is, levelY);
Xdr::read <StreamIO> (*ifd->is, dataSize);
if (tileXCoord != dx)
throw Iex::InputExc ("Unexpected tile x coordinate.");
if (tileYCoord != dy)
throw Iex::InputExc ("Unexpected tile y coordinate.");
if (levelX != lx)
throw Iex::InputExc ("Unexpected tile x level number coordinate.");
if (levelY != ly)
throw Iex::InputExc ("Unexpected tile y level number coordinate.");
if (dataSize > (int) ifd->tileBufferSize)
throw Iex::InputExc ("Unexpected tile block length.");
//
// Read the pixel data.
//
if (ifd->is->isMemoryMapped ())
buffer = ifd->is->readMemoryMapped (dataSize);
else
ifd->is->read (buffer, dataSize);
//
// Keep track of which tile is the next one in
// the file, so that we can avoid redundant seekg()
// operations (seekg() can be fairly expensive).
//
ifd->currentPosition = tileOffset + 5 * Xdr::size<int>() + dataSize;
}
void
readNextTileData (TiledInputFile::Data *ifd,
int &dx, int &dy,
int &lx, int &ly,
char * & buffer,
int &dataSize)
{
//
// Read the next tile block from the file
//
//
// Read the first few bytes of the tile (the header).
//
Xdr::read <StreamIO> (*ifd->is, dx);
Xdr::read <StreamIO> (*ifd->is, dy);
Xdr::read <StreamIO> (*ifd->is, lx);
Xdr::read <StreamIO> (*ifd->is, ly);
Xdr::read <StreamIO> (*ifd->is, dataSize);
if (dataSize > (int) ifd->tileBufferSize)
throw Iex::InputExc ("Unexpected tile block length.");
//
// Read the pixel data.
//
ifd->is->read (buffer, dataSize);
//
// Keep track of which tile is the next one in
// the file, so that we can avoid redundant seekg()
// operations (seekg() can be fairly expensive).
//
ifd->currentPosition += 5 * Xdr::size<int>() + dataSize;
}
//
// A TileBufferTask encapsulates the task of uncompressing
// a single tile and copying it into the frame buffer.
//
class TileBufferTask : public Task
{
public:
TileBufferTask (TaskGroup *group,
TiledInputFile::Data *ifd,
TileBuffer *tileBuffer);
virtual ~TileBufferTask ();
virtual void execute ();
private:
TiledInputFile::Data * _ifd;
TileBuffer * _tileBuffer;
};
TileBufferTask::TileBufferTask
(TaskGroup *group,
TiledInputFile::Data *ifd,
TileBuffer *tileBuffer)
:
Task (group),
_ifd (ifd),
_tileBuffer (tileBuffer)
{
// empty
}
TileBufferTask::~TileBufferTask ()
{
//
// Signal that the tile buffer is now free
//
_tileBuffer->post ();
}
void
TileBufferTask::execute ()
{
try
{
//
// Calculate information about the tile
//
Box2i tileRange = Imf::dataWindowForTile (_ifd->tileDesc,
_ifd->minX, _ifd->maxX,
_ifd->minY, _ifd->maxY,
_tileBuffer->dx,
_tileBuffer->dy,
_tileBuffer->lx,
_tileBuffer->ly);
int numPixelsPerScanLine = tileRange.max.x - tileRange.min.x + 1;
int numPixelsInTile = numPixelsPerScanLine *
(tileRange.max.y - tileRange.min.y + 1);
int sizeOfTile = _ifd->bytesPerPixel * numPixelsInTile;
//
// Uncompress the data, if necessary
//
if (_tileBuffer->compressor && _tileBuffer->dataSize < sizeOfTile)
{
_tileBuffer->format = _tileBuffer->compressor->format();
_tileBuffer->dataSize = _tileBuffer->compressor->uncompressTile
(_tileBuffer->buffer, _tileBuffer->dataSize,
tileRange, _tileBuffer->uncompressedData);
}
else
{
//
// If the line is uncompressed, it's in XDR format,
// regardless of the compressor's output format.
//
_tileBuffer->format = Compressor::XDR;
_tileBuffer->uncompressedData = _tileBuffer->buffer;
}
//
// Convert the tile of pixel data back from the machine-independent
// representation, and store the result in the frame buffer.
//
const char *readPtr = _tileBuffer->uncompressedData;
// points to where we
// read from in the
// tile block
//
// Iterate over the scan lines in the tile.
//
for (int y = tileRange.min.y; y <= tileRange.max.y; ++y)
{
//
// Iterate over all image channels.
//
for (unsigned int i = 0; i < _ifd->slices.size(); ++i)
{
const TInSliceInfo &slice = _ifd->slices[i];
//
// These offsets are used to facilitate both
// absolute and tile-relative pixel coordinates.
//
int xOffset = slice.xTileCoords * tileRange.min.x;
int yOffset = slice.yTileCoords * tileRange.min.y;
//
// Fill the frame buffer with pixel data.
//
if (slice.skip)
{
//
// The file contains data for this channel, but
// the frame buffer contains no slice for this channel.
//
skipChannel (readPtr, slice.typeInFile,
numPixelsPerScanLine);
}
else
{
//
// The frame buffer contains a slice for this channel.
//
char *writePtr = slice.base +
(y - yOffset) * slice.yStride +
(tileRange.min.x - xOffset) *
slice.xStride;
char *endPtr = writePtr +
(numPixelsPerScanLine - 1) * slice.xStride;
copyIntoFrameBuffer (readPtr, writePtr, endPtr,
slice.xStride,
slice.fill, slice.fillValue,
_tileBuffer->format,
slice.typeInFrameBuffer,
slice.typeInFile);
}
}
}
}
catch (std::exception &e)
{
if (!_tileBuffer->hasException)
{
_tileBuffer->exception = e.what ();
_tileBuffer->hasException = true;
}
}
catch (...)
{
if (!_tileBuffer->hasException)
{
_tileBuffer->exception = "unrecognized exception";
_tileBuffer->hasException = true;
}
}
}
TileBufferTask *
newTileBufferTask
(TaskGroup *group,
TiledInputFile::Data *ifd,
int number,
int dx, int dy,
int lx, int ly)
{
//
// Wait for a tile buffer to become available,
// fill the buffer with raw data from the file,
// and create a new TileBufferTask whose execute()
// method will uncompress the tile and copy the
// tile's pixels into the frame buffer.
//
TileBuffer *tileBuffer = ifd->getTileBuffer (number);
try
{
tileBuffer->wait();
tileBuffer->dx = dx;
tileBuffer->dy = dy;
tileBuffer->lx = lx;
tileBuffer->ly = ly;
tileBuffer->uncompressedData = 0;
readTileData (ifd, dx, dy, lx, ly,
tileBuffer->buffer,
tileBuffer->dataSize);
}
catch (...)
{
//
// Reading from the file caused an exception.
// Signal that the tile buffer is free, and
// re-throw the exception.
//
tileBuffer->post();
throw;
}
return new TileBufferTask (group, ifd, tileBuffer);
}
} // namespace
TiledInputFile::TiledInputFile (const char fileName[], int numThreads):
_data (new Data (true, numThreads))
{
//
// This constructor is called when a user
// explicitly wants to read a tiled file.
//
try
{
_data->is = new StdIFStream (fileName);
_data->header.readFrom (*_data->is, _data->version);
initialize();
}
catch (Iex::BaseExc &e)
{
delete _data;
REPLACE_EXC (e, "Cannot open image file "
"\"" << fileName << "\". " << e);
throw;
}
catch (...)
{
delete _data;
throw;
}
}
TiledInputFile::TiledInputFile (IStream &is, int numThreads):
_data (new Data (false, numThreads))
{
//
// This constructor is called when a user
// explicitly wants to read a tiled file.
//
try
{
_data->is = &is;
_data->header.readFrom (*_data->is, _data->version);
initialize();
}
catch (Iex::BaseExc &e)
{
delete _data;
REPLACE_EXC (e, "Cannot open image file "
"\"" << is.fileName() << "\". " << e);
throw;
}
catch (...)
{
delete _data;
throw;
}
}
TiledInputFile::TiledInputFile
(const Header &header,
IStream *is,
int version,
int numThreads)
:
_data (new Data (false, numThreads))
{
//
// This constructor called by class Imf::InputFile
// when a user wants to just read an image file, and
// doesn't care or know if the file is tiled.
//
_data->is = is;
_data->header = header;
_data->version = version;
initialize();
}
void
TiledInputFile::initialize ()
{
if (!isTiled (_data->version))
throw Iex::ArgExc ("Expected a tiled file but the file is not tiled.");
_data->header.sanityCheck (true);
_data->tileDesc = _data->header.tileDescription();
_data->lineOrder = _data->header.lineOrder();
//
// Save the dataWindow information
//
const Box2i &dataWindow = _data->header.dataWindow();
_data->minX = dataWindow.min.x;
_data->maxX = dataWindow.max.x;
_data->minY = dataWindow.min.y;
_data->maxY = dataWindow.max.y;
//
// Precompute level and tile information to speed up utility functions
//
precalculateTileInfo (_data->tileDesc,
_data->minX, _data->maxX,
_data->minY, _data->maxY,
_data->numXTiles, _data->numYTiles,
_data->numXLevels, _data->numYLevels);
_data->bytesPerPixel = calculateBytesPerPixel (_data->header);
_data->maxBytesPerTileLine = _data->bytesPerPixel * _data->tileDesc.xSize;
_data->tileBufferSize = _data->maxBytesPerTileLine * _data->tileDesc.ySize;
//
// Create all the TileBuffers and allocate their internal buffers
//
for (size_t i = 0; i < _data->tileBuffers.size(); i++)
{
_data->tileBuffers[i] = new TileBuffer (newTileCompressor
(_data->header.compression(),
_data->maxBytesPerTileLine,
_data->tileDesc.ySize,
_data->header));
if (!_data->is->isMemoryMapped ())
_data->tileBuffers[i]->buffer = new char [_data->tileBufferSize];
}
_data->tileOffsets = TileOffsets (_data->tileDesc.mode,
_data->numXLevels,
_data->numYLevels,
_data->numXTiles,
_data->numYTiles);
_data->tileOffsets.readFrom (*(_data->is), _data->fileIsComplete);
_data->currentPosition = _data->is->tellg();
}
TiledInputFile::~TiledInputFile ()
{
if (!_data->is->isMemoryMapped())
for (size_t i = 0; i < _data->tileBuffers.size(); i++)
delete [] _data->tileBuffers[i]->buffer;
delete _data;
}
const char *
TiledInputFile::fileName () const
{
return _data->is->fileName();
}
const Header &
TiledInputFile::header () const
{
return _data->header;
}
int
TiledInputFile::version () const
{
return _data->version;
}
void
TiledInputFile::setFrameBuffer (const FrameBuffer &frameBuffer)
{
Lock lock (*_data);
//
// Set the frame buffer
//
//
// Check if the new frame buffer descriptor is
// compatible with the image file header.
//
const ChannelList &channels = _data->header.channels();
for (FrameBuffer::ConstIterator j = frameBuffer.begin();
j != frameBuffer.end();
++j)
{
ChannelList::ConstIterator i = channels.find (j.name());
if (i == channels.end())
continue;
if (i.channel().xSampling != j.slice().xSampling ||
i.channel().ySampling != j.slice().ySampling)
THROW (Iex::ArgExc, "X and/or y subsampling factors "
"of \"" << i.name() << "\" channel "
"of input file \"" << fileName() << "\" are "
"not compatible with the frame buffer's "
"subsampling factors.");
}
//
// Initialize the slice table for readPixels().
//
vector<TInSliceInfo> slices;
ChannelList::ConstIterator i = channels.begin();
for (FrameBuffer::ConstIterator j = frameBuffer.begin();
j != frameBuffer.end();
++j)
{
while (i != channels.end() && strcmp (i.name(), j.name()) < 0)
{
//
// Channel i is present in the file but not
// in the frame buffer; data for channel i
// will be skipped during readPixels().
//
slices.push_back (TInSliceInfo (i.channel().type,
i.channel().type,
0, // base
0, // xStride
0, // yStride
false, // fill
true, // skip
0.0)); // fillValue
++i;
}
bool fill = false;
if (i == channels.end() || strcmp (i.name(), j.name()) > 0)
{
//
// Channel i is present in the frame buffer, but not in the file.
// In the frame buffer, slice j will be filled with a default value.
//
fill = true;
}
slices.push_back (TInSliceInfo (j.slice().type,
fill? j.slice().type: i.channel().type,
j.slice().base,
j.slice().xStride,
j.slice().yStride,
fill,
false, // skip
j.slice().fillValue,
(j.slice().xTileCoords)? 1: 0,
(j.slice().yTileCoords)? 1: 0));
if (i != channels.end() && !fill)
++i;
}
while (i != channels.end())
{
//
// Channel i is present in the file but not
// in the frame buffer; data for channel i
// will be skipped during readPixels().
//
slices.push_back (TInSliceInfo (i.channel().type,
i.channel().type,
0, // base
0, // xStride
0, // yStride
false, // fill
true, // skip
0.0)); // fillValue
++i;
}
//
// Store the new frame buffer.
//
_data->frameBuffer = frameBuffer;
_data->slices = slices;
}
const FrameBuffer &
TiledInputFile::frameBuffer () const
{
Lock lock (*_data);
return _data->frameBuffer;
}
bool
TiledInputFile::isComplete () const
{
return _data->fileIsComplete;
}
void
TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int lx, int ly)
{
//
// Read a range of tiles from the file into the framebuffer
//
try
{
Lock lock (*_data);
if (_data->slices.size() == 0)
throw Iex::ArgExc ("No frame buffer specified "
"as pixel data destination.");
//
// Determine the first and last tile coordinates in both dimensions.
// We always attempt to read the range of tiles in the order that
// they are stored in the file.
//
if (dx1 > dx2)
std::swap (dx1, dx2);
if (dy1 > dy2)
std::swap (dy1, dy2);
int dyStart = dy1;
int dyStop = dy2 + 1;
int dY = 1;
if (_data->lineOrder == DECREASING_Y)
{
dyStart = dy2;
dyStop = dy1 - 1;
dY = -1;
}
//
// Create a task group for all tile buffer tasks. When the
// task group goes out of scope, the destructor waits until
// all tasks are complete.
//
{
TaskGroup taskGroup;
int tileNumber = 0;
for (int dy = dyStart; dy != dyStop; dy += dY)
{
for (int dx = dx1; dx <= dx2; dx++)
{
if (!isValidTile (dx, dy, lx, ly))
THROW (Iex::ArgExc,
"Tile (" << dx << ", " << dy << ", " <<
lx << "," << ly << ") is not a valid tile.");
ThreadPool::addGlobalTask (newTileBufferTask (&taskGroup,
_data,
tileNumber++,
dx, dy,
lx, ly));
}
}
//
// finish all tasks
//
}
//
// Exeption handling:
//
// TileBufferTask::execute() may have encountered exceptions, but
// those exceptions occurred in another thread, not in the thread
// that is executing this call to TiledInputFile::readTiles().
// TileBufferTask::execute() has caught all exceptions and stored
// the exceptions' what() strings in the tile buffers.
// Now we check if any tile buffer contains a stored exception; if
// this is the case then we re-throw the exception in this thread.
// (It is possible that multiple tile buffers contain stored
// exceptions. We re-throw the first exception we find and
// ignore all others.)
//
const string *exception = 0;
for (size_t i = 0; i < _data->tileBuffers.size(); ++i)
{
TileBuffer *tileBuffer = _data->tileBuffers[i];
if (tileBuffer->hasException && !exception)
exception = &tileBuffer->exception;
tileBuffer->hasException = false;
}
if (exception)
throw Iex::IoExc (*exception);
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error reading pixel data from image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
void
TiledInputFile::readTiles (int dx1, int dx2, int dy1, int dy2, int l)
{
readTiles (dx1, dx2, dy1, dy2, l, l);
}
void
TiledInputFile::readTile (int dx, int dy, int lx, int ly)
{
readTiles (dx, dx, dy, dy, lx, ly);
}
void
TiledInputFile::readTile (int dx, int dy, int l)
{
readTile (dx, dy, l, l);
}
void
TiledInputFile::rawTileData (int &dx, int &dy,
int &lx, int &ly,
const char *&pixelData,
int &pixelDataSize)
{
try
{
Lock lock (*_data);
if (!isValidTile (dx, dy, lx, ly))
throw Iex::ArgExc ("Tried to read a tile outside "
"the image file's data window.");
TileBuffer *tileBuffer = _data->getTileBuffer (0);
readNextTileData (_data, dx, dy, lx, ly,
tileBuffer->buffer,
pixelDataSize);
pixelData = tileBuffer->buffer;
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error reading pixel data from image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
unsigned int
TiledInputFile::tileXSize () const
{
return _data->tileDesc.xSize;
}
unsigned int
TiledInputFile::tileYSize () const
{
return _data->tileDesc.ySize;
}
LevelMode
TiledInputFile::levelMode () const
{
return _data->tileDesc.mode;
}
LevelRoundingMode
TiledInputFile::levelRoundingMode () const
{
return _data->tileDesc.roundingMode;
}
int
TiledInputFile::numLevels () const
{
if (levelMode() == RIPMAP_LEVELS)
THROW (Iex::LogicExc, "Error calling numLevels() on image "
"file \"" << fileName() << "\" "
"(numLevels() is not defined for files "
"with RIPMAP level mode).");
return _data->numXLevels;
}
int
TiledInputFile::numXLevels () const
{
return _data->numXLevels;
}
int
TiledInputFile::numYLevels () const
{
return _data->numYLevels;
}
bool
TiledInputFile::isValidLevel (int lx, int ly) const
{
if (lx < 0 || ly < 0)
return false;
if (levelMode() == MIPMAP_LEVELS && lx != ly)
return false;
if (lx >= numXLevels() || ly >= numYLevels())
return false;
return true;
}
int
TiledInputFile::levelWidth (int lx) const
{
try
{
return levelSize (_data->minX, _data->maxX, lx,
_data->tileDesc.roundingMode);
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error calling levelWidth() on image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
int
TiledInputFile::levelHeight (int ly) const
{
try
{
return levelSize (_data->minY, _data->maxY, ly,
_data->tileDesc.roundingMode);
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error calling levelHeight() on image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
int
TiledInputFile::numXTiles (int lx) const
{
if (lx < 0 || lx >= _data->numXLevels)
{
THROW (Iex::ArgExc, "Error calling numXTiles() on image "
"file \"" << _data->is->fileName() << "\" "
"(Argument is not in valid range).");
}
return _data->numXTiles[lx];
}
int
TiledInputFile::numYTiles (int ly) const
{
if (ly < 0 || ly >= _data->numYLevels)
{
THROW (Iex::ArgExc, "Error calling numYTiles() on image "
"file \"" << _data->is->fileName() << "\" "
"(Argument is not in valid range).");
}
return _data->numYTiles[ly];
}
Box2i
TiledInputFile::dataWindowForLevel (int l) const
{
return dataWindowForLevel (l, l);
}
Box2i
TiledInputFile::dataWindowForLevel (int lx, int ly) const
{
try
{
return Imf::dataWindowForLevel (_data->tileDesc,
_data->minX, _data->maxX,
_data->minY, _data->maxY,
lx, ly);
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error calling dataWindowForLevel() on image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
Box2i
TiledInputFile::dataWindowForTile (int dx, int dy, int l) const
{
return dataWindowForTile (dx, dy, l, l);
}
Box2i
TiledInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const
{
try
{
if (!isValidTile (dx, dy, lx, ly))
throw Iex::ArgExc ("Arguments not in valid range.");
return Imf::dataWindowForTile (_data->tileDesc,
_data->minX, _data->maxX,
_data->minY, _data->maxY,
dx, dy, lx, ly);
}
catch (Iex::BaseExc &e)
{
REPLACE_EXC (e, "Error calling dataWindowForTile() on image "
"file \"" << fileName() << "\". " << e);
throw;
}
}
bool
TiledInputFile::isValidTile (int dx, int dy, int lx, int ly) const
{
return ((lx < _data->numXLevels && lx >= 0) &&
(ly < _data->numYLevels && ly >= 0) &&
(dx < _data->numXTiles[lx] && dx >= 0) &&
(dy < _data->numYTiles[ly] && dy >= 0));
}
} // namespace Imf
| [
"castano@0f2971b0-9fc2-11dd-b4aa-53559073bf4c"
]
| [
[
[
1,
1302
]
]
]
|
c5465e163e2b41a21f10317cf4ff658304408882 | c8ab6c440f0e70e848c5f69ccbbfd9fe2913fbad | /bowling/Gutter.h | 80cf885106d92d871849080a2edf2ca343fac3ce | []
| no_license | alyshamsy/power-bowling | 2b6426cfd4feb355928de95f1840bd39eb88de0b | dd650b2a8e146f6cdf7b6ce703801b96360a90fe | refs/heads/master | 2020-12-24T16:50:09.092801 | 2011-05-12T14:37:15 | 2011-05-12T14:37:15 | 32,115,585 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | #ifndef Gutter_H
#define Gutter_H
#include <gl/glfw.h>
#include <cyclone/cyclone.h>
#include "app.h"
#include "timing.h"
#include <iostream>
#include <stdio.h>
class Gutter : public cyclone::CollisionBox
{
public:
bool isOverlapping;
Gutter();
~Gutter();
void render(GLuint texture);
void setState(const cyclone::Vector3 &position, const cyclone::Quaternion &orientation, const cyclone::Vector3 &extents, const cyclone::Vector3 &velocity);
void calculateMassProperties(cyclone::real invDensity);
};
#endif | [
"aly.shamsy@71b57f4a-8c0b-a9ba-d1fe-6729e2c2215a"
]
| [
[
[
1,
25
]
]
]
|
3cd789bf6a989ddbdd83ca5871e9bc2636914ecc | 5e0422794380a8f3bf06d0c37ac2354f4b91fefb | /echo_client/stdafx.h | e5427e574d673778d8d7d420a36a139f70e761a5 | []
| no_license | OrAlien/fastnetwork | 1d8fb757b855b1f23cc844cda4d8dc7a568bc38e | 792d28d8b5829c227aebe8378f60db17de4d6f14 | refs/heads/master | 2021-05-28T20:30:24.031458 | 2010-06-02T14:30:04 | 2010-06-02T14:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: reference additional headers your program requires here
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <string>
#include <iostream>
using namespace std;
#include <assert.h>
| [
"everwanna@8b0bd7a0-72c1-11de-90d8-1fdda9445408"
]
| [
[
[
1,
25
]
]
]
|
dfeb04d552536674a7483343bd70a4edb88b2178 | 78d40fe09df2496088fd22859876eb6e7be954c0 | /s7app.h | 9f8139f0ca941e5216171be9aaaa7b560b665986 | []
| no_license | icedman/style7 | f1086f650b43784735542e6fac7df64197d0f00e | 6834d4d1021bd805631379dc4795427eae8d6893 | refs/heads/master | 2021-01-23T04:00:10.384380 | 2010-04-08T10:40:37 | 2010-04-08T10:40:37 | 35,222,984 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | h | #pragma once
#include <QtCore>
#include <QtScript>
#include "res.h"
#include "bb.h"
class S7App : public QObject
{
Q_OBJECT
public:
S7App();
~S7App();
public Q_SLOTS:
bool init();
bool load(const QString &filename);
void setTargetFile(const QString &filename);
void setTemplate(const QString &type, const QString &name);
void setAnalysis(bool a);
bool begin(int w = 0, int h = 0);
void end();
void drawTemplate(int x, int y);
void drawFrame(int frame, int x, int y, int w, int h);
void setClip(int x, int y, int w, int h);
void setTranslate(int x, int y);
bool run(const QString &filename);
public:
QImage& image();
private:
QScriptEngine engine;
QString filename;
QString type;
QString name;
QRect clip;
QPoint translate;
BBStyle style;
ResHack res;
QImage buffer;
QImage original;
bool analysis;
}; | [
"m4rvin2005@12bdf7b2-7090-17ef-321a-d85e0c66d2ab"
]
| [
[
[
1,
54
]
]
]
|
215ea30688c473f1826d0feef7446d802ce849bb | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/nebula2/src/scene/ntextshapenode_main.cc | 94facb25d67b2cfa28aa12dfa8a9df33451acf0e | []
| 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 | 6,359 | cc | //------------------------------------------------------------------------------
// ntextshapenode_main.cc
// (C) 2006 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/ntextshapenode.h"
#include "gfx2/nfontdesc.h"
nNebulaClass(nTextShapeNode, "nshapenode");
//------------------------------------------------------------------------------
/**
*/
nTextShapeNode::nTextShapeNode()
{
this->transformNodeClass = kernelServer->FindClass("ntransformnode");
this->fontFlags = nFont2::NoClip | nFont2::Center | nFont2::VCenter;
}
//------------------------------------------------------------------------------
/**
*/
nTextShapeNode::~nTextShapeNode()
{
// empty
}
//------------------------------------------------------------------------------
/**
Load the resources needed by this object.
*/
bool
nTextShapeNode::LoadResources()
{
if (nShapeNode::LoadResources())
{
return this->LoadFont();
}
return false;
}
//------------------------------------------------------------------------------
/**
Unload the resources if refcount has reached zero.
*/
void
nTextShapeNode::UnloadResources()
{
nShapeNode::UnloadResources();
this->UnloadFont();
}
//------------------------------------------------------------------------------
/**
Load font resource
Resource name: TypeFace_Height_Weight_ItalicUnderlineAntiAliased
i.E.: Arial_10_3_001
Arial, Height = 10, Weight = Normal,
Italic = false, Underline = false, AntiAliased = true
*/
bool
nTextShapeNode::LoadFont()
{
if (!this->refFont.isvalid())
{
// get render flags
this->fontFlags = nFont2::StringToRenderFlag(this->GetStringAttr("rlGuiHAlignment").Get());
this->fontFlags |= nFont2::StringToRenderFlag(this->GetStringAttr("rlGuiVAlignment").Get());
// append mesh usage to mesh resource name
nString resourceName;
nFontDesc fontDesc;
fontDesc.SetItalic(this->GetBoolAttr("rlGuiItalic"));
fontDesc.SetAntiAliased(this->GetBoolAttr("rlGuiAntiAliased"));
fontDesc.SetUnderline(this->GetBoolAttr("rlGuiUnderline"));
fontDesc.SetHeight(this->GetIntAttr("rlGuiHeight"));
fontDesc.SetTypeFace(this->GetStringAttr("rlGuiTypeFace").Get());
fontDesc.SetWeight(nFontDesc::StringToWeight(this->GetStringAttr("rlGuiWeight")));
fontDesc.SetFilename(this->GetStringAttr("rlGuiFilePath").Get());
// FIXME:
// Filename is not included in the resource name
resourceName.Format("%s_%u_%u_%u%u%u",
fontDesc.GetTypeFace(),
fontDesc.GetHeight(),
fontDesc.GetWeight(),
fontDesc.GetItalic(),
fontDesc.GetUnderline(),
fontDesc.GetAntiAliased());
// get a new or shared font
nFont2* font = nGfxServer2::Instance()->NewFont(resourceName, fontDesc);
n_assert(font);
if (!font->IsLoaded())
{
if (!font->Load())
{
n_printf("nMeshNode: Error loading font '%s'\n", resourceName.Get());
font->Release();
return false;
}
}
this->refFont = font;
}
return true;
}
//------------------------------------------------------------------------------
/**
Unload font resource if valid.
*/
void
nTextShapeNode::UnloadFont()
{
if (this->refFont.isvalid())
{
this->refFont->Release();
this->refFont.invalidate();
}
}
//------------------------------------------------------------------------------
/**
Perform pre-instancing actions needed for rendering geometry. This
is called once before multiple instances of this shape node are
actually rendered.
*/
bool
nTextShapeNode::ApplyGeometry(nSceneServer* sceneServer)
{
n_assert(this->refFont->IsValid());
// set font
nGfxServer2::Instance()->SetFont(this->refFont);
return nShapeNode::ApplyGeometry(sceneServer);
}
//------------------------------------------------------------------------------
/**
Update the screen space rectangle. This gets the bounding box from
our Nebula2 node, resolves the hierarchy transforms, and transforms
the result to screen space.
*/
void
nTextShapeNode::UpdateScreenSpaceRect()
{
// compute flattened transformation matrix
matrix44 m = this->GetTransform();
nTransformNode* parentNode = (nTransformNode*) this->GetParent();
while (parentNode && parentNode->IsA(this->transformNodeClass))
{
m = m * parentNode->GetTransform();
parentNode = (nTransformNode*) parentNode->GetParent();
}
// multiply by orthogonal projection matrix, this must be the same
// as used by the GUI shader!
m = m * matrix44::ortho;
// get local bounding box and transform to screen space
bbox3 box = this->GetLocalBox();
box.transform_divw(m);
// build screen space rectangle from result, move the range
// from (-1.0, 1.0) to (0.0, 1.0)
vector2 vmin, vmax;
vmin.x = (box.vmin.x + 1.0f) * 0.5f;
vmin.y = 1.0f - ((box.vmax.y + 1.0f) * 0.5f);
vmax.x = (box.vmax.x + 1.0f) * 0.5f;
vmax.y = 1.0f - ((box.vmin.y + 1.0f) * 0.5f);
this->screenSpaceRect.set(vmin, vmax);
}
//------------------------------------------------------------------------------
/**
Render the text Immediate with the given font.
Reset the font to the original font after rendering.
*/
bool
nTextShapeNode::RenderGeometry(nSceneServer* sceneServer, nRenderContext* renderContext)
{
// update text element rectangle
this->UpdateScreenSpaceRect();
nString text = this->GetStringAttr("rlGuiText");
vector4 color = this->GetVector4Attr("rlGuiColor");
// FIXME: Alpha value not exported
color.w = 1.0f;
nGfxServer2::Instance()->DrawText(text, color, this->screenSpaceRect, this->fontFlags, true);
return nShapeNode::RenderGeometry(sceneServer, renderContext);
} | [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
195
]
]
]
|
c4626c54314f62a449f819459136e7a989c1531e | 1e976ee65d326c2d9ed11c3235a9f4e2693557cf | /CommonSources/XNamedColors.cpp | 9102078d439d2105c1858cf82f6708d31c79bcee | []
| 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 | 17,981 | cpp | // /*
// *
// * 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
// *
// */
// NOTE ABOUT PRECOMPILED HEADERS:
// This file does not need to be compiled with precompiled headers (.pch).
// To disable this, go to Project | Settings | C/C++ | Precompiled Headers
// and select "Not using precompiled headers". Be sure to do this for all
// build configurations.
//#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <crtdbg.h>
#include "XNamedColors.h"
#pragma warning(disable : 4127) // conditional expression is constant (_ASSERTE)
#pragma warning(disable : 4996) // disable bogus deprecation warning
///////////////////////////////////////////////////////////////////////////////
// array of colors and names
const CXNamedColors::COLORNAMES CXNamedColors::m_aColorNames[] =
{
// named HTML colors
{ colorAliceBlue, _T("AliceBlue") },
{ colorAntiqueWhite, _T("AntiqueWhite") },
{ colorAqua, _T("Aqua") },
{ colorAquamarine, _T("Aquamarine") },
{ colorAzure, _T("Azure") },
{ colorBeige, _T("Beige") },
{ colorBisque, _T("Bisque") },
{ colorBlack, _T("Black") },
{ colorBlanchedAlmond, _T("BlanchedAlmond") },
{ colorBlue, _T("Blue") },
{ colorBlueViolet, _T("BlueViolet") },
{ colorBrown, _T("Brown") },
{ colorBurlywood, _T("Burlywood") },
{ colorCadetBlue, _T("CadetBlue") },
{ colorChartreuse, _T("Chartreuse") },
{ colorChocolate, _T("Chocolate") },
{ colorCoral, _T("Coral") },
{ colorCornflowerBlue, _T("CornflowerBlue") },
{ colorCornsilk, _T("Cornsilk") },
{ colorCrimson, _T("Crimson") },
{ colorCyan, _T("Cyan") },
{ colorDarkBlue, _T("DarkBlue") },
{ colorDarkCyan, _T("DarkCyan") },
{ colorDarkGoldenRod, _T("DarkGoldenRod") },
{ colorDarkGray, _T("DarkGray") },
{ colorDarkGreen, _T("DarkGreen") },
{ colorDarkKhaki, _T("DarkKhaki") },
{ colorDarkMagenta, _T("DarkMagenta") },
{ colorDarkOliveGreen, _T("DarkOliveGreen") },
{ colorDarkOrange, _T("DarkOrange") },
{ colorDarkOrchid, _T("DarkOrchid") },
{ colorDarkRed, _T("DarkRed") },
{ colorDarkSalmon, _T("DarkSalmon") },
{ colorDarkSeaGreen, _T("DarkSeaGreen") },
{ colorDarkSlateBlue, _T("DarkSlateBlue") },
{ colorDarkSlateGray, _T("DarkSlateGray") },
{ colorDarkTurquoise, _T("DarkTurquoise") },
{ colorDarkViolet, _T("DarkViolet") },
{ colorDeepPink, _T("DeepPink") },
{ colorDeepSkyBlue, _T("DeepSkyBlue") },
{ colorDimGray, _T("DimGray") },
{ colorDodgerBlue, _T("DodgerBlue") },
{ colorFireBrick, _T("FireBrick") },
{ colorFloralWhite, _T("FloralWhite") },
{ colorForestGreen, _T("ForestGreen") },
{ colorFuchsia, _T("Fuchsia") },
{ colorGainsboro, _T("Gainsboro") },
{ colorGhostWhite, _T("GhostWhite") },
{ colorGold, _T("Gold") },
{ colorGoldenRod, _T("GoldenRod") },
{ colorGray, _T("Gray") },
{ colorGreen, _T("Green") },
{ colorGreenYellow, _T("GreenYellow") },
{ colorHoneyDew, _T("HoneyDew") },
{ colorHotPink, _T("HotPink") },
{ colorIndianRed, _T("IndianRed") },
{ colorIndigo, _T("Indigo") },
{ colorIvory, _T("Ivory") },
{ colorKhaki, _T("Khaki") },
{ colorLavender, _T("Lavender") },
{ colorLavenderBlush, _T("LavenderBlush") },
{ colorLawngreen, _T("Lawngreen") },
{ colorLemonChiffon, _T("LemonChiffon") },
{ colorLightBlue, _T("LightBlue") },
{ colorLightCoral, _T("LightCoral") },
{ colorLightCyan, _T("LightCyan") },
{ colorLightGoldenRodYellow, _T("LightGoldenRodYellow")},
{ colorLightGreen, _T("LightGreen") },
{ colorLightGrey, _T("LightGrey") },
{ colorLightPink, _T("LightPink") },
{ colorLightSalmon, _T("LightSalmon") },
{ colorLightSeaGreen, _T("LightSeaGreen") },
{ colorLightSkyBlue, _T("LightSkyBlue") },
{ colorLightSlateGray, _T("LightSlateGray") },
{ colorLightSteelBlue, _T("LightSteelBlue") },
{ colorLightYellow, _T("LightYellow") },
{ colorLime, _T("Lime") },
{ colorLimeGreen, _T("LimeGreen") },
{ colorLinen, _T("Linen") },
{ colorMagenta, _T("Magenta") },
{ colorMaroon, _T("Maroon") },
{ colorMediumAquamarine, _T("MediumAquamarine") },
{ colorMediumBlue, _T("MediumBlue") },
{ colorMediumOrchid, _T("MediumOrchid") },
{ colorMediumPurple, _T("MediumPurple") },
{ colorMediumSeaGreen, _T("MediumSeaGreen") },
{ colorMediumSlateBlue, _T("MediumSlateBlue") },
{ colorMediumSpringGreen, _T("MediumSpringGreen") },
{ colorMediumTurquoise, _T("MediumTurquoise") },
{ colorMediumVioletRed, _T("MediumVioletRed") },
{ colorMidnightBlue, _T("MidnightBlue") },
{ colorMintCream, _T("MintCream") },
{ colorMistyRose, _T("MistyRose") },
{ colorMoccasin, _T("Moccasin") },
{ colorNavajoWhite, _T("NavajoWhite") },
{ colorNavy, _T("Navy") },
{ colorOldLace, _T("OldLace") },
{ colorOlive, _T("Olive") },
{ colorOliveDrab, _T("OliveDrab") },
{ colorOrange, _T("Orange") },
{ colorOrangeRed, _T("OrangeRed") },
{ colorOrchid, _T("Orchid") },
{ colorPaleGoldenRod, _T("PaleGoldenRod") },
{ colorPaleGreen, _T("PaleGreen") },
{ colorPaleTurquoise, _T("PaleTurquoise") },
{ colorPaleVioletRed, _T("PaleVioletRed") },
{ colorPapayaWhip, _T("PapayaWhip") },
{ colorPeachPuff, _T("PeachPuff") },
{ colorPeru, _T("Peru") },
{ colorPink, _T("Pink") },
{ colorPlum, _T("Plum") },
{ colorPowderBlue, _T("PowderBlue") },
{ colorPurple, _T("Purple") },
{ colorRed, _T("Red") },
{ colorRosyBrown, _T("RosyBrown") },
{ colorRoyalBlue, _T("RoyalBlue") },
{ colorSaddleBrown, _T("SaddleBrown") },
{ colorSalmon, _T("Salmon") },
{ colorSandyBrown, _T("SandyBrown") },
{ colorSeaGreen, _T("SeaGreen") },
{ colorSeaShell, _T("SeaShell") },
{ colorSienna, _T("Sienna") },
{ colorSilver, _T("Silver") },
{ colorSkyBlue, _T("SkyBlue") },
{ colorSlateBlue, _T("SlateBlue") },
{ colorSlateGray, _T("SlateGray") },
{ colorSnow, _T("Snow") },
{ colorSpringGreen, _T("SpringGreen") },
{ colorSteelBlue, _T("SteelBlue") },
{ colorTan, _T("Tan") },
{ colorTeal, _T("Teal") },
{ colorThistle, _T("Thistle") },
{ colorTomato, _T("Tomato") },
{ colorTurquoise, _T("Turquoise") },
{ colorViolet, _T("Violet") },
{ colorWheat, _T("Wheat") },
{ colorWhite, _T("White") },
{ colorWhiteSmoke, _T("WhiteSmoke") },
{ colorYellow, _T("Yellow") },
{ colorYellowGreen, _T("YellowGreen") },
// Windows system colors
{ colorActiveBorder, _T("ActiveBorder") },
{ colorActiveCaption, _T("ActiveCaption") },
{ colorActiveCaptionText, _T("ActiveCaptionText") },
{ colorAppWorkspace, _T("AppWorkspace") },
{ colorBackground, _T("Background") },
{ colorBtnFace, _T("BtnFace") },
{ colorBtnHighlight, _T("BtnHighlight") },
{ colorBtnHilight, _T("BtnHilight") },
{ colorBtnShadow, _T("BtnShadow") },
{ colorBtnText, _T("BtnText") },
{ colorCaptionText, _T("CaptionText") },
{ colorControl, _T("Control") },
{ colorControlDark, _T("ControlDark") },
{ colorControlDarkDark, _T("ControlDarkDark") },
{ colorControlLight, _T("ControlLight") },
{ colorControlLightLight, _T("ControlLightLight") },
{ colorControlText, _T("ControlText") },
{ colorDesktop, _T("Desktop") },
{ colorGradientActiveCaption, _T("GradientActiveCaption") },
{ colorGradientInactiveCaption, _T("GradientInactiveCaption") },
{ colorGrayText, _T("GrayText") },
{ colorHighlight, _T("Highlight") },
{ colorHighlightText, _T("HighlightText") },
{ colorHotLight, _T("HotLight") },
{ colorHotTrack, _T("HotTrack") },
{ colorInactiveBorder, _T("InactiveBorder") },
{ colorInactiveCaption, _T("InactiveCaption") },
{ colorInactiveCaptionText, _T("InactiveCaptionText") },
{ colorInfo, _T("Info") },
{ colorInfoBk, _T("InfoBk") },
{ colorInfoText, _T("InfoText") },
{ colorMenu, _T("Menu") },
{ colorMenuBar, _T("MenuBar") },
{ colorMenuHilight, _T("MenuHilight") },
{ colorMenuText, _T("MenuText") },
{ colorScrollBar, _T("ScrollBar") },
{ colorWindow, _T("Window") },
{ colorWindowFrame, _T("WindowFrame") },
{ colorWindowText, _T("WindowText") }
};
const int CXNamedColors::m_nNamedColors =
sizeof(CXNamedColors::m_aColorNames) /
sizeof(CXNamedColors::m_aColorNames[0]);
///////////////////////////////////////////////////////////////////////////////
CXNamedColors::CXNamedColors()
{
m_Color = RGB(0,0,0); // initialize to black
}
///////////////////////////////////////////////////////////////////////////////
// can be: "red" or "255,0,0" or "#0000FF"
CXNamedColors::CXNamedColors(LPCTSTR lpszColor)
{
SetColorFromString(lpszColor);
}
///////////////////////////////////////////////////////////////////////////////
CXNamedColors::CXNamedColors(COLORREF color)
{
m_Color = color;
}
///////////////////////////////////////////////////////////////////////////////
// nSysColorIndex is one of the values used with GetSysColor()
CXNamedColors::CXNamedColors(int nSysColorIndex)
{
SetSysColor(nSysColorIndex);
}
///////////////////////////////////////////////////////////////////////////////
CXNamedColors::~CXNamedColors()
{
}
///////////////////////////////////////////////////////////////////////////////
int CXNamedColors::GetColorIndex()
{
int rc = -1;
for (int i = 0; i < m_nNamedColors; i++)
{
if (m_Color == m_aColorNames[i].color)
{
rc = i;
break;
}
}
return rc;
}
///////////////////////////////////////////////////////////////////////////////
COLORREF CXNamedColors::GetColorByIndex(int index)
{
_ASSERTE((index >= 0) && (index < m_nNamedColors));
COLORREF rc = (DWORD)-1;
if ((index >= 0) && (index < m_nNamedColors))
{
rc = m_aColorNames[index].color;
if (rc & 0x80000000L)
rc = GetSysColor(rc & 0x7FFFFFFFL);
}
return rc;
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::GetColorNameByIndex(int index,
LPTSTR lpszBuf,
DWORD nBufSize)
{
_ASSERTE(lpszBuf);
_ASSERTE(nBufSize > 0);
_ASSERTE((index >= 0) && (index < m_nNamedColors));
if (!lpszBuf || (nBufSize == 0))
return;
if ((index >= 0) && (index < m_nNamedColors))
{
memset(lpszBuf, 0, nBufSize*sizeof(TCHAR));
_tcsncpy(lpszBuf, m_aColorNames[index].pszName, nBufSize-1);
}
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::GetHex(LPTSTR lpszBuf, DWORD nBufSize) // nBufSize in TCHARs
{
_ASSERTE(lpszBuf);
_ASSERTE(nBufSize > 0);
if (!lpszBuf || (nBufSize == 0))
return;
memset(lpszBuf, 0, nBufSize*sizeof(TCHAR));
BYTE r = GetRValue(GetRGB());
BYTE g = GetGValue(GetRGB());
BYTE b = GetBValue(GetRGB());
_sntprintf(lpszBuf, nBufSize-1, _T("#%02X%02X%02X"), r, g, b);
}
///////////////////////////////////////////////////////////////////////////////
COLORREF CXNamedColors::GetRGB()
{
COLORREF rc = m_Color;
if (IsSystemColor())
rc = GetSysColor(m_Color & 0x7FFFFFFFL);
return rc;
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::GetName(LPTSTR lpszBuf, DWORD nBufSize) // nBufSize in TCHARs
{
_ASSERTE(lpszBuf);
_ASSERTE(nBufSize > 0);
if (!lpszBuf || (nBufSize == 0))
return;
memset(lpszBuf, 0, nBufSize*sizeof(TCHAR));
for (int i = 0; i < m_nNamedColors; i++)
{
if (m_Color == m_aColorNames[i].color)
{
_tcsncpy(lpszBuf, m_aColorNames[i].pszName, nBufSize-1);
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::GetRGBString(LPTSTR lpszBuf, DWORD nBufSize) // nBufSize in TCHARs
{
_ASSERTE(lpszBuf);
_ASSERTE(nBufSize > 0);
if (!lpszBuf || (nBufSize == 0))
return;
memset(lpszBuf, 0, nBufSize*sizeof(TCHAR));
_sntprintf(lpszBuf, nBufSize-1, _T("%u,%u,%u"), GetR(), GetG(), GetB());
}
///////////////////////////////////////////////////////////////////////////////
// #RRGGBB
void CXNamedColors::SetHex(LPCTSTR lpszHex)
{
_ASSERTE(lpszHex);
if (!lpszHex)
return;
COLORREF rgb = RGB(0,0,0);
LPCTSTR cp = lpszHex;
if ((*cp == _T('#')) && (_tcslen(lpszHex) == 7))
{
TCHAR s[3] = { _T('\0') };
cp++;
s[0] = *cp++;
s[1] = *cp++;
BYTE r = (BYTE)_tcstoul(s, NULL, 16);
s[0] = *cp++;
s[1] = *cp++;
BYTE g = (BYTE)_tcstoul(s, NULL, 16);
s[0] = *cp++;
s[1] = *cp++;
BYTE b = (BYTE)_tcstoul(s, NULL, 16);
rgb = RGB(r,g,b);
}
m_Color = rgb;
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::SetName(LPCTSTR lpszColorName)
{
_ASSERTE(lpszColorName);
if (!lpszColorName)
return;
COLORREF rgb = RGB(0,0,0);
for (int i = 0; i < m_nNamedColors; i++)
{
if (_tcsicmp(lpszColorName, m_aColorNames[i].pszName) == 0)
{
rgb = m_aColorNames[i].color;
break;
}
}
m_Color = rgb;
}
///////////////////////////////////////////////////////////////////////////////
// lpszColor: "red" or "255,0,0" or "#0000FF"
void CXNamedColors::SetColorFromString(LPCTSTR lpszColor)
{
_ASSERTE(lpszColor);
if (!lpszColor)
return;
m_Color = RGB(0,0,0); // initialize to black
BYTE r = 0;
BYTE g = 0;
BYTE b = 0;
TCHAR *cp = 0;
if ((cp = (TCHAR*)_tcschr(lpszColor, _T(','))) != NULL)
{
// "255,0,0"
r = (BYTE) _ttoi(lpszColor);
cp++;
g = (BYTE) _ttoi(cp);
cp = _tcschr(cp, _T(','));
if (cp)
{
cp++;
b = (BYTE) _ttoi(cp);
}
m_Color = RGB(r,g,b);
}
else if ((cp = (TCHAR*)_tcschr(lpszColor, _T('#'))) != NULL)
{
// "#0000FF"
if (_tcslen(lpszColor) == 7)
{
TCHAR s[3] = { _T('\0') };
cp++;
s[0] = *cp++;
s[1] = *cp++;
r = (BYTE)_tcstoul(s, NULL, 16);
s[0] = *cp++;
s[1] = *cp++;
g = (BYTE)_tcstoul(s, NULL, 16);
s[0] = *cp++;
s[1] = *cp++;
b = (BYTE)_tcstoul(s, NULL, 16);
m_Color = RGB(r,g,b);
}
}
else
{
// "red"
for (int i = 0; i < m_nNamedColors; i++)
{
if (_tcsicmp(lpszColor, m_aColorNames[i].pszName) == 0)
{
m_Color = m_aColorNames[i].color;
break;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
void CXNamedColors::SetRGB(BYTE r, BYTE g, BYTE b)
{
m_Color = RGB(r, g, b);
}
///////////////////////////////////////////////////////////////////////////////
// nSysColorIndex is one of the values used with GetSysColor()
void CXNamedColors::SetSysColor(int nSysColorIndex)
{
_ASSERTE((nSysColorIndex >= 0) && (nSysColorIndex <= COLOR_MENUBAR));
if ((nSysColorIndex >= 0) && (nSysColorIndex <= COLOR_MENUBAR))
m_Color = (DWORD) (nSysColorIndex | 0x80000000);
}
#ifdef _DEBUG
///////////////////////////////////////////////////////////////////////////////
//
// Dumps the color table in a form suitable for a HTML table, e.g.:
//
// <tr>
// <td style="background-color:#F0F8FF; color:black" align="center">AliceBlue<br>(#F0F8FF)</td>
// <td style="background-color:#FAEBD7; color:black" align="center">AntiqueWhite<br>(#FAEBD7)</td>
// <td style="background-color:#00FFFF; color:black" align="center">Aqua<br>(#00FFFF)</td>
// <td style="background-color:#7FFFD4; color:black" align="center">Aquamarine<br>(#7FFFD4)</td>
// <td style="background-color:#F0FFFF; color:black" align="center">Azure<br>(#F0FFFF)</td>
// </tr>
//
void CXNamedColors::Dump(LPCTSTR lpszFile)
{
_ASSERTE(lpszFile);
if (!lpszFile)
return;
FILE * f = _tfopen(lpszFile, _T("w"));
if (f)
{
_ftprintf(f, _T("<html><body>\n"));
_ftprintf(f, _T("<center><table bgcolor=\"gray\" border=1 cellspacing=1 cellpadding=3 summary=\"named colors\">"));
TCHAR szBuf[100];
for (int j = 0; j < m_nNamedColors; )
{
_ftprintf(f, _T("<tr>\n"));
int cols = (j >= 140) ? 4 : 5;
for (int k = 0; k < cols; k++)
{
if (m_aColorNames[j].color & 0x80000000)
{
DWORD index = m_aColorNames[j].color;
index = index & 0x7FFFFFFF;
SetSysColor(index);
}
else
{
SetRGB(m_aColorNames[j].color);
}
GetHex(szBuf, 99);
TCHAR *text = _T("black");
if (_tcscmp(szBuf, _T("#000000")) == 0)
text = _T("white");
_ftprintf(f,
_T("<td style=\"background-color:%s; color:%s\" align=\"center\">%s<br>(%s)</td>\n"),
szBuf,
text,
CXNamedColors::m_aColorNames[j].pszName,
szBuf);
j++;
if (j >= CXNamedColors::m_nNamedColors)
break;
}
_ftprintf(f, _T("</tr>\n\n"));
}
_ftprintf(f, _T("</table></center></body></html>\n"));
fclose(f);
}
}
#endif
| [
"outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678"
]
| [
[
[
1,
567
]
]
]
|
35d4f9b2e4672dd8ce8a1069c765f59c47e8c939 | 8a88075abf60e213a490840bebee97df01b8827a | /implementation/geometry_tests/geometry/hintersections_3d_tests.cpp | 2791b3e2f8864c6ffd0ceb4aaf3f0b629945fd5a | []
| no_license | DavidGeorge528/minigeolib | e078f1bbc874c09584ae48e1c269f5f90789ebfb | 58233609203953acf1c0346cd48950d2212b8922 | refs/heads/master | 2020-05-20T09:36:53.921996 | 2009-04-23T16:25:30 | 2009-04-23T16:25:30 | 33,925,133 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,575 | cpp | #include "geometry/homogenous/intersections.hpp"
#include "geometry/homogenous/vertex.hpp"
#include "geometry/homogenous/hcoord_system.hpp"
#include "geometry/homogenous/direction.hpp"
#include "geometry/homogenous/distances.hpp"
#include "geometry/plane.hpp"
#include "geometry/line.hpp"
#include "../tests_common.hpp"
#include "../test_traits.hpp"
#include <boost/mpl/list.hpp>
namespace
{
using namespace geometry;
typedef hcoord_system< 3, float, algebra::unit_traits< float> > float_hcoord_system;
typedef hcoord_system< 3, double, algebra::unit_traits< double> > double_hcoord_system;
typedef vertex< float_hcoord_system> float_vertex;
typedef vertex< double_hcoord_system> double_vertex;
typedef line< float_hcoord_system> float_line;
typedef line< double_hcoord_system> double_line;
typedef plane< float_hcoord_system> float_plane;
typedef plane< double_hcoord_system> double_plane;
typedef boost::mpl::list<
boost::mpl::pair< float_line, float_vertex>,
boost::mpl::pair< double_line, double_vertex> >
tested_lines;
typedef boost::mpl::list<
boost::mpl::pair< float_line, float_plane>,
boost::mpl::pair< double_line, double_plane> >
tested_planes;
BOOST_AUTO_TEST_CASE_TEMPLATE( test_line_intersection, P, tested_lines)
{
typedef typename P::first line;
typedef typename P::second vertex;
typedef typename vertex::unit_type unit_type;
typedef typename vertex::unit_traits_type unit_traits_type;
typedef typename line::direction_type direction;
// Intersection case
line
lx( vertex( 1,3,10), direction( 1,0,0)),
ly( vertex( 2,1,10), direction( 0,1,0));
vertex v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_EQUAL_UNIT( 2, v.x());
ALGTEST_CHECK_EQUAL_UNIT( 3, v.y());
ALGTEST_CHECK_EQUAL_UNIT( 10, v.z());
// Intersection is the same as base vertex
lx = line( vertex( 3,2,10), direction( 1,0,0)),
ly = line( vertex( 3,2,10), direction( 0,1,0));
v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_EQUAL_UNIT( 3, v.x());
ALGTEST_CHECK_EQUAL_UNIT( 2, v.y());
ALGTEST_CHECK_EQUAL_UNIT( 10, v.z());
// Parallel lines
lx = line( vertex( 1, 2, 3), direction( 1, 1, 1));
ly = line( vertex( 5, 4, 3), direction( 1, 1, 1));
v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_INVALID_UNIT( v.x());
ALGTEST_CHECK_INVALID_UNIT( v.y());
ALGTEST_CHECK_INVALID_UNIT( v.z());
// Skewed lines
lx = line( vertex( 3,2,0), direction( 1,0,0)),
ly = line( vertex( 3,2,10), direction( 0,1,0));
v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_INVALID_UNIT( v.x());
ALGTEST_CHECK_INVALID_UNIT( v.y());
ALGTEST_CHECK_INVALID_UNIT( v.z());
// Superimposed lines
lx = line( vertex( 1, 2, 3), direction( 1, 1, 1));
ly = line( vertex( 2, 3, 4), direction( 1, 1, 1));
v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_INVALID_UNIT( v.x());
ALGTEST_CHECK_INVALID_UNIT( v.y());
ALGTEST_CHECK_INVALID_UNIT( v.z());
// Superimposed with the same base
lx = line( vertex( 1, 2, 3), direction( 1, 1, 1));
ly = line( vertex( 1, 2, 3), direction( 1, 1, 1));
v = intersect<vertex>( lx, ly);
ALGTEST_CHECK_INVALID_UNIT( v.x());
ALGTEST_CHECK_INVALID_UNIT( v.y());
ALGTEST_CHECK_INVALID_UNIT( v.z());
}
// ---------------------------------------------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE_TEMPLATE( test_plane_intersection, P, tested_planes)
{
typedef typename P::first line;
typedef typename P::second plane;
typedef typename line::vertex_type vertex;
typedef typename line::direction_type direction;
typedef typename plane::unit_type unit_type;
typedef typename plane::unit_traits_type unit_traits_type;
// Intersecting planes
plane p1( vertex( 1, 2, 3), direction( 0, 0, 1)); // plane parallel with XY
plane p2( vertex( 5, 6, 7), direction( 0, 1, 0)); // plane parallel with XZ
line l = intersect<line>( p1, p2);
vertex base = l.base();
direction dir = l.dir();
ALGTEST_CHECK_SMALL( distance( base, p1));
ALGTEST_CHECK_SMALL( distance( base, p2));
ALGTEST_CHECK_EQUAL_UNIT( -1, dir.dx());
ALGTEST_CHECK_EQUAL_UNIT( 0, dir.dy());
ALGTEST_CHECK_EQUAL_UNIT( 0, dir.dz());
// Parallel planes (with same direction for normals).
p1 = plane( vertex( 1, 2, 3), direction( 1, 2, 3));
p2 = plane( vertex( 6, 5, 3), direction( 1, 2, 3));
l = intersect<line>( p1, p2);
dir = l.dir();
ALGTEST_CHECK_INVALID_UNIT( dir.dx());
ALGTEST_CHECK_INVALID_UNIT( dir.dy());
ALGTEST_CHECK_INVALID_UNIT( dir.dz());
// Parallel planes (with oposite direction for normals).
p1 = plane( vertex( 1, 2, 3), direction( 1, 2, 3));
p2 = plane( vertex( 6, 5, 3), direction( -1, -2, -3));
l = intersect<line>( p1, p2);
dir = l.dir();
ALGTEST_CHECK_INVALID_UNIT( dir.dx());
ALGTEST_CHECK_INVALID_UNIT( dir.dy());
ALGTEST_CHECK_INVALID_UNIT( dir.dz());
// Superimposed planes (with same direction for normals)
p1 = plane( vertex( 1, 2, 3), direction( 1, 2, 3));
p2 = plane( vertex( 1, 2, 3), direction( 1, 2, 3));
l = intersect<line>( p1, p2);
dir = l.dir();
ALGTEST_CHECK_INVALID_UNIT( dir.dx());
ALGTEST_CHECK_INVALID_UNIT( dir.dy());
ALGTEST_CHECK_INVALID_UNIT( dir.dz());
// Superimposed planes (with oposite direction for normals)
p1 = plane( vertex( 1, 2, 3), direction( 1, 2, 3));
p2 = plane( vertex( 1, 2, 3), direction( -1, -2, -3));
l = intersect<line>( p1, p2);
dir = l.dir();
ALGTEST_CHECK_INVALID_UNIT( dir.dx());
ALGTEST_CHECK_INVALID_UNIT( dir.dy());
ALGTEST_CHECK_INVALID_UNIT( dir.dz());
}
} // namespace
| [
"cpitis@834bb202-e8be-11dd-9d8c-a70aa0a93a20"
]
| [
[
[
1,
154
]
]
]
|
2d9fb23e5c7725cf1b997a6989d921c8602bdeed | 0b66a94448cb545504692eafa3a32f435cdf92fa | /branches/nn/cbear.berlios.de/range/helper.hpp | c47425079811a6990e15346738b7b89cb5ebb287 | [
"MIT"
]
| permissive | BackupTheBerlios/cbear-svn | e6629dfa5175776fbc41510e2f46ff4ff4280f08 | 0109296039b505d71dc215a0b256f73b1a60b3af | refs/heads/master | 2021-03-12T22:51:43.491728 | 2007-09-28T01:13:48 | 2007-09-28T01:13:48 | 40,608,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,319 | hpp | #ifndef CBEAR_BERLIOS_DE_RANGE_HELPER_HPP_INCLUDED
#define CBEAR_BERLIOS_DE_RANGE_HELPER_HPP_INCLUDED
// std::distance
#include <iterator>
// boost::prior, boost::next
#include <boost/utility.hpp>
// boost::is_same
#include <boost/type_traits/is_same.hpp>
#include <cbear.berlios.de/base/default.hpp>
#include <cbear.berlios.de/base/empty.hpp>
#include <cbear.berlios.de/base/integer.hpp>
namespace cbear_berlios_de
{
namespace range
{
template<class Container, class Base>
class helper_t: public Base
{
public:
typedef Container container_t;
typedef typename Base::iterator iterator;
typedef typename Base::const_iterator const_iterator;
typedef ::std::iterator_traits<iterator> iterator_traits;
typedef ::std::iterator_traits<const_iterator> const_iterator_traits;
typedef typename const_iterator_traits::value_type value_type;
typedef typename const_iterator_traits::difference_type difference_type;
typedef typename base::make_unsigned<difference_type>::type size_type;
typedef typename iterator_traits::reference reference;
typedef typename const_iterator_traits::reference const_reference;
typedef typename iterator_traits::pointer pointer;
typedef typename const_iterator_traits::pointer const_pointer;
typedef typename ::std::reverse_iterator<iterator>
reverse_iterator;
typedef typename ::std::reverse_iterator<const_iterator>
const_reverse_iterator;
typedef iterator_range<iterator> iterator_range_t;
typedef iterator_range<const_iterator> const_iterator_range_t;
helper_t()
{
}
template<class T>
helper_t(T const &X):
Base(X)
{
}
template<class T1, class T2>
helper_t(T1 const &X1, T2 const &X2):
Base(X1, X2)
{
}
bool empty() const
{
return this->This().begin()==this->This().end();
}
size_type size() const
{
return size_type(::std::distance(
this->This().begin(), this->This().end()));
}
reference front()
{
return *This().begin();
}
const_reference front() const
{
return *This().begin();
}
reference back()
{
return *boost::prior(This().end());
}
const_reference back() const
{
return *boost::prior(This().end());
}
reference at(size_type I)
{
return *boost::next(this->This().begin(), I);
}
const_reference at(size_type I) const
{
return *boost::next(this->This().begin(), I);
}
reference operator[](size_type I)
{
return this->at(I);
}
const_reference operator[](size_type I) const
{
return this->at(I);
}
reverse_iterator rbegin()
{
return reverse_iterator(This().end());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(This().end());
}
reverse_iterator rend()
{
return reverse_iterator(This().begin());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(This().begin());
}
template<class Stream>
void write(Stream &S) const
{
typedef typename Stream::value_type char_t;
BOOST_STATIC_ASSERT((boost::is_same<char_t, value_type>::value));
S.push_back_range(this->This());
}
void resize(size_type S)
{
difference_type dif =
static_cast<difference_type>(S) -
static_cast<difference_type>(this->This().size());
if(dif > 0)
{
this->This().insert_range(this->This().end(), make_fill(base::default_(), dif));
}
else if(dif < 0)
{
this->This().erase_range(iterator_range_t(
::boost::prior(this->This().end(), -dif), this->This().end()));
}
}
template<class T>
iterator insert(iterator I, T const &X)
{
return this->This().insert_range(I, make_fill(X, 1));
}
void push_front(const_reference X)
{
this->insert(this->This().begin(), X);
}
void push_front()
{
this->insert(this->This().begin(), base::default_());
}
void push_back(const_reference X)
{
this->insert(this->This().end(), X);
}
void push_back()
{
this->insert(this->This().end(), base::default_());
}
void erase(iterator I)
{
this->This().erase_range(iterator_range_t(I, 1));
}
private:
container_t &This()
{
return *static_cast<container_t *>(this);
}
container_t const &This() const
{
return *static_cast<container_t const *>(this);
}
};
}
}
#endif
| [
"nn0@e6e9985e-9100-0410-869a-e199dc1b6838"
]
| [
[
[
1,
191
]
]
]
|
86024c62b385af7319c36958d645697090c3460a | 927e18c69355c4bf87b59dffefe59c2974e86354 | /super-go-proj/SgBlackWhite.h | c4f67875116c4430e18f4ca193b521b886991860 | []
| no_license | lqhl/iao-gim-ca | 6fc40adc91a615fa13b72e5b4016a8b154196b8f | f177268804d1ba6edfd407fa44a113a44203ec30 | refs/heads/master | 2020-05-18T17:07:17.972573 | 2011-06-17T03:54:51 | 2011-06-17T03:54:51 | 32,191,309 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,498 | h | //----------------------------------------------------------------------------
/** @file SgBlackWhite.h
Color of player in two-player games (black/white). */
//----------------------------------------------------------------------------
#ifndef SG_BLACKWHITE_H
#define SG_BLACKWHITE_H
#include <Poco/Debugger.h>
//----------------------------------------------------------------------------
/** Black stone, black player. */
const int SG_BLACK = 0;
/** White stone, white player. */
const int SG_WHITE = 1;
// must be consecutive for color for-loops
poco_static_assert(SG_BLACK + 1 == SG_WHITE);
/** SG_BLACK or SG_WHITE */
typedef int SgBlackWhite;
inline bool SgIsBlackWhite(int c)
{
return c == SG_BLACK || c == SG_WHITE;
}
#define SG_ASSERT_BW(c) poco_assert(SgIsBlackWhite(c))
inline SgBlackWhite SgOppBW(SgBlackWhite c)
{
SG_ASSERT_BW(c);
return SG_BLACK + SG_WHITE - c;
}
inline char SgBW(SgBlackWhite color)
{
SG_ASSERT_BW(color);
return color == SG_BLACK ? 'B' : 'W';
}
//----------------------------------------------------------------------------
/** Iterator over both colors, Black and White.
The function Opp() returns the opponent since this is often needed too.
Usage example:
@verbatim
for (SgBWIterator it; it; ++it)
{
"this section will be executed twice:"
"first with *it == SG_BLACK, then with *it == SG_WHITE"
(unless it encounters a break or return inside)
}
@endverbatim */
class SgBWIterator
{
public:
SgBWIterator()
: m_color(SG_BLACK)
{ }
/** Advance the state of the iteration to the next element. */
void operator++()
{
SG_ASSERT_BW(m_color);
++m_color;
}
/** Return the value of the current element. */
SgBlackWhite operator*() const
{
return m_color;
}
/** Return the value of the current element. */
SgBlackWhite Opp() const
{
return SgOppBW(m_color);
}
/** Return true if iteration is valid, otherwise false. */
operator bool() const
{
return m_color <= SG_WHITE;
}
private:
int m_color;
/** Not implemented */
SgBWIterator(const SgBWIterator&);
/** Not implemented */
SgBWIterator& operator=(const SgBWIterator&);
};
//----------------------------------------------------------------------------
#endif // SG_BLACKWHITE_H
| [
"[email protected]"
]
| [
[
[
1,
102
]
]
]
|
18e9402443867e2156bb74e44587d60593ddaa76 | 802817310cdf7c69dbeab815b4abfc9fca393bcc | /src/ModelImage.cpp | 36a7af03e4dee3683c0a0d8d534b78e91092001d | []
| no_license | spjoe/echtzeitlu | a77b4c6765c8d4d88e52fda715fb96485f28d0eb | 6df1ad920e45c0624405b3620059a2fdf67d5fad | refs/heads/master | 2021-01-18T14:22:07.337680 | 2011-01-25T13:53:39 | 2011-01-25T13:53:39 | 32,144,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,678 | cpp | #include "ModelImage.h"
using namespace echtzeitlu;
ModelImage::ModelImage(domImage* img){
domImage* imageElement = img;
if ( !imageElement )
return;
imageElement->getInit_from()->getValue().str();
const std::string file = cdom::uriToNativePath(imageElement->getInit_from()->getValue().str());
GLFWimage image;
if (glfwReadImage(file.c_str(), &image, GLFW_ORIGIN_UL_BIT) != GL_TRUE)
return;
get_errors();
glGenTextures(1, &_id);
get_errors();
glBindTexture(GL_TEXTURE_2D, _id);
get_errors();
// Load texture from file, and build all mipmap levels
//if( !glfwLoadTexture2D( file.c_str(), GLFW_ORIGIN_UL_BIT | GLFW_BUILD_MIPMAPS_BIT ) )
//{
// return;
//}
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
get_errors();
// Use trilinear interpolation for minification
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR );
get_errors();
// Use bilinear interpolation for magnification
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );
get_errors();
//if(glfwLoadMemoryTexture2D(image.Data, image.BytesPerPixel * image.Height * image.Width, GLFW_BUILD_MIPMAPS_BIT) == GL_FALSE);
// return;
//image.Format;
#ifdef GL_GENERATE_MIPMAP_SEG_AVOIDANCE
#ifdef DEBUG
printf("using gluBuild2DMipmaps()\n");
#endif
gluBuild2DMipmaps(GL_TEXTURE_2D, 0x8C40 /*SRGB_EXT*/, image.Width, image.Height,image.Format, GL_UNSIGNED_BYTE, reinterpret_cast<void*>(image.Data));
#else
glTexImage2D(GL_TEXTURE_2D, 0, 0x8C40 /*SRGB_EXT*/, image.Width, image.Height,
0, image.Format, GL_UNSIGNED_BYTE,
reinterpret_cast<void*>(image.Data));
glGenerateMipmap(GL_TEXTURE_2D);
#endif
get_errors();
glfwFreeImage(&image);
}
unsigned ModelImage::getTexId(){
return _id;
}
ModelImage::ModelImage(string file){
GLFWimage image;
if (glfwReadImage(file.c_str(), &image, GLFW_ORIGIN_UL_BIT) != GL_TRUE){
printf("\nModelImage::ModelImage::glfwReadImage Cannot load file '%s' (Do you have unix file endings?)\n", file.c_str());
return;
}
get_errors();
glGenTextures(1, &_id);
get_errors();
glBindTexture(GL_TEXTURE_2D, _id);
get_errors();
// Load texture from file, and build all mipmap levels
//if( !glfwLoadTexture2D( file.c_str(), GLFW_ORIGIN_UL_BIT | GLFW_BUILD_MIPMAPS_BIT ) )
//{
// return;
//}
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
get_errors();
// Use trilinear interpolation for minification
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR );
get_errors();
// Use bilinear interpolation for magnification
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR );
get_errors();
//if(glfwLoadMemoryTexture2D(image.Data, image.BytesPerPixel * image.Height * image.Width, GLFW_BUILD_MIPMAPS_BIT) == GL_FALSE);
// return;
//image.Format;
#ifdef GL_GENERATE_MIPMAP_SEG_AVOIDANCE
#ifdef DEBUG
printf("using gluBuild2DMipmaps()\n");
#endif
if(image.BytesPerPixel == 1){
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, image.Width, image.Height, GL_RED, GL_UNSIGNED_BYTE, reinterpret_cast<void*>(image.Data));
get_errors("ModelImage:gluBuild2DMipmaps Grauwert Bild einlesen!");
}else{
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_SRGB, image.Width, image.Height,image.Format, GL_UNSIGNED_BYTE, reinterpret_cast<void*>(image.Data));
get_errors("ModelImage:gluBuild2DMipmaps Farb Bild einlesen!");
}
#else
if(image.BytesPerPixel == 1){
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.Width, image.Height,
0, GL_RED, GL_UNSIGNED_BYTE,
reinterpret_cast<void*>(image.Data));
get_errors("ModelImage:glTexImage2D Grauwert Bild einlesen! A");
glGenerateMipmap(GL_TEXTURE_2D);
get_errors("ModelImage:glGenerateMipmap Grauwert Bild einlesen! B");
}else{
glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB, image.Width, image.Height,
0, image.Format, GL_UNSIGNED_BYTE,
reinterpret_cast<void*>(image.Data));
glGenerateMipmap(GL_TEXTURE_2D);
get_errors("ModelImage:glTexImage2D Farb Bild einlesen! ");
}
#endif
get_errors();
glfwFreeImage(&image);
}
| [
"cdellmour@2895edc6-717a-dc9c-75a2-8897665f464c",
"t.moerwald@2895edc6-717a-dc9c-75a2-8897665f464c"
]
| [
[
[
1,
48
],
[
50,
50
],
[
52,
67
],
[
70,
70
],
[
72,
130
]
],
[
[
49,
49
],
[
51,
51
],
[
68,
69
],
[
71,
71
],
[
131,
131
]
]
]
|
ba44ff4c90e607dbb11acbeb25d1db2c59fb4426 | b08e948c33317a0a67487e497a9afbaf17b0fc4c | /Display/RenderTarget.cpp | aacda4141d431dc0c10fa4ba15a95f7c8024c6d7 | []
| 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 | 18,851 | cpp | #include "stdafx.h"
#include "../Display/RenderTarget.h"
#include "../Display/Camera.h"
#include "../Core/Util.h"
namespace ElixirEngine
{
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
VertexElement DisplayRenderTargetGeometry::Vertex::s_aDecl[6] =
{
{ 0, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITIONT, 0 },
{ 0, 16, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 },
{ 0, 28, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1 },
{ 0, 40, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2 },
{ 0, 52, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3 },
D3DDECL_END()
};
DisplayRenderTargetGeometry::DisplayRenderTargetGeometry(DisplayRef _rDisplay)
: DisplayObject(),
m_rDisplay(*Display::GetInstance()),
m_pPreviousVertexBuffer(NULL),
m_pPreviousVertexDecl(NULL),
m_uVertexDecl(0),
m_uPreviousVBOffset(0),
m_uPreviousVBStride(0)
{
}
DisplayRenderTargetGeometry::~DisplayRenderTargetGeometry()
{
}
bool DisplayRenderTargetGeometry::Create(const boost::any& _rConfig)
{
CreateInfo* pInfo = boost::any_cast<CreateInfo*>(_rConfig);
bool bResult = (NULL != pInfo);
if (false != bResult)
{
Release();
m_fFullWidth = float(pInfo->m_uWidth);
m_fFullHeight = float(pInfo->m_uHeight);
const float fWidth = pInfo->m_uWidth * 0.5f;
const float fHeight = pInfo->m_uHeight * 0.5f;
const Vertex aQuad[4] =
{
{ -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 0.0f, float(DisplayCamera::EFrustumCorner_FARTOPLEFT), 0.0f, 0.0f, float(DisplayCamera::EFrustumCorner_FARTOPLEFT) },
{ -0.5f, fHeight - 0.5f, 1.0f, 1.0f, 0.0f, 0.5f, float(DisplayCamera::EFrustumCorner_FARBOTTOMLEFT), 0.0f, 1.0f, float(DisplayCamera::EFrustumCorner_FARBOTTOMLEFT) },
{ fWidth - 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.0f, float(DisplayCamera::EFrustumCorner_FARTOPRIGHT), 1.0f, 0.0f, float(DisplayCamera::EFrustumCorner_FARTOPRIGHT) },
{ fWidth - 0.5f, fHeight - 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, float(DisplayCamera::EFrustumCorner_FARBOTTOMRIGHT), 1.0f, 1.0f, float(DisplayCamera::EFrustumCorner_FARBOTTOMRIGHT) }
};
memcpy(m_aQuad, aQuad, 4 * sizeof(Vertex));
m_uVertexDecl = m_rDisplay.CreateVertexDeclaration(DisplayRenderTargetGeometry::Vertex::s_aDecl);
bResult = (0 != m_uVertexDecl);
}
return bResult;
}
void DisplayRenderTargetGeometry::Update()
{
}
void DisplayRenderTargetGeometry::Release()
{
if (0 != m_uVertexDecl)
{
m_rDisplay.ReleaseVertexDeclaration(m_uVertexDecl);
m_uVertexDecl = 0;
}
m_pPreviousVertexBuffer = NULL;
m_pPreviousVertexDecl = NULL;
m_uPreviousVBOffset = 0;
m_uPreviousVBStride = 0;
}
void DisplayRenderTargetGeometry::RenderBegin()
{
//DevicePtr pDevice = m_rDisplay.GetDevicePtr();
//pDevice->GetStreamSource(0, &m_pPreviousVertexBuffer, &m_uPreviousVBOffset, &m_uPreviousVBStride);
//pDevice->GetVertexDeclaration(&m_pPreviousVertexDecl);
//if (m_pPreviousVertexDecl != m_uVertexDecl)
//{
// pDevice->SetVertexDeclaration(m_uVertexDecl);
//}
DisplayPtr pDisplay = Display::GetInstance();
if (m_uVertexDecl != pDisplay->GetCurrentVertexDeclaration())
{
pDisplay->SetVertexDeclaration(m_uVertexDecl);
}
}
void DisplayRenderTargetGeometry::Render()
{
// use current view port to map geometry size and texture coordinates.
ViewportPtr pViewport = m_rDisplay.GetCurrentCamera()->GetCurrentViewport();
const float fWidth = float(pViewport->Width);
const float fHeight = float(pViewport->Height);
const float fX = float(pViewport->X);
const float fY = float(pViewport->Y);
m_aQuad[0].x = fX - 0.5f; m_aQuad[0].y = fY - 0.5f;
m_aQuad[1].x = fX - 0.5f; m_aQuad[1].y = fY + fHeight - 0.5f;
m_aQuad[2].x = fX + fWidth - 0.5f; m_aQuad[2].y = fY - 0.5f;
m_aQuad[3].x = fX + fWidth - 0.5f; m_aQuad[3].y = fY + fHeight - 0.5f;
m_aQuad[0].tu = 0.0f; m_aQuad[0].tv = 0.0f;
m_aQuad[1].tu = 0.0f; m_aQuad[1].tv = fHeight / m_fFullHeight;
m_aQuad[2].tu = fWidth / m_fFullWidth; m_aQuad[2].tv = 0.0f;
m_aQuad[3].tu = fWidth / m_fFullWidth; m_aQuad[3].tv = fHeight / m_fFullHeight;
// update frustum corners values.
Vector3Ptr pFrustumCorners = m_rDisplay.GetCurrentCamera()->GetFrustumCorners();
for (UInt i = 0 ; 4 > i ; ++i)
{
Vertex& rVertex = m_aQuad[i];
Vector3Ptr pFarCorner = &pFrustumCorners[UInt(rVertex.tw)];
Vector3Ptr pNearCorner = &pFrustumCorners[UInt(rVertex.tw) + 4];
rVertex.tu3 = pFarCorner->x;
rVertex.tv3 = pFarCorner->y;
rVertex.tw3 = pFarCorner->z;
rVertex.tu4 = pNearCorner->x;
rVertex.tv4 = pNearCorner->y;
rVertex.tw4 = pNearCorner->z;
}
m_rDisplay.GetDevicePtr()->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, m_aQuad, sizeof(Vertex));
}
void DisplayRenderTargetGeometry::RenderEnd()
{
//if ((m_pPreviousVertexDecl != m_uVertexDecl) && (NULL != m_pPreviousVertexDecl))
//{
// DevicePtr pDevice = m_rDisplay.GetDevicePtr();
// pDevice->SetStreamSource(0, m_pPreviousVertexBuffer, m_uPreviousVBOffset, m_uPreviousVBStride);
// pDevice->SetVertexDeclaration(m_pPreviousVertexDecl);
//}
}
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
DisplayRenderTarget::DisplayRenderTarget(DisplayRef _rDisplay)
: CoreObject(),
m_strName(),
m_rDisplay(_rDisplay),
m_pPreviousBufferSurf(NULL),
m_pCurrentBufferTex(NULL),
m_pRTOverrideTex(NULL),
m_pRTOverrideSurf(NULL),
m_uCurrentBuffer(0),
m_uRTIndex(0),
m_uPassIndex(0),
m_uRTSemanticNameKey(0),
m_uORTSemanticNameKey(0),
m_eRenderState(ERenderState_UNKNOWN),
m_eMode(ERenderMode_UNKNOWNPROCESS),
m_bFirstRender(true),
m_bImmediateWrite(false),
m_bEnabled(false),
m_bSwap(false)
{
for (UInt i = 0 ; c_uBufferCount > i ; ++i)
{
m_pDoubleBufferTex[i] = NULL;
m_pDoubleBufferSurf[i] = NULL;
}
}
DisplayRenderTarget::~DisplayRenderTarget()
{
}
bool DisplayRenderTarget::Create(const boost::any& _rConfig)
{
CreateInfo* pInfo = boost::any_cast<CreateInfo*>(_rConfig);
bool bResult = (NULL != pInfo);
if (false != bResult)
{
Release();
m_strName = pInfo->m_strName;
m_uRTIndex = pInfo->m_uIndex;
m_bImmediateWrite = pInfo->m_bImmediateWrite;
m_eRenderState = ERenderState_UNKNOWN;
m_eMode = ERenderMode_UNKNOWNPROCESS;
m_pCurrentBufferTex = NULL;
m_uCurrentBuffer = 0;
string strSemanticName = boost::str(boost::format("RT2D0%1%") % m_uRTIndex);
m_uRTSemanticNameKey = MakeKey(strSemanticName);
strSemanticName = boost::str(boost::format("ORT2D0%1%") % m_uRTIndex);
m_uORTSemanticNameKey = MakeKey(strSemanticName);
for (UInt i = 0 ; c_uBufferCount > i ; ++i)
{
string strTexName = boost::str(boost::format("%1%_%2%") % m_strName % i);
bResult = m_rDisplay.GetTextureManager()->New(strTexName, pInfo->m_uWidth, pInfo->m_uHeight, pInfo->m_uFormat, false, DisplayTexture::EType_2D, DisplayTexture::EUsage_RENDERTARGET);
if (false == bResult)
{
vsoutput(__FUNCTION__" : %s, could not create texture\n", strTexName.c_str());
break;
}
m_pDoubleBufferTex[i] = m_rDisplay.GetTextureManager()->Get(strTexName);
TexturePtr pTexture = static_cast<TexturePtr>(m_pDoubleBufferTex[i]->GetBase());
pTexture->GetSurfaceLevel(0, &m_pDoubleBufferSurf[i]);
}
}
return bResult;
}
void DisplayRenderTarget::Update()
{
}
void DisplayRenderTarget::Release()
{
SetRTOverride(NULL);
for (UInt i = 0 ; c_uBufferCount > i ; ++i)
{
if (NULL != m_pDoubleBufferSurf[i])
{
m_pDoubleBufferSurf[i]->Release();
m_pDoubleBufferSurf[i] = NULL;
}
if (NULL != m_pDoubleBufferTex[i])
{
string strTexName = boost::str(boost::format("%1%_%2%") % m_strName % i);
m_rDisplay.GetTextureManager()->Unload(strTexName);
m_pDoubleBufferTex[i] = NULL;
}
}
}
void DisplayRenderTarget::RenderBegin(const ERenderMode& _eMode)
{
m_bSwap = false;
if ((false != m_bEnabled) && ((ERenderState_UNKNOWN == m_eRenderState) || (ERenderState_RENDEREND == m_eRenderState)))
{
m_eRenderState = ERenderState_RENDERBEGIN;
//if (false == m_bImmediateWrite)
if (0 == m_uRTIndex)
{
m_rDisplay.GetDevicePtr()->GetRenderTarget(m_uRTIndex, &m_pPreviousBufferSurf);
}
m_eMode = _eMode;
if (ERenderMode_NORMALPROCESS == m_eMode)
{
m_uCurrentBuffer = 0;
m_bFirstRender = true;
m_pCurrentBufferTex = NULL;
}
}
}
void DisplayRenderTarget::RenderBeginPass(const UInt _uIndex)
{
m_bSwap = false;
if ((false != m_bEnabled) && ((ERenderState_RENDERBEGIN == m_eRenderState) || (ERenderState_RENDERENDPASS == m_eRenderState)))
{
m_uPassIndex = _uIndex;
m_eRenderState = ERenderState_RENDERBEGINPASS;
if ((ERenderMode_POSTPROCESS == m_eMode) || (NULL == m_pCurrentBufferTex))
{
if (ERenderMode_POSTPROCESS == m_eMode)
{
m_rDisplay.GetTextureManager()->SetBySemantic(m_uRTSemanticNameKey, m_pCurrentBufferTex);
m_rDisplay.GetTextureManager()->SetBySemantic(m_uORTSemanticNameKey, m_pDoubleBufferTex[c_uOriginalBuffer]);
}
if (false == m_bImmediateWrite)
{
if (NULL == m_pRTOverrideSurf)
{
const UInt uNewIndex = (false != m_bFirstRender) ? c_uOriginalBuffer : m_uCurrentBuffer;
if (m_pDoubleBufferTex[uNewIndex] != m_pCurrentBufferTex)
{
m_pCurrentBufferTex = m_pDoubleBufferTex[uNewIndex];
m_rDisplay.GetDevicePtr()->SetRenderTarget(m_uRTIndex, m_pDoubleBufferSurf[uNewIndex]);
m_bSwap = true;
}
}
else if (m_pCurrentBufferTex != m_pRTOverrideTex)
{
m_pCurrentBufferTex = m_pRTOverrideTex;
m_rDisplay.GetDevicePtr()->SetRenderTarget(m_uRTIndex, m_pRTOverrideSurf);
m_bSwap = true;
}
}
}
}
}
void DisplayRenderTarget::RenderEndPass()
{
m_bSwap = false;
if ((false != m_bEnabled) && (ERenderState_RENDERBEGINPASS == m_eRenderState))
{
m_eRenderState = ERenderState_RENDERENDPASS;
if (ERenderMode_POSTPROCESS == m_eMode)
{
m_rDisplay.GetTextureManager()->SetBySemantic(m_uRTSemanticNameKey, NULL);
m_rDisplay.GetTextureManager()->SetBySemantic(m_uORTSemanticNameKey, NULL);
}
if (false == m_bImmediateWrite)
{
m_uCurrentBuffer = 1 - m_uCurrentBuffer;
}
}
}
void DisplayRenderTarget::RenderEnd()
{
m_bSwap = false;
if ((false != m_bEnabled) && ((ERenderState_RENDERBEGIN == m_eRenderState) || (ERenderState_RENDERENDPASS == m_eRenderState)))
{
m_eRenderState = ERenderState_RENDEREND;
m_bFirstRender = false;
if ((0 != m_uRTIndex) || (NULL != m_pPreviousBufferSurf))
{
m_rDisplay.GetDevicePtr()->SetRenderTarget(m_uRTIndex, m_pPreviousBufferSurf);
}
if (NULL != m_pPreviousBufferSurf)
{
m_pPreviousBufferSurf->Release();
m_pPreviousBufferSurf = NULL;
}
}
}
DisplayTexturePtr DisplayRenderTarget::GetTexture()
{
return m_pCurrentBufferTex;
}
void DisplayRenderTarget::SetEnabled(const bool _bState)
{
m_bEnabled = _bState;
SetRTOverride(NULL);
}
bool DisplayRenderTarget::IsEnabled()
{
return m_bEnabled;
}
void DisplayRenderTarget::SetIndex(const UInt _uIndex)
{
m_uRTIndex = _uIndex;
}
UInt DisplayRenderTarget::GetIndex()
{
return m_uRTIndex;
}
bool DisplayRenderTarget::SwapOccured()
{
return m_bSwap;
}
void DisplayRenderTarget::SetRTOverride(DisplayTexturePtr _RTOverride)
{
if (m_pRTOverrideTex != _RTOverride)
{
if (NULL != m_pRTOverrideSurf)
{
m_pRTOverrideSurf->Release();
m_pRTOverrideSurf = NULL;
}
m_pRTOverrideTex = _RTOverride;
if (NULL != m_pRTOverrideTex)
{
TexturePtr pTexture = static_cast<TexturePtr>(m_pRTOverrideTex->GetBase());
pTexture->GetSurfaceLevel(0, &m_pRTOverrideSurf);
}
}
}
void DisplayRenderTarget::SetImmediateWrite(const bool& _bState)
{
if (m_bImmediateWrite != _bState)
{
m_bImmediateWrite = _bState;
if ((false != m_bImmediateWrite)
&& (NULL != m_pPreviousBufferSurf))
{
m_rDisplay.GetDevicePtr()->SetRenderTarget(m_uRTIndex, m_pPreviousBufferSurf);
m_pPreviousBufferSurf->Release();
m_pPreviousBufferSurf = NULL;
}
else if ((false == m_bImmediateWrite) && (NULL == m_pPreviousBufferSurf) && ( 0 == m_uRTIndex))
{
m_rDisplay.GetDevicePtr()->GetRenderTarget(m_uRTIndex, &m_pPreviousBufferSurf);
}
}
}
bool DisplayRenderTarget::GetImmediateWrite()
{
return m_bImmediateWrite;
}
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------
DisplayRenderTargetChain::DisplayRenderTargetChain(DisplayRef _rDisplay)
: CoreObject(),
m_rDisplay(_rDisplay),
m_vGBuffer(),
m_sDepthBufferIndex(-1),
m_bImmediateWrite(false)
{
}
DisplayRenderTargetChain::~DisplayRenderTargetChain()
{
}
bool DisplayRenderTargetChain::Create(const boost::any& _rConfig)
{
CreateInfo* pInfo = boost::any_cast<CreateInfo*>(_rConfig);
bool bResult = (NULL != pInfo);
if (false != bResult)
{
GraphicConfigDataPtr pGraphicConfig = pInfo->m_pGraphicConfig;
for (UInt i = 0 ; pGraphicConfig->m_uDXGBufferCount > i ; ++i)
{
const string strRTName = boost::str(boost::format("%1%_buffer%2%") % pInfo->m_strName % i);
DisplayRenderTarget::CreateInfo oRTRTCInfo = { strRTName, pInfo->m_uWidth, pInfo->m_uHeight, D3DFORMAT(pGraphicConfig->m_aDXGBufferFormat[i]), i };
DisplayRenderTargetPtr pRT = new DisplayRenderTarget(m_rDisplay);
bResult = pRT->Create(boost::any(&oRTRTCInfo));
if (false == bResult)
{
CoreObject::ReleaseDeleteReset(pRT);
break;
}
m_vGBuffer.push_back(pRT);
}
m_sDepthBufferIndex = pGraphicConfig->m_sDXGufferDepthIndex;
}
return bResult;
}
void DisplayRenderTargetChain::Update()
{
}
void DisplayRenderTargetChain::Release()
{
while (false == m_vGBuffer.empty())
{
CoreObject::ReleaseDeleteReset(m_vGBuffer.back());
m_vGBuffer.pop_back();
}
}
void DisplayRenderTargetChain::RenderBegin(const DisplayRenderTarget::ERenderMode& _eMode)
{
m_rDisplay.GetDevicePtr()->BeginScene();
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
while (iEnd != iRT)
{
DisplayRenderTargetPtr pRT = *iRT;
if (false != pRT->IsEnabled())
{
pRT->RenderBegin(_eMode);
}
++iRT;
}
}
void DisplayRenderTargetChain::RenderBeginPass(const UInt _uIndex)
{
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
bool bSwap = false;
while (iEnd != iRT)
{
DisplayRenderTargetPtr pRT = *iRT;
if (false != pRT->IsEnabled())
{
pRT->RenderBeginPass(_uIndex);
bSwap = bSwap || pRT->SwapOccured();
}
++iRT;
}
// Since SetRenderViewport reset the view port to full screen size we need to force back previously requested view port.
if (false != bSwap)
{
m_rDisplay.GetDevicePtr()->SetViewport(m_rDisplay.GetCurrentCamera()->GetCurrentViewport());
}
}
void DisplayRenderTargetChain::RenderEndPass()
{
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
while (iEnd != iRT)
{
DisplayRenderTargetPtr pRT = *iRT;
if (false != pRT->IsEnabled())
{
pRT->RenderEndPass();
}
++iRT;
}
}
void DisplayRenderTargetChain::RenderEnd()
{
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
while (iEnd != iRT)
{
DisplayRenderTargetPtr pRT = *iRT;
if (false != pRT->IsEnabled())
{
pRT->RenderEnd();
}
++iRT;
}
m_rDisplay.GetDevicePtr()->EndScene();
}
DisplayTexturePtr DisplayRenderTargetChain::GetTexture(const UInt _uRTIndex)
{
DisplayTexturePtr pResult = (_uRTIndex < m_vGBuffer.size()) ? m_vGBuffer[_uRTIndex]->GetTexture() : NULL;
return pResult;
}
DisplayRenderTargetPtr DisplayRenderTargetChain::GetRenderTarget(const UInt _uRTIndex)
{
DisplayRenderTargetPtr pResult = (_uRTIndex < m_vGBuffer.size()) ? m_vGBuffer[_uRTIndex] : NULL;
return pResult;
}
void DisplayRenderTargetChain::EnableAllRenderTargets()
{
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
UInt uIndex = 0;
while (iEnd != iRT)
{
(*iRT)->SetEnabled(true);
(*iRT)->SetIndex(uIndex);
++iRT;
++uIndex;
}
//SetImmediateWrite(false);
}
void DisplayRenderTargetChain::DisableAllRenderTargets()
{
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
while (iEnd != iRT)
{
(*iRT)->SetEnabled(false);
++iRT;
}
//SetImmediateWrite(true);
}
void DisplayRenderTargetChain::Clear(const UInt _uClearColor)
{
//EnableAllRenderTargets();
RenderBegin(DisplayRenderTarget::ERenderMode_NORMALPROCESS);
RenderBeginPass(0);
m_rDisplay.GetDevicePtr()->Clear(0L, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, _uClearColor, 1.0f, 0L);
RenderEndPass();
RenderEnd();
}
void DisplayRenderTargetChain::SetImmediateWrite(const bool& _bState)
{
if (_bState != m_bImmediateWrite)
{
m_bImmediateWrite = _bState;
DisplayRenderTargetPtrVec::iterator iRT = m_vGBuffer.begin();
DisplayRenderTargetPtrVec::iterator iEnd = m_vGBuffer.end();
while (iEnd != iRT)
{
(*iRT)->SetImmediateWrite(_bState);
++iRT;
}
}
}
bool DisplayRenderTargetChain::GetImmediateWrite()
{
return m_bImmediateWrite;
}
}
| [
"voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329"
]
| [
[
[
1,
615
]
]
]
|
ee2da3275c1971529c752c7e9e7f4dfc3e290d36 | 38926bfe477f933a307f51376dd3c356e7893ffc | /Source/CryEngine/CryCommon/CREBaseCloud.h | 1ffe8b9b8a27309b08deade6788e07ae0983af80 | []
| no_license | richmondx/dead6 | b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161 | 955f76f35d94ed5f991871407f3d3ad83f06a530 | refs/heads/master | 2021-12-05T14:32:01.782047 | 2008-01-01T13:13:39 | 2008-01-01T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,630 | h |
/*=============================================================================
CREBaseCloud.h : Cloud RE declarations/implementations.
Copyright (c) 2001-2005 Crytek Studios. All Rights Reserved.
Revision history:
=============================================================================*/
#ifndef __CREBASECLOUD_H__
#define __CREBASECLOUD_H__
//================================================================================
class SCloudParticle
{
public:
inline SCloudParticle();
inline SCloudParticle(const Vec3& vPos, float fRadius, const ColorF& baseColor, float fTransparency = 0);
inline SCloudParticle(const Vec3& vPos, float fRadiusX, float fRadiusY, float fRotMin, float fRotMax, Vec2 vUV[]);
inline ~SCloudParticle();
float GetRadiusX() const { return m_fSize[0]; }
float GetRadiusY() const { return m_fSize[1]; }
float GetTransparency() const { return m_fTransparency; }
const Vec3& GetPosition() const { return m_vPosition; }
const ColorF& GetBaseColor() const { return m_vBaseColor; }
uint GetNumLitColors() const { return m_vLitColors.size(); }
inline const ColorF GetLitColor(unsigned int index) const;
float GetSquareSortDistance() const { return m_fSquareSortDistance; }
//! Sets the radius of the particle.
void SetRadiusX(float rad) { m_fSize[0] = rad; }
void SetRadiusY(float rad) { m_fSize[1] = rad; }
void SetTransparency(float trans) { m_fTransparency = trans; }
void SetPosition(const Vec3& pos) { m_vPosition = pos; }
void SetBaseColor(const ColorF& col) { m_vBaseColor = col; }
void AddLitColor(const ColorF& col) { m_vLitColors.push_back(col); }
void ClearLitColors() { m_vLitColors.clear(); }
void SetSquareSortDistance(float fSquareDistance) { m_fSquareSortDistance = fSquareDistance; }
bool operator<(const SCloudParticle& p) const
{
return (m_fSquareSortDistance < p.m_fSquareSortDistance);
}
bool operator>(const SCloudParticle& p) const
{
return (m_fSquareSortDistance > p.m_fSquareSortDistance);
}
protected:
float m_fTransparency;
Vec3 m_vPosition;
float m_fSize[2];
float m_fRotMin;
float m_fRotMax;
ColorF m_vBaseColor;
TArray<ColorF> m_vLitColors;
Vec3 m_vEye;
// for sorting particles during shading
float m_fSquareSortDistance;
public:
Vec2 m_vUV[2];
};
inline SCloudParticle::SCloudParticle()
{
m_fSize[0] = 0;
m_fTransparency = 0;
m_vPosition = Vec3(0, 0, 0);
m_vBaseColor = Col_Black;
m_vEye = Vec3(0, 0, 0);
m_fSquareSortDistance = 0;
m_vLitColors.clear();
}
inline SCloudParticle::SCloudParticle(const Vec3& pos, float fRadius, const ColorF& baseColor, float fTransparency)
{
m_fSize[0] = fRadius;
m_fSize[1] = fRadius;
m_fTransparency = fTransparency;
m_vPosition = pos;
m_vBaseColor = baseColor;
m_vUV[0] = Vec2(0,0);
m_vUV[1] = Vec2(1,1);
m_fRotMin = 0;
m_fRotMax = 0;
m_vEye = Vec3(0, 0, 0);
m_fSquareSortDistance = 0;
m_vLitColors.clear();
}
inline SCloudParticle::SCloudParticle(const Vec3& vPos, float fRadiusX, float fRadiusY, float fRotMin, float fRotMax, Vec2 vUV[2])
{
m_fSize[0] = fRadiusX;
m_fSize[1] = fRadiusY;
m_vPosition = vPos;
m_vBaseColor = Col_White;
m_vUV[0] = vUV[0];
m_vUV[1] = vUV[1];
m_fRotMin = fRotMin;
m_fRotMax = fRotMax;
m_fTransparency = 1.0f;
m_vEye = Vec3(0, 0, 0);
m_fSquareSortDistance = 0;
m_vLitColors.clear();
}
inline SCloudParticle::~SCloudParticle()
{
m_vLitColors.clear();
}
inline const ColorF SCloudParticle::GetLitColor(unsigned int index) const
{
if (index <= m_vLitColors.size())
return m_vLitColors[index];
else
return Col_Black;
}
//===========================================================================
class CREBaseCloud : public CRendElement
{
friend class CRECloud;
public:
CREBaseCloud() : CRendElement()
{
mfSetType(eDATA_Cloud);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual void SetParticles(SCloudParticle *pParticles, int nNumParticles) = 0;
};
#endif // __CREBASECLOUD_H__
| [
"[email protected]"
]
| [
[
[
1,
145
]
]
]
|
7e8c035ab43498644263610687fac5ce39564b38 | a705a17ff1b502ec269b9f5e3dc3f873bd2d3b9c | /include/point.hpp | b5b2670296ed23489146bf24d3da67e04b98d727 | []
| no_license | cantidio/ChicolinusQuest | 82431a36516d17271685716590fe7aaba18226a0 | 9b77adabed9325bba23c4d99a3815e7f47456a4d | refs/heads/master | 2021-01-25T07:27:54.263356 | 2011-08-09T11:17:53 | 2011-08-09T11:17:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 234 | hpp | #ifndef _POINT_
#define _POINT_
class Point
{
public:
double x;
double y;
Point();
Point(const double& pX, const double& pY);
Point& operator = (const Point& pPoint);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
15
]
]
]
|
d5a554d516dff8c7435470ce64b3a4ba52a40544 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Stellar_/code/Render/frame/framebatch.cc | 5e24584fb2727fcbea93ff95fb1cc0ba0076456a | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,029 | cc | //------------------------------------------------------------------------------
// framebatch.cc
// (C) 2007 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "frame/framebatch.h"
#include "coregraphics/renderdevice.h"
#include "coregraphics/shaderserver.h"
//#include "models/visresolver.h"
//#include "models/model.h"
//#include "models/modelnodeinstance.h"
//#include "graphics/modelentity.h"
//#include "lighting/lightserver.h"
namespace Frame
{
ImplementClass(Frame::FrameBatch, 'FBTH', Core::RefCounted);
//using namespace Graphics;
using namespace CoreGraphics;
//using namespace Models;
using namespace Util;
//using namespace Lighting;
//------------------------------------------------------------------------------
/**
*/
FrameBatch::FrameBatch() :
batchType(BatchType::InvalidBatchType),
//nodeFilter(ModelNodeType::InvalidModelNodeType),
lightingMode(LightingMode::None),
sortingMode(SortingMode::None),
shaderFeatures(0)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
FrameBatch::~FrameBatch()
{
// make sure Discard() has been called
s_assert(!this->shader.isvalid());
s_assert(this->shaderVariables.empty());
}
//------------------------------------------------------------------------------
/**
*/
void
FrameBatch::Discard()
{
if (this->shader.isvalid())
{
this->shader->Discard();
this->shader = 0;
}
this->shaderVariables.clear();
}
//------------------------------------------------------------------------------
/**
*/
void
FrameBatch::Render()
{
RenderDevice* renderDevice = RenderDevice::Instance();
// apply shader variables
IndexT varIndex;
for (varIndex = 0; varIndex < this->shaderVariables.size(); varIndex++)
{
this->shaderVariables[varIndex]->Apply();
}
// render the batch
renderDevice->BeginBatch(this->batchType, this->shader);
this->RenderBatch();
renderDevice->EndBatch();
}
//------------------------------------------------------------------------------
/**
*/
void
FrameBatch::RenderBatch()
{
//ShaderServer* shaderServer = ShaderServer::Instance();
//VisResolver* visResolver = VisResolver::Instance();
//LightServer* lightServer = LightServer::Instance();
//// for each visible model...
//const Array<Ptr<Model>>& models = visResolver->GetVisibleModels(this->nodeFilter);
//IndexT modelIndex;
//for (modelIndex = 0; modelIndex < models.Size(); modelIndex++)
//{
// // for each visible model node of the model...
// const Array<Ptr<ModelNode>>& modelNodes = visResolver->GetVisibleModelNodes(this->nodeFilter, models[modelIndex]);
// IndexT modelNodeIndex;
// for (modelNodeIndex = 0; modelNodeIndex < modelNodes.Size(); modelNodeIndex++)
// {
// // apply render state which is shared by all instances
// shaderServer->ResetFeatureBits();
// shaderServer->SetFeatureBits(this->shaderFeatures);
// const Ptr<ModelNode>& modelNode = modelNodes[modelNodeIndex];
// modelNode->ApplySharedState();
// // if lighting mode is Off, we can render all node instances with the same shader
// const Ptr<ShaderInstance>& shaderInst = shaderServer->GetActiveShaderInstance();
// if (LightingMode::None == this->lightingMode)
// {
// shaderInst->SelectActiveVariation(shaderServer->GetFeatureBits());
// SizeT numPasses = shaderInst->Begin();
// s_assert(1 == numPasses);
// shaderInst->BeginPass(0);
// }
// // render instances
// const Array<Ptr<ModelNodeInstance>>& nodeInstances = visResolver->GetVisibleModelNodeInstances(this->nodeFilter, modelNode);
// IndexT nodeInstIndex;
// for (nodeInstIndex = 0; nodeInstIndex < nodeInstances.Size(); nodeInstIndex++)
// {
// const Ptr<ModelNodeInstance>& nodeInstance = nodeInstances[nodeInstIndex];
// // if single-pass lighting is enabled, we need to setup the lighting
// // shader states
// // FIXME: This may set a new shader variation for every node instance
// // which is expensive! Would be better to sort node instances by number
// // of active lights!!!
// if (LightingMode::SinglePass == this->lightingMode)
// {
// // setup lighting render states
// // NOTE: this may change the shader feature bit mask which may select
// // a different shader variation per entity
// const Ptr<ModelEntity>& modelEntity = nodeInstance->GetModelInstance()->GetModelEntity();
// lightServer->ApplyModelEntityLights(modelEntity);
// shaderInst->SelectActiveVariation(shaderServer->GetFeatureBits());
// SizeT numPasses = shaderInst->Begin();
// s_assert(1 == numPasses);
// shaderInst->BeginPass(0);
// }
// // render the node instance
// nodeInstance->ApplyState();
// shaderInst->Commit();
// nodeInstance->Render();
// if (LightingMode::SinglePass == this->lightingMode)
// {
// shaderInst->EndPass();
// shaderInst->End();
// }
// }
// if (LightingMode::None == this->lightingMode)
// {
// shaderInst->EndPass();
// shaderInst->End();
// }
// }
//}
}
} // namespace Frame
| [
"ctuomail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
165
]
]
]
|
24000d7d6247ebded3ac6e3c64f0c87659caf577 | 11da90929ba1488c59d25c57a5fb0899396b3bb2 | /Src/WindowsCE/Messages.hpp | 0a66f0eba4c3d3f29f8c4dabf126189d2cb0bdfc | []
| 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 | 173 | hpp | #ifndef ARSLEXIS_WIN_MESSAGES_H__
#define ARSLEXIS_WIN_MESSAGES_H__
#include <Debug.hpp>
const char_t* MessageName(UINT msg);
#endif // ARSLEXIS_WIN_MESSAGES_H__
| [
"andrzejc@10a9aba9-86da-0310-ac04-a2df2cc00fd9"
]
| [
[
[
1,
8
]
]
]
|
e8e7e171f5b65426b1b4c424096a7ef0dd56d537 | 9ef88cf6a334c82c92164c3f8d9f232d07c37fc3 | /Libraries/RakNet/include/AutoRPC.h | 841c4bb78ac5aa4d9a23a35ecd0372240e94c173 | []
| no_license | Gussoh/bismuthengine | eba4f1d6c2647d4b73d22512405da9d7f4bde88a | 4a35e7ae880cebde7c557bd8c8f853a9a96f5c53 | refs/heads/master | 2016-09-05T11:28:11.194130 | 2010-01-10T14:09:24 | 2010-01-10T14:09:24 | 33,263,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 44,642 | h | /// \file AutoRPC.h
/// \brief Automatically serializing and deserializing RPC system. More advanced RPC, but possibly not cross-platform.
///
/// This file is part of RakNet Copyright 2003 Jenkins Software LLC
///
/// Usage of RakNet is subject to the appropriate license agreement.
#ifndef __AUTO_RPC_H
#define __AUTO_RPC_H
class RakPeerInterface;
class NetworkIDManager;
#include "PluginInterface2.h"
#include "DS_Map.h"
#include "PacketPriority.h"
#include "RakNetTypes.h"
#include "BitStream.h"
#include "Gen_RPC8.h"
#include "RakString.h"
#ifdef _MSC_VER
#pragma warning( push )
#endif
/// \defgroup AUTO_RPC_GROUP AutoRPC
/// \brief Depreciated. Uses Assembly to do RPC
/// \details
/// \ingroup PLUGINS_GROUP
namespace RakNet
{
/// Maximum amount of data that can be passed on the stack in a function call
#define ARPC_MAX_STACK_SIZE 65536
#if defined (_WIN32)
/// Easier way to get a pointer to a function member of a C++ class
/// \note Recommended you use ARPC_REGISTER_CPP_FUNCTION0 to ARPC_REGISTER_CPP_FUNCTION9 (below)
/// \note ARPC_REGISTER_CPP_FUNCTION is not Linux compatible, and cannot validate the number of parameters is correctly passed.
/// \param[in] autoRPCInstance A pointer to an instance of AutoRPC
/// \param[in] _IDENTIFIER_ C string identifier to use on the remote system to call the function
/// \param[in] _RETURN_ Return value of the function
/// \param[in] _CLASS_ Base-most class of the containing class that contains your function
/// \param[in] _FUNCTION_ Name of the function
/// \param[in] _PARAMS_ Parameter list, include parenthesis
#define ARPC_REGISTER_CPP_FUNCTION(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS_) \
{ \
union \
{ \
_RETURN_ (AUTO_RPC_CALLSPEC _CLASS_::*__memberFunctionPtr)_PARAMS_; \
void* __voidFunc; \
}; \
__memberFunctionPtr=&_CLASS_::_FUNCTION_; \
(autoRPCInstance)->RegisterFunction(_IDENTIFIER_, __voidFunc, true, -1); \
}
/// \internal Used by ARPC_REGISTER_CPP_FUNCTION0 to ARPC_REGISTER_CPP_FUNCTION9
#define ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS_, _PARAM_COUNT_) \
{ \
union \
{ \
_RETURN_ (AUTO_RPC_CALLSPEC _CLASS_::*__memberFunctionPtr)_PARAMS_; \
void* __voidFunc; \
}; \
__memberFunctionPtr=&_CLASS_::_FUNCTION_; \
(autoRPCInstance)->RegisterFunction(_IDENTIFIER_, __voidFunc, true, _PARAM_COUNT_); \
}
/// Same as ARPC_REGISTER_CPP_FUNCTION, but specifies how many parameters the function has
#define ARPC_REGISTER_CPP_FUNCTION0(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_) (autoRPCInstance)->RegisterFunction(_IDENTIFIER_, __voidFunc, true, 0);
#define ARPC_REGISTER_CPP_FUNCTION1(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_), 0)
#define ARPC_REGISTER_CPP_FUNCTION2(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_), 1)
#define ARPC_REGISTER_CPP_FUNCTION3(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_), 2)
#define ARPC_REGISTER_CPP_FUNCTION4(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_), 3)
#define ARPC_REGISTER_CPP_FUNCTION5(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_,_PARAMS5_), 4)
#define ARPC_REGISTER_CPP_FUNCTION6(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_,_PARAMS5_,_PARAMS6_), 5)
#define ARPC_REGISTER_CPP_FUNCTION7(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_,_PARAMS5_,_PARAMS6_,_PARAMS7_), 6)
#define ARPC_REGISTER_CPP_FUNCTION8(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_,_PARAMS5_,_PARAMS6_,_PARAMS7_,_PARAMS8_), 7)
#define ARPC_REGISTER_CPP_FUNCTION9(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_, _PARAMS9_) ARPC_REGISTER_CPP_FUNCTIONX(autoRPCInstance,_IDENTIFIER_,_RETURN_,_CLASS_,_FUNCTION_,(_PARAMS1_,_PARAMS2_,_PARAMS3_,_PARAMS4_,_PARAMS5_,_PARAMS6_,_PARAMS7_,_PARAMS8_,_PARAMS9_), 8)
#else
#define ARPC_REGISTER_CPP_FUNCTION0(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*)) &_CLASS_::_FUNCTION_, true, 0 );
#define ARPC_REGISTER_CPP_FUNCTION1(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_ )) &_CLASS_::_FUNCTION_, true, 0 );
#define ARPC_REGISTER_CPP_FUNCTION2(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_ )) &_CLASS_::_FUNCTION_, true, 1 );
#define ARPC_REGISTER_CPP_FUNCTION3(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_ )) &_CLASS_::_FUNCTION_, true, 2 );
#define ARPC_REGISTER_CPP_FUNCTION4(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_ )) &_CLASS_::_FUNCTION_, true, 3 );
#define ARPC_REGISTER_CPP_FUNCTION5(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_ )) &_CLASS_::_FUNCTION_, true, 4 );
#define ARPC_REGISTER_CPP_FUNCTION6(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_ )) &_CLASS_::_FUNCTION_, true, 5 );
#define ARPC_REGISTER_CPP_FUNCTION7(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_ )) &_CLASS_::_FUNCTION_, true, 6 );
#define ARPC_REGISTER_CPP_FUNCTION8(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_ )) &_CLASS_::_FUNCTION_, true, 7 );
#define ARPC_REGISTER_CPP_FUNCTION9(autoRPCInstance, _IDENTIFIER_, _RETURN_, _CLASS_, _FUNCTION_, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_, _PARAMS9_) \
(autoRPCInstance)->RegisterFunction((_IDENTIFIER_), (void*)(_RETURN_ (*) (_CLASS_*, _PARAMS1_, _PARAMS2_, _PARAMS3_, _PARAMS4_, _PARAMS5_, _PARAMS6_, _PARAMS7_, _PARAMS8_, _PARAMS9_ )) &_CLASS_::_FUNCTION_, true, 8 );
#endif
/// Error codes returned by a remote system as to why an RPC function call cannot execute
/// Follows packet ID ID_RPC_REMOTE_ERROR
/// Name of the function will be appended, if available. Read as follows:
/// char outputBuff[256];
/// stringCompressor->DecodeString(outputBuff,256,&RakNet::BitStream(p->data+sizeof(MessageID)+1,p->length-sizeof(MessageID)-1,false),0);
/// printf("Function: %s\n", outputBuff);
enum RPCErrorCodes
{
/// AutoRPC::SetNetworkIDManager() was not called, and it must be called to call a C++ object member
RPC_ERROR_NETWORK_ID_MANAGER_UNAVAILABLE,
/// Cannot execute C++ object member call because the object specified by SetRecipientObject() does not exist on this system
RPC_ERROR_OBJECT_DOES_NOT_EXIST,
/// Internal error, index optimization for function lookup does not exist
RPC_ERROR_FUNCTION_INDEX_OUT_OF_RANGE,
/// Named function was not registered with RegisterFunction(). Check your spelling.
RPC_ERROR_FUNCTION_NOT_REGISTERED,
/// Named function was registered, but later unregistered with UnregisterFunction() and can no longer be called.
RPC_ERROR_FUNCTION_NO_LONGER_REGISTERED,
/// SetRecipientObject() was not called before Call(), but RegisterFunction() was called with isObjectMember=true
/// If you intended to call a CPP function, call SetRecipientObject() with a valid object first.
RPC_ERROR_CALLING_CPP_AS_C,
/// SetRecipientObject() was called before Call(), but RegisterFunction() was called with isObjectMember=false
/// If you intended to call a C function, call SetRecipientObject(UNASSIGNED_NETWORK_ID) first.
RPC_ERROR_CALLING_C_AS_CPP,
/// Internal error, passed stack is bigger than current stack. Check that the version is the same on both systems.
RPC_ERROR_STACK_TOO_SMALL,
/// Internal error, formatting error with how the stack was serialized
RPC_ERROR_STACK_DESERIALIZATION_FAILED,
/// The \a parameterCount parameter passed to RegisterFunction() on this system does not match the \a parameterCount parameter passed to SendCall() on the remote system.
RPC_ERROR_INCORRECT_NUMBER_OF_PARAMETERS,
};
/// \deprecated See RakNet::RPC3
/// The AutoRPC plugin allows you to call remote functions as if they were local functions, using the standard function call syntax
/// No serialization or deserialization is needed.
/// Advantages are that this is easier to use than regular RPC system.
/// Disadvantages is that all parameters must be passable on the stack using memcpy (shallow copy). For other types of parameters, use SetOutgoingExtraData() and GetIncomingExtraData()
/// Pointers are automatically dereferenced and the contents copied with memcpy
/// Use the old system, or regular message passing, if you need greater flexibility
/// \ingroup AUTO_RPC_GROUP
class AutoRPC : public PluginInterface2
{
public:
// Constructor
AutoRPC();
// Destructor
virtual ~AutoRPC();
/// Sets the network ID manager to use for object lookup
/// Required to call C++ object member functions via SetRecipientObject()
/// \param[in] idMan Pointer to the network ID manager to use
void SetNetworkIDManager(NetworkIDManager *idMan);
/// Registers a function pointer to be callable given an identifier for the pointer
/// \param[in] uniqueIdentifier String identifying the function. Recommended that this is the name of the function
/// \param[in] functionPtr Pointer to the function. For C, just pass the name of the function. For C++, use ARPC_REGISTER_CPP_FUNCTION
/// \param[in] isObjectMember false if a C function. True if a member function of an object (C++)
/// \param[in] parameterCount Optional parameter to tell the system how many parameters this function has. If specified, and the wrong number of parameters are called by the remote system, the call is rejected. -1 indicates undefined
/// \return True on success, false on uniqueIdentifier already used.
bool RegisterFunction(const char *uniqueIdentifier, void *functionPtr, bool isObjectMember, char parameterCount=-1);
/// Unregisters a function pointer to be callable given an identifier for the pointer
/// \note This is not safe to call while connected
/// \param[in] uniqueIdentifier String identifying the function.
/// \param[in] isObjectMember false if a C function. True if a member function of an object (C++)
/// \return True on success, false on function was not previously or is not currently registered.
bool UnregisterFunction(const char *uniqueIdentifier, bool isObjectMember);
/// Send or stop sending a timestamp with all following calls to Call()
/// Use GetLastSenderTimestamp() to read the timestamp.
/// \param[in] timeStamp Non-zero to pass this timestamp using the ID_TIMESTAMP system. 0 to clear passing a timestamp.
void SetTimestamp(RakNetTime timeStamp);
/// Set parameters to pass to RakPeer::Send() for all following calls to Call()
/// Deafults to HIGH_PRIORITY, RELIABLE_ORDERED, ordering channel 0
/// \param[in] priority See RakPeer::Send()
/// \param[in] reliability See RakPeer::Send()
/// \param[in] orderingChannel See RakPeer::Send()
void SetSendParams(PacketPriority priority, PacketReliability reliability, char orderingChannel);
/// Set system to send to for all following calls to Call()
/// Defaults to UNASSIGNED_SYSTEM_ADDRESS, broadcast=true
/// \param[in] systemAddress See RakPeer::Send()
/// \param[in] broadcast See RakPeer::Send()
void SetRecipientAddress(SystemAddress systemAddress, bool broadcast);
/// Set the NetworkID to pass for all following calls to Call()
/// Defaults to UNASSIGNED_NETWORK_ID (none)
/// If set, the remote function will be considered a C++ function, e.g. an object member function
/// If set to UNASSIGNED_NETWORK_ID (none), the remote function will be considered a C function
/// If this is set incorrectly, you will get back either RPC_ERROR_CALLING_C_AS_CPP or RPC_ERROR_CALLING_CPP_AS_C
/// \sa NetworkIDManager
/// \param[in] networkID Returned from NetworkIDObject::GetNetworkID()
void SetRecipientObject(NetworkID networkID);
/// Write extra data to pass for all following calls to Call()
/// Use BitStream::Reset to clear extra data. Don't forget to do this or you will waste bandwidth.
/// \return A bitstream you can write to to send extra data with each following call to Call()
RakNet::BitStream *SetOutgoingExtraData(void);
/// If the last received function call has a timestamp included, it is stored and can be retrieved with this function.
/// \return 0 if the last call did not have a timestamp, else non-zero
RakNetTime GetLastSenderTimestamp(void) const;
/// Returns the system address of the last system to send us a received function call
/// Equivalent to the old system RPCParameters::sender
/// \return Last system to send an RPC call using this system
SystemAddress GetLastSenderAddress(void) const;
/// Returns the instance of RakPeer this plugin was attached to
RakPeerInterface *GetRakPeer(void) const;
/// Returns the currently running RPC call identifier, set from RegisterFunction::uniqueIdentifier
/// Returns an empty string "" if none
/// \return which RPC call is currently running
const char *GetCurrentExecution(void) const;
/// Gets the bitstream written to via SetOutgoingExtraData().
/// Data is updated with each incoming function call
/// \return A bitstream you can read from with extra data that was written with SetOutgoingExtraData();
RakNet::BitStream *GetIncomingExtraData(void);
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
bool Call(const char *uniqueIdentifier){
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 0);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1>
bool Call(const char *uniqueIdentifier, P1 p1) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 1);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 2);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 3);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3, P4 p4 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 4);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 5);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 6);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, p7, true, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 7);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
bool Call(const char *uniqueIdentifier, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8 ) {
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, p7, p8, true, true, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 8);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID){
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 0);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 1);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 2);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 3);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3, P4 p4 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 4);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 5);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 6);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6, class P7>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, p7, true, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 7);
}
/// Calls a remote function, using whatever was last passed to SetTimestamp(), SetSendParams(), SetRecipientAddress(), and SetRecipientObject()
/// Passed parameter(s), if any, are passed via memcpy and pushed on the stack for the remote function
/// \note This ONLY works with variables that are passable via memcpy! If you need more flexibility, use SetOutgoingExtraData() and GetIncomingExtraData()
/// \note The this pointer, for this instance of AutoRPC, is pushed as the last parameter on the stack. See AutoRPCSample.ccp for an example of this
/// \param[in] uniqueIdentifier parameter of the same name passed to RegisterFunction() on the remote system
/// \param[in] timeStamp See SetTimestamp()
/// \param[in] priority See SetSendParams()
/// \param[in] reliability See SetSendParams()
/// \param[in] orderingChannel See SetSendParams()
/// \param[in] systemAddress See SetRecipientAddress()
/// \param[in] broadcast See SetRecipientAddress()
/// \param[in] networkID See SetRecipientObject()
/// \return True on success, false on uniqueIdentifier already used.
template <class P1, class P2, class P3, class P4, class P5, class P6, class P7, class P8>
bool CallExplicit(const char *uniqueIdentifier, RakNetTime timeStamp, PacketPriority priority, PacketReliability reliability, char orderingChannel, SystemAddress systemAddress, bool broadcast, NetworkID networkID, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8 ) {
SetTimestamp(timeStamp);
SetSendParams(priority, reliability, orderingChannel);
SetRecipientAddress(systemAddress, broadcast);
SetRecipientObject(networkID);
char stack[ARPC_MAX_STACK_SIZE];
unsigned int bytesOnStack = GenRPC::BuildStack(stack, p1, p2, p3, p4, p5, p6, p7, p8, true, true, true, true, true, true, true, true);
return SendCall(uniqueIdentifier, stack, bytesOnStack, 8);
}
// If you need more than 8 parameters, just add it here...
// ---------------------------- ALL INTERNAL AFTER HERE ----------------------------
/// \internal
/// Identifies an RPC function, by string identifier and if it is a C or C++ function
struct RPCIdentifier
{
char *uniqueIdentifier;
bool isObjectMember;
};
/// \internal
/// The RPC identifier, and a pointer to the function
struct LocalRPCFunction
{
RPCIdentifier identifier;
void *functionPtr;
char parameterCount;
};
/// \internal
/// The RPC identifier, and the index of the function on a remote system
struct RemoteRPCFunction
{
RPCIdentifier identifier;
unsigned int functionIndex;
};
/// \internal
static int RemoteRPCFunctionComp( const RPCIdentifier &key, const RemoteRPCFunction &data );
/// \internal
/// Sends the RPC call, with a given serialized stack
bool SendCall(const char *uniqueIdentifier, const char *stack, unsigned int bytesOnStack, char parameterCount);
protected:
// --------------------------------------------------------------------------------------------
// Packet handling functions
// --------------------------------------------------------------------------------------------
void OnAttach(void);
virtual PluginReceiveResult OnReceive(Packet *packet);
virtual void OnAutoRPCCall(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes);
virtual void OnRPCRemoteIndex(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes);
virtual void OnRPCUnknownRemoteIndex(SystemAddress systemAddress, unsigned char *data, unsigned int lengthInBytes, RakNetTime timestamp);
virtual void OnClosedConnection(SystemAddress systemAddress, RakNetGUID rakNetGUID, PI2_LostConnectionReason lostConnectionReason );
virtual void OnShutdown(void);
void Clear(void);
void SendError(SystemAddress target, unsigned char errorCode, const char *functionName);
unsigned GetLocalFunctionIndex(RPCIdentifier identifier);
bool GetRemoteFunctionIndex(SystemAddress systemAddress, RPCIdentifier identifier, unsigned int *outerIndex, unsigned int *innerIndex);
DataStructures::List<LocalRPCFunction> localFunctions;
DataStructures::Map<SystemAddress, DataStructures::OrderedList<RPCIdentifier, RemoteRPCFunction, AutoRPC::RemoteRPCFunctionComp> *> remoteFunctions;
RakNetTime outgoingTimestamp;
PacketPriority outgoingPriority;
PacketReliability outgoingReliability;
char outgoingOrderingChannel;
SystemAddress outgoingSystemAddress;
bool outgoingBroadcast;
NetworkID outgoingNetworkID;
RakNet::BitStream outgoingExtraData;
RakNetTime incomingTimeStamp;
SystemAddress incomingSystemAddress;
RakNet::BitStream incomingExtraData;
NetworkIDManager *networkIdManager;
char currentExecution[512];
};
} // End namespace
#endif
#ifdef _MSC_VER
#pragma warning( pop )
#endif
| [
"[email protected]@aefdbfa2-c794-11de-8410-e5b1e99fc78e"
]
| [
[
[
1,
663
]
]
]
|
209c6d5bfc9b535c6123fa109ef997d937af723c | ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc | /computer_graphics/lab5/Src/Application/light.cpp | dcda03be29f297edf3c6d3e18edb734129267387 | []
| no_license | smi13/semester07 | 6789be72d74d8d502f0a0d919dca07ad5cbaed0d | 4d1079a446269646e1a0e3fe12e8c5e74c9bb409 | refs/heads/master | 2021-01-25T09:53:45.424234 | 2011-01-07T16:08:11 | 2011-01-07T16:08:11 | 859,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,703 | cpp | #include <d3dx9.h>
#include "light.h"
#include "render_context.h"
using namespace cg_labs;
Light::Light( const char *name, D3DLIGHTTYPE type ) :
_type(type), _name(std::string(name)), _id(getLightCounter())
{
}
std::string &Light::getName()
{
return _name;
}
int Light::getType()
{
return _type;
}
void Light::toggle()
{
if (_enabled)
{
_enabled = false;
/*if (_obj != 0)
;_obj->setColor(D3DCOLOR_XRGB(0, 0, 0));*/
}
else
{
_enabled = true;
/*if (_obj != 0)
_obj->setColor((DWORD)_col);*/
}
}
Light::~Light()
{
}
PointLight::PointLight( const char *name, D3DXVECTOR3 &pos, D3DXCOLOR col ) :
Light(name, D3DLIGHT_POINT), _pos(pos)
{
_col = col;
}
void PointLight::set()
{
D3DLIGHT9 light;
ZeroMemory(&light, sizeof(D3DLIGHT9));
light.Type = _type;
light.Attenuation0 = 0.02f;
light.Attenuation1 = 0.000f;//0.001f;
light.Attenuation2 = 0.0001f;//0.001f;
light.Range = 1000.0f;
light.Position = _pos;
light.Diffuse = D3DXCOLOR(16.7f, 16.7f, 16.7f, 0.0f);
light.Ambient = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.0f);
light.Specular = D3DXCOLOR(0.3f, 0.3f, 0.3f, 1.0f);
getDevice()->SetLight(_id, &light);
getDevice()->LightEnable(_id, _enabled);
}
DirectionalLight::DirectionalLight( const char *name,
D3DXVECTOR3 &dir, D3DXCOLOR col ) :
Light(name, D3DLIGHT_DIRECTIONAL), _dir(dir)
{
D3DXVec3Normalize(&_dir, &_dir);
_col = col;
}
void DirectionalLight::set()
{
D3DLIGHT9 light;
ZeroMemory(&light, sizeof(D3DLIGHT9));
light.Type = _type;
light.Attenuation0 = 0.05f;
light.Attenuation1 = 0.001f;
light.Attenuation2 = 0.001f;
light.Range = 100.0f;
light.Direction = _dir;
light.Diffuse = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
light.Ambient = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
light.Specular = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
getDevice()->SetLight(_id, &light);
getDevice()->LightEnable(_id, _enabled);
}
SpotLight::SpotLight( const char *name, D3DXVECTOR3 &pos, D3DXVECTOR3 &dir,
float theta, float phi, D3DXCOLOR col ) :
Light(name, D3DLIGHT_SPOT), _dir(dir), _pos(pos), _theta(theta), _phi(phi)
{
D3DXVec3Normalize(&_dir, &_dir);
_col = col;
}
void SpotLight::rotateX( float angle )
{
}
void SpotLight::rotateY( float angle )
{
D3DXMATRIX rot;
D3DXMatrixRotationY(&rot, angle);
D3DXVECTOR4 tmp;
D3DXVec3Transform(&tmp, &_pos, &rot);
_pos.x = tmp.x;
_pos.y = tmp.y;
_pos.z = tmp.z;
}
void SpotLight::rotateZ( float angle )
{
D3DXMATRIX rot;
D3DXMatrixRotationZ(&rot, angle);
D3DXVECTOR4 tmp;
D3DXVec3Transform(&tmp, &_dir, &rot);
_dir.x = tmp.x;
_dir.y = tmp.y;
_dir.z = tmp.z;
}
void SpotLight::translate( float x, float y, float z )
{
_pos += D3DXVECTOR3(x, y, z);
}
void SpotLight::set()
{
D3DLIGHT9 light;
ZeroMemory(&light, sizeof(D3DLIGHT9));
light.Type = _type;
light.Attenuation0 = 0.1f;
//light.Attenuation1 = 0.001f;//0.001f;
//light.Attenuation2 = 0.001f;//0.001f;
light.Range = 50.0f;
light.Direction = _dir;
light.Position = _pos;
/*light.Diffuse = D3DXCOLOR(1.7f, 1.7f, 1.7f, 1.0f);
light.Ambient = D3DXCOLOR(1.7f, 1.7f, 1.7f, 1.0f);
light.Specular = D3DXCOLOR(1.7f, 1.7f, 1.7f, 1.0f);*/
light.Diffuse = _col;
light.Theta = _theta;
light.Phi = _phi;
light.Falloff = 2.5f;
getDevice()->SetLight(_id, &light);
getDevice()->LightEnable(_id, _enabled);
} | [
"[email protected]"
]
| [
[
[
1,
169
]
]
]
|
6294052914a9b66672a95d1be00b7fad1b05b385 | 3eb83d1b36fb5ada2c7bcd35607f1ead259e283f | /DS/Projects/C3DSprites/include/Blob.h | c366a1469d41f03de2499b0b15f5a7a47fc36aea | []
| no_license | mickvangelderen/uwars | 2235b8883649843ed9dc2dca34260649132aa306 | 2cc4f6380f5046afa533b6a898b5513c1ab43af6 | refs/heads/master | 2021-01-01T18:18:44.665224 | 2010-03-23T15:43:17 | 2010-03-23T15:43:17 | 32,515,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | h | #pragma once
#include <PA9.h>
#include "Cell.h"
#include "C3DSpriteData.h"
#include "Team.h"
#define MAX_BLOBS 128
enum BLOB_STATE{
INACTIVE,
CREATION,
TRAVEL,
COLLISION,
DESTINATION
};
class Blob{
private:
static C3DSpriteData s_spriteData;
s32 m_x, m_y;
u16 m_str;
u16 m_radius;
Cell * m_target;
u32 m_velocity;
s16 m_vx;
s16 m_vy;
TEAM m_team;
BLOB_STATE m_state;
u8 m_id;
void UpdateVelocity();
public:
Blob();
~Blob();
void Set(s32 x, s32 y, TEAM team, Cell * const target, u16 velocity, u16 str, BLOB_STATE state);
static void CreateSpriteData(void * sprite, void * palette, u16 width, u16 height, u8 textureType);
static void DestroySpriteData();
s32 X()const;
s32 Y()const;
u16 SpriteId()const;
u32 Strength()const;
u32 Velocity()const;
u16 Radius()const;
TEAM Team()const;
BLOB_STATE State()const;
void SetStrength(u32 str);
void SetXY(s32 x, s32 y);
void SetTeam(TEAM team);
void SetVelocity(u32 velocity);
void Reset();
void Update();
};
| [
"mickfreeze@097d8bfe-0ac2-11df-beaf-bb271b2086c6"
]
| [
[
[
1,
60
]
]
]
|
7f14000628aac1511270716c3a911de2ce48a98a | 1eb0e6d7119d33fa76bdad32363483d0c9ace9b2 | /PointCloud/trunk/PointCloud/ANN/kd_util.cpp | 8fa321cc7b11ca543fa6a8b61b63e0b5c5cd2725 | []
| no_license | kbdacaa/point-clouds-mesh | 90f174a534eddb373a1ac6f5481ee7a80b05f806 | 73b6bc17aa5c597192ace1a3356bff4880ca062f | refs/heads/master | 2016-09-08T00:22:30.593144 | 2011-06-04T01:54:24 | 2011-06-04T01:54:24 | 41,203,780 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 15,531 | cpp | #include "stdafx.h"
//----------------------------------------------------------------------
// File: kd_util.cpp
// Programmer: Sunil Arya and David Mount
// Description: Common utilities for kd-trees
// Last modified: 01/04/05 (Version 1.0)
//----------------------------------------------------------------------
// Copyright (c) 1997-2005 University of Maryland and Sunil Arya and
// David Mount. All Rights Reserved.
//
// This software and related documentation is part of the Approximate
// Nearest Neighbor Library (ANN). This software is provided under
// the provisions of the Lesser GNU Public License (LGPL). See the
// file ../ReadMe.txt for further information.
//
// The University of Maryland (U.M.) and the authors make no
// representations about the suitability or fitness of this software for
// any purpose. It is provided "as is" without express or implied
// warranty.
//----------------------------------------------------------------------
// History:
// Revision 0.1 03/04/98
// Initial release
//----------------------------------------------------------------------
#include "kd_util.h" // kd-utility declarations
#include "ANNperf.h" // performance evaluation
//----------------------------------------------------------------------
// The following routines are utility functions for manipulating
// points sets, used in determining splitting planes for kd-tree
// construction.
//----------------------------------------------------------------------
//----------------------------------------------------------------------
// NOTE: Virtually all point indexing is done through an index (i.e.
// permutation) array pidx. Consequently, a reference to the d-th
// coordinate of the i-th point is pa[pidx[i]][d]. The macro PA(i,d)
// is a shorthand for this.
//----------------------------------------------------------------------
// standard 2-d indirect indexing
#define PA(i,d) (pa[pidx[(i)]][(d)])
// accessing a single point
#define PP(i) (pa[pidx[(i)]])
//----------------------------------------------------------------------
// annAspectRatio
// Compute the aspect ratio (ratio of longest to shortest side)
// of a rectangle.
//----------------------------------------------------------------------
double annAspectRatio(
int dim, // dimension
const ANNorthRect &bnd_box) // bounding cube
{
ANNcoord length = bnd_box.hi[0] - bnd_box.lo[0];
ANNcoord min_length = length; // min side length
ANNcoord max_length = length; // max side length
for (int d = 0; d < dim; d++) {
length = bnd_box.hi[d] - bnd_box.lo[d];
if (length < min_length) min_length = length;
if (length > max_length) max_length = length;
}
return max_length/min_length;
}
//----------------------------------------------------------------------
// annEnclRect, annEnclCube
// These utilities compute the smallest rectangle and cube enclosing
// a set of points, respectively.
//----------------------------------------------------------------------
void annEnclRect(
ANNpointArray pa, // point array
ANNidxArray pidx, // point indices
int n, // number of points
int dim, // dimension
ANNorthRect &bnds) // bounding cube (returned)
{
for (int d = 0; d < dim; d++) { // find smallest enclosing rectangle
ANNcoord lo_bnd = PA(0,d); // lower bound on dimension d
ANNcoord hi_bnd = PA(0,d); // upper bound on dimension d
for (int i = 0; i < n; i++) {
if (PA(i,d) < lo_bnd) lo_bnd = PA(i,d);
else if (PA(i,d) > hi_bnd) hi_bnd = PA(i,d);
}
bnds.lo[d] = lo_bnd;
bnds.hi[d] = hi_bnd;
}
}
void annEnclCube( // compute smallest enclosing cube
ANNpointArray pa, // point array
ANNidxArray pidx, // point indices
int n, // number of points
int dim, // dimension
ANNorthRect &bnds) // bounding cube (returned)
{
int d;
// compute smallest enclosing rect
annEnclRect(pa, pidx, n, dim, bnds);
ANNcoord max_len = 0; // max length of any side
for (d = 0; d < dim; d++) { // determine max side length
ANNcoord len = bnds.hi[d] - bnds.lo[d];
if (len > max_len) { // update max_len if longest
max_len = len;
}
}
for (d = 0; d < dim; d++) { // grow sides to match max
ANNcoord len = bnds.hi[d] - bnds.lo[d];
ANNcoord half_diff = (max_len - len) / 2;
bnds.lo[d] -= half_diff;
bnds.hi[d] += half_diff;
}
}
//----------------------------------------------------------------------
// annBoxDistance - utility routine which computes distance from point to
// box (Note: most distances to boxes are computed using incremental
// distance updates, not this function.)
//----------------------------------------------------------------------
ANNdist annBoxDistance( // compute distance from point to box
const ANNpoint q, // the point
const ANNpoint lo, // low point of box
const ANNpoint hi, // high point of box
int dim) // dimension of space
{
register ANNdist dist = 0.0; // sum of squared distances
register ANNdist t;
for (register int d = 0; d < dim; d++) {
if (q[d] < lo[d]) { // q is left of box
t = ANNdist(lo[d]) - ANNdist(q[d]);
dist = ANN_SUM(dist, ANN_POW(t));
}
else if (q[d] > hi[d]) { // q is right of box
t = ANNdist(q[d]) - ANNdist(hi[d]);
dist = ANN_SUM(dist, ANN_POW(t));
}
}
ANN_FLOP(4*dim) // increment floating op count
return dist;
}
//----------------------------------------------------------------------
// annSpread - find spread along given dimension
// annMinMax - find min and max coordinates along given dimension
// annMaxSpread - find dimension of max spread
//----------------------------------------------------------------------
ANNcoord annSpread( // compute point spread along dimension
ANNpointArray pa, // point array
ANNidxArray pidx, // point indices
int n, // number of points
int d) // dimension to check
{
ANNcoord min = PA(0,d); // compute max and min coords
ANNcoord max = PA(0,d);
for (int i = 1; i < n; i++) {
ANNcoord c = PA(i,d);
if (c < min) min = c;
else if (c > max) max = c;
}
return (max - min); // total spread is difference
}
void annMinMax( // compute min and max coordinates along dim
ANNpointArray pa, // point array
ANNidxArray pidx, // point indices
int n, // number of points
int d, // dimension to check
ANNcoord &min, // minimum value (returned)
ANNcoord &max) // maximum value (returned)
{
min = PA(0,d); // compute max and min coords
max = PA(0,d);
for (int i = 1; i < n; i++) {
ANNcoord c = PA(i,d);
if (c < min) min = c;
else if (c > max) max = c;
}
}
int annMaxSpread( // compute dimension of max spread
ANNpointArray pa, // point array
ANNidxArray pidx, // point indices
int n, // number of points
int dim) // dimension of space
{
int max_dim = 0; // dimension of max spread
ANNcoord max_spr = 0; // amount of max spread
if (n == 0) return max_dim; // no points, who cares?
for (int d = 0; d < dim; d++) { // compute spread along each dim
ANNcoord spr = annSpread(pa, pidx, n, d);
if (spr > max_spr) { // bigger than current max
max_spr = spr;
max_dim = d;
}
}
return max_dim;
}
//----------------------------------------------------------------------
// annMedianSplit - split point array about its median
// Splits a subarray of points pa[0..n] about an element of given
// rank (median: n_lo = n/2) with respect to dimension d. It places
// the element of rank n_lo-1 correctly (because our splitting rule
// takes the mean of these two). On exit, the array is permuted so
// that:
//
// pa[0..n_lo-2][d] <= pa[n_lo-1][d] <= pa[n_lo][d] <= pa[n_lo+1..n-1][d].
//
// The mean of pa[n_lo-1][d] and pa[n_lo][d] is returned as the
// splitting value.
//
// All indexing is done indirectly through the index array pidx.
//
// This function uses the well known selection algorithm due to
// C.A.R. Hoare.
//----------------------------------------------------------------------
// swap two points in pa array
#define PASWAP(a,b) { int tmp = pidx[a]; pidx[a] = pidx[b]; pidx[b] = tmp; }
void annMedianSplit(
ANNpointArray pa, // points to split
ANNidxArray pidx, // point indices
int n, // number of points
int d, // dimension along which to split
ANNcoord &cv, // cutting value
int n_lo) // split into n_lo and n-n_lo
{
int l = 0; // left end of current subarray
int r = n-1; // right end of current subarray
while (l < r) {
register int i = (r+l)/2; // select middle as pivot
register int k;
if (PA(i,d) > PA(r,d)) // make sure last > pivot
PASWAP(i,r)
PASWAP(l,i); // move pivot to first position
ANNcoord c = PA(l,d); // pivot value
i = l;
k = r;
for(;;) { // pivot about c
while (PA(++i,d) < c) ;
while (PA(--k,d) > c) ;
if (i < k) PASWAP(i,k) else break;
}
PASWAP(l,k); // pivot winds up in location k
if (k > n_lo) r = k-1; // recurse on proper subarray
else if (k < n_lo) l = k+1;
else break; // got the median exactly
}
if (n_lo > 0) { // search for next smaller item
ANNcoord c = PA(0,d); // candidate for max
int k = 0; // candidate's index
for (int i = 1; i < n_lo; i++) {
if (PA(i,d) > c) {
c = PA(i,d);
k = i;
}
}
PASWAP(n_lo-1, k); // max among pa[0..n_lo-1] to pa[n_lo-1]
}
// cut value is midpoint value
cv = (PA(n_lo-1,d) + PA(n_lo,d))/2.0;
}
//----------------------------------------------------------------------
// annPlaneSplit - split point array about a cutting plane
// Split the points in an array about a given plane along a
// given cutting dimension. On exit, br1 and br2 are set so
// that:
//
// pa[ 0 ..br1-1] < cv
// pa[br1..br2-1] == cv
// pa[br2.. n -1] > cv
//
// All indexing is done indirectly through the index array pidx.
//
//----------------------------------------------------------------------
void annPlaneSplit( // split points by a plane
ANNpointArray pa, // points to split
ANNidxArray pidx, // point indices
int n, // number of points
int d, // dimension along which to split
ANNcoord cv, // cutting value
int &br1, // first break (values < cv)
int &br2) // second break (values == cv)
{
int l = 0;
int r = n-1;
for(;;) { // partition pa[0..n-1] about cv
while (l < n && PA(l,d) < cv) l++;
while (r >= 0 && PA(r,d) >= cv) r--;
if (l > r) break;
PASWAP(l,r);
l++; r--;
}
br1 = l; // now: pa[0..br1-1] < cv <= pa[br1..n-1]
r = n-1;
for(;;) { // partition pa[br1..n-1] about cv
while (l < n && PA(l,d) <= cv) l++;
while (r >= br1 && PA(r,d) > cv) r--;
if (l > r) break;
PASWAP(l,r);
l++; r--;
}
br2 = l; // now: pa[br1..br2-1] == cv < pa[br2..n-1]
}
//----------------------------------------------------------------------
// annBoxSplit - split point array about a orthogonal rectangle
// Split the points in an array about a given orthogonal
// rectangle. On exit, n_in is set to the number of points
// that are inside (or on the boundary of) the rectangle.
//
// All indexing is done indirectly through the index array pidx.
//
//----------------------------------------------------------------------
void annBoxSplit( // split points by a box
ANNpointArray pa, // points to split
ANNidxArray pidx, // point indices
int n, // number of points
int dim, // dimension of space
ANNorthRect &box, // the box
int &n_in) // number of points inside (returned)
{
int l = 0;
int r = n-1;
for(;;) { // partition pa[0..n-1] about box
while (l < n && box.inside(dim, PP(l))) l++;
while (r >= 0 && !box.inside(dim, PP(r))) r--;
if (l > r) break;
PASWAP(l,r);
l++; r--;
}
n_in = l; // now: pa[0..n_in-1] inside and rest outside
}
//----------------------------------------------------------------------
// annSplitBalance - compute balance factor for a given plane split
// Balance factor is defined as the number of points lying
// below the splitting value minus n/2 (median). Thus, a
// median split has balance 0, left of this is negative and
// right of this is positive. (The points are unchanged.)
//----------------------------------------------------------------------
int annSplitBalance( // determine balance factor of a split
ANNpointArray pa, // points to split
ANNidxArray pidx, // point indices
int n, // number of points
int d, // dimension along which to split
ANNcoord cv) // cutting value
{
int n_lo = 0;
for(int i = 0; i < n; i++) { // count number less than cv
if (PA(i,d) < cv) n_lo++;
}
return n_lo - n/2;
}
//----------------------------------------------------------------------
// annBox2Bnds - convert bounding box to list of bounds
// Given two boxes, an inner box enclosed within a bounding
// box, this routine determines all the sides for which the
// inner box is strictly contained with the bounding box,
// and adds an appropriate entry to a list of bounds. Then
// we allocate storage for the final list of bounds, and return
// the resulting list and its size.
//----------------------------------------------------------------------
void annBox2Bnds( // convert inner box to bounds
const ANNorthRect &inner_box, // inner box
const ANNorthRect &bnd_box, // enclosing box
int dim, // dimension of space
int &n_bnds, // number of bounds (returned)
ANNorthHSArray &bnds) // bounds array (returned)
{
int i;
n_bnds = 0; // count number of bounds
for (i = 0; i < dim; i++) {
if (inner_box.lo[i] > bnd_box.lo[i]) // low bound is inside
n_bnds++;
if (inner_box.hi[i] < bnd_box.hi[i]) // high bound is inside
n_bnds++;
}
bnds = new ANNorthHalfSpace[n_bnds]; // allocate appropriate size
int j = 0;
for (i = 0; i < dim; i++) { // fill the array
if (inner_box.lo[i] > bnd_box.lo[i]) {
bnds[j].cd = i;
bnds[j].cv = inner_box.lo[i];
bnds[j].sd = +1;
j++;
}
if (inner_box.hi[i] < bnd_box.hi[i]) {
bnds[j].cd = i;
bnds[j].cv = inner_box.hi[i];
bnds[j].sd = -1;
j++;
}
}
}
//----------------------------------------------------------------------
// annBnds2Box - convert list of bounds to bounding box
// Given an enclosing box and a list of bounds, this routine
// computes the corresponding inner box. It is assumed that
// the box points have been allocated already.
//----------------------------------------------------------------------
void annBnds2Box(
const ANNorthRect &bnd_box, // enclosing box
int dim, // dimension of space
int n_bnds, // number of bounds
ANNorthHSArray bnds, // bounds array
ANNorthRect &inner_box) // inner box (returned)
{
annAssignRect(dim, inner_box, bnd_box); // copy bounding box to inner
for (int i = 0; i < n_bnds; i++) {
bnds[i].project(inner_box.lo); // project each endpoint
bnds[i].project(inner_box.hi);
}
}
| [
"huangchunkuangke@e87e5053-baee-b2b1-302d-3646b6e6cf75"
]
| [
[
[
1,
440
]
]
]
|
4d1f5547dbf1488c16d76d5f8f7ea30b85b7f370 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Math/WmlBandedMatrix.cpp | ae1ad6b40a5a886a35f5d12aa382526e0ab72a56 | []
| no_license | argapratama/kucgbowling | 20dbaefe1596358156691e81ccceb9151b15efb0 | 65e40b6f33c5511bddf0fa350c1eefc647ace48a | refs/heads/master | 2018-01-08T15:27:44.784437 | 2011-06-19T15:23:39 | 2011-06-19T15:23:39 | 36,738,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,539 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlBandedMatrix.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
BandedMatrix<Real>::BandedMatrix (int iSize, int iLBands, int iUBands)
{
assert( iSize > 0 && iLBands >= 0 && iUBands >= 0 );
assert( iLBands < iSize && iUBands < iSize );
m_iSize = iSize;
m_iLBands = iLBands;
m_iUBands = iUBands;
Allocate();
}
//----------------------------------------------------------------------------
template <class Real>
BandedMatrix<Real>::BandedMatrix (const BandedMatrix& rkM)
{
m_afDBand = 0;
m_aafLBand = 0;
m_aafUBand = 0;
*this = rkM;
}
//----------------------------------------------------------------------------
template <class Real>
BandedMatrix<Real>::~BandedMatrix ()
{
Deallocate();
}
//----------------------------------------------------------------------------
template <class Real>
BandedMatrix<Real>& BandedMatrix<Real>::operator= (const BandedMatrix& rkM)
{
Deallocate();
m_iSize = rkM.m_iSize;
m_iLBands = rkM.m_iLBands;
m_iUBands = rkM.m_iUBands;
Allocate();
memcpy(m_afDBand,rkM.m_afDBand,m_iSize*sizeof(Real));
int i;
for (i = 0; i < m_iLBands; i++)
memcpy(m_aafLBand[i],rkM.m_aafLBand[i],(m_iSize-1-i)*sizeof(Real));
for (i = 0; i < m_iUBands; i++)
memcpy(m_aafUBand[i],rkM.m_aafUBand[i],(m_iSize-1-i)*sizeof(Real));
return *this;
}
//----------------------------------------------------------------------------
template <class Real>
int BandedMatrix<Real>::GetSize () const
{
return m_iSize;
}
//----------------------------------------------------------------------------
template <class Real>
int BandedMatrix<Real>::GetLBands () const
{
return m_iLBands;
}
//----------------------------------------------------------------------------
template <class Real>
int BandedMatrix<Real>::GetUBands () const
{
return m_iUBands;
}
//----------------------------------------------------------------------------
template <class Real>
Real* BandedMatrix<Real>::GetDBand ()
{
return m_afDBand;
}
//----------------------------------------------------------------------------
template <class Real>
const Real* BandedMatrix<Real>::GetDBand () const
{
return m_afDBand;
}
//----------------------------------------------------------------------------
template <class Real>
int BandedMatrix<Real>::GetLBandMax (int i) const
{
assert( 0 <= i && i < m_iLBands );
return m_iSize-1-i;
}
//----------------------------------------------------------------------------
template <class Real>
Real* BandedMatrix<Real>::GetLBand (int i)
{
if ( m_aafLBand )
{
assert( 0 <= i && i < m_iLBands );
return m_aafLBand[i];
}
return 0;
}
//----------------------------------------------------------------------------
template <class Real>
const Real* BandedMatrix<Real>::GetLBand (int i) const
{
if ( m_aafLBand )
{
assert( 0 <= i && i < m_iLBands );
return m_aafLBand[i];
}
return 0;
}
//----------------------------------------------------------------------------
template <class Real>
int BandedMatrix<Real>::GetUBandMax (int i) const
{
assert( 0 <= i && i < m_iUBands );
return m_iSize-1-i;
}
//----------------------------------------------------------------------------
template <class Real>
Real* BandedMatrix<Real>::GetUBand (int i)
{
if ( m_aafUBand )
{
assert( 0 <= i && i < m_iUBands );
return m_aafUBand[i];
}
return 0;
}
//----------------------------------------------------------------------------
template <class Real>
const Real* BandedMatrix<Real>::GetUBand (int i) const
{
if ( m_aafUBand )
{
assert( 0 <= i && i < m_iUBands );
return m_aafUBand[i];
}
return 0;
}
//----------------------------------------------------------------------------
template <class Real>
Real& BandedMatrix<Real>::operator() (int iRow, int iCol)
{
assert( 0 <= iRow && iRow < m_iSize && 0 <= iCol && iCol < m_iSize );
int iBand = iCol - iRow;
if ( iBand > 0 )
{
if ( --iBand < m_iUBands && iRow < m_iSize-1-iBand )
return m_aafUBand[iBand][iRow];
}
else if ( iBand < 0 )
{
iBand = -iBand;
if ( --iBand < m_iLBands && iCol < m_iSize-1-iBand )
return m_aafLBand[iBand][iCol];
}
else
{
return m_afDBand[iRow];
}
static Real s_fDummy = (Real)0.0;
return s_fDummy;
}
//----------------------------------------------------------------------------
template <class Real>
Real BandedMatrix<Real>::operator() (int iRow, int iCol) const
{
assert( 0 <= iRow && iRow < m_iSize && 0 <= iCol && iCol < m_iSize );
int iBand = iCol - iRow;
if ( iBand > 0 )
{
if ( --iBand < m_iUBands && iRow < m_iSize-1-iBand )
return m_aafUBand[iBand][iRow];
}
else if ( iBand < 0 )
{
iBand = -iBand;
if ( --iBand < m_iLBands && iCol < m_iSize-1-iBand )
return m_aafLBand[iBand][iCol];
}
else
{
return m_afDBand[iRow];
}
return 0.0;
}
//----------------------------------------------------------------------------
template <class Real>
void BandedMatrix<Real>::SetZero ()
{
assert( m_iSize > 0 );
memset(m_afDBand,0,m_iSize*sizeof(Real));
int i;
for (i = 0; i < m_iLBands; i++)
memset(m_aafLBand[i],0,(m_iSize-1-i)*sizeof(Real));
for (i = 0; i < m_iUBands; i++)
memset(m_aafUBand[i],0,(m_iSize-1-i)*sizeof(Real));
}
//----------------------------------------------------------------------------
template <class Real>
void BandedMatrix<Real>::SetIdentity ()
{
assert( m_iSize > 0 );
int i;
for (i = 0; i < m_iSize; i++)
m_afDBand[i] = (Real)1.0;
for (i = 0; i < m_iLBands; i++)
memset(m_aafLBand[i],0,(m_iSize-1-i)*sizeof(Real));
for (i = 0; i < m_iUBands; i++)
memset(m_aafUBand[i],0,(m_iSize-1-i)*sizeof(Real));
}
//----------------------------------------------------------------------------
template <class Real>
void BandedMatrix<Real>::Allocate ()
{
// assert: m_iSize, m_iLBands, m_iRBandQuantity already set
// assert: m_afDBand, m_aafLBand, m_aafUBand all null
m_afDBand = new Real[m_iSize];
memset(m_afDBand,0,m_iSize*sizeof(Real));
if ( m_iLBands > 0 )
m_aafLBand = new Real*[m_iLBands];
else
m_aafLBand = 0;
if ( m_iUBands > 0 )
m_aafUBand = new Real*[m_iUBands];
else
m_aafUBand = 0;
int i;
for (i = 0; i < m_iLBands; i++)
{
m_aafLBand[i] = new Real[m_iSize-1-i];
memset(m_aafLBand[i],0,(m_iSize-1-i)*sizeof(Real));
}
for (i = 0; i < m_iUBands; i++)
{
m_aafUBand[i] = new Real[m_iSize-1-i];
memset(m_aafUBand[i],0,(m_iSize-1-i)*sizeof(Real));
}
}
//----------------------------------------------------------------------------
template <class Real>
void BandedMatrix<Real>::Deallocate ()
{
delete[] m_afDBand;
int i;
if ( m_aafLBand )
{
for (i = 0; i < m_iLBands; i++)
delete[] m_aafLBand[i];
delete[] m_aafLBand;
m_aafLBand = 0;
}
if ( m_aafUBand )
{
for (i = 0; i < m_iUBands; i++)
delete[] m_aafUBand[i];
delete[] m_aafUBand;
m_aafUBand = 0;
}
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template class WML_ITEM BandedMatrix<float>;
template class WML_ITEM BandedMatrix<double>;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
299
]
]
]
|
a87b681808a4e6a98d0f3d68c54e855b29c47b57 | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/server/ai_basenpc.h | dd2c5c0dc95d1a349899f2f2abe8f239fc31a403 | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 116,108 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Base NPC character with AI
//
//=============================================================================//
#ifndef AI_BASENPC_H
#define AI_BASENPC_H
#ifdef _WIN32
#pragma once
#endif
#include "simtimer.h"
#include "basecombatcharacter.h"
#include "ai_debug.h"
#include "ai_default.h"
#include "ai_schedule.h"
#include "ai_condition.h"
#include "ai_component.h"
#include "ai_task.h"
#include "ai_movetypes.h"
#include "ai_navtype.h"
#include "ai_namespaces.h"
#include "ai_npcstate.h"
#include "ai_hull.h"
#include "ai_utils.h"
#include "ai_moveshoot.h"
#include "entityoutput.h"
#include "utlvector.h"
#include "activitylist.h"
#include "bitstring.h"
#include "ai_basenpc.h"
#include "ai_navgoaltype.h" //GoalType_t enum
#include "eventlist.h"
#include "soundent.h"
#include "ai_navigator.h"
#include "tier1/functors.h"
#define PLAYER_SQUADNAME "player_squad"
class CAI_Schedule;
class CAI_Network;
class CAI_Route;
class CAI_Hint;
class CAI_Node;
class CAI_Navigator;
class CAI_Pathfinder;
class CAI_Senses;
class CAI_Enemies;
class CAI_Squad;
class CAI_Expresser;
class CAI_BehaviorBase;
class CAI_GoalEntity;
class CAI_Motor;
class CAI_MoveProbe;
class CAI_LocalNavigator;
class CAI_TacticalServices;
class CVarBitVec;
class CAI_ScriptedSequence;
class CSceneEntity;
class CBaseGrenade;
class CBaseDoor;
class CBasePropDoor;
struct AI_Waypoint_t;
class AI_Response;
class CBaseFilter;
//////
// SO2 - James
// Add NPC lag compensation
// http://developer.valvesoftware.com/wiki/NPC_Lag_Compensation
#define MAX_LAYER_RECORDS (CBaseAnimatingOverlay::MAX_OVERLAYS)
struct LayerRecordNPC
{
int m_sequence;
float m_cycle;
float m_weight;
int m_order;
LayerRecordNPC()
{
m_sequence = 0;
m_cycle = 0;
m_weight = 0;
m_order = 0;
}
LayerRecordNPC( const LayerRecordNPC& src )
{
m_sequence = src.m_sequence;
m_cycle = src.m_cycle;
m_weight = src.m_weight;
m_order = src.m_order;
}
};
struct LagRecordNPC
{
public:
LagRecordNPC()
{
m_fFlags = 0;
m_vecOrigin.Init();
m_vecAngles.Init();
m_vecMins.Init();
m_vecMaxs.Init();
m_flSimulationTime = -1;
m_masterSequence = 0;
m_masterCycle = 0;
}
LagRecordNPC( const LagRecordNPC& src )
{
m_fFlags = src.m_fFlags;
m_vecOrigin = src.m_vecOrigin;
m_vecAngles = src.m_vecAngles;
m_vecMins = src.m_vecMins;
m_vecMaxs = src.m_vecMaxs;
m_flSimulationTime = src.m_flSimulationTime;
for( int layerIndex = 0; layerIndex < MAX_LAYER_RECORDS; ++layerIndex )
{
m_layerRecords[layerIndex] = src.m_layerRecords[layerIndex];
}
m_masterSequence = src.m_masterSequence;
m_masterCycle = src.m_masterCycle;
}
// Did player die this frame
int m_fFlags;
// Player position, orientation and bbox
Vector m_vecOrigin;
QAngle m_vecAngles;
Vector m_vecMins;
Vector m_vecMaxs;
float m_flSimulationTime;
// Player animation details, so we can get the legs in the right spot.
LayerRecordNPC m_layerRecords[MAX_LAYER_RECORDS];
int m_masterSequence;
float m_masterCycle;
};
//////
typedef CBitVec<MAX_CONDITIONS> CAI_ScheduleBits;
// Used to control optimizations mostly dealing with pathfinding for NPCs
extern ConVar ai_strong_optimizations;
extern bool AIStrongOpt( void );
// AI_MONITOR_FOR_OSCILLATION defaults to OFF. If you build with this ON, you can flag
// NPC's and monitor them to detect oscillations in their schedule (circular logic and conditions bugs)
// DO NOT SHIP WITH THIS ON!
#undef AI_MONITOR_FOR_OSCILLATION
//=============================================================================
//
// Constants & enumerations
//
//=============================================================================
#define TURRET_CLOSE_RANGE 200
#define TURRET_MEDIUM_RANGE 500
#define COMMAND_GOAL_TOLERANCE 48 // 48 inches.
#define TIME_CARE_ABOUT_DAMAGE 3.0
#define ITEM_PICKUP_TOLERANCE 48.0f
// Max's of the box used to search for a weapon to pick up. 45x45x~8 ft.
#define WEAPON_SEARCH_DELTA Vector( 540, 540, 100 )
enum Interruptability_t
{
GENERAL_INTERRUPTABILITY,
DAMAGEORDEATH_INTERRUPTABILITY,
DEATH_INTERRUPTABILITY
};
//-------------------------------------
// Memory
//-------------------------------------
#define MEMORY_CLEAR 0
#define bits_MEMORY_PROVOKED ( 1 << 0 )// right now only used for houndeyes.
#define bits_MEMORY_INCOVER ( 1 << 1 )// npc knows it is in a covered position.
#define bits_MEMORY_SUSPICIOUS ( 1 << 2 )// Ally is suspicious of the player, and will move to provoked more easily
#define bits_MEMORY_TASK_EXPENSIVE ( 1 << 3 )// NPC has completed a task which is considered costly, so don't do another task this frame
//#define bits_MEMORY_ ( 1 << 4 )
#define bits_MEMORY_PATH_FAILED ( 1 << 5 )// Failed to find a path
#define bits_MEMORY_FLINCHED ( 1 << 6 )// Has already flinched
//#define bits_MEMORY_ ( 1 << 7 )
#define bits_MEMORY_TOURGUIDE ( 1 << 8 )// I have been acting as a tourguide.
//#define bits_MEMORY_ ( 1 << 9 )//
#define bits_MEMORY_LOCKED_HINT ( 1 << 10 )//
//#define bits_MEMORY_ ( 1 << 12 )
#define bits_MEMORY_TURNING ( 1 << 13 )// Turning, don't interrupt me.
#define bits_MEMORY_TURNHACK ( 1 << 14 )
#define bits_MEMORY_HAD_ENEMY ( 1 << 15 )// Had an enemy
#define bits_MEMORY_HAD_PLAYER ( 1 << 16 )// Had player
#define bits_MEMORY_HAD_LOS ( 1 << 17 )// Had LOS to enemy
#define bits_MEMORY_MOVED_FROM_SPAWN ( 1 << 18 )// Has moved since spawning.
#define bits_MEMORY_CUSTOM4 ( 1 << 28 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM3 ( 1 << 29 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM2 ( 1 << 30 ) // NPC-specific memory
#define bits_MEMORY_CUSTOM1 ( 1 << 31 ) // NPC-specific memory
//-------------------------------------
// Spawn flags
//-------------------------------------
#define SF_NPC_WAIT_TILL_SEEN ( 1 << 0 ) // spawnflag that makes npcs wait until player can see them before attacking.
#define SF_NPC_GAG ( 1 << 1 ) // no idle noises from this npc
#define SF_NPC_FALL_TO_GROUND ( 1 << 2 ) // used my NPC_Maker
#define SF_NPC_DROP_HEALTHKIT ( 1 << 3 ) // Drop a healthkit upon death
#define SF_NPC_START_EFFICIENT ( 1 << 4 ) // Set into efficiency mode from spawn
// ( 1 << 5 )
// ( 1 << 6 )
#define SF_NPC_WAIT_FOR_SCRIPT ( 1 << 7 ) // spawnflag that makes npcs wait to check for attacking until the script is done or they've been attacked
#define SF_NPC_LONG_RANGE ( 1 << 8 ) // makes npcs look far and relaxes weapon range limit
#define SF_NPC_FADE_CORPSE ( 1 << 9 ) // Fade out corpse after death
#define SF_NPC_ALWAYSTHINK ( 1 << 10 ) // Simulate even when player isn't in PVS.
#define SF_NPC_TEMPLATE ( 1 << 11 ) // This NPC will be used as a template by an npc_maker -- do not spawn.
#define SF_NPC_ALTCOLLISION ( 1 << 12 )
#define SF_NPC_NO_WEAPON_DROP ( 1 << 13 ) // This NPC will not actually drop a weapon that can be picked up
#define SF_NPC_NO_PLAYER_PUSHAWAY ( 1 << 14 )
// ( 1 << 15 )
// !! Flags above ( 1 << 15 ) are reserved for NPC sub-classes
//-------------------------------------
//
// Return codes from CanPlaySequence.
//
//-------------------------------------
enum CanPlaySequence_t
{
CANNOT_PLAY = 0, // Can't play for any number of reasons.
CAN_PLAY_NOW, // Can play the script immediately.
CAN_PLAY_ENQUEUED, // Can play the script after I finish playing my current script.
};
//-------------------------------------
// Weapon holstering
//-------------------------------------
enum DesiredWeaponState_t
{
DESIREDWEAPONSTATE_IGNORE = 0,
DESIREDWEAPONSTATE_HOLSTERED,
DESIREDWEAPONSTATE_HOLSTERED_DESTROYED, // Put the weapon away, then destroy it.
DESIREDWEAPONSTATE_UNHOLSTERED,
DESIREDWEAPONSTATE_CHANGING,
DESIREDWEAPONSTATE_CHANGING_DESTROY, // Destroy the weapon when this change is complete.
};
//-------------------------------------
//
// Efficiency modes
//
//-------------------------------------
enum AI_Efficiency_t
{
// Run at full tilt
AIE_NORMAL,
// Run decision process less often
AIE_EFFICIENT,
// Run decision process even less often, ignore other NPCs
AIE_VERY_EFFICIENT,
// Run decision process even less often, ignore other NPCs
AIE_SUPER_EFFICIENT,
// Don't run at all
AIE_DORMANT,
};
enum AI_MoveEfficiency_t
{
AIME_NORMAL,
AIME_EFFICIENT,
};
//-------------------------------------
//
// Sleep state
//
//-------------------------------------
enum AI_SleepState_t
{
AISS_AWAKE,
AISS_WAITING_FOR_THREAT,
AISS_WAITING_FOR_PVS,
AISS_WAITING_FOR_INPUT,
AISS_AUTO_PVS,
AISS_AUTO_PVS_AFTER_PVS, // Same as AUTO_PVS, except doesn't activate until/unless the NPC is IN the player's PVS.
};
#define AI_SLEEP_FLAGS_NONE 0x00000000
#define AI_SLEEP_FLAG_AUTO_PVS 0x00000001
#define AI_SLEEP_FLAG_AUTO_PVS_AFTER_PVS 0x00000002
//-------------------------------------
//
// Debug bits
//
//-------------------------------------
enum DebugBaseNPCBits_e
{
bits_debugDisableAI = 0x00000001, // disable AI
bits_debugStepAI = 0x00000002, // step AI
};
//-------------------------------------
//
// Base Sentence index for behaviors
//
//-------------------------------------
enum SentenceIndex_t
{
SENTENCE_BASE_BEHAVIOR_INDEX = 1000,
};
#ifdef AI_MONITOR_FOR_OSCILLATION
struct AIScheduleChoice_t
{
float m_flTimeSelected;
CAI_Schedule *m_pScheduleSelected;
};
#endif//AI_MONITOR_FOR_OSCILLATION
#define MARK_TASK_EXPENSIVE() \
if ( GetOuter() ) \
{ \
GetOuter()->Remember( bits_MEMORY_TASK_EXPENSIVE ); \
}
//=============================================================================
//
// Types used by CAI_BaseNPC
//
//=============================================================================
struct AIScheduleState_t
{
int iCurTask;
TaskStatus_e fTaskStatus;
float timeStarted;
float timeCurTaskStarted;
AI_TaskFailureCode_t taskFailureCode;
int iTaskInterrupt;
bool bTaskRanAutomovement;
bool bTaskUpdatedYaw;
bool bScheduleWasInterrupted;
DECLARE_SIMPLE_DATADESC();
};
// -----------------------------------------
// An entity that this NPC can't reach
// -----------------------------------------
struct UnreachableEnt_t
{
EHANDLE hUnreachableEnt; // Entity that's unreachable
float fExpireTime; // Time to forget this information
Vector vLocationWhenUnreachable;
DECLARE_SIMPLE_DATADESC();
};
//=============================================================================
// SCRIPTED NPC INTERACTIONS
//=============================================================================
// -----------------------------------------
// Scripted NPC interaction flags
// -----------------------------------------
#define SCNPC_FLAG_TEST_OTHER_ANGLES ( 1 << 1 )
#define SCNPC_FLAG_TEST_OTHER_VELOCITY ( 1 << 2 )
#define SCNPC_FLAG_LOOP_IN_ACTION ( 1 << 3 )
#define SCNPC_FLAG_NEEDS_WEAPON_ME ( 1 << 4 )
#define SCNPC_FLAG_NEEDS_WEAPON_THEM ( 1 << 5 )
#define SCNPC_FLAG_DONT_TELEPORT_AT_END_ME ( 1 << 6 )
#define SCNPC_FLAG_DONT_TELEPORT_AT_END_THEM ( 1 << 7 )
// -----------------------------------------
// Scripted NPC interaction trigger methods
// -----------------------------------------
enum
{
SNPCINT_CODE = 0,
SNPCINT_AUTOMATIC_IN_COMBAT = 1,
};
// -----------------------------------------
// Scripted NPC interaction loop breaking trigger methods
// -----------------------------------------
#define SNPCINT_LOOPBREAK_ON_DAMAGE ( 1 << 1 )
#define SNPCINT_LOOPBREAK_ON_FLASHLIGHT_ILLUM ( 1 << 2 )
// -----------------------------------------
// Scripted NPC interaction anim phases
// -----------------------------------------
enum
{
SNPCINT_ENTRY = 0,
SNPCINT_SEQUENCE,
SNPCINT_EXIT,
SNPCINT_NUM_PHASES
};
struct ScriptedNPCInteraction_Phases_t
{
string_t iszSequence;
int iActivity;
DECLARE_SIMPLE_DATADESC();
};
// Allowable delta from the desired dynamic scripted sequence point
#define DSS_MAX_DIST 6
#define DSS_MAX_ANGLE_DIFF 4
// Interaction Logic States
enum
{
NPCINT_NOT_RUNNING = 0,
NPCINT_RUNNING_ACTIVE, // I'm in an interaction that I initiated
NPCINT_RUNNING_PARTNER, // I'm in an interaction that was initiated by the other NPC
NPCINT_MOVING_TO_MARK, // I'm moving to a position to do an interaction
};
#define NPCINT_NONE -1
#define MAXTACLAT_IGNORE -1
// -----------------------------------------
// A scripted interaction between NPCs
// -----------------------------------------
struct ScriptedNPCInteraction_t
{
ScriptedNPCInteraction_t()
{
iszInteractionName = NULL_STRING;
iFlags = 0;
iTriggerMethod = SNPCINT_CODE;
iLoopBreakTriggerMethod = 0;
vecRelativeOrigin = vec3_origin;
bValidOnCurrentEnemy = false;
flDelay = 5.0;
flDistSqr = (DSS_MAX_DIST * DSS_MAX_DIST);
flNextAttemptTime = 0;
iszMyWeapon = NULL_STRING;
iszTheirWeapon = NULL_STRING;
for ( int i = 0; i < SNPCINT_NUM_PHASES; i++)
{
sPhases[i].iszSequence = NULL_STRING;
sPhases[i].iActivity = ACT_INVALID;
}
}
// Fill out these when passing to AddScriptedNPCInteraction
string_t iszInteractionName;
int iFlags;
int iTriggerMethod;
int iLoopBreakTriggerMethod;
Vector vecRelativeOrigin; // (forward, right, up)
QAngle angRelativeAngles;
Vector vecRelativeVelocity; // Desired relative velocity of the other NPC
float flDelay; // Delay before interaction can be used again
float flDistSqr; // Max distance sqr from the relative origin the NPC is allowed to be to trigger
string_t iszMyWeapon; // Classname of the weapon I'm holding, if any
string_t iszTheirWeapon; // Classname of the weapon my interaction partner is holding, if any
ScriptedNPCInteraction_Phases_t sPhases[SNPCINT_NUM_PHASES];
// These will be filled out for you in AddScriptedNPCInteraction
VMatrix matDesiredLocalToWorld; // Desired relative position / angles of the other NPC
bool bValidOnCurrentEnemy;
float flNextAttemptTime;
DECLARE_SIMPLE_DATADESC();
};
//=============================================================================
//
// Utility functions
//
//=============================================================================
Vector VecCheckToss ( CBaseEntity *pEdict, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
Vector VecCheckToss ( CBaseEntity *pEntity, ITraceFilter *pFilter, Vector vecSpot1, Vector vecSpot2, float flHeightMaxRatio, float flGravityAdj, bool bRandomize, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
Vector VecCheckThrow( CBaseEntity *pEdict, const Vector &vecSpot1, Vector vecSpot2, float flSpeed, float flGravityAdj = 1.0f, Vector *vecMins = NULL, Vector *vecMaxs = NULL );
extern Vector g_vecAttackDir;
bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget );
bool FBoxVisible ( CBaseEntity *pLooker, CBaseEntity *pTarget, Vector &vecTargetOrigin, float flSize = 0.0 );
// FIXME: move to utils?
float DeltaV( float v0, float v1, float d );
float ChangeDistance( float flInterval, float flGoalDistance, float flGoalVelocity, float flCurVelocity, float flIdealVelocity, float flAccelRate, float &flNewDistance, float &flNewVelocity );
//=============================================================================
//
// class CAI_Manager
//
// Central location for components of the AI to operate across all AIs without
// iterating over the global list of entities.
//
//=============================================================================
class CAI_Manager
{
public:
CAI_Manager();
CAI_BaseNPC ** AccessAIs();
int NumAIs();
void AddAI( CAI_BaseNPC *pAI );
void RemoveAI( CAI_BaseNPC *pAI );
bool FindAI( CAI_BaseNPC *pAI ) { return ( m_AIs.Find( pAI ) != m_AIs.InvalidIndex() ); }
private:
enum
{
MAX_AIS = 256
};
typedef CUtlVector<CAI_BaseNPC *> CAIArray;
CAIArray m_AIs;
};
//-------------------------------------
extern CAI_Manager g_AI_Manager;
//=============================================================================
//
// class CAI_BaseNPC
//
//=============================================================================
class CAI_BaseNPC : public CBaseCombatCharacter,
public CAI_DefMovementSink
{
DECLARE_CLASS( CAI_BaseNPC, CBaseCombatCharacter );
public:
//-----------------------------------------------------
//
// Initialization, cleanup, serialization, identity
//
CAI_BaseNPC();
~CAI_BaseNPC();
//---------------------------------
DECLARE_DATADESC();
DECLARE_SERVERCLASS();
virtual int Save( ISave &save );
virtual int Restore( IRestore &restore );
virtual void OnRestore();
void SaveConditions( ISave &save, const CAI_ScheduleBits &conditions );
void RestoreConditions( IRestore &restore, CAI_ScheduleBits *pConditions );
bool ShouldSavePhysics() { return false; }
virtual unsigned int PhysicsSolidMaskForEntity( void ) const;
virtual bool KeyValue( const char *szKeyName, const char *szValue );
//---------------------------------
virtual void PostConstructor( const char *szClassname );
virtual void Activate( void );
virtual void Precache( void ); // derived calls at start of Spawn()
virtual bool CreateVPhysics();
virtual void NPCInit( void ); // derived calls after Spawn()
void NPCInitThink( void );
virtual void PostNPCInit() {};// called after NPC_InitThink
virtual void StartNPC( void );
virtual bool IsTemplate( void );
virtual void CleanupOnDeath( CBaseEntity *pCulprit = NULL, bool bFireDeathOutput = true );
virtual void UpdateOnRemove( void );
virtual int UpdateTransmitState();
//---------------------------------
// Component creation factories
//
// The master call, override if you introduce new component types. Call base first
virtual bool CreateComponents();
// Components defined by the base AI class
virtual CAI_Senses * CreateSenses();
virtual CAI_MoveProbe * CreateMoveProbe();
virtual CAI_Motor * CreateMotor();
virtual CAI_LocalNavigator *CreateLocalNavigator();
virtual CAI_Navigator * CreateNavigator();
virtual CAI_Pathfinder *CreatePathfinder();
virtual CAI_TacticalServices *CreateTacticalServices();
//---------------------------------
virtual bool IsNPC( void ) const { return true; }
//---------------------------------
void TestPlayerPushing( CBaseEntity *pPlayer );
void CascadePlayerPush( const Vector &push, const Vector &pushOrigin );
void NotifyPushMove();
public:
//-----------------------------------------------------
//
// AI processing - thinking, schedule selection and task running
//
//-----------------------------------------------------
void CallNPCThink( void );
// Thinking, including core thinking, movement, animation
virtual void NPCThink( void );
// Core thinking (schedules & tasks)
virtual void RunAI( void );// core ai function!
// Called to gather up all relevant conditons
virtual void GatherConditions( void );
// Called immediately prior to schedule processing
virtual void PrescheduleThink( void );
// Called immediately after schedule processing
virtual void PostscheduleThink( void ) { return; };
// Notification that the current schedule, if any, is ending and a new one is being selected
virtual void OnScheduleChange( void );
// Notification that a new schedule is about to run its first task
virtual void OnStartSchedule( int scheduleType ) {};
// This function implements a decision tree for the NPC. It is responsible for choosing the next behavior (schedule)
// based on the current conditions and state.
virtual int SelectSchedule( void );
virtual int SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode );
// After the schedule has been selected, it will be processed by this function so child NPC classes can
// remap base schedules into child-specific behaviors
virtual int TranslateSchedule( int scheduleType );
virtual void StartTask( const Task_t *pTask );
virtual void RunTask( const Task_t *pTask );
void ClearTransientConditions();
virtual void HandleAnimEvent( animevent_t *pEvent );
virtual bool IsInterruptable();
virtual void OnStartScene( void ) {} // Called when an NPC begins a cine scene (useful for clean-up)
virtual bool ShouldPlayerAvoid( void );
virtual void SetPlayerAvoidState( void );
virtual void PlayerPenetratingVPhysics( void );
virtual bool ShouldAlwaysThink();
void ForceGatherConditions() { m_bForceConditionsGather = true; SetEfficiency( AIE_NORMAL ); } // Force an NPC out of PVS to call GatherConditions on next think
virtual float LineOfSightDist( const Vector &vecDir = vec3_invalid, float zEye = FLT_MAX );
virtual void MakeTracer( const Vector &vecTracerSrc, const trace_t &tr, int iTracerType );
virtual const char *GetTracerType( void );
virtual void DoImpactEffect( trace_t &tr, int nDamageType );
enum
{
NEXT_SCHEDULE = LAST_SHARED_SCHEDULE,
NEXT_TASK = LAST_SHARED_TASK,
NEXT_CONDITION = LAST_SHARED_CONDITION,
};
//////
// SO2 - James
// Add NPC lag compensation
// http://developer.valvesoftware.com/wiki/NPC_Lag_Compensation
CUtlFixedLinkedList<LagRecordNPC>* GetLagTrack() { return m_LagTrack; }
LagRecordNPC* GetLagRestoreData() { if ( m_RestoreData != NULL ) return m_RestoreData; else return new LagRecordNPC(); }
LagRecordNPC* GetLagChangeData() { if ( m_ChangeData != NULL ) return m_ChangeData; else return new LagRecordNPC(); }
void SetLagRestoreData(LagRecordNPC* l) { if ( m_RestoreData != NULL ) delete m_RestoreData; m_RestoreData = l; }
void SetLagChangeData(LagRecordNPC* l) { if ( m_ChangeData != NULL ) delete m_ChangeData; m_ChangeData = l; }
void FlagForLagCompensation( bool tempValue ) { m_bFlaggedForLagCompensation = tempValue; }
bool IsLagFlagged() { return m_bFlaggedForLagCompensation; }
//////
protected:
// Used by derived classes to chain a task to a task that might not be the
// one they are currently handling:
void ChainStartTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; StartTask( (const Task_t *)&tempTask ); }
void ChainRunTask( int task, float taskData = 0 ) { Task_t tempTask = { task, taskData }; RunTask( (const Task_t *) &tempTask ); }
void StartTaskOverlay();
void RunTaskOverlay();
void EndTaskOverlay();
virtual void PostRunStopMoving();
bool CheckPVSCondition();
private:
bool CanThinkRebalance();
void RebalanceThinks();
bool PreNPCThink();
void PostNPCThink();
bool PreThink( void );
void PerformSensing();
void CheckOnGround( void );
void MaintainSchedule( void );
void RunAnimation( void );
void PostRun( void );
void PerformMovement();
void PostMovement();
virtual int StartTask ( Task_t *pTask ) { DevMsg( "Called wrong StartTask()\n" ); StartTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
virtual int RunTask ( Task_t *pTask ) { DevMsg( "Called wrong RunTask()\n" ); RunTask( (const Task_t *)pTask ); return 0; } // to ensure correct signature in derived classes
//////
// SO2 - James
// Add NPC lag compensation
// http://developer.valvesoftware.com/wiki/NPC_Lag_Compensation
CUtlFixedLinkedList<LagRecordNPC>* m_LagTrack;
LagRecordNPC* m_RestoreData;
LagRecordNPC* m_ChangeData;
bool m_bFlaggedForLagCompensation;
//////
public:
//-----------------------------------------------------
//
// Schedules & tasks
//
//-----------------------------------------------------
void SetSchedule( CAI_Schedule *pNewSchedule );
bool SetSchedule( int localScheduleID );
void SetDefaultFailSchedule( int failSchedule ) { m_failSchedule = failSchedule; }
void ClearSchedule( const char *szReason );
CAI_Schedule * GetCurSchedule() { return m_pSchedule; }
bool IsCurSchedule( int schedId, bool fIdeal = true );
virtual CAI_Schedule *GetSchedule(int localScheduleID);
virtual int GetLocalScheduleId( int globalScheduleID ) { return AI_IdIsLocal( globalScheduleID ) ? globalScheduleID : GetClassScheduleIdSpace()->ScheduleGlobalToLocal( globalScheduleID ); }
virtual int GetGlobalScheduleId( int localScheduleID ) { return AI_IdIsGlobal( localScheduleID ) ? localScheduleID : GetClassScheduleIdSpace()->ScheduleLocalToGlobal( localScheduleID ); }
float GetTimeScheduleStarted() const { return m_ScheduleState.timeStarted; }
//---------------------------------
const Task_t* GetTask( void );
int TaskIsRunning( void );
virtual void TaskFail( AI_TaskFailureCode_t );
void TaskFail( const char *pszGeneralFailText ) { TaskFail( MakeFailCode( pszGeneralFailText ) ); }
void TaskComplete( bool fIgnoreSetFailedCondition = false );
void TaskInterrupt() { m_ScheduleState.iTaskInterrupt++; }
void ClearTaskInterrupt() { m_ScheduleState.iTaskInterrupt = 0; }
int GetTaskInterrupt() const { return m_ScheduleState.iTaskInterrupt; }
void TaskMovementComplete( void );
inline int TaskIsComplete( void ) { return (GetTaskStatus() == TASKSTATUS_COMPLETE); }
virtual const char *TaskName(int taskID);
float GetTimeTaskStarted() const { return m_ScheduleState.timeCurTaskStarted; }
virtual int GetLocalTaskId( int globalTaskId) { return GetClassScheduleIdSpace()->TaskGlobalToLocal( globalTaskId ); }
virtual const char *GetSchedulingErrorName() { return "CAI_BaseNPC"; }
protected:
static bool LoadSchedules(void);
virtual bool LoadedSchedules(void);
virtual void BuildScheduleTestBits( void );
//---------------------------------
// This is the main call to select/translate a schedule
virtual CAI_Schedule *GetNewSchedule( void );
virtual CAI_Schedule *GetFailSchedule( void );
//---------------------------------
virtual bool CanFlinch( void );
virtual void CheckFlinches( void );
virtual void PlayFlinchGesture( void );
int SelectFlinchSchedule( void );
virtual bool IsAllowedToDodge( void );
bool IsInChoreo() const;
/////
// SO2 - James
// Improve zombies' perception of their surroundings
// http://developer.valvesoftware.com/wiki/AI_Perception_Behavior_Enhancement
// Moved from private to protected for access
// Made virtual for access purposes
virtual int SelectAlertSchedule();
/////
private:
// This function maps the type through TranslateSchedule() and then retrieves the pointer
// to the actual CAI_Schedule from the database of schedules available to this class.
CAI_Schedule * GetScheduleOfType( int scheduleType );
bool FHaveSchedule( void );
bool FScheduleDone ( void );
CAI_Schedule * ScheduleInList( const char *pName, CAI_Schedule **pList, int listCount );
int GetScheduleCurTaskIndex() const { return m_ScheduleState.iCurTask; }
inline int IncScheduleCurTaskIndex();
inline void ResetScheduleCurTaskIndex();
void NextScheduledTask ( void );
bool IsScheduleValid ( void );
bool ShouldSelectIdealState( void );
// Selecting the ideal state
NPC_STATE SelectIdleIdealState();
NPC_STATE SelectAlertIdealState();
NPC_STATE SelectScriptIdealState();
// Various schedule selections based on NPC_STATE
int SelectIdleSchedule();
/////
// SO2 - James
// Improve zombies' perception of their surroundings
// http://developer.valvesoftware.com/wiki/AI_Perception_Behavior_Enhancement
// Moved from private to protected for access
// Made virtual for access purposes
//int SelectAlertSchedule();
/////
int SelectCombatSchedule();
virtual int SelectDeadSchedule();
int SelectScriptSchedule();
int SelectInteractionSchedule();
void OnStartTask( void ) { SetTaskStatus( TASKSTATUS_RUN_MOVE_AND_TASK ); }
void SetTaskStatus( TaskStatus_e status ) { m_ScheduleState.fTaskStatus = status; }
TaskStatus_e GetTaskStatus() const { return m_ScheduleState.fTaskStatus; }
void DiscardScheduleState();
//---------------------------------
CAI_Schedule * m_pSchedule;
int m_IdealSchedule;
AIScheduleState_t m_ScheduleState;
int m_failSchedule; // Schedule type to choose if current schedule fails
bool m_bDoPostRestoreRefindPath;
bool m_bUsingStandardThinkTime;
float m_flLastRealThinkTime;
int m_iFrameBlocked;
bool m_bInChoreo;
static int gm_iNextThinkRebalanceTick;
static float gm_flTimeLastSpawn;
static int gm_nSpawnedThisFrame;
protected: // pose parameters
int m_poseAim_Pitch;
int m_poseAim_Yaw;
int m_poseMove_Yaw;
virtual void PopulatePoseParameters( void );
public:
inline bool HasPoseMoveYaw() { return ( m_poseMove_Yaw >= 0 ); }
// Return the stored pose parameter for "move_yaw"
inline int LookupPoseMoveYaw() { return m_poseMove_Yaw; }
//-----------------------------------------------------
//
// Hooks for CAI_Behaviors, *if* derived class supports them
//
//-----------------------------------------------------
template <class BEHAVIOR_TYPE>
bool GetBehavior( BEHAVIOR_TYPE **ppBehavior )
{
CAI_BehaviorBase **ppBehaviors = AccessBehaviors();
*ppBehavior = NULL;
for ( int i = 0; i < NumBehaviors(); i++ )
{
*ppBehavior = dynamic_cast<BEHAVIOR_TYPE *>(ppBehaviors[i]);
if ( *ppBehavior )
return true;
}
return false;
}
virtual CAI_BehaviorBase *GetRunningBehavior() { return NULL; }
virtual bool ShouldAcceptGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) { return true; }
virtual void OnClearGoal( CAI_BehaviorBase *pBehavior, CAI_GoalEntity *pGoal ) {}
// Notification that the status behavior ability to select schedules has changed.
// Return "true" to signal a schedule interrupt is desired
virtual bool OnBehaviorChangeStatus( CAI_BehaviorBase *pBehavior, bool fCanFinishSchedule ) { return false; }
private:
virtual CAI_BehaviorBase ** AccessBehaviors() { return NULL; }
virtual int NumBehaviors() { return 0; }
public:
//-----------------------------------------------------
//
// Conditions
//
//-----------------------------------------------------
virtual const char* ConditionName(int conditionID);
virtual void RemoveIgnoredConditions ( void );
void SetCondition( int iCondition /*, bool state = true*/ );
bool HasCondition( int iCondition );
bool HasCondition( int iCondition, bool bUseIgnoreConditions );
bool HasInterruptCondition( int iCondition );
bool HasConditionsToInterruptSchedule( int nLocalScheduleID );
void ClearCondition( int iCondition );
void ClearConditions( int *pConditions, int nConditions );
void SetIgnoreConditions( int *pConditions, int nConditions );
void ClearIgnoreConditions( int *pConditions, int nConditions );
bool ConditionInterruptsCurSchedule( int iCondition );
bool ConditionInterruptsSchedule( int schedule, int iCondition );
void SetCustomInterruptCondition( int nCondition );
bool IsCustomInterruptConditionSet( int nCondition );
void ClearCustomInterruptCondition( int nCondition );
void ClearCustomInterruptConditions( void );
bool ConditionsGathered() const { return m_bConditionsGathered; }
const CAI_ScheduleBits &AccessConditionBits() const { return m_Conditions; }
CAI_ScheduleBits & AccessConditionBits() { return m_Conditions; }
bool DidChooseEnemy() const { return !m_bSkippedChooseEnemy; }
private:
CAI_ScheduleBits m_Conditions;
CAI_ScheduleBits m_CustomInterruptConditions; //Bit string assembled by the schedule running, then
//modified by leaf classes to suit their needs
CAI_ScheduleBits m_ConditionsPreIgnore;
CAI_ScheduleBits m_InverseIgnoreConditions;
bool m_bForceConditionsGather;
bool m_bConditionsGathered;
bool m_bSkippedChooseEnemy;
public:
//-----------------------------------------------------
//
// NPC State
//
//-----------------------------------------------------
inline void SetIdealState( NPC_STATE eIdealState );
inline NPC_STATE GetIdealState();
virtual NPC_STATE SelectIdealState( void );
void SetState( NPC_STATE State );
virtual bool ShouldGoToIdleState( void ) { return ( false ); }
virtual void OnStateChange( NPC_STATE OldState, NPC_STATE NewState ) {/*Base class doesn't care*/};
NPC_STATE GetState( void ) { return m_NPCState; }
AI_Efficiency_t GetEfficiency() const { return m_Efficiency; }
void SetEfficiency( AI_Efficiency_t efficiency ) { m_Efficiency = efficiency; }
AI_MoveEfficiency_t GetMoveEfficiency() const { return m_MoveEfficiency; }
void SetMoveEfficiency( AI_MoveEfficiency_t efficiency ) { m_MoveEfficiency = efficiency; }
virtual void UpdateEfficiency( bool bInPVS );
void ForceDecisionThink() { m_flNextDecisionTime = 0; SetEfficiency( AIE_NORMAL ); }
bool IsFlaggedEfficient() const { return HasSpawnFlags( SF_NPC_START_EFFICIENT ); }
AI_SleepState_t GetSleepState() const { return m_SleepState; }
void SetSleepState( AI_SleepState_t sleepState ) { m_SleepState = sleepState; }
void AddSleepFlags( int flags ) { m_SleepFlags |= flags; }
void RemoveSleepFlags( int flags ) { m_SleepFlags &= ~flags; }
bool HasSleepFlags( int flags ) { return (m_SleepFlags & flags) == flags; }
void UpdateSleepState( bool bInPVS );
virtual void Wake( bool bFireOutput = true );
void Sleep();
bool WokeThisTick() const;
//---------------------------------
NPC_STATE m_NPCState; // npc's current state
float m_flLastStateChangeTime;
private:
NPC_STATE m_IdealNPCState; // npc should change to this state
AI_Efficiency_t m_Efficiency;
AI_MoveEfficiency_t m_MoveEfficiency;
float m_flNextDecisionTime;
AI_SleepState_t m_SleepState;
int m_SleepFlags;
float m_flWakeRadius;
bool m_bWakeSquad;
int m_nWakeTick;
public:
//-----------------------------------------------------
//
// Activities
//
//-----------------------------------------------------
Activity TranslateActivity( Activity idealActivity, Activity *pIdealWeaponActivity = NULL );
Activity NPC_TranslateActivity( Activity eNewActivity );
Activity GetActivity( void ) { return m_Activity; }
virtual void SetActivity( Activity NewActivity );
Activity GetIdealActivity( void ) { return m_IdealActivity; }
void SetIdealActivity( Activity NewActivity );
void ResetIdealActivity( Activity newIdealActivity );
void SetSequenceByName( char *szSequence );
void SetSequenceById( int iSequence );
Activity GetScriptCustomMoveActivity( void );
int GetScriptCustomMoveSequence( void );
Activity GetStoppedActivity( void );
inline bool HaveSequenceForActivity( Activity activity );
inline bool IsActivityStarted(void);
virtual bool IsActivityFinished( void );
virtual bool IsActivityMovementPhased( Activity activity );
virtual void OnChangeActivity( Activity eNewActivity );
void MaintainActivity(void);
void ResetActivity(void) { m_Activity = ACT_RESET; }
void SetActivityAndSequence(Activity NewActivity, int iSequence, Activity translatedActivity, Activity weaponActivity);
private:
void AdvanceToIdealActivity(void);
void ResolveActivityToSequence(Activity NewActivity, int &iSequence, Activity &translatedActivity, Activity &weaponActivity);
Activity m_Activity; // Current animation state
Activity m_translatedActivity; // Current actual translated animation
Activity m_IdealActivity; // Desired animation state
int m_nIdealSequence; // Desired animation sequence
Activity m_IdealTranslatedActivity; // Desired actual translated animation state
Activity m_IdealWeaponActivity; // Desired weapon animation state
CNetworkVar(int, m_iDeathPose );
CNetworkVar(int, m_iDeathFrame );
public:
//-----------------------------------------------------
//
// Senses
//
//-----------------------------------------------------
CAI_Senses * GetSenses() { return m_pSenses; }
const CAI_Senses * GetSenses() const { return m_pSenses; }
void SetDistLook( float flDistLook );
virtual bool QueryHearSound( CSound *pSound );
virtual bool QuerySeeEntity( CBaseEntity *pEntity, bool bOnlyHateOrFearIfNPC = false );
virtual void OnLooked( int iDistance );
virtual void OnListened();
virtual void OnSeeEntity( CBaseEntity *pEntity ) {}
// If true, AI will try to see this entity regardless of distance.
virtual bool ShouldNotDistanceCull() { return false; }
virtual int GetSoundInterests( void );
virtual int GetSoundPriority( CSound *pSound );
CSound * GetLoudestSoundOfType( int iType );
virtual CSound * GetBestSound( int validTypes = ALL_SOUNDS );
virtual CSound * GetBestScent( void );
virtual float HearingSensitivity( void ) { return 1.0; }
virtual bool ShouldIgnoreSound( CSound * ) { return false; }
bool SoundIsVisible( CSound *pSound );
protected:
virtual void ClearSenseConditions( void );
private:
void LockBestSound();
void UnlockBestSound();
CAI_Senses * m_pSenses;
CSound * m_pLockedBestSound;
public:
//-----------------------------------------------------
//
// Enemy and target
//
//-----------------------------------------------------
Vector GetSmoothedVelocity( void );
CBaseEntity* GetEnemy() { return m_hEnemy.Get(); }
CBaseEntity* GetEnemy() const { return m_hEnemy.Get(); }
float GetTimeEnemyAcquired() { return m_flTimeEnemyAcquired; }
void SetEnemy( CBaseEntity *pEnemy, bool bSetCondNewEnemy = true );
const Vector & GetEnemyLKP() const;
float GetEnemyLastTimeSeen() const;
void MarkEnemyAsEluded();
void ClearEnemyMemory();
bool EnemyHasEludedMe() const;
virtual CBaseEntity *BestEnemy(); // returns best enemy in memory list
virtual bool IsValidEnemy( CBaseEntity *pEnemy );
virtual bool CanBeAnEnemyOf( CBaseEntity *pEnemy );
void ForceChooseNewEnemy() { m_EnemiesSerialNumber = -1; }
bool ChooseEnemy();
virtual bool ShouldChooseNewEnemy();
virtual void GatherEnemyConditions( CBaseEntity *pEnemy );
virtual float EnemyDistTolerance() { return 0; } // Enemy distances within this tolerance of each other are considered equivalent.
float EnemyDistance( CBaseEntity *pEnemy );
CBaseCombatCharacter *GetEnemyCombatCharacterPointer();
void SetEnemyOccluder(CBaseEntity *pBlocker);
CBaseEntity *GetEnemyOccluder(void);
virtual void StartTargetHandling( CBaseEntity *pTargetEnt );
//---------------------------------
CBaseEntity* GetTarget() { return m_hTargetEnt.Get(); }
void SetTarget( CBaseEntity *pTarget );
void CheckTarget( CBaseEntity *pTarget );
float GetAcceptableTimeSeenEnemy( void ) { return m_flAcceptableTimeSeenEnemy; }
virtual CAI_BaseNPC *CreateCustomTarget( const Vector &vecOrigin, float duration = -1 );
void SetDeathPose( const int &iDeathPose ) { m_iDeathPose = iDeathPose; }
void SetDeathPoseFrame( const int &iDeathPoseFrame ) { m_iDeathFrame = iDeathPoseFrame; }
void SelectDeathPose( const CTakeDamageInfo &info );
virtual bool ShouldPickADeathPose( void ) { return true; }
virtual bool AllowedToIgnite( void ) { return false; }
protected:
virtual float GetGoalRepathTolerance( CBaseEntity *pGoalEnt, GoalType_t type, const Vector &curGoal, const Vector &curTargetPos );
private:
void * CheckEnemy( CBaseEntity *pEnemy ) { return NULL; } // OBSOLETE, replaced by GatherEnemyConditions(), left here to make derived code not compile
// Updates the goal position in case of GOALTYPE_ENEMY
void UpdateEnemyPos();
// Updates the goal position in case of GOALTYPE_TARGETENT
void UpdateTargetPos();
//---------------------------------
EHANDLE m_hEnemy; // the entity that the npc is fighting.
float m_flTimeEnemyAcquired; // The time at which the entity the NPC is fighting became the NPC's enemy.
EHANDLE m_hTargetEnt; // the entity that the npc is trying to reach
CRandStopwatch m_GiveUpOnDeadEnemyTimer;
CSimpleSimTimer m_FailChooseEnemyTimer;
int m_EnemiesSerialNumber;
float m_flAcceptableTimeSeenEnemy;
CSimpleSimTimer m_UpdateEnemyPosTimer;
static CSimpleSimTimer m_AnyUpdateEnemyPosTimer;
public:
//-----------------------------------------------------
//
// Commander mode stuff.
//
//-----------------------------------------------------
virtual bool IsCommandable() { return false; }
virtual bool IsPlayerAlly( CBasePlayer *pPlayer = NULL );
virtual bool IsMedic() { return false; }
virtual bool IsCommandMoving() { return false; }
virtual bool ShouldAutoSummon() { return false; }
virtual void SetCommandGoal( const Vector &vecGoal );
virtual void ClearCommandGoal();
virtual void OnTargetOrder() {}
virtual void OnMoveOrder() {}
virtual bool IsValidCommandTarget( CBaseEntity *pTarget ) { return false; }
const Vector &GetCommandGoal() const { return m_vecCommandGoal; }
virtual void OnMoveToCommandGoalFailed() {}
string_t GetPlayerSquadName() const { Assert( gm_iszPlayerSquad != NULL_STRING ); return gm_iszPlayerSquad; }
bool IsInPlayerSquad() const;
virtual CAI_BaseNPC *GetSquadCommandRepresentative() { return NULL; }
virtual bool TargetOrder( CBaseEntity *pTarget, CAI_BaseNPC **Allies, int numAllies ) { OnTargetOrder(); return true; }
virtual void MoveOrder( const Vector &vecDest, CAI_BaseNPC **Allies, int numAllies ) { SetCommandGoal( vecDest ); SetCondition( COND_RECEIVED_ORDERS ); OnMoveOrder(); }
// Return true if you're willing to be idly talked to by other friends.
virtual bool CanBeUsedAsAFriend( void );
private:
Vector m_vecCommandGoal;
static string_t gm_iszPlayerSquad;
public:
CAI_MoveMonitor m_CommandMoveMonitor;
//-----------------------------------------------------
// Dynamic scripted NPC interactions
//-----------------------------------------------------
public:
float GetInteractionYaw( void ) const { return m_flInteractionYaw; }
protected:
void ParseScriptedNPCInteractions( void );
void AddScriptedNPCInteraction( ScriptedNPCInteraction_t *pInteraction );
const char *GetScriptedNPCInteractionSequence( ScriptedNPCInteraction_t *pInteraction, int iPhase );
void StartRunningInteraction( CAI_BaseNPC *pOtherNPC, bool bActive );
void StartScriptedNPCInteraction( CAI_BaseNPC *pOtherNPC, ScriptedNPCInteraction_t *pInteraction, Vector vecOtherOrigin, QAngle angOtherAngles );
void CheckForScriptedNPCInteractions( void );
void CalculateValidEnemyInteractions( void );
void CheckForcedNPCInteractions( void );
bool InteractionCouldStart( CAI_BaseNPC *pOtherNPC, ScriptedNPCInteraction_t *pInteraction, Vector &vecOrigin, QAngle &angAngles );
virtual bool CanRunAScriptedNPCInteraction( bool bForced = false );
bool IsRunningDynamicInteraction( void ) { return (m_iInteractionState != NPCINT_NOT_RUNNING && (m_hCine != NULL)); }
bool IsActiveDynamicInteraction( void ) { return (m_iInteractionState == NPCINT_RUNNING_ACTIVE && (m_hCine != NULL)); }
ScriptedNPCInteraction_t *GetRunningDynamicInteraction( void ) { return &(m_ScriptedInteractions[m_iInteractionPlaying]); }
void SetInteractionCantDie( bool bCantDie ) { m_bCannotDieDuringInteraction = bCantDie; }
bool HasInteractionCantDie( void );
void InputForceInteractionWithNPC( inputdata_t &inputdata );
void StartForcedInteraction( CAI_BaseNPC *pNPC, int iInteraction );
void CleanupForcedInteraction( void );
void CalculateForcedInteractionPosition( void );
CAI_BaseNPC *GetInteractionPartner( void );
private:
// Forced interactions
CHandle<CAI_BaseNPC> m_hForcedInteractionPartner;
Vector m_vecForcedWorldPosition;
float m_flForcedInteractionTimeout; // Abort the interaction if it hasn't started by this time.
CHandle<CAI_BaseNPC> m_hInteractionPartner;
EHANDLE m_hLastInteractionTestTarget;
bool m_bCannotDieDuringInteraction;
int m_iInteractionState;
int m_iInteractionPlaying;
CUtlVector<ScriptedNPCInteraction_t> m_ScriptedInteractions;
float m_flInteractionYaw;
public:
//-----------------------------------------------------
//
// Sounds
//
//-----------------------------------------------------
virtual CanPlaySequence_t CanPlaySequence( bool fDisregardState, int interruptLevel );
virtual bool CanPlaySentence( bool fDisregardState ) { return IsAlive(); }
virtual int PlaySentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, CBaseEntity *pListener = NULL );
virtual int PlayScriptedSentence( const char *pszSentence, float delay, float volume, soundlevel_t soundlevel, bool bConcurrent, CBaseEntity *pListener );
virtual bool FOkToMakeSound( int soundPriority = 0 );
virtual void JustMadeSound( int soundPriority = 0, float flSoundLength = 0.0f );
virtual void DeathSound( const CTakeDamageInfo &info ) { return; };
virtual void AlertSound( void ) { return; };
virtual void IdleSound( void ) { return; };
virtual void PainSound( const CTakeDamageInfo &info ) { return; };
virtual void FearSound( void ) { return; };
virtual void LostEnemySound( void ) { return; };
virtual void FoundEnemySound( void ) { return; };
virtual void BarnacleDeathSound( void ) { CTakeDamageInfo info; PainSound( info ); }
virtual void SpeakSentence( int sentenceType ) { return; };
virtual bool ShouldPlayIdleSound( void );
virtual void MakeAIFootstepSound( float volume, float duration = 0.5f );
//---------------------------------
virtual CAI_Expresser *GetExpresser() { return NULL; }
const CAI_Expresser *GetExpresser() const { return const_cast<CAI_BaseNPC *>(this)->GetExpresser(); }
//---------------------------------
// NPC Event Response System
virtual bool CanRespondToEvent( const char *ResponseConcept ) { return false; }
virtual bool RespondedTo( const char *ResponseConcept, bool bForce, bool bCancelScene ) { return false; }
virtual void PlayerHasIlluminatedNPC( CBasePlayer *pPlayer, float flDot );
virtual void ModifyOrAppendCriteria( AI_CriteriaSet& set );
protected:
float SoundWaitTime() const { return m_flSoundWaitTime; }
public:
//-----------------------------------------------------
//
// Capabilities report (from CBaseCombatCharacter)
//
//-----------------------------------------------------
virtual int CapabilitiesGet( void ) const;
// local capabilities access
int CapabilitiesAdd( int capabilities );
int CapabilitiesRemove( int capabilities );
void CapabilitiesClear( void );
private:
int m_afCapability; // tells us what a npc can/can't do.
public:
//-----------------------------------------------------
//
// Pathfinding, navigation & movement
//
//-----------------------------------------------------
CAI_Navigator * GetNavigator() { return m_pNavigator; }
const CAI_Navigator *GetNavigator() const { return m_pNavigator; }
CAI_LocalNavigator *GetLocalNavigator() { return m_pLocalNavigator; }
const CAI_LocalNavigator *GetLocalNavigator() const { return m_pLocalNavigator; }
CAI_Pathfinder * GetPathfinder() { return m_pPathfinder; }
const CAI_Pathfinder *GetPathfinder() const { return m_pPathfinder; }
CAI_MoveProbe * GetMoveProbe() { return m_pMoveProbe; }
const CAI_MoveProbe *GetMoveProbe() const { return m_pMoveProbe; }
CAI_Motor * GetMotor() { return m_pMotor; }
const CAI_Motor * GetMotor() const { return m_pMotor; }
//---------------------------------
static bool FindSpotForNPCInRadius( Vector *pResult, const Vector &vStartPos, CAI_BaseNPC *pNPC, float radius, bool bOutOfPlayerViewcone = false );
//---------------------------------
virtual bool IsNavigationUrgent();
virtual bool ShouldFailNav( bool bMovementFailed );
virtual bool ShouldBruteForceFailedNav() { return false; }
// The current navigation (movement) mode (e.g. fly, swim, locomote, etc)
Navigation_t GetNavType() const;
void SetNavType( Navigation_t navType );
CBaseEntity * GetNavTargetEntity(void);
bool IsMoving( void );
virtual float GetTimeToNavGoal();
// NPCs can override this to tweak with how costly particular movements are
virtual bool MovementCost( int moveType, const Vector &vecStart, const Vector &vecEnd, float *pCost );
// Turns a directional vector into a yaw value that points down that vector.
float VecToYaw( const Vector &vecDir );
// Turning
virtual float CalcIdealYaw( const Vector &vecTarget );
virtual float MaxYawSpeed( void ); // Get max yaw speed
bool FacingIdeal( void );
void SetUpdatedYaw() { m_ScheduleState.bTaskUpdatedYaw = true; }
// Add multiple facing goals while moving/standing still.
virtual void AddFacingTarget( CBaseEntity *pTarget, float flImportance, float flDuration, float flRamp = 0.0 );
virtual void AddFacingTarget( const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 );
virtual void AddFacingTarget( CBaseEntity *pTarget, const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 );
virtual float GetFacingDirection( Vector &vecDir );
// ------------
// Methods used by motor to query properties/preferences/move-related state
// ------------
virtual bool CanStandOn( CBaseEntity *pSurface ) const;
virtual bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos ) const; // Override for specific creature types
bool IsJumpLegal( const Vector &startPos, const Vector &apex, const Vector &endPos, float maxUp, float maxDown, float maxDist ) const;
bool ShouldMoveWait();
virtual float StepHeight() const { return 18.0f; }
float GetStepDownMultiplier() const;
virtual float GetMaxJumpSpeed() const { return 350.0f; }
virtual float GetJumpGravity() const { return 1.0f; }
//---------------------------------
virtual bool OverrideMove( float flInterval ); // Override to take total control of movement (return true if done so)
virtual bool OverrideMoveFacing( const AILocalMoveGoal_t &move, float flInterval );
//---------------------------------
virtual bool IsUnusableNode(int iNodeID, CAI_Hint *pHint); // Override for special NPC behavior
virtual bool ValidateNavGoal();
virtual bool IsCurTaskContinuousMove();
virtual bool IsValidMoveAwayDest( const Vector &vecDest ) { return true; }
//---------------------------------
//
// Notifications from navigator
//
virtual void OnMovementFailed() {};
virtual void OnMovementComplete() {};
//---------------------------------
bool FindNearestValidGoalPos( const Vector &vTestPoint, Vector *pResult );
void RememberUnreachable( CBaseEntity* pEntity, float duration = -1 ); // Remember that entity is unreachable
virtual bool IsUnreachable( CBaseEntity* pEntity ); // Is entity is unreachable?
//---------------------------------
// Inherited from IAI_MotorMovementServices
virtual float CalcYawSpeed( void );
virtual bool OnCalcBaseMove( AILocalMoveGoal_t *pMoveGoal,
float distClear,
AIMoveResult_t *pResult );
virtual bool OnObstructionPreSteer( AILocalMoveGoal_t *pMoveGoal,
float distClear,
AIMoveResult_t *pResult );
// Translations of the above into some useful game terms
virtual bool OnObstructingDoor( AILocalMoveGoal_t *pMoveGoal,
CBaseDoor *pDoor,
float distClear,
AIMoveResult_t *pResult );
virtual bool OnUpcomingPropDoor( AILocalMoveGoal_t *pMoveGoal,
CBasePropDoor *pDoor,
float distClear,
AIMoveResult_t *pResult );
void OpenPropDoorBegin( CBasePropDoor *pDoor );
void OpenPropDoorNow( CBasePropDoor *pDoor );
//---------------------------------
void DelayMoveStart( float delay ) { m_flMoveWaitFinished = gpGlobals->curtime + delay; }
float m_flMoveWaitFinished;
//
// Stuff for opening doors.
//
void OnDoorFullyOpen(CBasePropDoor *pDoor);
void OnDoorBlocked(CBasePropDoor *pDoor);
CHandle<CBasePropDoor> m_hOpeningDoor; // The CBasePropDoor that we are in the midst of opening for navigation.
protected:
// BRJ 4/11
// Semi-obsolete-looking Lars code I moved out of the engine and into here
int FlyMove( const Vector& vecPosition, unsigned int mask );
int WalkMove( const Vector& vecPosition, unsigned int mask );
// Unreachable Entities
CUtlVector<UnreachableEnt_t> m_UnreachableEnts; // Array of unreachable entities
private:
CAI_Navigator * m_pNavigator;
CAI_LocalNavigator *m_pLocalNavigator;
CAI_Pathfinder * m_pPathfinder;
CAI_MoveProbe * m_pMoveProbe;
CAI_Motor * m_pMotor;
EHANDLE m_hGoalEnt; // path corner we are heading towards
float m_flTimeLastMovement;
CSimpleSimTimer m_CheckOnGroundTimer;
public:
//-----------------------------------------------------
//
// Eye position, view offset, head direction, eye direction
//
//-----------------------------------------------------
void SetDefaultEyeOffset ( void );
const Vector & GetDefaultEyeOffset( void ) { return m_vDefaultEyeOffset; }
virtual Vector GetNodeViewOffset() { return GetViewOffset(); }
virtual Vector EyeOffset( Activity nActivity );
virtual Vector EyePosition( void );
//---------------------------------
virtual Vector HeadDirection2D( void );
virtual Vector HeadDirection3D( void );
virtual Vector EyeDirection2D( void );
virtual Vector EyeDirection3D( void );
virtual CBaseEntity *EyeLookTarget( void ); // Overridden by subclass to force look at an entity
virtual void AddLookTarget( CBaseEntity *pTarget, float flImportance, float flDuration, float flRamp = 0.0 ) { };
virtual void AddLookTarget( const Vector &vecPosition, float flImportance, float flDuration, float flRamp = 0.0 ) { };
virtual void SetHeadDirection( const Vector &vTargetPos, float flInterval );
virtual void MaintainLookTargets( float flInterval );
virtual bool ValidEyeTarget(const Vector &lookTargetPos);
virtual Vector FacingPosition( void ) { return EyePosition(); }; // position that other npc's use when facing you
virtual void MaintainTurnActivity( void );
virtual bool FInAimCone( const Vector &vecSpot );
virtual void AimGun();
virtual void SetAim( const Vector &aimDir );
virtual void RelaxAim( void );
virtual CBaseEntity *GetAlternateMoveShootTarget() { return NULL; }
protected:
Vector m_vDefaultEyeOffset;
float m_flNextEyeLookTime; // Next time a pick a new place to look
float m_flEyeIntegRate; // How fast does eye move to target
private:
Vector m_vEyeLookTarget; // Where I want to be looking
Vector m_vCurEyeTarget; // Direction I'm looking at
EHANDLE m_hEyeLookTarget; // What I want to be looking at
float m_flHeadYaw; // Current head yaw
float m_flHeadPitch; // Current head pitch
protected:
float m_flOriginalYaw; // This is the direction facing when the level designer placed the NPC in the level.
public:
//-----------------------------------------------------
// Mapmaker Scripting
//
// Set when the NPC is being scripted by a mapmaker, and
// shouldn't be responding to external stimuli that would
// break him out of his "script". NOT a scripted sequence.
//-----------------------------------------------------
inline bool IsInAScript( void ) { return m_bInAScript; }
inline void SetInAScript( bool bScript ) { m_bInAScript = bScript; }
void InputStartScripting( inputdata_t &inputdata ) { m_bInAScript = true; }
void InputStopScripting( inputdata_t &inputdata ) { m_bInAScript = false; }
void InputGagEnable( inputdata_t &inputdata ) { AddSpawnFlags(SF_NPC_GAG); }
void InputGagDisable( inputdata_t &inputdata ) { RemoveSpawnFlags(SF_NPC_GAG); }
bool HandleInteraction(int interactionType, void *data, CBaseCombatCharacter* sourceEnt);
virtual void InputOutsideTransition( inputdata_t &inputdata );
virtual void InputInsideTransition( inputdata_t &inputdata );
void CleanupScriptsOnTeleport( bool bEnrouteAsWell );
virtual void SetScriptedScheduleIgnoreConditions( Interruptability_t interrupt );
private:
bool m_bInAScript;
public:
//-----------------------------------------------------
//
// Scripting
//
//-----------------------------------------------------
// Scripted sequence Info
enum SCRIPTSTATE
{
SCRIPT_PLAYING = 0, // Playing the action animation.
SCRIPT_WAIT, // Waiting on everyone in the script to be ready. Plays the pre idle animation if there is one.
SCRIPT_POST_IDLE, // Playing the post idle animation after playing the action animation.
SCRIPT_CLEANUP, // Cancelling the script / cleaning up.
SCRIPT_WALK_TO_MARK, // Walking to the scripted sequence position.
SCRIPT_RUN_TO_MARK, // Running to the scripted sequence position.
SCRIPT_CUSTOM_MOVE_TO_MARK, // Moving to the scripted sequence position while playing a custom movement animation.
};
bool ExitScriptedSequence();
bool CineCleanup();
virtual void Teleport( const Vector *newPosition, const QAngle *newAngles, const Vector *newVelocity );
// forces movement and sets a new schedule
virtual bool ScheduledMoveToGoalEntity( int scheduleType, CBaseEntity *pGoalEntity, Activity movementActivity );
virtual bool ScheduledFollowPath( int scheduleType, CBaseEntity *pPathStart, Activity movementActivity );
static void ForceSelectedGo(CBaseEntity *pPlayer, const Vector &targetPos, const Vector &traceDir, bool bRun);
static void ForceSelectedGoRandom(void);
bool AutoMovement( CBaseEntity *pTarget = NULL, AIMoveTrace_t *pTraceResult = NULL );
bool AutoMovement( float flInterval, CBaseEntity *pTarget = NULL, AIMoveTrace_t *pTraceResult = NULL );
bool TaskRanAutomovement( void ) { return m_ScheduleState.bTaskRanAutomovement; }
SCRIPTSTATE m_scriptState; // internal cinematic state
CHandle<CAI_ScriptedSequence> m_hCine;
Activity m_ScriptArrivalActivity;
string_t m_strScriptArrivalSequence;
//-----------------------------------------------------
//
// Scenes
//
//-----------------------------------------------------
void AddSceneLock( float flDuration = 0.2f ) { m_flSceneTime = max( gpGlobals->curtime + flDuration, m_flSceneTime ); };
void ClearSceneLock( float flDuration = 0.2f ) { m_flSceneTime = gpGlobals->curtime + flDuration; };
bool IsInLockedScene( void ) { return m_flSceneTime > gpGlobals->curtime; };
float m_flSceneTime;
string_t m_iszSceneCustomMoveSeq;
public:
//-----------------------------------------------------
//
// Memory
//
//-----------------------------------------------------
inline void Remember( int iMemory ) { m_afMemory |= iMemory; }
inline void Forget( int iMemory ) { m_afMemory &= ~iMemory; }
inline bool HasMemory( int iMemory ) { if ( m_afMemory & iMemory ) return TRUE; return FALSE; }
inline bool HasAllMemories( int iMemory ) { if ( (m_afMemory & iMemory) == iMemory ) return TRUE; return FALSE; }
virtual CAI_Enemies *GetEnemies( void );
virtual void RemoveMemory( void );
virtual bool UpdateEnemyMemory( CBaseEntity *pEnemy, const Vector &position, CBaseEntity *pInformer = NULL );
virtual float GetReactionDelay( CBaseEntity *pEnemy );
void SetLastAttackTime( float time) { m_flLastAttackTime = time; }
float GetLastAttackTime() const { return m_flLastAttackTime; }
float GetLastDamageTime() const { return m_flLastDamageTime; }
float GetLastPlayerDamageTime() const { return m_flLastPlayerDamageTime; }
float GetLastEnemyTime() const { return m_flLastEnemyTime; }
// Set up the shot regulator based on the equipped weapon
virtual void OnChangeActiveWeapon( CBaseCombatWeapon *pOldWeapon, CBaseCombatWeapon *pNewWeapon );
// Weapon holstering
virtual bool CanHolsterWeapon( void );
virtual int HolsterWeapon( void );
virtual int UnholsterWeapon( void );
void InputHolsterWeapon( inputdata_t &inputdata );
void InputHolsterAndDestroyWeapon( inputdata_t &inputdata );
void InputUnholsterWeapon( inputdata_t &inputdata );
bool IsWeaponHolstered( void );
bool IsWeaponStateChanging( void );
void SetDesiredWeaponState( DesiredWeaponState_t iState ) { m_iDesiredWeaponState = iState; }
// NOTE: The Shot Regulator is used to manage the RangeAttack1 weapon.
inline CAI_ShotRegulator* GetShotRegulator() { return &m_ShotRegulator; }
virtual void OnRangeAttack1();
protected:
// Shot regulator code
virtual void OnUpdateShotRegulator( );
protected:
CAI_Enemies * m_pEnemies; // Holds information about enemies / danger positions / shared between sqaud members
int m_afMemory;
EHANDLE m_hEnemyOccluder; // The entity my enemy is hiding behind.
float m_flSumDamage; // How much consecutive damage I've received
float m_flLastDamageTime; // Last time I received damage
float m_flLastPlayerDamageTime; // Last time I received damage from the player
float m_flLastSawPlayerTime; // Last time I saw the player
float m_flLastAttackTime; // Last time that I attacked my current enemy
float m_flLastEnemyTime;
float m_flNextWeaponSearchTime; // next time to search for a better weapon
string_t m_iszPendingWeapon; // THe NPC should create and equip this weapon.
bool m_bIgnoreUnseenEnemies;
private:
CAI_ShotRegulator m_ShotRegulator; // When should I shoot next?
DesiredWeaponState_t m_iDesiredWeaponState;
public:
//-----------------------------------------------------
//
// Squads & tactics
//
//-----------------------------------------------------
virtual bool InitSquad( void );
virtual const char* SquadSlotName(int slotID) { return gm_SquadSlotNamespace.IdToSymbol(slotID); }
bool OccupyStrategySlot( int squadSlotID );
bool OccupyStrategySlotRange( int slotIDStart, int slotIDEnd );
bool HasStrategySlot( int squadSlotID );
bool HasStrategySlotRange( int slotIDStart, int slotIDEnd );
int GetMyStrategySlot() { return m_iMySquadSlot; }
void VacateStrategySlot( void );
bool IsStrategySlotRangeOccupied( int slotIDStart, int slotIDEnd ); // Returns true if all in the range are occupied
CAI_Squad * GetSquad() { return m_pSquad; }
virtual void SetSquad( CAI_Squad *pSquad );
void AddToSquad( string_t name );
void RemoveFromSquad();
void CheckSquad();
void SetSquadName( string_t name ) { m_SquadName = name; }
bool IsInSquad() const { return m_pSquad != NULL; }
virtual bool IsSilentSquadMember() const { return false; }
int NumWeaponsInSquad( const char *pszWeaponClassname );
string_t GetHintGroup( void ) { return m_strHintGroup; }
void ClearHintGroup( void ) { SetHintGroup( NULL_STRING ); }
void SetHintGroup( string_t name, bool bHintGroupNavLimiting = false );
bool IsLimitingHintGroups( void ) { return m_bHintGroupNavLimiting; }
//---------------------------------
CAI_TacticalServices *GetTacticalServices() { return m_pTacticalServices; }
const CAI_TacticalServices *GetTacticalServices() const { return m_pTacticalServices; }
//---------------------------------
// Cover
virtual bool FindCoverPos( CBaseEntity *pEntity, Vector *pResult );
virtual bool FindCoverPosInRadius( CBaseEntity *pEntity, const Vector &goalPos, float coverRadius, Vector *pResult );
virtual bool FindCoverPos( CSound *pSound, Vector *pResult );
virtual bool IsValidCover ( const Vector &vecCoverLocation, CAI_Hint const *pHint );
virtual bool IsValidShootPosition ( const Vector &vecCoverLocation, CAI_Node *pNode, CAI_Hint const *pHint );
virtual bool TestShootPosition(const Vector &vecShootPos, const Vector &targetPos ) { return WeaponLOSCondition( vecShootPos, targetPos, false ); }
virtual bool IsCoverPosition( const Vector &vecThreat, const Vector &vecPosition );
virtual float CoverRadius( void ) { return 1024; } // Default cover radius
virtual float GetMaxTacticalLateralMovement( void ) { return MAXTACLAT_IGNORE; }
protected:
virtual void OnChangeHintGroup( string_t oldGroup, string_t newGroup ) {}
CAI_Squad * m_pSquad; // The squad that I'm on
string_t m_SquadName;
int m_iMySquadSlot; // this is the behaviour slot that the npc currently holds in the squad.
private:
string_t m_strHintGroup;
bool m_bHintGroupNavLimiting;
CAI_TacticalServices *m_pTacticalServices;
public:
//-----------------------------------------------------
//
// Base schedule & task support; Miscellaneous
//
//-----------------------------------------------------
void InitRelationshipTable( void );
void AddRelationship( const char *pszRelationship, CBaseEntity *pActivator );
virtual void AddEntityRelationship( CBaseEntity *pEntity, Disposition_t nDisposition, int nPriority );
virtual void AddClassRelationship( Class_T nClass, Disposition_t nDisposition, int nPriority );
void NPCUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value );
CBaseGrenade* IncomingGrenade(void);
virtual bool ShouldFadeOnDeath( void );
void NPCInitDead( void ); // Call after animation/pose is set up
void CorpseFallThink( void );
float ThrowLimit( const Vector &vecStart, const Vector &vecEnd, float fGravity, float fArcSize, const Vector &mins, const Vector &maxs, CBaseEntity *pTarget, Vector *jumpVel, CBaseEntity **pBlocker);
// these functions will survey conditions and set appropriate conditions bits for attack types.
virtual int RangeAttack1Conditions( float flDot, float flDist );
virtual int RangeAttack2Conditions( float flDot, float flDist );
virtual int MeleeAttack1Conditions( float flDot, float flDist );
virtual int MeleeAttack2Conditions( float flDot, float flDist );
virtual float InnateRange1MinRange( void ) { return 0.0f; }
virtual float InnateRange1MaxRange( void ) { return FLT_MAX; }
virtual bool OnBeginMoveAndShoot( void ) { return true; }
virtual void OnEndMoveAndShoot( void ) {}
virtual bool UseAttackSquadSlots() { return false; }
//---------------------------------
virtual CBaseEntity *FindNamedEntity( const char *pszName, IEntityFindFilter *pFilter = NULL );
//---------------------------------
// States
//---------------------------------
virtual void ClearAttackConditions( void );
void GatherAttackConditions( CBaseEntity *pTarget, float flDist );
virtual bool ShouldLookForBetterWeapon();
bool Weapon_IsBetterAvailable ( void ) ;
virtual Vector Weapon_ShootPosition( void );
virtual void GiveWeapon( string_t iszWeaponName );
virtual void OnGivenWeapon( CBaseCombatWeapon *pNewWeapon ) { }
bool IsMovingToPickupWeapon();
virtual bool WeaponLOSCondition(const Vector &ownerPos, const Vector &targetPos, bool bSetConditions);
virtual bool CurrentWeaponLOSCondition(const Vector &targetPos, bool bSetConditions) { return WeaponLOSCondition( GetAbsOrigin(), targetPos, bSetConditions ); }
virtual bool IsWaitingToRappel( void ) { return false; }
virtual void BeginRappel() {}
// override to change the chase location of an enemy
// This is where your origin should go when you are chasing pEnemy when his origin is at chasePosition
// by default, leave this alone to make your origin coincide with his.
virtual void TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition);
virtual float GetDefaultNavGoalTolerance() { return (GetHullWidth() * 2.0); }
virtual bool FCanCheckAttacks ( void );
virtual void CheckAmmo( void ) {}
virtual bool FValidateHintType( CAI_Hint *pHint );
virtual Activity GetHintActivity( short sHintType, Activity HintsActivity );
virtual float GetHintDelay( short sHintType );
virtual Activity GetCoverActivity( CAI_Hint* pHint );
virtual Activity GetReloadActivity( CAI_Hint* pHint );
virtual void SetTurnActivity( void );
bool UpdateTurnGesture( void );
// Returns the time when the door will be open
float OpenDoorAndWait( CBaseEntity *pDoor );
bool BBoxFlat( void );
//---------------------------------
virtual void Ignite( float flFlameLifetime, bool bNPCOnly = true, float flSize = 0.0f, bool bCalledByLevelDesigner = false );
virtual bool PassesDamageFilter( const CTakeDamageInfo &info );
//---------------------------------
void MakeDamageBloodDecal( int cCount, float flNoise, trace_t *ptr, Vector vecDir );
virtual float GetHitgroupDamageMultiplier( int iHitGroup, const CTakeDamageInfo &info );
void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr );
void DecalTrace( trace_t *pTrace, char const *decalName );
void ImpactTrace( trace_t *pTrace, int iDamageType, char *pCustomImpactName );
virtual bool PlayerInSpread( const Vector &sourcePos, const Vector &targetPos, float flSpread, float maxDistOffCenter, bool ignoreHatedPlayers = true );
CBaseEntity * PlayerInRange( const Vector &vecLocation, float flDist );
bool PointInSpread( CBaseCombatCharacter *pCheckEntity, const Vector &sourcePos, const Vector &targetPos, const Vector &testPoint, float flSpread, float maxDistOffCenter );
bool IsSquadmateInSpread( const Vector &sourcePos, const Vector &targetPos, float flSpread, float maxDistOffCenter );
//---------------------------------
// combat functions
//---------------------------------
virtual bool InnateWeaponLOSCondition( const Vector &ownerPos, const Vector &targetPos, bool bSetConditions );
virtual Activity GetFlinchActivity( bool bHeavyDamage, bool bGesture );
virtual bool ShouldGib( const CTakeDamageInfo &info ) { return false; } // Always ragdoll, unless specified by the leaf class
virtual bool Event_Gibbed( const CTakeDamageInfo &info );
virtual void Event_Killed( const CTakeDamageInfo &info );
virtual Vector GetShootEnemyDir( const Vector &shootOrigin, bool bNoisy = true );
#ifdef HL2_DLL
virtual Vector GetActualShootPosition( const Vector &shootOrigin );
virtual Vector GetActualShootTrajectory( const Vector &shootOrigin );
virtual Vector GetAttackSpread( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget = NULL );
virtual float GetSpreadBias( CBaseCombatWeapon *pWeapon, CBaseEntity *pTarget );
#endif //HL2_DLL
virtual void CollectShotStats( const Vector &vecShootOrigin, const Vector &vecShootDir );
virtual Vector BodyTarget( const Vector &posSrc, bool bNoisy = true );
virtual Vector GetAutoAimCenter() { return BodyTarget(vec3_origin, false); }
virtual void FireBullets( const FireBulletsInfo_t &info );
// OLD VERSION! Use the struct version
void FireBullets( int cShots, const Vector &vecSrc, const Vector &vecDirShooting,
const Vector &vecSpread, float flDistance, int iAmmoType, int iTracerFreq = 4,
int firingEntID = -1, int attachmentID = -1, int iDamage = 0,
CBaseEntity *pAttacker = NULL, bool bFirstShotAccurate = false );
virtual bool ShouldMoveAndShoot( void );
//---------------------------------
// Damage
//---------------------------------
virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info );
virtual int OnTakeDamage_Dying( const CTakeDamageInfo &info );
virtual int OnTakeDamage_Dead( const CTakeDamageInfo &info );
virtual void NotifyFriendsOfDamage( CBaseEntity *pAttackerEntity );
virtual void OnFriendDamaged( CBaseCombatCharacter *pSquadmate, CBaseEntity *pAttacker );
virtual bool IsLightDamage( const CTakeDamageInfo &info );
virtual bool IsHeavyDamage( const CTakeDamageInfo &info );
void DoRadiusDamage( const CTakeDamageInfo &info, int iClassIgnore, CBaseEntity *pEntityIgnore );
void DoRadiusDamage( const CTakeDamageInfo &info, const Vector &vecSrc, int iClassIgnore, CBaseEntity *pEntityIgnore );
//---------------------------------
virtual void PickupWeapon( CBaseCombatWeapon *pWeapon );
virtual void PickupItem( CBaseEntity *pItem ) { };
CBaseEntity* DropItem( char *pszItemName, Vector vecPos, QAngle vecAng );// drop an item.
//---------------------------------
// Inputs
//---------------------------------
void InputSetRelationship( inputdata_t &inputdata );
void InputSetEnemyFilter( inputdata_t &inputdata );
void InputSetHealth( inputdata_t &inputdata );
void InputBeginRappel( inputdata_t &inputdata );
void InputSetSquad( inputdata_t &inputdata );
void InputWake( inputdata_t &inputdata );
void InputForgetEntity( inputdata_t &inputdata );
void InputIgnoreDangerSounds( inputdata_t &inputdata );
void InputUpdateEnemyMemory( inputdata_t &inputdata );
//---------------------------------
virtual void NotifyDeadFriend( CBaseEntity *pFriend ) { return; }
//---------------------------------
// Utility methods
static Vector CalcThrowVelocity(const Vector &startPos, const Vector &endPos, float fGravity, float fArcSize);
//---------------------------------
float SetWait( float minWait, float maxWait = 0.0 );
void ClearWait();
float GetWaitFinishTime() { return m_flWaitFinished; }
bool IsWaitFinished();
bool IsWaitSet();
CBaseEntity* GetGoalEnt() { return m_hGoalEnt; }
void SetGoalEnt( CBaseEntity *pGoalEnt ) { m_hGoalEnt.Set( pGoalEnt ); }
CAI_Hint *GetHintNode() { return m_pHintNode; }
const CAI_Hint *GetHintNode() const { return m_pHintNode; }
void SetHintNode( CAI_Hint *pHintNode );
void ClearHintNode( float reuseDelay = 0.0 );
float m_flWaitFinished; // if we're told to wait, this is the time that the wait will be over.
float m_flNextFlinchTime; // Time at which we'll flinch fully again (as opposed to just doing gesture flinches)
float m_flNextDodgeTime; // Time at which I can dodge again. Used so that the behavior doesn't happen over and over.
CAI_MoveAndShootOverlay m_MoveAndShootOverlay;
Vector m_vecLastPosition; // npc sometimes wants to return to where it started after an operation.
Vector m_vSavePosition; // position stored by code that called this schedules
Vector m_vInterruptSavePosition; // position stored by a task that was interrupted
private:
CHandle<CAI_Hint> m_pHintNode; // this is the hint that the npc is moving towards or performing active idle on.
public:
int m_cAmmoLoaded; // how much ammo is in the weapon (used to trigger reload anim sequences)
float m_flDistTooFar; // if enemy farther away than this, bits_COND_ENEMY_TOOFAR set in GatherEnemyConditions
string_t m_spawnEquipment;
bool m_fNoDamageDecal;
EHANDLE m_hStoredPathTarget; // For TASK_SET_GOAL
Vector m_vecStoredPathGoal; //
GoalType_t m_nStoredPathType; //
int m_fStoredPathFlags; //
CHandle<CBaseFilter> m_hEnemyFilter;
string_t m_iszEnemyFilterName;
bool m_bDidDeathCleanup;
IMPLEMENT_NETWORK_VAR_FOR_DERIVED( m_lifeState );
//---------------------------------
// Outputs
//---------------------------------
COutputEvent m_OnDamaged;
COutputEvent m_OnDeath;
COutputEvent m_OnHalfHealth;
COutputEHANDLE m_OnFoundEnemy;
COutputEvent m_OnLostEnemyLOS;
COutputEvent m_OnLostEnemy;
COutputEHANDLE m_OnFoundPlayer;
COutputEvent m_OnLostPlayerLOS;
COutputEvent m_OnLostPlayer;
COutputEvent m_OnHearWorld;
COutputEvent m_OnHearPlayer;
COutputEvent m_OnHearCombat;
COutputEvent m_OnDamagedByPlayer;
COutputEvent m_OnDamagedByPlayerSquad;
COutputEvent m_OnDenyCommanderUse;
COutputEvent m_OnRappelTouchdown;
COutputEvent m_OnSleep;
COutputEvent m_OnWake;
COutputEvent m_OnForcedInteractionStarted;
COutputEvent m_OnForcedInteractionAborted;
COutputEvent m_OnForcedInteractionFinished;
public:
// use this to shrink the bbox temporarily
void SetHullSizeNormal( bool force = false );
bool SetHullSizeSmall( bool force = false );
bool IsUsingSmallHull() const { return m_fIsUsingSmallHull; }
const Vector & GetHullMins() const { return NAI_Hull::Mins(GetHullType()); }
const Vector & GetHullMaxs() const { return NAI_Hull::Maxs(GetHullType()); }
float GetHullWidth() const { return NAI_Hull::Width(GetHullType()); }
float GetHullHeight() const { return NAI_Hull::Height(GetHullType()); }
void SetupVPhysicsHull();
virtual void StartTouch( CBaseEntity *pOther );
void CheckPhysicsContacts();
private:
void TryRestoreHull( void );
bool m_fIsUsingSmallHull;
bool m_bCheckContacts;
private:
// Task implementation helpers
void StartTurn( float flDeltaYaw );
bool FindCoverFromEnemy( bool bNodesOnly = false, float flMinDistance = 0, float flMaxDistance = FLT_MAX );
bool FindCoverFromBestSound( Vector *pCoverPos );
void StartScriptMoveToTargetTask( int task );
void RunDieTask();
void RunAttackTask( int task );
protected:
virtual float CalcReasonableFacing( bool bIgnoreOriginalFacing = false );
virtual bool IsValidReasonableFacing( const Vector &vecSightDir, float sightDist ) { return true; }
virtual float GetReasonableFacingDist( void );
public:
inline int UsableNPCObjectCaps( int baseCaps )
{
if ( IsAlive() )
baseCaps |= FCAP_IMPULSE_USE;
return baseCaps;
}
virtual int ObjectCaps() { return (BaseClass::ObjectCaps() | FCAP_NOTIFY_ON_TRANSITION); }
//-----------------------------------------------------
//
// Core mapped data structures
//
// String Registries for default AI Shared by all CBaseNPCs
// These are used only during initialization and in debug
//-----------------------------------------------------
static void InitSchedulingTables();
static CAI_GlobalScheduleNamespace *GetSchedulingSymbols() { return &gm_SchedulingSymbols; }
static CAI_ClassScheduleIdSpace &AccessClassScheduleIdSpaceDirect() { return gm_ClassScheduleIdSpace; }
virtual CAI_ClassScheduleIdSpace * GetClassScheduleIdSpace() { return &gm_ClassScheduleIdSpace; }
static int GetScheduleID (const char* schedName);
static int GetActivityID (const char* actName);
static int GetConditionID (const char* condName);
static int GetTaskID (const char* taskName);
static int GetSquadSlotID (const char* slotName);
virtual const char* GetSquadSlotDebugName( int iSquadSlot );
static const char* GetActivityName (int actID);
static void AddActivityToSR(const char *actName, int conID);
static void AddEventToSR(const char *eventName, int conID);
static const char* GetEventName (int actID);
static int GetEventID (const char* actName);
public:
//-----------------------------------------------------
// Crouch handling
//-----------------------------------------------------
bool CrouchIsDesired( void ) const;
virtual bool IsCrouching( void );
inline void ForceCrouch( void );
inline void ClearForceCrouch( void );
protected:
virtual bool Crouch( void );
virtual bool Stand( void );
virtual void DesireCrouch( void );
inline void DesireStand( void );
bool CouldShootIfCrouching( CBaseEntity *pTarget );
virtual bool IsCrouchedActivity( Activity activity );
protected:
// Override these in your derived NPC class
virtual Vector GetCrouchEyeOffset( void ) { return Vector(0,0,40); }
virtual Vector GetCrouchGunOffset( void ) { return Vector(0,0,36); }
private:
bool m_bCrouchDesired;
bool m_bForceCrouch;
bool m_bIsCrouching;
//-----------------------------------------------------
//-----------------------------------------------------
// ai_post_frame_navigation
//-----------------------------------------------------
private:
bool m_bDeferredNavigation; // This NPCs has a navigation query that's being deferred until later in the frame
public:
void SetNavigationDeferred( bool bState ) { m_bDeferredNavigation = bState; }
bool IsNavigationDeferred( void ) { return m_bDeferredNavigation; }
//-----------------------------------------------------
protected:
static CAI_GlobalNamespace gm_SquadSlotNamespace;
static CAI_LocalIdSpace gm_SquadSlotIdSpace;
private:
// Checks to see that the nav hull is valid for the NPC
bool IsNavHullValid() const;
friend class CAI_SystemHook;
friend class CAI_SchedulesManager;
static bool LoadDefaultSchedules(void);
static void InitDefaultScheduleSR(void);
static void InitDefaultTaskSR(void);
static void InitDefaultConditionSR(void);
static void InitDefaultActivitySR(void);
static void InitDefaultSquadSlotSR(void);
static CStringRegistry* m_pActivitySR;
static int m_iNumActivities;
static CStringRegistry* m_pEventSR;
static int m_iNumEvents;
static CAI_GlobalScheduleNamespace gm_SchedulingSymbols;
static CAI_ClassScheduleIdSpace gm_ClassScheduleIdSpace;
public:
//----------------------------------------------------
// Debugging tools
//
// -----------------------------
// Debuging Fields and Methods
// -----------------------------
const char* m_failText; // Text of why it failed
const char* m_interruptText; // Text of why schedule interrupted
CAI_Schedule* m_failedSchedule; // The schedule that failed last
CAI_Schedule* m_interuptSchedule; // The schedule that was interrupted last
int m_nDebugCurIndex; // Index used for stepping through AI
virtual void ReportAIState( void );
virtual void ReportOverThinkLimit( float time );
void DumpTaskTimings();
void DrawDebugGeometryOverlays(void);
virtual int DrawDebugTextOverlays(void);
void ToggleFreeze(void);
static void ClearAllSchedules(void);
static int m_nDebugBits;
static CAI_BaseNPC* m_pDebugNPC;
static int m_nDebugPauseIndex; // Current step
static inline void SetDebugNPC( CAI_BaseNPC *pNPC ) { m_pDebugNPC = pNPC; }
static inline bool IsDebugNPC( CAI_BaseNPC *pNPC ) { return( pNPC == m_pDebugNPC ); }
float m_LastShootAccuracy;
int m_TotalShots;
int m_TotalHits;
#ifdef _DEBUG
bool m_bSelected;
#endif
float m_flSoundWaitTime; // Time when I'm allowed to make another sound
int m_nSoundPriority;
float m_flIgnoreDangerSoundsUntil;
#ifdef AI_MONITOR_FOR_OSCILLATION
CUtlVector<AIScheduleChoice_t> m_ScheduleHistory;
#endif//AI_MONITOR_FOR_OSCILLATION
private:
// Break into pieces!
void Break( CBaseEntity *pBreaker );
void InputBreak( inputdata_t &inputdata );
friend void CC_NPC_Go();
friend void CC_NPC_GoRandom();
friend void CC_NPC_Freeze( const CCommand &args );
public:
CNetworkVar( bool, m_bPerformAvoidance );
CNetworkVar( bool, m_bIsMoving );
CNetworkVar( bool, m_bFadeCorpse );
CNetworkVar( bool, m_bImportanRagdoll );
CNetworkVar( bool, m_bSpeedModActive );
CNetworkVar( int, m_iSpeedModRadius );
CNetworkVar( int, m_iSpeedModSpeed );
CNetworkVar( float, m_flTimePingEffect ); // Display the pinged effect until this time
void InputActivateSpeedModifier( inputdata_t &inputdata ) { m_bSpeedModActive = true; }
void InputDisableSpeedModifier( inputdata_t &inputdata ) { m_bSpeedModActive = false; }
void InputSetSpeedModifierRadius( inputdata_t &inputdata );
void InputSetSpeedModifierSpeed( inputdata_t &inputdata );
virtual bool ShouldProbeCollideAgainstEntity( CBaseEntity *pEntity );
bool m_bPlayerAvoidState;
void GetPlayerAvoidBounds( Vector *pMins, Vector *pMaxs );
void StartPingEffect( void ) { m_flTimePingEffect = gpGlobals->curtime + 2.0f; DispatchUpdateTransmitState(); }
};
//-----------------------------------------------------------------------------
// Purpose: Returns whether our ideal activity has started. If not, we are in
// a transition sequence.
//-----------------------------------------------------------------------------
inline bool CAI_BaseNPC::IsActivityStarted(void)
{
return (GetSequence() == m_nIdealSequence);
}
//-----------------------------------------------------------------------------
// Bullet firing (legacy)...
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::FireBullets( int cShots, const Vector &vecSrc,
const Vector &vecDirShooting, const Vector &vecSpread, float flDistance,
int iAmmoType, int iTracerFreq, int firingEntID, int attachmentID,
int iDamage, CBaseEntity *pAttacker, bool bFirstShotAccurate )
{
FireBulletsInfo_t info;
info.m_iShots = cShots;
info.m_vecSrc = vecSrc;
info.m_vecDirShooting = vecDirShooting;
info.m_vecSpread = vecSpread;
info.m_flDistance = flDistance;
info.m_iAmmoType = iAmmoType;
info.m_iTracerFreq = iTracerFreq;
info.m_iDamage = iDamage;
info.m_pAttacker = pAttacker;
info.m_nFlags = bFirstShotAccurate ? FIRE_BULLETS_FIRST_SHOT_ACCURATE : 0;
FireBullets( info );
}
//-----------------------------------------------------------------------------
// Purpose: Sets the ideal state of this NPC.
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::SetIdealState( NPC_STATE eIdealState )
{
if (eIdealState != m_IdealNPCState)
{
/*switch (eIdealState)
{
case NPC_STATE_NONE:
Msg("%s.SetIdealState: NPC_STATE_NONE\n", GetDebugName());
break;
case NPC_STATE_IDLE:
Msg("%s.SetIdealState: NPC_STATE_IDLE\n", GetDebugName());
break;
case NPC_STATE_ALERT:
Msg("%s.SetIdealState: NPC_STATE_ALERT\n", GetDebugName());
break;
case NPC_STATE_COMBAT:
Msg("%s.SetIdealState: NPC_STATE_COMBAT\n", GetDebugName());
break;
case NPC_STATE_SCRIPT:
Msg("%s.SetIdealState: NPC_STATE_SCRIPT\n", GetDebugName());
break;
case NPC_STATE_PLAYDEAD:
Msg("%s.SetIdealState: NPC_STATE_PLAYDEAD\n", GetDebugName());
break;
case NPC_STATE_PRONE:
Msg("%s.SetIdealState: NPC_STATE_PRONE\n", GetDebugName());
break;
case NPC_STATE_DEAD:
Msg("%s.SetIdealState: NPC_STATE_DEAD\n", GetDebugName());
break;
default:
Msg("%s.SetIdealState: <Unknown>\n", GetDebugName());
break;
}*/
m_IdealNPCState = eIdealState;
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns the current ideal state the NPC will try to achieve.
//-----------------------------------------------------------------------------
inline NPC_STATE CAI_BaseNPC::GetIdealState()
{
return m_IdealNPCState;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
inline int CAI_BaseNPC::IncScheduleCurTaskIndex()
{
m_ScheduleState.iTaskInterrupt = 0;
m_ScheduleState.bTaskRanAutomovement = false;
m_ScheduleState.bTaskUpdatedYaw = false;
return ++m_ScheduleState.iCurTask;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::ResetScheduleCurTaskIndex()
{
m_ScheduleState.iCurTask = 0;
m_ScheduleState.iTaskInterrupt = 0;
m_ScheduleState.bTaskRanAutomovement = false;
m_ScheduleState.bTaskUpdatedYaw = false;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
inline bool CAI_BaseNPC::CrouchIsDesired( void ) const
{
return ( (CapabilitiesGet() & bits_CAP_DUCK) && (m_bCrouchDesired | m_bForceCrouch) );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::DesireStand( void )
{
m_bCrouchDesired = false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::ForceCrouch( void )
{
m_bForceCrouch = true;
Crouch();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
inline void CAI_BaseNPC::ClearForceCrouch( void )
{
m_bForceCrouch = false;
if ( IsCrouching() )
{
Stand();
}
}
inline bool CAI_BaseNPC::HaveSequenceForActivity( Activity activity )
{
#if STUDIO_SEQUENCE_ACTIVITY_LOOKUPS_ARE_SLOW
return ( (GetModelPtr()) ? (SelectWeightedSequence( activity ) != ACTIVITY_NOT_AVAILABLE) : false );
#else
return ( (GetModelPtr()) ? GetModelPtr()->HaveSequenceForActivity(activity) : false );
#endif
}
typedef CHandle<CAI_BaseNPC> AIHANDLE;
// ============================================================================
// Macros for introducing new schedules in sub-classes
//
// Strings registries and schedules use unique ID's for each item, but
// sub-class enumerations are non-unique, so we translate between the
// enumerations and unique ID's
// ============================================================================
#define AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( derivedClass ) \
IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass ) \
void derivedClass::InitCustomSchedules( void ) \
{ \
typedef derivedClass CNpc; \
const char *pszClassName = #derivedClass; \
\
CUtlVector<char *> schedulesToLoad; \
CUtlVector<AIScheduleLoadFunc_t> reqiredOthers; \
CAI_NamespaceInfos scheduleIds; \
CAI_NamespaceInfos taskIds; \
CAI_NamespaceInfos conditionIds;
//-----------------
#define AI_BEGIN_CUSTOM_NPC( className, derivedClass ) \
IMPLEMENT_CUSTOM_AI(className, derivedClass ) \
void derivedClass::InitCustomSchedules( void ) \
{ \
typedef derivedClass CNpc; \
const char *pszClassName = #derivedClass; \
\
CUtlVector<char *> schedulesToLoad; \
CUtlVector<AIScheduleLoadFunc_t> reqiredOthers; \
CAI_NamespaceInfos scheduleIds; \
CAI_NamespaceInfos taskIds; \
CAI_NamespaceInfos conditionIds; \
CAI_NamespaceInfos squadSlotIds;
//-----------------
#define EXTERN_SCHEDULE( id ) \
scheduleIds.PushBack( #id, id ); \
extern const char * g_psz##id; \
schedulesToLoad.AddToTail( (char *)g_psz##id );
//-----------------
#define DEFINE_SCHEDULE( id, text ) \
scheduleIds.PushBack( #id, id ); \
char * g_psz##id = \
"\n Schedule" \
"\n " #id \
text \
"\n"; \
schedulesToLoad.AddToTail( (char *)g_psz##id );
//-----------------
#define DECLARE_CONDITION( id ) \
conditionIds.PushBack( #id, id );
//-----------------
#define DECLARE_TASK( id ) \
taskIds.PushBack( #id, id );
//-----------------
#define DECLARE_ACTIVITY( id ) \
ADD_CUSTOM_ACTIVITY( CNpc, id );
//-----------------
#define DECLARE_SQUADSLOT( id ) \
squadSlotIds.PushBack( #id, id );
//-----------------
#define DECLARE_INTERACTION( interaction ) \
ADD_CUSTOM_INTERACTION( interaction );
//-----------------
#define DECLARE_ANIMEVENT( id ) \
ADD_CUSTOM_ANIMEVENT( CNpc, id );
//-----------------
#define DECLARE_USES_SCHEDULE_PROVIDER( classname ) reqiredOthers.AddToTail( ScheduleLoadHelper(classname) );
//-----------------
// IDs are stored and then added in order due to constraints in the namespace implementation
#define AI_END_CUSTOM_SCHEDULE_PROVIDER() \
\
int i; \
\
CNpc::AccessClassScheduleIdSpaceDirect().Init( pszClassName, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
\
scheduleIds.Sort(); \
taskIds.Sort(); \
conditionIds.Sort(); \
\
for ( i = 0; i < scheduleIds.Count(); i++ ) \
{ \
ADD_CUSTOM_SCHEDULE_NAMED( CNpc, scheduleIds[i].pszName, scheduleIds[i].localId ); \
} \
\
for ( i = 0; i < taskIds.Count(); i++ ) \
{ \
ADD_CUSTOM_TASK_NAMED( CNpc, taskIds[i].pszName, taskIds[i].localId ); \
} \
\
for ( i = 0; i < conditionIds.Count(); i++ ) \
{ \
if ( ValidateConditionLimits( conditionIds[i].pszName ) ) \
{ \
ADD_CUSTOM_CONDITION_NAMED( CNpc, conditionIds[i].pszName, conditionIds[i].localId ); \
} \
} \
\
for ( i = 0; i < reqiredOthers.Count(); i++ ) \
{ \
(*reqiredOthers[i])(); \
} \
\
for ( i = 0; i < schedulesToLoad.Count(); i++ ) \
{ \
if ( CNpc::gm_SchedLoadStatus.fValid ) \
{ \
CNpc::gm_SchedLoadStatus.fValid = g_AI_SchedulesManager.LoadSchedulesFromBuffer( pszClassName, schedulesToLoad[i], &AccessClassScheduleIdSpaceDirect() ); \
} \
else \
break; \
} \
}
inline bool ValidateConditionLimits( const char *pszNewCondition )
{
int nGlobalConditions = CAI_BaseNPC::GetSchedulingSymbols()->NumConditions();
if ( nGlobalConditions >= MAX_CONDITIONS )
{
AssertMsg2( 0, "Exceeded max number of conditions (%d), ignoring condition %s\n", MAX_CONDITIONS, pszNewCondition );
DevWarning( "Exceeded max number of conditions (%d), ignoring condition %s\n", MAX_CONDITIONS, pszNewCondition );
return false;
}
return true;
}
//-------------------------------------
// IDs are stored and then added in order due to constraints in the namespace implementation
#define AI_END_CUSTOM_NPC() \
\
int i; \
\
CNpc::AccessClassScheduleIdSpaceDirect().Init( pszClassName, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
CNpc::gm_SquadSlotIdSpace.Init( &BaseClass::gm_SquadSlotNamespace, &BaseClass::gm_SquadSlotIdSpace); \
\
scheduleIds.Sort(); \
taskIds.Sort(); \
conditionIds.Sort(); \
squadSlotIds.Sort(); \
\
for ( i = 0; i < scheduleIds.Count(); i++ ) \
{ \
ADD_CUSTOM_SCHEDULE_NAMED( CNpc, scheduleIds[i].pszName, scheduleIds[i].localId ); \
} \
\
for ( i = 0; i < taskIds.Count(); i++ ) \
{ \
ADD_CUSTOM_TASK_NAMED( CNpc, taskIds[i].pszName, taskIds[i].localId ); \
} \
\
for ( i = 0; i < conditionIds.Count(); i++ ) \
{ \
if ( ValidateConditionLimits( conditionIds[i].pszName ) ) \
{ \
ADD_CUSTOM_CONDITION_NAMED( CNpc, conditionIds[i].pszName, conditionIds[i].localId ); \
} \
} \
\
for ( i = 0; i < squadSlotIds.Count(); i++ ) \
{ \
ADD_CUSTOM_SQUADSLOT_NAMED( CNpc, squadSlotIds[i].pszName, squadSlotIds[i].localId ); \
} \
\
for ( i = 0; i < reqiredOthers.Count(); i++ ) \
{ \
(*reqiredOthers[i])(); \
} \
\
for ( i = 0; i < schedulesToLoad.Count(); i++ ) \
{ \
if ( CNpc::gm_SchedLoadStatus.fValid ) \
{ \
CNpc::gm_SchedLoadStatus.fValid = g_AI_SchedulesManager.LoadSchedulesFromBuffer( pszClassName, schedulesToLoad[i], &AccessClassScheduleIdSpaceDirect() ); \
} \
else \
break; \
} \
}
//-------------------------------------
struct AI_NamespaceAddInfo_t
{
AI_NamespaceAddInfo_t( const char *pszName, int localId )
: pszName( pszName ),
localId( localId )
{
}
const char *pszName;
int localId;
};
class CAI_NamespaceInfos : public CUtlVector<AI_NamespaceAddInfo_t>
{
public:
void PushBack( const char *pszName, int localId )
{
AddToTail( AI_NamespaceAddInfo_t( pszName, localId ) );
}
void Sort()
{
CUtlVector<AI_NamespaceAddInfo_t>::Sort( Compare );
}
private:
static int __cdecl Compare(const AI_NamespaceAddInfo_t *pLeft, const AI_NamespaceAddInfo_t *pRight )
{
return pLeft->localId - pRight->localId;
}
};
//-------------------------------------
// Declares the static variables that hold the string registry offset for the new subclass
// as well as the initialization in schedule load functions
struct AI_SchedLoadStatus_t
{
bool fValid;
int signature;
};
// Load schedules pulled out to support stepping through with debugger
inline bool AI_DoLoadSchedules( bool (*pfnBaseLoad)(), void (*pfnInitCustomSchedules)(),
AI_SchedLoadStatus_t *pLoadStatus )
{
(*pfnBaseLoad)();
if (pLoadStatus->signature != g_AI_SchedulesManager.GetScheduleLoadSignature())
{
(*pfnInitCustomSchedules)();
pLoadStatus->fValid = true;
pLoadStatus->signature = g_AI_SchedulesManager.GetScheduleLoadSignature();
}
return pLoadStatus->fValid;
}
//-------------------------------------
typedef bool (*AIScheduleLoadFunc_t)();
// @Note (toml 02-16-03): The following class exists to allow us to establish an anonymous friendship
// in DEFINE_CUSTOM_SCHEDULE_PROVIDER. The particulars of this implementation is almost entirely
// defined by bugs in MSVC 6.0
class ScheduleLoadHelperImpl
{
public:
template <typename T>
static AIScheduleLoadFunc_t AccessScheduleLoadFunc(T *)
{
return (&T::LoadSchedules);
}
};
#define ScheduleLoadHelper( type ) (ScheduleLoadHelperImpl::AccessScheduleLoadFunc((type *)0))
//-------------------------------------
#define DEFINE_CUSTOM_SCHEDULE_PROVIDER\
static AI_SchedLoadStatus_t gm_SchedLoadStatus; \
static CAI_ClassScheduleIdSpace gm_ClassScheduleIdSpace; \
static const char * gm_pszErrorClassName;\
\
static CAI_ClassScheduleIdSpace & AccessClassScheduleIdSpaceDirect() { return gm_ClassScheduleIdSpace; } \
virtual CAI_ClassScheduleIdSpace * GetClassScheduleIdSpace() { return &gm_ClassScheduleIdSpace; } \
virtual const char * GetSchedulingErrorName() { return gm_pszErrorClassName; } \
\
static void InitCustomSchedules(void);\
\
static bool LoadSchedules(void);\
virtual bool LoadedSchedules(void); \
\
friend class ScheduleLoadHelperImpl; \
\
class CScheduleLoader \
{ \
public: \
CScheduleLoader(); \
} m_ScheduleLoader; \
\
friend class CScheduleLoader;
//-------------------------------------
#define DEFINE_CUSTOM_AI\
DEFINE_CUSTOM_SCHEDULE_PROVIDER \
\
static CAI_LocalIdSpace gm_SquadSlotIdSpace; \
\
const char* SquadSlotName (int squadSlotID);
//-------------------------------------
#define IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass)\
AI_SchedLoadStatus_t derivedClass::gm_SchedLoadStatus = { true, -1 }; \
CAI_ClassScheduleIdSpace derivedClass::gm_ClassScheduleIdSpace; \
const char * derivedClass::gm_pszErrorClassName = #derivedClass; \
\
derivedClass::CScheduleLoader::CScheduleLoader()\
{ \
derivedClass::LoadSchedules(); \
} \
\
/* --------------------------------------------- */ \
/* Load schedules for this type of NPC */ \
/* --------------------------------------------- */ \
bool derivedClass::LoadSchedules(void)\
{\
return AI_DoLoadSchedules( derivedClass::BaseClass::LoadSchedules, \
derivedClass::InitCustomSchedules, \
&derivedClass::gm_SchedLoadStatus ); \
}\
\
bool derivedClass::LoadedSchedules(void) \
{ \
return derivedClass::gm_SchedLoadStatus.fValid;\
}
//-------------------------------------
// Initialize offsets and implement methods for loading and getting squad info for the subclass
#define IMPLEMENT_CUSTOM_AI(className, derivedClass)\
IMPLEMENT_CUSTOM_SCHEDULE_PROVIDER(derivedClass)\
\
CAI_LocalIdSpace derivedClass::gm_SquadSlotIdSpace; \
\
/* -------------------------------------------------- */ \
/* Given squadSlot enumeration return squadSlot name */ \
/* -------------------------------------------------- */ \
const char* derivedClass::SquadSlotName(int slotEN)\
{\
return gm_SquadSlotNamespace.IdToSymbol( derivedClass::gm_SquadSlotIdSpace.LocalToGlobal(slotEN) );\
}
//-------------------------------------
#define ADD_CUSTOM_SCHEDULE_NAMED(derivedClass,schedName,schedEN)\
if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddSchedule( schedName, schedEN, derivedClass::gm_pszErrorClassName ) ) return;
#define ADD_CUSTOM_SCHEDULE(derivedClass,schedEN) ADD_CUSTOM_SCHEDULE_NAMED(derivedClass,#schedEN,schedEN)
#define ADD_CUSTOM_TASK_NAMED(derivedClass,taskName,taskEN)\
if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddTask( taskName, taskEN, derivedClass::gm_pszErrorClassName ) ) return;
#define ADD_CUSTOM_TASK(derivedClass,taskEN) ADD_CUSTOM_TASK_NAMED(derivedClass,#taskEN,taskEN)
#define ADD_CUSTOM_CONDITION_NAMED(derivedClass,condName,condEN)\
if ( !derivedClass::AccessClassScheduleIdSpaceDirect().AddCondition( condName, condEN, derivedClass::gm_pszErrorClassName ) ) return;
#define ADD_CUSTOM_CONDITION(derivedClass,condEN) ADD_CUSTOM_CONDITION_NAMED(derivedClass,#condEN,condEN)
//-------------------------------------
#define INIT_CUSTOM_AI(derivedClass)\
derivedClass::AccessClassScheduleIdSpaceDirect().Init( #derivedClass, BaseClass::GetSchedulingSymbols(), &BaseClass::AccessClassScheduleIdSpaceDirect() ); \
derivedClass::gm_SquadSlotIdSpace.Init( &CAI_BaseNPC::gm_SquadSlotNamespace, &BaseClass::gm_SquadSlotIdSpace);
#define ADD_CUSTOM_INTERACTION( interaction ) { interaction = CBaseCombatCharacter::GetInteractionID(); }
#define ADD_CUSTOM_SQUADSLOT_NAMED(derivedClass,squadSlotName,squadSlotEN)\
if ( !derivedClass::gm_SquadSlotIdSpace.AddSymbol( squadSlotName, squadSlotEN, "squadslot", derivedClass::gm_pszErrorClassName ) ) return;
#define ADD_CUSTOM_SQUADSLOT(derivedClass,squadSlotEN) ADD_CUSTOM_SQUADSLOT_NAMED(derivedClass,#squadSlotEN,squadSlotEN)
#define ADD_CUSTOM_ACTIVITY_NAMED(derivedClass,activityName,activityEnum)\
REGISTER_PRIVATE_ACTIVITY(activityEnum);\
CAI_BaseNPC::AddActivityToSR(activityName,activityEnum);
#define ADD_CUSTOM_ACTIVITY(derivedClass,activityEnum) ADD_CUSTOM_ACTIVITY_NAMED(derivedClass,#activityEnum,activityEnum)
#define ADD_CUSTOM_ANIMEVENT_NAMED(derivedClass,eventName,eventEnum)\
REGISTER_PRIVATE_ANIMEVENT(eventEnum);\
CAI_BaseNPC::AddEventToSR(eventName,eventEnum);
#define ADD_CUSTOM_ANIMEVENT(derivedClass,eventEnum) ADD_CUSTOM_ANIMEVENT_NAMED(derivedClass,#eventEnum,eventEnum)
//=============================================================================
// class CAI_Component
//=============================================================================
inline const Vector &CAI_Component::GetLocalOrigin() const
{
return GetOuter()->GetLocalOrigin();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetLocalOrigin(const Vector &origin)
{
GetOuter()->SetLocalOrigin(origin);
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::GetAbsOrigin() const
{
return GetOuter()->GetAbsOrigin();
}
//-----------------------------------------------------------------------------
inline const QAngle &CAI_Component::GetAbsAngles() const
{
return GetOuter()->GetAbsAngles();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetSolid( SolidType_t val )
{
GetOuter()->SetSolid(val);
}
//-----------------------------------------------------------------------------
inline SolidType_t CAI_Component::GetSolid() const
{
return GetOuter()->GetSolid();
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::WorldAlignMins() const
{
return GetOuter()->WorldAlignMins();
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::WorldAlignMaxs() const
{
return GetOuter()->WorldAlignMaxs();
}
//-----------------------------------------------------------------------------
inline Hull_t CAI_Component::GetHullType() const
{
return GetOuter()->GetHullType();
}
//-----------------------------------------------------------------------------
inline Vector CAI_Component::WorldSpaceCenter() const
{
return GetOuter()->WorldSpaceCenter();
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetGravity() const
{
return GetOuter()->GetGravity();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetGravity( float flGravity )
{
GetOuter()->SetGravity( flGravity );
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetHullWidth() const
{
return NAI_Hull::Width(GetOuter()->GetHullType());
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetHullHeight() const
{
return NAI_Hull::Height(GetOuter()->GetHullType());
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::GetHullMins() const
{
return NAI_Hull::Mins(GetOuter()->GetHullType());
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::GetHullMaxs() const
{
return NAI_Hull::Maxs(GetOuter()->GetHullType());
}
//-----------------------------------------------------------------------------
inline int CAI_Component::GetCollisionGroup() const
{
return GetOuter()->GetCollisionGroup();
}
//-----------------------------------------------------------------------------
inline CBaseEntity *CAI_Component::GetEnemy()
{
return GetOuter()->GetEnemy();
}
//-----------------------------------------------------------------------------
inline const Vector &CAI_Component::GetEnemyLKP() const
{
return GetOuter()->GetEnemyLKP();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::TranslateNavGoal( CBaseEntity *pEnemy, Vector &chasePosition )
{
GetOuter()->TranslateNavGoal( pEnemy, chasePosition );
}
//-----------------------------------------------------------------------------
inline CBaseEntity *CAI_Component::GetTarget()
{
return GetOuter()->GetTarget();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetTarget( CBaseEntity *pTarget )
{
GetOuter()->SetTarget( pTarget );
}
//-----------------------------------------------------------------------------
inline const Task_t *CAI_Component::GetCurTask()
{
return GetOuter()->GetTask();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::TaskFail( AI_TaskFailureCode_t code )
{
GetOuter()->TaskFail( code );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::TaskFail( const char *pszGeneralFailText )
{
GetOuter()->TaskFail( pszGeneralFailText );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::TaskComplete( bool fIgnoreSetFailedCondition )
{
GetOuter()->TaskComplete( fIgnoreSetFailedCondition );
}
//-----------------------------------------------------------------------------
inline int CAI_Component::TaskIsRunning()
{
return GetOuter()->TaskIsRunning();
}
//-----------------------------------------------------------------------------
inline int CAI_Component::TaskIsComplete()
{
return GetOuter()->TaskIsComplete();
}
//-----------------------------------------------------------------------------
inline Activity CAI_Component::GetActivity()
{
return GetOuter()->GetActivity();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetActivity( Activity NewActivity )
{
GetOuter()->SetActivity( NewActivity );
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetIdealSpeed() const
{
return GetOuter()->GetIdealSpeed();
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetIdealAccel() const
{
return GetOuter()->GetIdealAccel();
}
//-----------------------------------------------------------------------------
inline int CAI_Component::GetSequence()
{
return GetOuter()->GetSequence();
}
//-----------------------------------------------------------------------------
inline int CAI_Component::GetEntFlags() const
{
return GetOuter()->GetFlags();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::AddEntFlag( int flags )
{
GetOuter()->AddFlag( flags );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::RemoveEntFlag( int flagsToRemove )
{
GetOuter()->RemoveFlag( flagsToRemove );
}
//-----------------------------------------------------------------------------
// Purpose: Change the ground entity for the outer
// Input : *ground -
// Output : inline void
//-----------------------------------------------------------------------------
inline void CAI_Component::SetGroundEntity( CBaseEntity *ground )
{
GetOuter()->SetGroundEntity( ground );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::ToggleEntFlag( int flagToToggle )
{
GetOuter()->ToggleFlag( flagToToggle );
}
//-----------------------------------------------------------------------------
inline CBaseEntity* CAI_Component::GetGoalEnt()
{
return GetOuter()->GetGoalEnt();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetGoalEnt( CBaseEntity *pGoalEnt )
{
GetOuter()->SetGoalEnt( pGoalEnt );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::Remember( int iMemory )
{
GetOuter()->Remember( iMemory );
}
//-----------------------------------------------------------------------------
inline void CAI_Component::Forget( int iMemory )
{
GetOuter()->Forget( iMemory );
}
//-----------------------------------------------------------------------------
inline bool CAI_Component::HasMemory( int iMemory )
{
return GetOuter()->HasMemory( iMemory );
}
//-----------------------------------------------------------------------------
inline CAI_Enemies *CAI_Component::GetEnemies()
{
return GetOuter()->GetEnemies();
}
//-----------------------------------------------------------------------------
inline const char *CAI_Component::GetEntClassname()
{
return GetOuter()->GetClassname();
}
//-----------------------------------------------------------------------------
inline int CAI_Component::CapabilitiesGet()
{
return GetOuter()->CapabilitiesGet();
}
//-----------------------------------------------------------------------------
inline void CAI_Component::SetLocalAngles( const QAngle& angles )
{
GetOuter()->SetLocalAngles( angles );
}
//-----------------------------------------------------------------------------
inline const QAngle &CAI_Component::GetLocalAngles( void ) const
{
return GetOuter()->GetLocalAngles();
}
//-----------------------------------------------------------------------------
inline edict_t *CAI_Component::GetEdict()
{
return GetOuter()->NetworkProp()->edict();
}
//-----------------------------------------------------------------------------
inline float CAI_Component::GetLastThink( const char *szContext )
{
return GetOuter()->GetLastThink( szContext );
}
// ============================================================================
abstract_class INPCInteractive
{
public:
virtual bool CanInteractWith( CAI_BaseNPC *pUser ) = 0;
virtual bool HasBeenInteractedWith() = 0;
virtual void NotifyInteraction( CAI_BaseNPC *pUser ) = 0;
// Alyx specific interactions
virtual void AlyxStartedInteraction( void ) = 0;
virtual void AlyxFinishedInteraction( void ) = 0;
};
// Base Class for any NPC that wants to be interactable by other NPCS (i.e. Alyx Hackable)
// NOTE: YOU MUST DEFINE THE OUTPUTS IN YOUR CLASS'S DATADESC!
// THE DO SO, INSERT THE FOLLOWING MACRO INTO YOUR CLASS'S DATADESC.
//
#define DEFINE_BASENPCINTERACTABLE_DATADESC() \
DEFINE_OUTPUT( m_OnAlyxStartedInteraction, "OnAlyxStartedInteraction" ), \
DEFINE_OUTPUT( m_OnAlyxFinishedInteraction, "OnAlyxFinishedInteraction" ), \
DEFINE_INPUTFUNC( FIELD_VOID, "InteractivePowerDown", InputPowerdown )
template <class NPC_CLASS>
class CNPCBaseInteractive : public NPC_CLASS, public INPCInteractive
{
DECLARE_CLASS( CNPCBaseInteractive, NPC_CLASS );
public:
virtual bool CanInteractWith( CAI_BaseNPC *pUser ) { return false; };
virtual bool HasBeenInteractedWith() { return false; };
virtual void NotifyInteraction( CAI_BaseNPC *pUser ) { return; };
virtual void InputPowerdown( inputdata_t &inputdata )
{
}
// Alyx specific interactions
virtual void AlyxStartedInteraction( void )
{
m_OnAlyxStartedInteraction.FireOutput( this, this );
}
virtual void AlyxFinishedInteraction( void )
{
m_OnAlyxFinishedInteraction.FireOutput( this, this );
}
public:
// Outputs
// Alyx specific interactions
COutputEvent m_OnAlyxStartedInteraction;
COutputEvent m_OnAlyxFinishedInteraction;
};
//
// Deferred Navigation calls go here
//
extern ConVar ai_post_frame_navigation;
class CPostFrameNavigationHook : public CBaseGameSystemPerFrame
{
public:
virtual const char *Name( void ) { return "CPostFrameNavigationHook"; }
virtual bool Init( void );
virtual void FrameUpdatePostEntityThink( void );
virtual void FrameUpdatePreEntityThink( void );
bool IsGameFrameRunning( void ) { return m_bGameFrameRunning; }
void SetGrameFrameRunning( bool bState ) { m_bGameFrameRunning = bState; }
void EnqueueEntityNavigationQuery( CAI_BaseNPC *pNPC, CFunctor *functor );
private:
CUtlVector<CFunctor *> m_Functors;
bool m_bGameFrameRunning;
};
extern CPostFrameNavigationHook *PostFrameNavigationSystem( void );
#endif // AI_BASENPC_H
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
3260
]
]
]
|
321ee8ff277f33676d0568fbbd30a9b997898f94 | 29c5bc6757634a26ac5103f87ed068292e418d74 | /src/Helper.cpp | a28213346043398641f637c0452667c4ed6cf9d4 | []
| 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 | 2,962 | cpp | #include "Helper.h"
void xcept(const char *fmt, ...)
{
static char xcept_str[0x100];
va_list args;
va_start(args, fmt);
memset(xcept_str, 0, sizeof(xcept_str));
//vsnprintf(xcept_str, sizeof(xcept_str)-1, fmt, args);
vsnprintf_s(xcept_str, sizeof(xcept_str)-1, 0x100, fmt, args);
throw (const char*)xcept_str;
}
double getLogTimer()
{
static Timer logTimer;
return logTimer.getTime();
}
void log(const char *fmt, ...)
{
va_list args;
va_start(args,fmt);
string s = vformat(fmt,args);
double t = getLogTimer();
s = format("%4.3f %s\n",t,s.c_str());
printf("%s",s.c_str());
};
void log(const wchar_t* fmt, ...)
{
va_list args;
va_start(args,fmt);
wstring s = vwformat(fmt, args);
double t = getLogTimer();
s = wformat(L"%4.3f %s\n", t, s.c_str());
wprintf(L"%s", s.c_str());
}
void logColor(const WORD colorFMT, const char *fmt, ...)
{
static HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
SetConsoleTextAttribute(hstdout, colorFMT);
va_list args;
va_start(args,fmt);
string s = vformat(fmt,args);
double t = getLogTimer();
s = format("%4.3f %s\n",t,s.c_str());
printf("%s",s.c_str());
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
}
void logColor(const WORD colorFMT, const wchar_t *fmt, ...)
{
static HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(hstdout, &csbi);
SetConsoleTextAttribute(hstdout, colorFMT);
va_list args;
va_start(args,fmt);
wstring s = vwformat(fmt, args);
double t = getLogTimer();
s = wformat(L"%4.3f %s\n", t, s.c_str());
wprintf(L"%s", s.c_str());
SetConsoleTextAttribute(hstdout, csbi.wAttributes);
}
string format(const char *format, ...)
{
string res("");
va_list args;
va_start(args,format);
size_t len = _vscprintf(format,args);
res.resize(len+1);
char*buf = (char*)res.c_str();
vsprintf_s(buf,len+1,format,args);
//buf[len]='\0';
return res.c_str();
}
wstring wformat(const wchar_t *format, ...)
{
wstring res(L"");
va_list args;
va_start(args, format);
size_t len = _vscwprintf(format, args);
res.resize(len+1);
wchar_t *buf = (wchar_t*)res.c_str();
vswprintf_s(buf, len+2, format, args);
return res.c_str();
}
string vformat(const char *format, va_list args)
{
string res("");
size_t len = _vscprintf(format,args);
res.resize(len+1);
char* buf = (char*)res.c_str();
vsprintf_s(buf,len+1,format,args);
//buf[len]='\0';
return res.c_str();
}
wstring vwformat(const wchar_t *format, va_list args)
{
wstring res(L"");
size_t len = _vscwprintf(format, args);
res.resize(len+2);
wchar_t* buf = (wchar_t*)res.c_str();
vswprintf_s(buf, len+2, format, args);
//buf[len]='\0';
return res.c_str();
}
| [
"drivehappy@53ea644a-42e2-1498-a4e7-6aa81ae25522"
]
| [
[
[
1,
123
]
]
]
|
ace6e17b3dea7126afb105d3e3dcbf4aa6877a72 | 305f56324b8c1625a5f3ba7966d1ce6c540e9d97 | /src/lister/TaskMacroByDriverGrid.h | cde2f54369231cd8cd776888f03915f4d1cff441 | []
| no_license | radtek/lister | be45f7ac67da72c1c2ac0d7cd878032c9648af7b | 71418c72b31823624f545ad86cc804c43b6e9426 | refs/heads/master | 2021-01-01T19:56:30.878680 | 2011-06-22T17:04:13 | 2011-06-22T17:04:13 | 41,946,076 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,390 | h | #ifndef _lister_lister_TaskMacroByDriverGrid_h_
#define _lister_lister_TaskMacroByDriverGrid_h_
#include <lister/Urp/UrpGrid.h>
#include <lister/Urp/UrpInput.h> // Need BoolOption
class Connection;
//==============================================================================================
class TaskMacroByDriverGrid : public UrpGrid {
public:
typedef TaskMacroByDriverGrid CLASSNAME;
EditString fldNote;
EditStringNotNull fldSearchFor;
EditStringNotNull fldReplaceWith;
int taskId; // Filter all tests by task id, for manageability
// Count of fixed columns that are present for all sets
int driverColumnOffset;
// Count of driver columns (currently 3 x the drivers
int driverColumnsPresent;
int driverCount;
// List of pointers to EditString objects created on the fly and destroyed in our destructor
VectorMap<
String,
EditString *> editors;
TaskMacroByDriverGrid ();
~TaskMacroByDriverGrid ();
virtual void Build (Connection *pconnection); // Mandatory UrpGrid implementation
virtual void Load (); // Mandatory UrpGrid implementation
void SetTaskId(int ptaskId);
// Added manually from appending a row.
void EnterNewRow (); // New generic name
// Completed a new row and you want to save it
void CompleteNewRow();
// GridCtrl will remove the row if we do not cancel the remove.
void RemoveRow ();
// For When callbacks it's easier to call a no-arg function
void SavePrompt ();
void SaveNoPrompt ();
void FieldLayout (FieldOperator& fo);
void Save (bool prompt);
void SaveRow (int row, int newProcessOrder);
bool MeaningfulDataChange ();
};
#endif
| [
"jeffshumphreys@97668ed5-8355-0e3d-284e-ab2976d7b0b4"
]
| [
[
[
1,
54
]
]
]
|
6be321739c407d161b709c15f868cec21086f461 | 47e686442752f1d82ef5081326d02a53be3f5188 | /source/gui/GUIFrame.cpp | 50513c11588a6dbf8952ffa6d02633b39fcb1d67 | []
| no_license | xiaohuangyu/raytrace | 7339b82e2d2fc85366d4a3bc8de09ceb4ff58358 | 26bbf62f3fd03d58ad1580427e055921f269f972 | refs/heads/master | 2020-04-26T15:47:53.362314 | 2011-06-30T14:58:28 | 2011-06-30T14:58:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,247 | cpp | ///////////////////////////////////////////////////////////////////////////
// C++ code generated with wxFormBuilder (version Feb 17 2010)
// http://www.wxformbuilder.org/
//
// PLEASE DO "NOT" EDIT THIS FILE!
///////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif //__BORLANDC__
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif //WX_PRECOMP
#include "GUIFrame.h"
///////////////////////////////////////////////////////////////////////////
GUIFrame::GUIFrame( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
mbar = new wxMenuBar( 0 );
fileMenu = new wxMenu();
wxMenuItem* menuFileOpen;
menuFileOpen = new wxMenuItem( fileMenu, idMenuOpen, wxString( wxT("打开(&O)") ) + wxT('\t') + wxT("Ctrl+O"), wxT("打开文件"), wxITEM_NORMAL );
fileMenu->Append( menuFileOpen );
wxMenuItem* menuFileSave;
menuFileSave = new wxMenuItem( fileMenu, idMenuSave, wxString( wxT("保存(&S)") ) + wxT('\t') + wxT("Ctrl+S"), wxT("保存数据"), wxITEM_NORMAL );
fileMenu->Append( menuFileSave );
wxMenuItem* m_separator1;
m_separator1 = fileMenu->AppendSeparator();
wxMenuItem* menuFileQuit;
menuFileQuit = new wxMenuItem( fileMenu, idMenuQuit, wxString( wxT("退出(&Q)") ) + wxT('\t') + wxT("Alt+F4"), wxT("退出本程序"), wxITEM_NORMAL );
fileMenu->Append( menuFileQuit );
mbar->Append( fileMenu, wxT("文件(&F)") );
helpMenu = new wxMenu();
wxMenuItem* menuHelpAbout;
menuHelpAbout = new wxMenuItem( helpMenu, idMenuAbout, wxString( wxT("关于(&A)") ) + wxT('\t') + wxT("F1"), wxT("关于"), wxITEM_NORMAL );
helpMenu->Append( menuHelpAbout );
mbar->Append( helpMenu, wxT("帮助(&H)") );
this->SetMenuBar( mbar );
statusBar = this->CreateStatusBar( 2, wxST_SIZEGRIP, wxID_ANY );
wxFlexGridSizer* fgSizer1;
fgSizer1 = new wxFlexGridSizer( 2, 1, 0, 0 );
fgSizer1->SetFlexibleDirection( wxBOTH );
fgSizer1->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
sys_data = new wxGrid( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
// Grid
sys_data->CreateGrid( 1, 5 );
sys_data->EnableEditing( true );
sys_data->EnableGridLines( true );
sys_data->EnableDragGridSize( false );
sys_data->SetMargins( 0, 0 );
// Columns
sys_data->SetColSize( 0, 72 );
sys_data->SetColSize( 1, 85 );
sys_data->SetColSize( 2, 81 );
sys_data->SetColSize( 3, 83 );
sys_data->SetColSize( 4, 80 );
sys_data->EnableDragColMove( false );
sys_data->EnableDragColSize( false );
sys_data->SetColLabelSize( 30 );
sys_data->SetColLabelValue( 0, wxT("表面数N") );
sys_data->SetColLabelValue( 1, wxT("入瞳距lpw") );
sys_data->SetColLabelValue( 2, wxT("孔阑直径2a") );
sys_data->SetColLabelValue( 3, wxT("视场角2W") );
sys_data->SetColLabelValue( 4, wxT("普通光线条数") );
sys_data->SetColLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Rows
sys_data->AutoSizeRows();
sys_data->EnableDragRowSize( false );
sys_data->SetRowLabelSize( 80 );
sys_data->SetRowLabelValue( 0, wxT("系统参数") );
sys_data->SetRowLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Label Appearance
// Cell Defaults
sys_data->SetDefaultCellAlignment( wxALIGN_LEFT, wxALIGN_TOP );
fgSizer1->Add( sys_data, 0, wxALL, 5 );
len_data = new wxGrid( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
// Grid
len_data->CreateGrid( 4, 5 );
len_data->EnableEditing( true );
len_data->EnableGridLines( true );
len_data->EnableDragGridSize( false );
len_data->SetMargins( 0, 0 );
// Columns
len_data->SetColSize( 0, 69 );
len_data->SetColSize( 1, 93 );
len_data->SetColSize( 2, 71 );
len_data->SetColSize( 3, 88 );
len_data->SetColSize( 4, 83 );
len_data->EnableDragColMove( false );
len_data->EnableDragColSize( true );
len_data->SetColLabelSize( 30 );
len_data->SetColLabelValue( 0, wxT("曲面半径r") );
len_data->SetColLabelValue( 1, wxT("与下一面间距d") );
len_data->SetColLabelValue( 2, wxT("折射率n") );
len_data->SetColLabelValue( 3, wxT("F光折射率nF") );
len_data->SetColLabelValue( 4, wxT("C光折射率nC") );
len_data->SetColLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Rows
len_data->EnableDragRowSize( true );
len_data->SetRowLabelSize( 80 );
len_data->SetRowLabelValue( 0, wxT("0(空气/物面)") );
len_data->SetRowLabelValue( 1, wxT("1") );
len_data->SetRowLabelValue( 2, wxT("2") );
len_data->SetRowLabelValue( 3, wxT("3") );
len_data->SetRowLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Label Appearance
// Cell Defaults
len_data->SetDefaultCellAlignment( wxALIGN_LEFT, wxALIGN_TOP );
fgSizer1->Add( len_data, 0, wxALL, 5 );
wxFlexGridSizer* fgSizer3;
fgSizer3 = new wxFlexGridSizer( 2, 2, 0, 0 );
fgSizer3->SetFlexibleDirection( wxBOTH );
fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
putong_data = new wxGrid( this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0 );
// Grid
putong_data->CreateGrid( 4, 3 );
putong_data->EnableEditing( true );
putong_data->EnableGridLines( true );
putong_data->EnableDragGridSize( false );
putong_data->SetMargins( 0, 0 );
// Columns
putong_data->EnableDragColMove( false );
putong_data->EnableDragColSize( true );
putong_data->SetColLabelSize( 30 );
putong_data->SetColLabelValue( 0, wxT("L") );
putong_data->SetColLabelValue( 1, wxT("U") );
putong_data->SetColLabelValue( 2, wxT("H") );
putong_data->SetColLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Rows
putong_data->EnableDragRowSize( true );
putong_data->SetRowLabelSize( 80 );
putong_data->SetRowLabelAlignment( wxALIGN_CENTRE, wxALIGN_CENTRE );
// Label Appearance
// Cell Defaults
putong_data->SetDefaultCellAlignment( wxALIGN_LEFT, wxALIGN_TOP );
fgSizer3->Add( putong_data, 0, wxALL, 5 );
wxGridSizer* gSizer1;
gSizer1 = new wxGridSizer( 3, 1, 0, 0 );
btRefresh = new wxButton( this, wxID_ANY, wxT("已自动刷新"), wxDefaultPosition, wxDefaultSize, 0 );
btRefresh->Enable( false );
gSizer1->Add( btRefresh, 0, wxALL, 5 );
btCal = new wxButton( this, wxID_ANY, wxT("计算"), wxDefaultPosition, wxDefaultSize, 0 );
btCal->SetDefault();
gSizer1->Add( btCal, 0, wxALL, 5 );
btDraw = new wxButton( this, wxID_ANY, wxT("画图"), wxDefaultPosition, wxDefaultSize, 0 );
gSizer1->Add( btDraw, 0, wxALL, 5 );
fgSizer3->Add( gSizer1, 1, wxALIGN_LEFT, 5 );
fgSizer1->Add( fgSizer3, 1, wxEXPAND, 5 );
this->SetSizer( fgSizer1 );
this->Layout();
fgSizer1->Fit( this );
// Connect Events
this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( GUIFrame::OnClose ) );
this->Connect( menuFileOpen->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnOpen ) );
this->Connect( menuFileSave->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnSave ) );
this->Connect( menuFileQuit->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnQuit ) );
this->Connect( menuHelpAbout->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnAbout ) );
btRefresh->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnRefresh ), NULL, this );
btCal->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnCal ), NULL, this );
btDraw->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnDraw ), NULL, this );
}
GUIFrame::~GUIFrame()
{
// Disconnect Events
this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( GUIFrame::OnClose ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnOpen ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnSave ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnQuit ) );
this->Disconnect( wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( GUIFrame::OnAbout ) );
btRefresh->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnRefresh ), NULL, this );
btCal->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnCal ), NULL, this );
btDraw->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( GUIFrame::OnDraw ), NULL, this );
}
DrawDlg::DrawDlg( wxWindow* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxDialog( parent, id, title, pos, size, style )
{
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
wxFlexGridSizer* fgSizer3;
fgSizer3 = new wxFlexGridSizer( 2, 1, 0, 0 );
fgSizer3->SetFlexibleDirection( wxBOTH );
fgSizer3->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
wxBoxSizer* bSizer5;
bSizer5 = new wxBoxSizer( wxVERTICAL );
bSizer5->SetMinSize( wxSize( 400,400 ) );
fgSizer3->Add( bSizer5, 1, wxEXPAND, 5 );
wxFlexGridSizer* fgSizer4;
fgSizer4 = new wxFlexGridSizer( 2, 5, 0, 0 );
fgSizer4->SetFlexibleDirection( wxBOTH );
fgSizer4->SetNonFlexibleGrowMode( wxFLEX_GROWMODE_SPECIFIED );
ButtonSph = new wxButton( this, wxID_ANY, wxT("球差曲线"), wxDefaultPosition, wxDefaultSize, 0 );
ButtonSph->SetDefault();
fgSizer4->Add( ButtonSph, 0, wxALL, 5 );
m_button8 = new wxButton( this, wxID_ANY, wxT("场曲曲线"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer4->Add( m_button8, 0, wxALL, 5 );
m_button9 = new wxButton( this, wxID_ANY, wxT("畸变曲线"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer4->Add( m_button9, 0, wxALL, 5 );
fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 );
fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 );
m_button7 = new wxButton( this, wxID_ANY, wxT("保存"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer4->Add( m_button7, 0, wxALL, 5 );
m_button81 = new wxButton( this, wxID_ANY, wxT("保存"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer4->Add( m_button81, 0, wxALL, 5 );
m_button91 = new wxButton( this, wxID_ANY, wxT("保存"), wxDefaultPosition, wxDefaultSize, 0 );
fgSizer4->Add( m_button91, 0, wxALL, 5 );
fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 );
fgSizer4->Add( 0, 0, 1, wxEXPAND, 5 );
fgSizer3->Add( fgSizer4, 1, wxEXPAND, 5 );
this->SetSizer( fgSizer3 );
this->Layout();
fgSizer3->Fit( this );
this->Centre( wxBOTH );
// Connect Events
this->Connect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( DrawDlg::OnClose ) );
ButtonSph->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawSph ), NULL, this );
m_button8->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawFld ), NULL, this );
m_button9->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawDis ), NULL, this );
m_button7->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveSph ), NULL, this );
m_button81->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveFld ), NULL, this );
m_button91->Connect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveDis ), NULL, this );
}
DrawDlg::~DrawDlg()
{
// Disconnect Events
this->Disconnect( wxEVT_CLOSE_WINDOW, wxCloseEventHandler( DrawDlg::OnClose ) );
ButtonSph->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawSph ), NULL, this );
m_button8->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawFld ), NULL, this );
m_button9->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnDrawDis ), NULL, this );
m_button7->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveSph ), NULL, this );
m_button81->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveFld ), NULL, this );
m_button91->Disconnect( wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( DrawDlg::OnSaveDis ), NULL, this );
}
| [
"qianweizju@29ddfad2-3a33-f12c-f700-e5bc6868e25f"
]
| [
[
[
1,
300
]
]
]
|
b5b2e197bcdd94928b2ef5d1a555e9d8757d713d | c9efecddc566c701b4b24b9d0997eb3cf929e5f5 | /TestRec/TestRec/Node.h | 436e0249528a5eecb018e490bdf583de3e79f10d | []
| no_license | vlalo001/metaballs3d | f8ee9404f28cda009654f8edf2f322c72d5bfe8a | a24fddce4ec73fc7348287e2074268cc2920cc2f | refs/heads/master | 2021-01-20T16:56:20.721059 | 2009-07-24T16:33:36 | 2009-07-24T16:33:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 422 | h | #pragma once
#include "Common.h"
#include "NodeState.h"
#include "Rule.h"
// ------------------------------------
// Node
// ------------------------------------
class Node
{
public:
Node(Rule* rule, const NodeState& state);
~Node(void);
const Rule* GetRule() const {return m_rule;}
const NodeState& Getstate() const {return m_state;}
private:
Rule* m_rule;
NodeState m_state;
};
| [
"garry.wls@99a8374a-4571-11de-aeda-3f4d37dfb5fa"
]
| [
[
[
1,
24
]
]
]
|
90de48146b61baa476a93ad7d9be7a824d218e88 | c3efe4021165e718d23ce0f853808e10c7114216 | /RbfConv/main.cpp | d38c2163bdda1a0cac0469f450a3549c810664ed | []
| no_license | lkdd/modstudio2 | 254b47ebd28a51a7d8c8682a86c576dafcc971bf | 287b4782580e37c8ac621046100dc550abd05b1d | refs/heads/master | 2021-01-10T08:14:56.230097 | 2009-03-08T19:14:16 | 2009-03-08T19:14:16 | 52,721,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,268 | cpp | /*
Copyright (c) 2008 Peter "Corsix" Cawley
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include "TextFileWriter.h"
#include "TextFileReader.h"
#include <stdio.h>
struct command_line_options_t
{
command_line_options_t()
: ePrintLevel(PRINT_NORMAL)
, cPathSeperator('|')
, pUCS(0)
, iUcsLimit(100)
, bSort(true)
, bCache(true)
, bInputIsList(false)
, bRelicStyle(false)
{
}
RainString sInput;
RainString sOutput;
RainString sUCS;
UcsFile *pUCS;
long iUcsLimit;
enum
{
PRINT_VERBOSE,
PRINT_NORMAL,
PRINT_QUIET,
} ePrintLevel;
char cPathSeperator;
bool bSort;
bool bCache;
bool bRelicStyle;
bool bInputIsList;
} g_oCommandLine;
int nullprintf(const wchar_t*, ...) {return 0;}
#define VERBOSEwprintf(...) ((g_oCommandLine.ePrintLevel <= command_line_options_t::PRINT_VERBOSE ? wprintf : nullprintf)(__VA_ARGS__))
#define NOTQUIETwprintf(...) ((g_oCommandLine.ePrintLevel < command_line_options_t::PRINT_QUIET ? wprintf : nullprintf)(__VA_ARGS__))
IFile* OpenInputFile(const RainString& sFile)
{
if(sFile.length() == 1 && sFile[0] == '-')
return RainOpenFilePtr(stdin, false);
else
return RainOpenFileNoThrow(sFile, FM_Read);
}
IFile* OpenOutputFile(const RainString& sFile, const RainString& sFileIn)
{
if(sFile.isEmpty())
{
RainString sNewFileName = sFileIn.beforeLast('.');
if(sFileIn.afterLast('.').compareCaseless("rbf") == 0)
sNewFileName += L".txt";
else
sNewFileName += L".rbf";
return RainOpenFileNoThrow(sNewFileName, FM_Write);
}
else
return RainOpenFileNoThrow(sFile, FM_Write);
}
void ConvertRbfToTxt(IFile *pIn, IFile *pOut)
{
RbfAttributeFile oAttribFile;
if(!g_oCommandLine.bSort)
oAttribFile.enableTableChildrenSort(false);
try
{
oAttribFile.load(pIn);
}
CATCH_THROW_SIMPLE({}, L"Cannot load input RBF");
RbfTxtWriter oWriter(pOut);
oWriter.setUCS(g_oCommandLine.pUCS, g_oCommandLine.iUcsLimit);
oWriter.setIndentProperties(2, ' ', g_oCommandLine.cPathSeperator);
std::auto_ptr<IAttributeTable> pTable(oAttribFile.getRootTable());
oWriter.writeTable(&*pTable);
}
void ConvertTxtToRbf(IFile *pIn, IFile *pOut)
{
RbfWriter oWriter;
TxtReader oReader(pIn, &oWriter);
if(!g_oCommandLine.bCache)
oWriter.enableCaching(false);
oWriter.initialise();
oReader.read();
if(g_oCommandLine.bRelicStyle)
{
RbfWriter oRelicStyled;
oRelicStyled.initialise();
oWriter.rewriteInRelicStyle(&oRelicStyled);
oRelicStyled.writeToFile(pOut, true);
}
else
oWriter.writeToFile(pOut);
VERBOSEwprintf(L"RBF stats:\n");
VERBOSEwprintf(L" %lu tables\n", oWriter.getTableCount());
VERBOSEwprintf(L" %lu keys\n", oWriter.getKeyCount());
VERBOSEwprintf(L" %lu data items via %lu indicies\n", oWriter.getDataCount(), oWriter.getDataIndexCount());
VERBOSEwprintf(L" %lu strings over %lu bytes\n", oWriter.getStringCount(), oWriter.getStringsLength());
VERBOSEwprintf(L" %lu bytes saved by caching\n", oWriter.getAmountSavedByCache());
}
bool DoWork(RainString& sInput, RainString& sOutput)
{
std::auto_ptr<IFile> pInFile;
std::auto_ptr<IFile> pOutFile;
pInFile.reset(OpenInputFile(sInput));
pOutFile.reset(OpenOutputFile(sOutput, sInput));
if(pInFile.get() && pOutFile.get())
{
if(sInput.afterLast('.').compareCaseless("rbf") == 0)
{
NOTQUIETwprintf(L"Converting RBF to text...\n");
ConvertRbfToTxt(&*pInFile, &*pOutFile);
}
else
{
NOTQUIETwprintf(L"Converting text to RBF...\n");
ConvertTxtToRbf(&*pInFile, &*pOutFile);
}
return true;
}
else
{
if(!pInFile.get())
fwprintf(stderr, L"Cannot open input file \'%s\'\n", sInput.getCharacters());
if(!pOutFile.get())
fwprintf(stderr, L"Cannot open output file \'%s\'\n", sOutput.getCharacters());
}
return false;
}
int wmain(int argc, wchar_t** argv)
{
#define REQUIRE_NEXT_ARG(noun) if((i + 1) >= argc) { \
fwprintf(stderr, L"Expected " L ## noun L" to follow \"%s\"\n", arg); \
return -2; \
}
for(int i = 1; i < argc; ++i)
{
wchar_t *arg = argv[i];
if(arg[0] == '-')
{
bool bValid = false;
if(arg[1] != 0 && arg[2] == 0)
{
bValid = true;
switch(arg[1])
{
case 'i':
REQUIRE_NEXT_ARG("filename");
g_oCommandLine.sInput = argv[++i];
break;
case 'o':
REQUIRE_NEXT_ARG("filename");
g_oCommandLine.sOutput = argv[++i];
break;
case 's':
g_oCommandLine.bSort = false;
break;
case 'R':
g_oCommandLine.bRelicStyle = true;
// no break
case 'c':
g_oCommandLine.bCache = false;
break;
case 'v':
g_oCommandLine.ePrintLevel = command_line_options_t::PRINT_VERBOSE;
break;
case 'q':
g_oCommandLine.ePrintLevel = command_line_options_t::PRINT_QUIET;
break;
case 'p':
REQUIRE_NEXT_ARG("path seperator");
g_oCommandLine.cPathSeperator = argv[++i][0];
break;
case 'u':
REQUIRE_NEXT_ARG("filename");
g_oCommandLine.sUCS = argv[++i];
break;
case 'U':
REQUIRE_NEXT_ARG("number");
g_oCommandLine.iUcsLimit = _wtoi(argv[++i]);
break;
case 'L':
g_oCommandLine.bInputIsList = true;
break;
default:
bValid = false;
break;
}
}
if(!bValid)
{
fwprintf(stderr, L"Unrecognised command line switch \"%s\"\n", arg);
return -1;
}
}
else
{
fwprintf(stderr, L"Expected command line switch rather than \"%s\"\n", arg);
return -3;
}
}
#undef REQUIRE_NEXT_ARG
NOTQUIETwprintf(L"** Corsix\'s Crude RBF Convertor **\n");
if(g_oCommandLine.sInput.isEmpty())
{
fwprintf(stderr, L"Expected an input filename. Command format is:\n");
fwprintf(stderr, L"%s -i infile [-L | -o outfile] [-q | -v] [-p \".\" | -p \" \"] [-u ucsfile] [-U threshold] [-s] [-R | -c]\n", wcsrchr(*argv, '\\') ? (wcsrchr(*argv, '\\') + 1) : (*argv));
fwprintf(stderr, L" -i; file to read from, either a .rbf file or a .txt file\n");
fwprintf(stderr, L" if \"-\", then uses stdin as input text file or input list file\n");
fwprintf(stderr, L" -o; file to write to, either a .rbf file or a .txt file\n");
fwprintf(stderr, L" if not given, then uses input name with .txt swapped for .rbf (and vice versa)\n");
fwprintf(stderr, L" -L; infile is a file containing a list of input files (one per line)\n");
fwprintf(stderr, L" -q; quiet output to console\n");
fwprintf(stderr, L" -v; verbose output to console\n");
fwprintf(stderr, L" Options for writing text files:\n");
fwprintf(stderr, L" -p; path seperator to use (defaults to vertical bar)\n");
fwprintf(stderr, L" -u; UCS file to use to comment number values\n");
fwprintf(stderr, L" -U; Integers above which to interpret as UCS references (defaults to 100)\n");
fwprintf(stderr, L" -s; Disable sorting of values (use order from RBF file)\n");
fwprintf(stderr, L" Options for writing RBF files:\n");
fwprintf(stderr, L" -c; Disable caching of data (faster, but makes larger file)\n");
fwprintf(stderr, L" -R; Write in Relic style (takes longer, also forces -c)\n");
return -4;
}
if(g_oCommandLine.sInput.compareCaseless(g_oCommandLine.sOutput) == 0)
{
fwprintf(stderr, L"Expected input file and output file to be different files");
return -5;
}
bool bAllGood = false;
try
{
if(!g_oCommandLine.sUCS.isEmpty())
{
g_oCommandLine.pUCS = new UcsFile;
g_oCommandLine.pUCS->loadFromFile(g_oCommandLine.sUCS);
}
if(g_oCommandLine.bInputIsList)
{
bAllGood = true;
g_oCommandLine.sOutput.clear();
std::auto_ptr<IFile> pListFile(OpenInputFile(g_oCommandLine.sInput));
BufferingInputTextStream<char> oListFile(&*pListFile);
while(!oListFile.isEOF())
{
RainString sLine(oListFile.readLine().trimWhitespace());
if(!sLine.isEmpty())
{
NOTQUIETwprintf(L"%s\n", sLine.getCharacters());
bAllGood = DoWork(sLine, g_oCommandLine.sOutput) && bAllGood;
}
}
}
else
bAllGood = DoWork(g_oCommandLine.sInput, g_oCommandLine.sOutput);
}
catch(RainException *pE)
{
bAllGood = false;
fwprintf(stderr, L"Fatal exception:\n");
for(RainException *p = pE; p; p = p->getPrevious())
{
fwprintf(stderr, L"%s:%li - %s\n", p->getFile().getCharacters(), p->getLine(), p->getMessage().getCharacters());
if(g_oCommandLine.ePrintLevel >= command_line_options_t::PRINT_QUIET)
break;
}
delete pE;
}
delete g_oCommandLine.pUCS;
if(bAllGood)
{
NOTQUIETwprintf(L"Done\n");
return 0;
}
return -10;
}
| [
"corsix@07142bc5-7355-0410-a98c-5fd2ca6e29ee"
]
| [
[
[
1,
324
]
]
]
|
2323ef9d88581ee9c01a929144995616853266f6 | 0019f0af5518efe2144b6c0e63a89e3bd2bdb597 | /antares/src/tests/kits/interface/picture/SVGViewView.cpp | 9790dc366d044c9c69b746ad79db54a4150792e2 | []
| no_license | mmanley/Antares | 5ededcbdf09ef725e6800c45bafd982b269137b1 | d35f39c12a0a62336040efad7540c8c5bce9678a | refs/heads/master | 2020-06-02T22:28:26.722064 | 2010-03-08T21:51:31 | 2010-03-08T21:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,718 | cpp | /*
* Copyright 2006, Antares Inc.
* Distributed under the terms of the MIT License.
*
* Authors:
* Marc Flerackers ([email protected])
*/
#include "SVGViewView.h"
named_color colors[] = {
{ "aliceblue", { 240, 248, 255, 255 } },
{ "antiquewhite", { 250, 235, 215, 255 } },
{ "aqua", { 0, 255, 255, 255 } },
{ "aquamarine", { 127, 255, 212, 255 } },
{ "azure", { 240, 255, 255, 255 } },
{ "beige", { 245, 245, 220, 255 } },
{ "bisque", { 255, 228, 196, 255 } },
{ "black", { 0, 0, 0, 255 } },
{ "blanchedalmond", { 255, 235, 205, 255 } },
{ "blue", { 0, 0, 255, 255 } },
{ "blueviolet", { 138, 43, 226, 255 } },
{ "brown", { 165, 42, 42, 255 } },
{ "burlywood", { 222, 184, 135, 255 } },
{ "cadetblue", { 95, 158, 160, 255 } },
{ "chartreuse", { 127, 255, 0, 255 } },
{ "chocolate", { 210, 105, 30, 255 } },
{ "coral", { 255, 127, 80, 255 } },
{ "cornflowerblue", { 100, 149, 237, 255 } },
{ "cornsilk", { 255, 248, 220, 255 } },
{ "crimson", { 220, 20, 60, 255 } },
{ "cyan", { 0, 255, 255, 255 } },
{ "darkblue", { 0, 0, 139, 255 } },
{ "darkcyan", { 0, 139, 139, 255 } },
{ "darkgoldenrod", { 184, 134, 11, 255 } },
{ "darkgray", { 169, 169, 169, 255 } },
{ "darkgreen", { 0, 100, 0, 255 } },
{ "darkgrey", { 169, 169, 169, 255 } },
{ "darkkhaki", { 189, 183, 107, 255 } },
{ "darkmagenta", { 139, 0, 139, 255 } },
{ "darkolivegreen", { 85, 107, 47, 255 } },
{ "darkorange", { 255, 140, 0, 255 } },
{ "darkorchid", { 153, 50, 204, 255 } },
{ "darkred", { 139, 0, 0, 255 } },
{ "darksalmon", { 233, 150, 122, 255 } },
{ "darkseagreen", { 143, 188, 143, 255 } },
{ "darkslateblue", { 72, 61, 139, 255 } },
{ "darkslategray", { 47, 79, 79, 255 } },
{ "darkslategrey", { 47, 79, 79, 255 } },
{ "darkturquoise", { 0, 206, 209, 255 } },
{ "darkviolet", { 148, 0, 211, 255 } },
{ "deeppink", { 255, 20, 147, 255 } },
{ "deepskyblue", { 0, 191, 255, 255 } },
{ "dimgray", { 105, 105, 105, 255 } },
{ "dimgrey", { 105, 105, 105, 255 } },
{ "dodgerblue", { 30, 144, 255, 255 } },
{ "firebrick", { 178, 34, 34, 255 } },
{ "floralwhite", { 255, 250, 240, 255 } },
{ "forestgreen", { 34, 139, 34, 255 } },
{ "fuchsia", { 255, 0, 255, 255 } },
{ "gainsboro", { 220, 220, 220, 255 } },
{ "ghostwhite", { 248, 248, 255, 255 } },
{ "gold", { 255, 215, 0, 255 } },
{ "goldenrod", { 218, 165, 32, 255 } },
{ "gray", { 128, 128, 128, 255 } },
{ "grey", { 128, 128, 128, 255 } },
{ "green", { 0, 128, 0, 255 } },
{ "greenyellow", { 173, 255, 47, 255 } },
{ "honeydew", { 240, 255, 240, 255 } },
{ "hotpink", { 255, 105, 180, 255 } },
{ "indianred", { 205, 92, 92, 255 } },
{ "indigo", { 75, 0, 130, 255 } },
{ "ivory", { 255, 255, 240, 255 } },
{ "khaki", { 240, 230, 140, 255 } },
{ "lavender", { 230, 230, 250, 255 } },
{ "lavenderblush", { 255, 240, 245, 255 } },
{ "lawngreen", { 124, 252, 0, 255 } },
{ "lemonchiffon", { 255, 250, 205, 255 } },
{ "lightblue", { 173, 216, 230, 255 } },
{ "lightcoral", { 240, 128, 128, 255 } },
{ "lightcyan", { 224, 255, 255, 255 } },
{ "lightgoldenrodyellow",{ 250, 250, 210, 255 } },
{ "lightgray", { 211, 211, 211, 255 } },
{ "lightgreen", { 144, 238, 144, 255 } },
{ "lightgrey", { 211, 211, 211, 255 } },
{ "lightpink", { 255, 182, 193, 255 } },
{ "lightsalmon", { 255, 160, 122, 255 } },
{ "lightseagreen", { 32, 178, 170, 255 } },
{ "lightskyblue", { 135, 206, 250, 255 } },
{ "lightslategray", { 119, 136, 153, 255 } },
{ "lightslategrey", { 119, 136, 153, 255 } },
{ "lightsteelblue", { 176, 196, 222, 255 } },
{ "lightyellow", { 255, 255, 224, 255 } },
{ "lime", { 0, 255, 0, 255 } },
{ "limegreen", { 50, 205, 50, 255 } },
{ "linen", { 250, 240, 230, 255 } },
{ "magenta", { 255, 0, 255, 255 } },
{ "maroon", { 128, 0, 0, 255 } },
{ "mediumaquamarine", { 102, 205, 170, 255 } },
{ "mediumblue", { 0, 0, 205, 255 } },
{ "mediumorchid", { 186, 85, 211, 255 } },
{ "mediumpurple", { 147, 112, 219, 255 } },
{ "mediumseagreen", { 60, 179, 113, 255 } },
{ "mediumslateblue", { 123, 104, 238, 255 } },
{ "mediumspringgreen", { 0, 250, 154, 255 } },
{ "mediumturquoise", { 72, 209, 204, 255 } },
{ "mediumvioletred", { 199, 21, 133, 255 } },
{ "midnightblue", { 25, 25, 112, 255 } },
{ "mintcream", { 245, 255, 250, 255 } },
{ "mistyrose", { 255, 228, 225, 255 } },
{ "moccasin", { 255, 228, 181, 255 } },
{ "navajowhite", { 255, 222, 173, 255 } },
{ "navy", { 0, 0, 128, 255 } },
{ "oldlace", { 253, 245, 230, 255 } },
{ "olive", { 128, 128, 0, 255 } },
{ "olivedrab", { 107, 142, 35, 255 } },
{ "orange", { 255, 165, 0, 255 } },
{ "orangered", { 255, 69, 0, 255 } },
{ "orchid", { 218, 112, 214, 255 } },
{ "palegoldenrod", { 238, 232, 170, 255 } },
{ "palegreen", { 152, 251, 152, 255 } },
{ "paleturquoise", { 175, 238, 238, 255 } },
{ "palevioletred", { 219, 112, 147, 255 } },
{ "papayawhip", { 255, 239, 213, 255 } },
{ "peachpuff", { 255, 218, 185, 255 } },
{ "peru", { 205, 133, 63, 255 } },
{ "pink", { 255, 192, 203, 255 } },
{ "plum", { 221, 160, 221, 255 } },
{ "powderblue", { 176, 224, 230, 255 } },
{ "purple", { 128, 0, 128, 255 } },
{ "red", { 255, 0, 0, 255 } },
{ "rosybrown", { 188, 143, 143, 255 } },
{ "royalblue", { 65, 105, 225, 255 } },
{ "saddlebrown", { 139, 69, 19, 255 } },
{ "salmon", { 250, 128, 114, 255 } },
{ "sandybrown", { 244, 164, 96, 255 } },
{ "seagreen", { 46, 139, 87, 255 } },
{ "seashell", { 255, 245, 238, 255 } },
{ "sienna", { 160, 82, 45, 255 } },
{ "silver", { 192, 192, 192, 255 } },
{ "skyblue", { 135, 206, 235, 255 } },
{ "slateblue", { 106, 90, 205, 255 } },
{ "slategray", { 112, 128, 144, 255 } },
{ "slategrey", { 112, 128, 144, 255 } },
{ "snow", { 255, 250, 250, 255 } },
{ "springgreen", { 0, 255, 127, 255 } },
{ "steelblue", { 70, 130, 180, 255 } },
{ "tan", { 210, 180, 140, 255 } },
{ "teal", { 0, 128, 128, 255 } },
{ "thistle", { 216, 191, 216, 255 } },
{ "tomato", { 255, 99, 71, 255 } },
{ "turquoise", { 64, 224, 208, 255 } },
{ "violet", { 238, 130, 238, 255 } },
{ "wheat", { 245, 222, 179, 255 } },
{ "white", { 255, 255, 255, 255 } },
{ "whitesmoke", { 245, 245, 245, 255 } },
{ "yellow", { 255, 255, 0, 255 } },
{ "yellowgreen", { 154, 205, 50, 255 } },
{ NULL , { 0, 0, 0, 255 } },
};
// Globals ---------------------------------------------------------------------
// Svg2PictureView class -------------------------------------------------------
Svg2PictureView::Svg2PictureView(BRect frame, const char *filename)
: BView(frame, "", B_FOLLOW_ALL, B_WILL_DRAW | B_FRAME_EVENTS),
fFileName(filename),
fPicture(NULL)
{
fPicture = new BPicture();
}
Svg2PictureView::~Svg2PictureView()
{
delete fPicture;
}
void
Svg2PictureView::AttachedToWindow()
{
BeginPicture(fPicture);
bool done = false;
FILE *file = fopen(fFileName.String(), "rb");
if (file) {
XML_Parser parser = XML_ParserCreate("UTF-8");
XML_SetUserData(parser, this);
XML_SetElementHandler(parser, (XML_StartElementHandler)_StartElement, (XML_EndElementHandler)_EndElement);
XML_SetCharacterDataHandler(parser, (XML_CharacterDataHandler)_CharacterDataHandler);
while (!done) {
char buf[256];
size_t len = fread(buf, 1, sizeof(buf), file);
done = len < sizeof(buf);
if (!XML_Parse(parser, buf, len, done))
break;
}
XML_ParserFree(parser);
fclose(file);
}
fPicture = EndPicture();
}
void
Svg2PictureView::Draw(BRect updateRect)
{
if (fPicture)
DrawPicture(fPicture);
}
//------------------------------------------------------------------------------
bool Svg2PictureView::HasAttribute(const XML_Char **attributes, const char *name) {
while (*attributes && strcasecmp(*attributes, name) != 0)
attributes += 2;
return (*attributes);
}
//------------------------------------------------------------------------------
float Svg2PictureView::GetFloatAttribute(const XML_Char **attributes, const char *name) {
while (*attributes && strcasecmp(*attributes, name) != 0)
attributes += 2;
if (*attributes)
return atof(*(attributes + 1));
else
return 0;
}
//------------------------------------------------------------------------------
const char *Svg2PictureView::GetStringAttribute(const XML_Char **attributes, const char *name) {
while (*attributes && strcasecmp(*attributes, name) != 0)
attributes += 2;
if (*attributes)
return *(attributes + 1);
else
return NULL;
}
//------------------------------------------------------------------------------
rgb_color Svg2PictureView::GetColorAttribute(const XML_Char **attributes, const char *name, uint8 alpha) {
const char *attr = GetStringAttribute(attributes, name);
if (!attr)
return colors[0].color;
int32 red, green, blue;
if (attr[0] == '#') {
if (strlen(attr) == 4) {
sscanf(attr, "#%1X%1X%1X", &red, &green, &blue);
red = (red << 4) + red;
green = (green << 4) + green;
blue = (blue << 4) + blue;
}
else
sscanf(attr, "#%2X%2X%2X", &red, &green, &blue);
rgb_color color;
color.red = red;
color.green = green;
color.blue = blue;
color.alpha = alpha;
return color;
}
if (sscanf(attr, "rgb(%d, %d, %d)", &red, &green, &blue) == 3) {
rgb_color color;
color.red = red;
color.green = green;
color.blue = blue;
color.alpha = alpha;
return color;
}
float redf, greenf, bluef;
if (sscanf(attr, "rgb(%f%%, %f%%, %f%%)", &redf, &greenf, &bluef) == 3) {
rgb_color color;
color.red = (int32)(redf * 2.55f);
color.green = (int32)(greenf * 2.55f);
color.blue = (int32)(bluef * 2.55f);
color.alpha = alpha;
return color;
}
if (strcasecmp(attr, "url")) {
const char *grad = strchr(attr, '#');
if (grad) {
for (int32 i = 0; i < fGradients.CountItems(); i++) {
named_color *item = (named_color*)fGradients.ItemAt(i);
if (strstr(grad, item->name)) {
rgb_color color = item->color;
color.alpha = alpha;
return color;
}
}
}
}
for (int32 i = 0; colors[i].name != NULL; i++)
if (strcasecmp(colors[i].name, attr) == 0) {
rgb_color color = colors[i].color;
color.alpha = alpha;
return color;
}
rgb_color color = colors[0].color;
color.alpha = alpha;
return color;
}
//------------------------------------------------------------------------------
void Svg2PictureView::GetPolygonAttribute(const XML_Char **attributes, const char *name, BShape &shape) {
const char *attr = NULL;
while (*attributes && strcasecmp(*attributes, name) != 0)
attributes += 2;
if (*attributes)
attr = *(attributes + 1);
if (!attr)
return;
char *ptr = const_cast<char*>(attr);
BPoint point;
bool first = true;
while (*ptr) {
// Skip white space and ','
while (*ptr && (*ptr == ' ') || (*ptr == ','))
ptr++;
sscanf(ptr, "%f", &point.x);
// Skip x
while (*ptr && *ptr != ',')
ptr++;
if (!*ptr || !*(ptr + 1))
break;
ptr++;
sscanf(ptr, "%f", &point.y);
if (first)
{
shape.MoveTo(point);
first = false;
}
else
shape.LineTo(point);
// Skip y
while (*ptr && (*ptr != ' ') && (*ptr != ','))
ptr++;
}
}
//------------------------------------------------------------------------------
void Svg2PictureView::GetMatrixAttribute(const XML_Char **attributes, const char *name, BMatrix *matrix) {
const char *attr = NULL;
while (*attributes && strcasecmp(*attributes, name) != 0)
attributes += 2;
if (*attributes)
attr = *(attributes + 1);
if (!attr)
return;
char *ptr = (char*)attr;
while (*ptr) {
while (*ptr == ' ')
ptr++;
char *transform_name = ptr;
while (*ptr != '(')
ptr++;
if (strncmp(transform_name, "translate", 9) == 0) {
float x, y;
if (sscanf(ptr, "(%f %f)", &x, &y) != 2)
sscanf(ptr, "(%f,%f)", &x, &y);
matrix->Translate(x, y);
}
else if (strncmp(transform_name, "rotate", 6) == 0) {
float angle;
sscanf(ptr, "(%f)", &angle);
matrix->Rotate(angle);
}
else if (strncmp(transform_name, "scale", 5) == 0) {
float sx, sy;
if (sscanf(ptr, "(%f,%f)", &sx, &sy) == 2)
matrix->Scale(sx, sy);
else
{
sscanf(ptr, "(%f)", &sx);
matrix->Scale(sx, sx);
}
}
else if (strncmp(transform_name, "skewX", 5) == 0) {
float angle;
sscanf(ptr, "(%f)", &angle);
matrix->SkewX(angle);
}
else if (strncmp(transform_name, "skewY", 5) == 0) {
float angle;
sscanf(ptr, "(%f)", &angle);
matrix->SkewY(angle);
}
while (*ptr != ')')
ptr++;
ptr++;
}
}
//------------------------------------------------------------------------------
double CalcVectorAngle(double ux, double uy, double vx, double vy) {
double ta = atan2(uy, ux);
double tb = atan2(vy, vx);
if (tb >= ta)
return tb - ta;
return 6.28318530718 - (ta - tb);
}
//------------------------------------------------------------------------------
char *SkipFloat(char *string) {
if (*string == '-')
string++;
int32 len = strspn(string, "1234567890.");
return string + len;
}
//------------------------------------------------------------------------------
char *FindFloat(char *string) {
return strpbrk(string, "1234567890-.");
}
//------------------------------------------------------------------------------
float GetFloat(char **string) {
*string = FindFloat(*string);
float f = atof(*string);
*string = SkipFloat(*string);
return f;
}
//------------------------------------------------------------------------------
void Svg2PictureView::GetShapeAttribute(const XML_Char **attributes, const char *name, BShape &shape) {
const char *attr = GetStringAttribute(attributes, name);
if (!attr)
return;
char *ptr = const_cast<char*>(attr);
float x, y, x1, y1, x2, y2, rx, ry, angle;
bool largeArcFlag, sweepFlag;
char command, prevCommand = 0;
BPoint prevCtlPt;
BPoint pos, startPos;
bool canMove = true;
while (*ptr) {
ptr = strpbrk(ptr, "ZzMmLlCcQqAaHhVvSsTt");
if (ptr == NULL)
break;
command = *ptr;
switch (command) {
case 'Z':
case 'z':
{
pos.Set(startPos.x, startPos.y);
canMove = true;
shape.Close();
ptr++;
break;
}
case 'M':
{
x = GetFloat(&ptr);
y = GetFloat(&ptr);
pos.Set(x, y);
if (canMove)
startPos = pos;
shape.MoveTo(pos);
break;
}
case 'm':
{
x = GetFloat(&ptr);
y = GetFloat(&ptr);
pos.x += x;
pos.y += y;
if (canMove)
startPos = pos;
shape.MoveTo(pos);
break;
}
case 'L':
{
x = GetFloat(&ptr);
y = GetFloat(&ptr);
pos.Set(x, y);
canMove = false;
shape.LineTo(pos);
break;
}
case 'l':
{
x = GetFloat(&ptr);
y = GetFloat(&ptr);
pos.x += x;
pos.y += y;
canMove = false;
shape.LineTo(pos);
break;
}
case 'C':
case 'c':
{
if (command == 'C') {
x1 = GetFloat(&ptr);
y1 = GetFloat(&ptr);
x2 = GetFloat(&ptr);
y2 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
}
else {
x1 = GetFloat(&ptr);
y1 = GetFloat(&ptr);
x2 = GetFloat(&ptr);
y2 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x1 += pos.x;
y1 += pos.y;
x2 += pos.x;
y2 += pos.y;
x += pos.x;
y += pos.y;
}
BPoint controlPoints[3];
controlPoints[0].Set(x1, y1);
controlPoints[1].Set(x2, y2);
controlPoints[2].Set(x, y);
pos.Set(x, y);
prevCtlPt = controlPoints[1];
canMove = false;
shape.BezierTo(controlPoints);
break;
}
case 'Q':
case 'q':
{
if (command == 'Q') {
x1 = GetFloat(&ptr);
y1 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
}
else {
x1 = GetFloat(&ptr);
y1 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x1 += pos.x;
y1 += pos.y;
x += pos.x;
y += pos.y;
}
BPoint controlPoints[3];
controlPoints[0].Set(pos.x + 2.0f / 3.0f * (x1 - pos.x),
pos.y + 2.0f / 3.0f * (y1 - pos.y));
controlPoints[1].Set(x1 + 1.0f / 3.0f * (x - x1),
y1 + 1.0f / 3.0f * (y - y1));
controlPoints[2].Set(x, y);
pos.Set(x, y);
prevCtlPt.Set(x1, y1);
canMove = false;
shape.BezierTo(controlPoints);
break;
}
case 'A':
case 'a':
{
x1 = pos.x;
y1 = pos.y;
if (command == 'A') {
rx = GetFloat(&ptr);
ry = GetFloat(&ptr);
angle = GetFloat(&ptr);
largeArcFlag = GetFloat(&ptr);
sweepFlag = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x2 = x;
y2 = y;
}
else {
rx = GetFloat(&ptr);
ry = GetFloat(&ptr);
angle = GetFloat(&ptr);
largeArcFlag = GetFloat(&ptr);
sweepFlag = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x2 = x + pos.x;
y2 = y + pos.y;
}
const double pi = 3.14159265359;
const double radPerDeg = pi / 180.0;
if (x1 == x2 && y1 == y2)
break;
if (rx == 0.0f || ry == 0.0f) {
shape.LineTo(BPoint((float)x2, (float)y2));
break;
}
if (rx < 0.0)
rx = -rx;
if (ry < 0.0)
ry = -ry;
double sinPhi = sin(angle * radPerDeg);
double cosPhi = cos(angle * radPerDeg);
double x1dash = cosPhi * (x1 - x2) / 2.0 +
sinPhi * (y1 - y2) / 2.0;
double y1dash = -sinPhi * (x1 - x2) / 2.0 +
cosPhi * (y1 - y2) / 2.0;
double root, numerator = rx * rx * ry * ry - rx * rx * y1dash * y1dash -
ry * ry * x1dash * x1dash;
if (numerator < 0.0) {
double s = (float)sqrt(1.0 - numerator / (rx * rx * ry * ry));
rx *= s;
ry *= s;
root = 0.0;
}
else {
root = (largeArcFlag == sweepFlag ? -1.0 : 1.0) *
sqrt(numerator /
(rx * rx * y1dash * y1dash + ry * ry * x1dash * x1dash));
}
double cxdash = root * rx * y1dash / ry, cydash = -root * ry * x1dash / rx;
double cx = cosPhi * cxdash - sinPhi * cydash + (x1 + x2) / 2.0;
double cy = sinPhi * cxdash + cosPhi * cydash + (y1 + y2) / 2.0;
double theta1 = CalcVectorAngle(1.0, 0.0, (x1dash - cxdash) / rx,
(y1dash - cydash) / ry ),
dtheta = CalcVectorAngle((x1dash - cxdash) / rx,
(y1dash - cydash) / ry, (-x1dash - cxdash) / rx,
(-y1dash - cydash) / ry);
if (!sweepFlag && dtheta > 0)
dtheta -= 2.0 * pi;
else if (sweepFlag && dtheta < 0)
dtheta += 2.0 * pi;
int segments = (int)ceil (fabs(dtheta / (pi / 2.0)));
double delta = dtheta / segments;
double t = 8.0/3.0 * sin(delta / 4.0) * sin( delta / 4.0) /
sin(delta / 2.0);
BPoint controlPoints[3];
for (int n = 0; n < segments; ++n) {
double cosTheta1 = cos(theta1);
double sinTheta1 = sin(theta1);
double theta2 = theta1 + delta;
double cosTheta2 = cos(theta2);
double sinTheta2 = sin(theta2);
double xe = cosPhi * rx * cosTheta2 - sinPhi * ry * sinTheta2 + cx;
double ye = sinPhi * rx * cosTheta2 + cosPhi * ry * sinTheta2 + cy;
double dx1 = t * (-cosPhi * rx * sinTheta1 - sinPhi * ry * cosTheta1);
double dy1 = t * (-sinPhi * rx * sinTheta1 + cosPhi * ry * cosTheta1);
double dxe = t * (cosPhi * rx * sinTheta2 + sinPhi * ry * cosTheta2);
double dye = t * (sinPhi * rx * sinTheta2 - cosPhi * ry * cosTheta2);
controlPoints[0].Set((float)(x1 + dx1), (float)(y1 + dy1));
controlPoints[1].Set((float)(xe + dxe), (float)(ye + dye));
controlPoints[2].Set((float)xe, (float)ye );
shape.BezierTo(controlPoints);
theta1 = theta2;
x1 = (float)xe;
y1 = (float)ye;
}
pos.Set(x2, y2);
break;
}
case 'H':
{
x = GetFloat(&ptr);
pos.x = x;
canMove = false;
shape.LineTo(pos);
break;
}
case 'h':
{
x = GetFloat(&ptr);
pos.x += x;
canMove = false;
shape.LineTo(pos);
break;
}
case 'V':
{
y = GetFloat(&ptr);
pos.y = y;
canMove = false;
shape.LineTo(pos);
break;
}
case 'v':
{
y = GetFloat(&ptr);
pos.y += y;
canMove = false;
shape.LineTo(pos);
break;
}
case 'S':
case 's':
{
if (command == 'S') {
x2 = GetFloat(&ptr);
y2 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
}
else {
x2 = GetFloat(&ptr);
y2 = GetFloat(&ptr);
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x2 += pos.x;
y2 += pos.y;
x += pos.x;
y += pos.y;
}
if (prevCommand == 'C' || prevCommand == 'c' ||
prevCommand == 'S' || prevCommand == 's') {
x1 = prevCtlPt.x + 2 * (pos.x - prevCtlPt.x);
y1 = prevCtlPt.y + 2 * (pos.y - prevCtlPt.y);
}
else {
x1 = pos.x;
y1 = pos.y;
}
BPoint controlPoints[3];
controlPoints[0].Set(x1, y1);
controlPoints[1].Set(x2, y2);
controlPoints[2].Set(x, y);
pos.Set(x, y);
prevCtlPt.Set(x2, y2);
canMove = false;
shape.BezierTo(controlPoints);
break;
}
case 'T':
case 't':
{
if (command == 'T') {
x = GetFloat(&ptr);
y = GetFloat(&ptr);
}
else {
x = GetFloat(&ptr);
y = GetFloat(&ptr);
x += pos.x;
y += pos.y;
}
if (prevCommand == 'Q' || prevCommand == 'q' ||
prevCommand == 'T' || prevCommand == 't') {
x1 = prevCtlPt.x + 2 * (pos.x - prevCtlPt.x);
y1 = prevCtlPt.y + 2 * (pos.y - prevCtlPt.y);
}
else {
x1 = pos.x;
y1 = pos.y;
}
BPoint controlPoints[3];
controlPoints[0].Set(pos.x + 2.0f / 3.0f * (x1 - pos.x),
pos.y + 2.0f / 3.0f * (y1 - pos.y));
controlPoints[1].Set(x1 + 1.0f / 3.0f * (x - x1),
y1 + 1.0f / 3.0f * (y - y1));
controlPoints[2].Set(x, y);
pos.Set(x, y);
prevCtlPt.Set(x1, y1);
canMove = false;
shape.BezierTo(controlPoints);
break;
}
}
prevCommand = command;
}
}
//------------------------------------------------------------------------------
void Svg2PictureView::CheckAttributes(const XML_Char **attributes) {
uint8 alpha = fState.fStrokeColor.alpha;
if (HasAttribute(attributes, "opacity")) {
float opacity = GetFloatAttribute(attributes, "opacity");
fState.fStrokeColor.alpha = (uint8)(opacity * alpha);
fState.fFlags |= STROKE_FLAG;
fState.fFillColor.alpha = (uint8)(opacity * alpha);
fState.fFlags |= FILL_FLAG;
}
if (HasAttribute(attributes, "color")) {
fState.fCurrentColor = GetColorAttribute(attributes, "color", fState.fCurrentColor.alpha);
}
if (HasAttribute(attributes, "stroke")) {
const char *stroke = GetStringAttribute(attributes, "stroke");
if (strcasecmp(stroke, "none") == 0)
fState.fStroke = false;
else if (strcasecmp(stroke, "currentColor") == 0) {
fState.fStrokeColor = fState.fCurrentColor;
fState.fStroke = true;
}
else {
fState.fStrokeColor = GetColorAttribute(attributes, "stroke", fState.fFillColor.alpha);
fState.fStroke = true;
SetHighColor(fState.fStrokeColor);
}
fState.fFlags |= STROKE_FLAG;
}
if (HasAttribute(attributes, "stroke-opacity")) {
fState.fStrokeColor.alpha = (uint8)(GetFloatAttribute(attributes, "stroke-opacity") * alpha);
fState.fFlags |= STROKE_FLAG;
}
if (HasAttribute(attributes, "fill")) {
const char *fill = GetStringAttribute(attributes, "fill");
if (strcasecmp(fill, "none") == 0)
fState.fFill = false;
else if (strcasecmp(fill, "currentColor") == 0) {
fState.fFillColor = fState.fCurrentColor;
fState.fFill = true;
}
else {
fState.fFillColor = GetColorAttribute(attributes, "fill", fState.fFillColor.alpha);
fState.fFill = true;
}
fState.fFlags |= FILL_FLAG;
}
if (HasAttribute(attributes, "fill-opacity")) {
fState.fFillColor.alpha = (uint8)(GetFloatAttribute(attributes, "fill-opacity") * alpha);
fState.fFlags |= FILL_FLAG;
}
if (HasAttribute(attributes, "stroke-width")) {
fState.fStrokeWidth = GetFloatAttribute(attributes, "stroke-width");
SetPenSize(fState.fStrokeWidth);
fState.fFlags |= STROKE_WIDTH_FLAG;
}
if (HasAttribute(attributes, "stroke-linecap")) {
const char *stroke_linecap = GetStringAttribute(attributes, "stroke-linecap");
if (strcasecmp(stroke_linecap, "but") == 0)
fState.fLineCap = B_BUTT_CAP;
else if (strcasecmp(stroke_linecap, "round") == 0)
fState.fLineCap = B_ROUND_CAP;
else if (strcasecmp(stroke_linecap, "square") == 0)
fState.fLineCap = B_SQUARE_CAP;
SetLineMode(fState.fLineCap, LineJoinMode(), LineMiterLimit());
fState.fFlags |= LINE_MODE_FLAG;
}
if (HasAttribute(attributes, "stroke-linejoin")) {
const char *stroke_linejoin = GetStringAttribute(attributes, "stroke-linejoin");
if (strcasecmp(stroke_linejoin, "miter") == 0)
fState.fLineJoin = B_MITER_JOIN;
else if (strcasecmp(stroke_linejoin, "round") == 0)
fState.fLineJoin = B_ROUND_JOIN;
else if (strcasecmp(stroke_linejoin, "bevel") == 0)
fState.fLineJoin = B_BEVEL_JOIN;
SetLineMode(LineCapMode(), fState.fLineJoin, LineMiterLimit());
fState.fFlags |= LINE_MODE_FLAG;
}
if (HasAttribute(attributes, "stroke-miterlimit")) {
fState.fLineMiterLimit = GetFloatAttribute(attributes, "stroke-miterlimit");
SetLineMode(LineCapMode(), LineJoinMode(), fState.fLineMiterLimit);
fState.fFlags |= LINE_MODE_FLAG;
}
if (HasAttribute(attributes, "font-size")) {
fState.fFontSize = GetFloatAttribute(attributes, "font-size");
SetFontSize(fState.fFontSize);
fState.fFlags |= FONT_SIZE_FLAG;
}
if (HasAttribute(attributes, "transform")) {
BMatrix matrix;
GetMatrixAttribute(attributes, "transform", &matrix);
fState.fMatrix *= matrix;
fState.fFlags |= MATRIX_FLAG;
}
}
//------------------------------------------------------------------------------
void Svg2PictureView::StartElement(const XML_Char *name, const XML_Char **attributes) {
Push();
CheckAttributes(attributes);
if (strcasecmp(name, "circle") == 0) {
BPoint c(GetFloatAttribute(attributes, "cx"), GetFloatAttribute(attributes, "cy"));
float r = GetFloatAttribute(attributes, "r");
if (fState.fFill) {
SetHighColor(fState.fFillColor);
FillEllipse(c, r, r);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeEllipse(c, r, r);
}
else if (strcasecmp(name, "ellipse") == 0) {
BPoint c(GetFloatAttribute(attributes, "cx"), GetFloatAttribute(attributes, "cy"));
float rx = GetFloatAttribute(attributes, "rx");
float ry = GetFloatAttribute(attributes, "ry");
if (fState.fFill) {
SetHighColor(fState.fFillColor);
FillEllipse(c, rx, ry);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeEllipse(c, rx, ry);
}
else if (strcasecmp(name, "image") == 0) {
BPoint topLeft(GetFloatAttribute(attributes, "x"), GetFloatAttribute(attributes, "y"));
BPoint bottomRight(topLeft.x + GetFloatAttribute(attributes, "width"),
topLeft.y + GetFloatAttribute(attributes, "height"));
fState.fMatrix.Transform(&topLeft);
fState.fMatrix.Transform(&bottomRight);
const char *href = GetStringAttribute(attributes, "xlink:href");
if (href) {
BBitmap *bitmap = BTranslationUtils::GetBitmap(href);
if (bitmap) {
DrawBitmap(bitmap, BRect(topLeft, bottomRight));
delete bitmap;
}
}
}
else if (strcasecmp(name, "line") == 0){
BPoint from(GetFloatAttribute(attributes, "x1"), GetFloatAttribute(attributes, "y1"));
BPoint to(GetFloatAttribute(attributes, "x2"), GetFloatAttribute(attributes, "y2"));
fState.fMatrix.Transform(&from);
fState.fMatrix.Transform(&to);
StrokeLine(from, to);
}
else if (strcasecmp(name, "linearGradient") == 0) {
fGradient = new named_gradient;
fGradient->name = strdup(GetStringAttribute(attributes, "id"));
fGradient->color.red = 0;
fGradient->color.green = 0;
fGradient->color.blue = 0;
fGradient->color.alpha = 255;
fGradient->started = false;
}
else if (strcasecmp(name, "path") == 0) {
BShape shape;
GetShapeAttribute(attributes, "d", shape);
fState.fMatrix.Transform(shape);
if (fState.fFill) {
SetHighColor(fState.fFillColor);
FillShape(&shape);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeShape(&shape);
}
else if (strcasecmp(name, "polygon") == 0) {
BShape shape;
GetPolygonAttribute(attributes, "points", shape);
shape.Close();
fState.fMatrix.Transform(shape);
if (fState.fFill) {
SetHighColor(fState.fFillColor);
FillShape(&shape);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeShape(&shape);
}
else if (strcasecmp(name, "polyline") == 0) {
BShape shape;
GetPolygonAttribute(attributes, "points", shape);
fState.fMatrix.Transform(shape);
if (fState.fFill) {
SetHighColor(fState.fFillColor);
FillShape(&shape);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeShape(&shape);
}
else if (strcasecmp(name, "radialGradient") == 0) {
fGradient = new named_gradient;
fGradient->name = strdup(GetStringAttribute(attributes, "id"));
fGradient->color.red = 0;
fGradient->color.green = 0;
fGradient->color.blue = 0;
fGradient->color.alpha = 255;
fGradient->started = false;
}
else if (strcasecmp(name, "stop") == 0) {
rgb_color color = GetColorAttribute(attributes, "stop-color", 255);
if (fGradient) {
if (fGradient->started) {
fGradient->color.red = (int8)(((int32)fGradient->color.red + (int32)color.red) / 2);
fGradient->color.green = (int8)(((int32)fGradient->color.green + (int32)color.green) / 2);
fGradient->color.blue = (int8)(((int32)fGradient->color.blue + (int32)color.blue) / 2);
}
else {
fGradient->color = color;
fGradient->started = true;
}
}
}
else if (strcasecmp(name, "rect") == 0) {
BPoint points[4];
points[0].x = points[3].x = GetFloatAttribute(attributes, "x");
points[0].y= points[1].y = GetFloatAttribute(attributes, "y");
points[1].x = points[2].x = points[0].x + GetFloatAttribute(attributes, "width");
points[2].y = points[3].y = points[0].y + GetFloatAttribute(attributes, "height");
/*const char *_rx = element->Attribute("rx");
const char *_ry = element->Attribute("ry");
if (_rx || _ry)
{
float rx, ry;
if (_rx)
{
rx = atof(_rx);
if (_ry)
ry = atof(_ry);
else
ry = rx;
}
else
rx = ry = atof(_ry);
if (fState.fFill)
{
SetHighColor(fState.fFillColor);
FillRoundRect(rect, rx, ry);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeRoundRect(rect, rx, ry);
}
else
{
if (fState.fFill)
{
SetHighColor(fState.fFillColor);
FillRect(rect);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeRect(rect);
}*/
BShape shape;
shape.MoveTo(points[0]);
shape.LineTo(points[1]);
shape.LineTo(points[2]);
shape.LineTo(points[3]);
shape.Close();
fState.fMatrix.Transform(shape);
if (fState.fFill)
{
SetHighColor(fState.fFillColor);
FillShape(&shape);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
StrokeShape(&shape);
}
else if (strcasecmp(name, "text") == 0) {
fTextPosition.Set(GetFloatAttribute(attributes, "x"), GetFloatAttribute(attributes, "y"));
fState.fMatrix.Transform(&fTextPosition);
}
}
//------------------------------------------------------------------------------
void Svg2PictureView::EndElement(const XML_Char *name) {
if (strcasecmp(name, "linearGradient") == 0) {
if (fGradient)
fGradients.AddItem(fGradient);
fGradient = NULL;
}
else if (strcasecmp(name, "radialGradient") == 0) {
if (fGradient)
fGradients.AddItem(fGradient);
fGradient = NULL;
}
else if (strcasecmp(name, "text") == 0) {
if (fState.fFill)
{
SetHighColor(fState.fFillColor);
DrawString(fText.String(), fTextPosition);
SetHighColor(fState.fStrokeColor);
}
if (fState.fStroke)
DrawString(fText.String(), fTextPosition);
printf("%f, %f\n", fTextPosition.x, fTextPosition.y);
}
Pop();
}
//------------------------------------------------------------------------------
void Svg2PictureView::CharacterDataHandler(const XML_Char *s, int len) {
fText.SetTo(s, len);
}
//------------------------------------------------------------------------------
void Svg2PictureView::Push() {
_state_ *state = new _state_(fState);
fStack.AddItem(state);
}
//------------------------------------------------------------------------------
void Svg2PictureView::Pop() {
if (fStack.CountItems() == 0)
printf("Unbalanced Push/Pop\n");
_state_ *state = (_state_*)fStack.LastItem();
if (fState.fFlags & STROKE_FLAG)
{
if (state->fStroke)
SetHighColor(state->fStrokeColor);
}
if (fState.fFlags & FILL_FLAG)
{
if (state->fFill)
SetHighColor(state->fFillColor);
}
if (fState.fFlags & STROKE_WIDTH_FLAG)
SetPenSize(state->fStrokeWidth);
if (fState.fFlags & LINE_MODE_FLAG)
SetLineMode(state->fLineCap, state->fLineJoin, state->fLineMiterLimit);
if (fState.fFlags & FONT_SIZE_FLAG)
SetFontSize(state->fFontSize);
fState = *state;
fStack.RemoveItem(state);
delete state;
}
//------------------------------------------------------------------------------
void Svg2PictureView::_StartElement(Svg2PictureView *view, const XML_Char *name, const XML_Char **attributes) {
view->StartElement(name, attributes);
}
//------------------------------------------------------------------------------
void Svg2PictureView::_EndElement(Svg2PictureView *view, const XML_Char *name) {
view->EndElement(name);
}
//------------------------------------------------------------------------------
void Svg2PictureView::_CharacterDataHandler(Svg2PictureView *view, const XML_Char *s, int len) {
view->CharacterDataHandler(s, len);
}
//------------------------------------------------------------------------------
| [
"michael@Inferno.(none)"
]
| [
[
[
1,
1267
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.