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
cf4b687577925005286ef67b4a487ec539c8eaf3
da9e4cd28021ecc9e17e48ac3ded33b798aae59c
/SRC/DRIVERS/HSMMC/HSMMCCh2/s3c6410_hsmmc_lib/sdhcslot.cpp
efdd78100da1235fd84b9b970d1046fc0061f40a
[]
no_license
hibive/sjmt6410pm090728
d45242e74b94f954cf0960a4392f07178088e560
45ceea6c3a5a28172f7cd0b439d40c494355015c
refs/heads/master
2021-01-10T10:02:35.925367
2011-01-27T04:22:44
2011-01-27T04:22:44
43,739,703
1
1
null
null
null
null
UTF-8
C++
false
false
83,885
cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // // Copyright (c) 2002 BSQUARE Corporation. All rights reserved. // DO NOT REMOVE --- BEGIN EXTERNALLY DEVELOPED SOURCE CODE ID 40973--- DO NOT REMOVE #include <bsp.h> #include "SDHC.h" #include "SDHCSlot.h" static volatile BSP_ARGS *v_gBspArgs; #ifdef OMNIBOOK_VER static HANDLE g_hEventSDMMCCH2ERR = NULL; #endif OMNIBOOK_VER #define CARD_INSERTED 1 #define CARD_REMOVED 2 #define _SRCCLK_48MHZ_ // USB_PHY 48MHZ Clock. Keep sync with "hsmmc_s3c6410.cpp" // Macros #define DX_D1_OR_D2(cps) ((cps) == D1 || (cps) == D2) #define SETFNAME() LPCTSTR pszFname = _T(__FUNCTION__) _T(":") #ifdef DEBUG // dump the current request info to the debugger static VOID DumpRequest( PSD_BUS_REQUEST pRequest, DWORD dwZone ) { PREFAST_DEBUGCHK(pRequest); if (dwZone) { DEBUGMSG(1, (TEXT("DumpCurrentRequest: 0x%08X\n"), pRequest)); DEBUGMSG(1, (TEXT("\t Command: %d\n"), pRequest->CommandCode)); DEBUGMSG(1, (TEXT("\t Argument: 0x%08x\n"), pRequest->CommandArgument)); DEBUGMSG(1, (TEXT("\t ResponseType: %d\n"), pRequest->CommandResponse.ResponseType)); DEBUGMSG(1, (TEXT("\t NumBlocks: %d\n"), pRequest->NumBlocks)); DEBUGMSG(1, (TEXT("\t BlockSize: %d\n"), pRequest->BlockSize)); DEBUGMSG(1, (TEXT("\t HCParam: %d\n"), pRequest->HCParam)); } } #else #define DumpRequest(ptr, dw) #endif CSDHCSlotBase::CSDHCSlotBase( ) { m_pregDevice = NULL; m_SlotDma = NULL; m_dwSlot = 0; m_pbRegisters = NULL; m_pHCDContext = NULL; m_dwSysIntr = 0; m_hBusAccess = NULL; m_interfaceType = InterfaceTypeUndefined; m_dwBusNumber = 0; m_dwVddWindows = 0; m_dwMaxClockRate = 0; m_dwTimeoutControl = 0; m_dwMaxBlockLen = 0; m_wRegClockControl = 0; m_wIntSignals = 0; m_cpsCurrent = D0; m_cpsAtPowerDown = D0; m_dwDefaultWakeupControl = 0; m_bWakeupControl = 0; #ifdef DEBUG m_dwReadyInts = 0; #endif m_fCommandCompleteOccurred = FALSE; m_fSleepsWithPower = FALSE; m_fPowerUpDisabledInts = FALSE; m_fIsPowerManaged = FALSE; m_fSDIOInterruptsEnabled = FALSE; m_fCardPresent = FALSE; m_fAutoCMD12Success = FALSE; m_fCheckSlot = TRUE; m_fCanWakeOnSDIOInterrupts = FALSE; m_f4BitMode = FALSE; m_fFakeCardRemoval = FALSE; m_pCurrentRequest = NULL; m_fCurrentRequestFastPath = FALSE; m_fCommandPolling = TRUE; m_fDisableDMA = FALSE; m_dwPollingModeSize = NUM_BYTE_FOR_POLLING_MODE ; } CSDHCSlotBase::~CSDHCSlotBase( ) { #ifdef OMNIBOOK_VER if (g_hEventSDMMCCH2ERR) { CloseHandle(g_hEventSDMMCCH2ERR); g_hEventSDMMCCH2ERR = NULL; } #endif OMNIBOOK_VER if (m_SlotDma) delete m_SlotDma; } BOOL CSDHCSlotBase::Init( DWORD dwSlot, volatile BYTE *pbRegisters, PSDCARD_HC_CONTEXT pHCDContext, DWORD dwSysIntr, HANDLE hBusAccess, INTERFACE_TYPE interfaceType, DWORD dwBusNumber, CReg *pregDevice ) { BOOL fRet = TRUE; DEBUGCHK(dwSlot < SDHC_MAX_SLOTS); DEBUGCHK(pbRegisters); DEBUGCHK(pHCDContext); DEBUGCHK(hBusAccess); PREFAST_DEBUGCHK(pregDevice && pregDevice->IsOK()); PREFAST_DEBUGCHK(m_SlotDma==NULL); m_dwSlot = dwSlot; m_pbRegisters = pbRegisters; m_pHCDContext = pHCDContext; m_dwSysIntr = dwSysIntr; m_hBusAccess = hBusAccess; m_interfaceType = interfaceType; m_dwBusNumber = dwBusNumber; m_pregDevice = pregDevice; fRet = SoftwareReset(SOFT_RESET_ALL); if (fRet) { Sleep(10); // Allow time for card to power down after a device reset SSDHC_CAPABILITIES caps = GetCapabilities(); DEBUGMSG(SDCARD_ZONE_INIT && caps.bits.SDMA, (_T("SDHC Will use DMA for slot %u\n"), m_dwSlot)); m_dwVddWindows = DetermineVddWindows(); m_dwMaxClockRate = DetermineMaxClockRate(); m_dwMaxBlockLen = DetermineMaxBlockLen(); m_dwTimeoutControl = DetermineTimeoutControl(); m_dwDefaultWakeupControl = DetermineWakeupSources(); m_fCanWakeOnSDIOInterrupts = m_pregDevice->ValueDW(SDHC_CAN_WAKE_ON_INT_KEY); m_dwPollingModeSize = m_pregDevice->ValueDW(SDHC_POLLINGMODE_SIZE, NUM_BYTE_FOR_POLLING_MODE); m_dwFastPathTimeoutTicks = m_pregDevice->ValueDW(SDHC_POLLINGMODE_TIMEOUT,POLLING_MODE_TIMEOUT_DEFAULT); m_fDisableDMA = (m_pregDevice->ValueDW(SDHC_DISABLE_DMA_KEY,0)!=0); Validate(); DumpRegisters(); PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; // Below code lines are needed for working as a mass storage device if (v_gBspArgs == NULL) { ioPhysicalBase.LowPart = IMAGE_SHARE_ARGS_PA_START; v_gBspArgs = (volatile BSP_ARGS *)MmMapIoSpace(ioPhysicalBase, sizeof(BSP_ARGS), FALSE); if (v_gBspArgs == NULL) { RETAILMSG(TRUE, (TEXT("[HSMMC2] HSMMC MmMapIoSpace: FAILED\r\n"))); if (v_gBspArgs) { MmUnmapIoSpace((PVOID) v_gBspArgs, sizeof(BSP_ARGS)); v_gBspArgs = NULL; } return FALSE; } #ifndef OMNIBOOK_VER v_gBspArgs->g_SDCardState = CARD_REMOVED; //initialize v_gBspArgs->g_SDCardDetectEvent = CreateEvent(NULL, FALSE, FALSE,NULL); #endif //!OMNIBOOK_VER } } return fRet; } SD_API_STATUS CSDHCSlotBase::Start( ) { Validate(); SD_API_STATUS status; if (SoftwareReset(SOFT_RESET_ALL)) { // timeout control WriteByte(SDHC_TIMEOUT_CONTROL, (BYTE) m_dwTimeoutControl); // Enable error interrupt status and signals for all but the vendor // errors. This allows any normal error to generate an interrupt. WriteWord(SDHC_ERROR_INT_STATUS_ENABLE, ~0 & ~ERR_INT_STATUS_VENDOR); WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE, ~0 & ~ERR_INT_STATUS_VENDOR); // disable the interrupt signals on the FIFO. WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE, 0x1FF); WriteWord(SDHC_NORMAL_INT_STATUS_ENABLE, NORMAL_INT_ENABLE_CARD_INSERTION | NORMAL_INT_ENABLE_CARD_REMOVAL); status = SD_API_STATUS_SUCCESS; } else { status = SD_API_STATUS_DEVICE_NOT_RESPONDING; } return status; } SD_API_STATUS CSDHCSlotBase::Stop( ) { if (m_fCardPresent) { // Remove device HandleRemoval(FALSE); } SoftwareReset(SOFT_RESET_ALL); #ifndef OMNIBOOK_VER if(NULL != v_gBspArgs->g_SDCardDetectEvent) { CloseHandle(v_gBspArgs->g_SDCardDetectEvent); v_gBspArgs->g_SDCardDetectEvent = NULL; } #endif //!OMNIBOOK_VER if (v_gBspArgs) { MmUnmapIoSpace((PVOID) v_gBspArgs, sizeof(BSP_ARGS)); v_gBspArgs = NULL; } return SD_API_STATUS_SUCCESS; } SD_API_STATUS CSDHCSlotBase::GetSlotInfo( PSDCARD_HC_SLOT_INFO pSlotInfo ) { PREFAST_DEBUGCHK(pSlotInfo); DEBUGCHK(m_pregDevice->IsOK()); // set the slot capabilities DWORD dwCap = SD_SLOT_SD_4BIT_CAPABLE | SD_SLOT_SD_1BIT_CAPABLE | SD_SLOT_SDIO_CAPABLE | SD_SLOT_SDIO_INT_DETECT_4BIT_MULTI_BLOCK; if (GetCapabilities().bits.HighSpeed){ dwCap |= SD_SLOT_HIGH_SPEED_CAPABLE; } SDHCDSetSlotCapabilities(pSlotInfo,dwCap ); SDHCDSetVoltageWindowMask(pSlotInfo, m_dwVddWindows); // Set optimal voltage SDHCDSetDesiredSlotVoltage(pSlotInfo, GetDesiredVddWindow()); // Controller may be able to clock at higher than the max SD rate, // but we should only report the highest rate in the range. DWORD dwMaxClockRateInSDRange = SD_FULL_SPEED_RATE; SetClockRate(&dwMaxClockRateInSDRange); SDHCDSetMaxClockRate(pSlotInfo, dwMaxClockRateInSDRange); // Set power up delay. We handle this in SetVoltage(). SDHCDSetPowerUpDelay(pSlotInfo, 1); return SD_API_STATUS_SUCCESS; } SD_API_STATUS CSDHCSlotBase::SlotOptionHandler( SD_SLOT_OPTION_CODE sdOption, PVOID pData, DWORD cbData ) { SD_API_STATUS status = SD_API_STATUS_SUCCESS; switch (sdOption) { case SDHCDSetSlotPower: { DEBUGCHK(cbData == sizeof(DWORD)); PDWORD pdwVddSetting = (PDWORD) pData; SetVoltage(*pdwVddSetting); break; } case SDHCDSetSlotInterface: { DEBUGCHK(cbData == sizeof(SD_CARD_INTERFACE)); PSD_CARD_INTERFACE pInterface = (PSD_CARD_INTERFACE) pData; DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("CSDHCSlotBase::SlotOptionHandler: Clock Setting: %d\n"), pInterface->ClockRate)); SD_CARD_INTERFACE_EX sdCardInterfaceEx; memset(&sdCardInterfaceEx,0, sizeof(sdCardInterfaceEx)); sdCardInterfaceEx.InterfaceModeEx.bit.sd4Bit = (((pInterface->InterfaceMode) == SD_INTERFACE_SD_4BIT)? 1:0); // An interface for DAT 8-Bit on MMCplus is added. sdCardInterfaceEx.InterfaceModeEx.bit.hsmmc8Bit = (((pInterface->InterfaceMode) == SD_INTERFACE_MMC_8BIT)? 1:0); sdCardInterfaceEx.ClockRate = pInterface->ClockRate; sdCardInterfaceEx.InterfaceModeEx.bit.sdWriteProtected = (pInterface->WriteProtected?1:0); SetInterface(&sdCardInterfaceEx); // Update the argument back. // The interface for DAT 8-Bit on MMCplus must be checked prior to orther interfaces. if (sdCardInterfaceEx.InterfaceModeEx.bit.hsmmc8Bit != 0) { pInterface->InterfaceMode = SD_INTERFACE_MMC_8BIT; } else { pInterface->InterfaceMode = (sdCardInterfaceEx.InterfaceModeEx.bit.sd4Bit!=0?SD_INTERFACE_SD_4BIT:SD_INTERFACE_SD_MMC_1BIT); } pInterface->ClockRate = sdCardInterfaceEx.ClockRate; pInterface->WriteProtected = (sdCardInterfaceEx.InterfaceModeEx.bit.sdWriteProtected!=0?TRUE:FALSE); break; } case SDHCDSetSlotInterfaceEx: { DEBUGCHK(cbData == sizeof(SD_CARD_INTERFACE_EX)); PSD_CARD_INTERFACE_EX pInterface = (PSD_CARD_INTERFACE_EX) pData; DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("CSDHCSlotBase::SlotOptionHandler: Clock Setting: %d\n"), pInterface->ClockRate)); SetInterface((PSD_CARD_INTERFACE_EX)pInterface); } case SDHCDEnableSDIOInterrupts: case SDHCDAckSDIOInterrupt: EnableSDIOInterrupts(TRUE); break; case SDHCDDisableSDIOInterrupts: EnableSDIOInterrupts(FALSE); break; case SDHCDGetWriteProtectStatus: { DEBUGCHK(cbData == sizeof(SD_CARD_INTERFACE)); PSD_CARD_INTERFACE pInterface = (PSD_CARD_INTERFACE) pData; pInterface->WriteProtected = IsWriteProtected(); break; } case SDHCDQueryBlockCapability: { DEBUGCHK(cbData == sizeof(SD_HOST_BLOCK_CAPABILITY)); PSD_HOST_BLOCK_CAPABILITY pBlockCaps = (PSD_HOST_BLOCK_CAPABILITY)pData; DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("CSDHCSlotBase::SlotOptionHandler: Read Block Length: %d , Read Blocks: %d\n"), pBlockCaps->ReadBlockSize, pBlockCaps->ReadBlocks)); DEBUGMSG(SDCARD_ZONE_INFO, (TEXT("CSDHCSlotBase::SlotOptionHandler: Write Block Length: %d , Write Blocks: %d\n"), pBlockCaps->WriteBlockSize, pBlockCaps->WriteBlocks)); pBlockCaps->ReadBlockSize = max(pBlockCaps->ReadBlockSize, SDHC_MIN_BLOCK_LENGTH); pBlockCaps->ReadBlockSize = min(pBlockCaps->ReadBlockSize, (USHORT) m_dwMaxBlockLen); pBlockCaps->WriteBlockSize = max(pBlockCaps->WriteBlockSize, SDHC_MIN_BLOCK_LENGTH); pBlockCaps->WriteBlockSize = min(pBlockCaps->WriteBlockSize, (USHORT) m_dwMaxBlockLen); break; } case SDHCDGetSlotPowerState: { DEBUGCHK(cbData == sizeof(CEDEVICE_POWER_STATE)); PCEDEVICE_POWER_STATE pcps = (PCEDEVICE_POWER_STATE) pData; *pcps = GetPowerState(); break; } case SDHCDSetSlotPowerState: { DEBUGCHK(cbData == sizeof(CEDEVICE_POWER_STATE)); PCEDEVICE_POWER_STATE pcps = (PCEDEVICE_POWER_STATE) pData; SetPowerState(*pcps); break; } case SDHCDWakeOnSDIOInterrupts: { DEBUGCHK(cbData == sizeof(BOOL)); PBOOL pfWake = (PBOOL) pData; if (m_fCanWakeOnSDIOInterrupts) { DWORD dwWakeupControl = m_dwDefaultWakeupControl; if (*pfWake) { dwWakeupControl |= WAKEUP_INTERRUPT; } m_bWakeupControl = (BYTE) dwWakeupControl; } else { status = SD_API_STATUS_UNSUCCESSFUL; } break; } case SDHCDGetSlotInfo: { DEBUGCHK(cbData == sizeof(SDCARD_HC_SLOT_INFO)); PSDCARD_HC_SLOT_INFO pSlotInfo = (PSDCARD_HC_SLOT_INFO) pData; status = GetSlotInfo(pSlotInfo); break; } case SDHCAllocateDMABuffer: { DEBUGCHK (cbData == sizeof(SD_HOST_ALLOC_FREE_DMA_BUFFER)); PREFAST_ASSERT(pData!=NULL); PSD_HOST_ALLOC_FREE_DMA_BUFFER pSdDmaBuffer = (PSD_HOST_ALLOC_FREE_DMA_BUFFER)pData; pSdDmaBuffer->VirtualAddress = SlotAllocDMABuffer(pSdDmaBuffer->Length, &pSdDmaBuffer->LogicalAddress,pSdDmaBuffer->CacheEnabled); status = (pSdDmaBuffer->VirtualAddress!=NULL? SD_API_STATUS_SUCCESS: SD_API_STATUS_BUFFER_OVERFLOW); break; } case SDHCFreeDMABuffer:{ DEBUGCHK (cbData == sizeof(SD_HOST_ALLOC_FREE_DMA_BUFFER)); PSD_HOST_ALLOC_FREE_DMA_BUFFER pSdDmaBuffer = (PSD_HOST_ALLOC_FREE_DMA_BUFFER)pData; BOOL fResult = SlotFreeDMABuffer(pSdDmaBuffer->Length, pSdDmaBuffer->LogicalAddress,pSdDmaBuffer->VirtualAddress,pSdDmaBuffer->CacheEnabled); status = (fResult? SD_API_STATUS_SUCCESS: SD_API_STATUS_INVALID_PARAMETER); break; } default: status = SD_API_STATUS_INVALID_PARAMETER; } return status; } DWORD CSDHCSlotBase::DetermineMaxClockRate( ) { DEBUGCHK(m_pregDevice->IsOK()); // We allow the registry to override what is in the capabilities register. DWORD dwMaxClockRate = m_pregDevice->ValueDW(SDHC_FREQUENCY_KEY); if (dwMaxClockRate == 0) { SSDHC_CAPABILITIES caps = GetCapabilities(); dwMaxClockRate = caps.bits.ClkFreq * 1000000; if (dwMaxClockRate == 0) { // No clock frequency specified. Use the highest possible that // could have been specified so that a working clock divisor // will be chosen. dwMaxClockRate = SDHC_MAX_CLOCK_FREQUENCY; DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDHC: No base clock frequency specified\n"))); DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("SDHC: Using default frequency of %u\n"), dwMaxClockRate)); } } return dwMaxClockRate; } DWORD CSDHCSlotBase::DetermineMaxBlockLen( ) { static const USHORT sc_rgusBlockLen[] = { SDHC_CAPABILITIES_MAX_BLOCK_LENGTH_0, SDHC_CAPABILITIES_MAX_BLOCK_LENGTH_1, SDHC_CAPABILITIES_MAX_BLOCK_LENGTH_2 }; SSDHC_CAPABILITIES caps = GetCapabilities(); // Determine the maximum block length DWORD dwMaxBlockLen; if (caps.bits.MaxBlockLen < _countof(sc_rgusBlockLen)) { dwMaxBlockLen = sc_rgusBlockLen[caps.bits.MaxBlockLen]; } else { // We hit reserved bit by Standard SDHC specification. So, it is better to returns smallest one. ASSERT(FALSE); dwMaxBlockLen = SDHC_CAPABILITIES_MAX_BLOCK_LENGTH_0 ; } return dwMaxBlockLen; } DWORD CSDHCSlotBase::DetermineTimeoutControl( ) { DEBUGCHK(m_pregDevice->IsOK()); return SDHC_TIMEOUT_CONTROL_MAX; } DWORD CSDHCSlotBase::DetermineWakeupSources( ) { DEBUGCHK(m_pregDevice->IsOK()); DWORD dwWakeupSources = m_pregDevice->ValueDW(SDHC_WAKEUP_SOURCES_KEY); dwWakeupSources &= WAKEUP_ALL_SOURCES; // Waking on SDIO interrupts must be enabled by the bus driver. dwWakeupSources &= ~WAKEUP_INTERRUPT; return dwWakeupSources; } VOID CSDHCSlotBase::SetVoltage( DWORD dwVddSetting ) { Validate(); UCHAR ucVoltageSelection = SDBUS_POWER_ON; UCHAR ucOldVoltage; DEBUGCHK(dwVddSetting & m_dwVddWindows); if ( dwVddSetting & (SD_VDD_WINDOW_3_2_TO_3_3 | SD_VDD_WINDOW_3_3_TO_3_4) ) { ucVoltageSelection |= SDBUS_VOLTAGE_SELECT_3_3V; } else if ( dwVddSetting & (SD_VDD_WINDOW_2_9_TO_3_0 | SD_VDD_WINDOW_3_0_TO_3_1) ) { ucVoltageSelection |= SDBUS_VOLTAGE_SELECT_3_0V; } else if ( dwVddSetting & (SD_VDD_WINDOW_1_7_TO_1_8 | SD_VDD_WINDOW_1_8_TO_1_9) ) { ucVoltageSelection |= SDBUS_VOLTAGE_SELECT_1_8V; } ucOldVoltage = ReadByte(SDHC_POWER_CONTROL); if (ucOldVoltage != ucVoltageSelection) { // SD Bus Power must be initially set to 0 when changing voltages WriteByte(SDHC_POWER_CONTROL, 0); WriteByte(SDHC_POWER_CONTROL, ucVoltageSelection); DEBUGMSG(SDCARD_ZONE_INFO,( TEXT("CSDHCSlotBase::SetVoltage: Set SDHC_POWER_CONTROL reg = 0x%02x\n"), ucVoltageSelection)); Sleep(GetPowerSupplyRampUpMs()); } } // Set up the controller according to the interface parameters. VOID CSDHCSlotBase::SetInterface( PSD_CARD_INTERFACE_EX pInterface ) { PREFAST_DEBUGCHK(pInterface); Validate(); BYTE bHostCtr = 0; #ifdef _MMC_SPEC_42_ if (0 != pInterface->InterfaceModeEx.bit.hsmmc8Bit) { DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SHCSDSlotOptionHandler - Setting for 8 bit mode\n"))); RETAILMSG(TRUE, (TEXT("[HSMMC2] Setting for 8 bit mode , Clock Rate = %d Hz\n"),pInterface->ClockRate)); bHostCtr |= HOSTCTL_DAT_WIDTH_8BIT; m_f4BitMode = TRUE; } else if (SD_INTERFACE_SD_MMC_1BIT == pInterface->InterfaceModeEx.bit.sd4Bit) { DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SHCSDSlotOptionHandler - Setting for 1 bit mode\n"))); RETAILMSG(TRUE, (TEXT("[HSMMC2] Setting for 1 bit mode , Clock Rate = %d Hz\n"),pInterface->ClockRate)); bHostCtr = 0; m_f4BitMode = FALSE; } else if (SD_INTERFACE_SD_4BIT == pInterface->InterfaceModeEx.bit.sd4Bit) { DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SHCSDSlotOptionHandler - Setting for 4 bit mode\n"))); RETAILMSG(TRUE, (TEXT("[HSMMC2] Setting for 4 bit mode , Clock Rate = %d Hz\n"),pInterface->ClockRate)); bHostCtr |= HOSTCTL_DAT_WIDTH; m_f4BitMode = TRUE; } #else m_f4BitMode = (pInterface->InterfaceModeEx.bit.sd4Bit!=0); bHostCtr |= (m_f4BitMode?HOSTCTL_DAT_WIDTH:0); bHostCtr |= (pInterface->InterfaceModeEx.bit.sdHighSpeed!=0?HOSTCTL_HIGH_SPEED:0); #endif if (m_SlotDma) { bHostCtr |= (m_SlotDma->DmaSelectBit()<<3); } DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SHCSDSlotOptionHandler - Setting Host Control Register %x \n"),bHostCtr)); WriteByte(SDHC_HOST_CONTROL, bHostCtr); SetClockRate(&pInterface->ClockRate); } VOID CSDHCSlotBase::SetPowerState( CEDEVICE_POWER_STATE cpsNew ) { DEBUGCHK(VALID_DX(cpsNew)); m_fIsPowerManaged = TRUE; if (DX_D1_OR_D2(cpsNew)) { cpsNew = D0; } if (m_cpsCurrent != cpsNew) { SetHardwarePowerState(cpsNew); } } VOID CSDHCSlotBase::PowerDown( ) { Validate(); m_cpsAtPowerDown = m_cpsCurrent; if (!m_fIsPowerManaged) { CEDEVICE_POWER_STATE cps; if (m_bWakeupControl) { cps = D3; } else { cps = D4; } SetHardwarePowerState(cps); } BOOL fKeepPower = FALSE; if (m_fSleepsWithPower || m_cpsCurrent == D0) { DEBUGCHK(!m_fSleepsWithPower || m_cpsCurrent == D3); fKeepPower = TRUE; } else m_fFakeCardRemoval = TRUE; PowerUpDown(FALSE, fKeepPower); } VOID CSDHCSlotBase::PowerUp( ) { Validate(); if (!m_fIsPowerManaged) { SetHardwarePowerState(m_cpsAtPowerDown); } else if (m_fSleepsWithPower) { WORD wIntStatus = ReadWord(SDHC_NORMAL_INT_STATUS); if (wIntStatus == NORMAL_INT_STATUS_CARD_INT) { // We woke system through a card interrupt. We need to clear // this so that the IST will not be signalled. EnableSDIOInterrupts(FALSE); m_fPowerUpDisabledInts = TRUE; } } PowerUpDown(TRUE, TRUE); if (m_fFakeCardRemoval){ Start(); SetInterruptEvent(); } } // // For BC, // 1. Returns SD_API_STATUS_FAST_PATH_SUCCESS, callback is NOT called. Fastpass only. // 2. Return !SD_API_SUCCESS(status). callback is NOT called. // 3. Return SD_API_STATUS_SUCCESS, callback is called // 4. Return SD_API_STATUS_PENDING, callback is NOT call Yet. // SD_API_STATUS CSDHCSlotBase::BusRequestHandler( PSD_BUS_REQUEST pRequest) { SETFNAME(); SD_API_STATUS status; PREFAST_DEBUGCHK(pRequest); Validate(); DEBUGMSG(SDHC_SEND_ZONE, (TEXT("%s CMD:%d\n"), pszFname, pRequest->CommandCode)); if (m_pCurrentRequest) { // We have outstand request. ASSERT(FALSE); IndicateBusRequestComplete(pRequest, SD_API_STATUS_CANCELED); m_pCurrentRequest = NULL; } if (!m_fCardPresent) { status= SD_API_STATUS_DEVICE_REMOVED; } else { WORD wIntSignals = ReadWord(SDHC_NORMAL_INT_SIGNAL_ENABLE); WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE,0); m_fCurrentRequestFastPath = FALSE ; m_pCurrentRequest = pRequest ; // if no data transfer involved, use FAST PATH if ((pRequest->SystemFlags & SD_FAST_PATH_AVAILABLE)!=0) { // Fastpath m_fCurrentRequestFastPath = TRUE; status = SubmitBusRequestHandler( pRequest ); if( status == SD_API_STATUS_PENDING ) { // Polling for completion. BOOL fCardInserted = TRUE; DWORD dwStartTicks = GetTickCount(); #ifdef _SMDK6410_CH2_EXTCD_ if (m_pCurrentRequest && (fCardInserted = (IsCardPresent() & TRUE)!=0) && GetTickCount() - dwStartTicks <= m_dwFastPathTimeoutTicks) { #else while (m_pCurrentRequest && (fCardInserted = (ReadDword(SDHC_PRESENT_STATE) & STATE_CARD_INSERTED)!=0 ) && ((GetTickCount() - dwStartTicks) <= m_dwFastPathTimeoutTicks)) { #endif HandleInterrupt(); } if (m_pCurrentRequest && fCardInserted ) { // Time out , need to switch to asyn.it will call callback after this pRequest->SystemFlags &= ~SD_FAST_PATH_AVAILABLE; m_fCurrentRequestFastPath = FALSE ; } else { // Fastpass completed. status = m_FastPathStatus; // Clear before status of fastpath. m_FastPathStatus = 0; if (m_pCurrentRequest) { ASSERT(FALSE); status = SD_API_STATUS_DEVICE_REMOVED; } } } if (status == SD_API_STATUS_SUCCESS) { status = SD_API_STATUS_FAST_PATH_SUCCESS; } } else status = SubmitBusRequestHandler( pRequest ); if (status!=SD_API_STATUS_PENDING && m_pCurrentRequest) { // if there is error case. We don't notify the callback function either So. m_fCurrentRequestFastPath = TRUE; IndicateBusRequestComplete(pRequest,status); } WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE,wIntSignals); } return status; } SD_API_STATUS CSDHCSlotBase::SubmitBusRequestHandler(PSD_BUS_REQUEST pRequest) { SETFNAME(); PREFAST_DEBUGCHK(pRequest); Validate(); WORD wRegCommand; SD_API_STATUS status; WORD wIntStatusEn; BOOL fSuccess; DEBUGCHK(m_dwReadyInts == 0); DEBUGCHK(!m_fCommandCompleteOccurred); DEBUGMSG(SDHC_SEND_ZONE, (TEXT("%s CMD:%d\n"), pszFname, pRequest->CommandCode)); // bypass CMD12 if AutoCMD12 was done by hardware if (pRequest->CommandCode == 12) { if (m_fAutoCMD12Success) { DEBUGMSG(SDHC_SEND_ZONE, (TEXT("%s AutoCMD12 Succeeded, bypass CMD12.\n"), pszFname)); // The response for Auto CMD12 is in a special area UNALIGNED DWORD *pdwResponseBuffer = (PDWORD) (pRequest->CommandResponse.ResponseBuffer + 1); // Skip CRC *pdwResponseBuffer = ReadDword(SDHC_R6); IndicateBusRequestComplete(pRequest, SD_API_STATUS_SUCCESS); status = SD_API_STATUS_SUCCESS; goto EXIT; } } m_fAutoCMD12Success = FALSE; // initialize command register with command code wRegCommand = (pRequest->CommandCode << CMD_INDEX_SHIFT) & CMD_INDEX_MASK; // check for a response switch (pRequest->CommandResponse.ResponseType) { case NoResponse: break; case ResponseR2: wRegCommand |= CMD_RESPONSE_R2; break; case ResponseR3: case ResponseR4: wRegCommand |= CMD_RESPONSE_R3_R4; break; case ResponseR1: case ResponseR5: case ResponseR6: case ResponseR7: wRegCommand |= CMD_RESPONSE_R1_R5_R6_R7; break; case ResponseR1b: wRegCommand |= CMD_RESPONSE_R1B_R5B; break; default: status = SD_API_STATUS_INVALID_PARAMETER; goto EXIT; } // Set up variable for the new interrupt sources. Note that we must // enable DMA and read/write interrupts in this routine (not in // HandleCommandComplete) or they will be missed. wIntStatusEn = ReadWord(SDHC_NORMAL_INT_STATUS_ENABLE); wIntStatusEn |= NORMAL_INT_ENABLE_CMD_COMPLETE | NORMAL_INT_ENABLE_TRX_COMPLETE; // check command inhibit, wait until OK fSuccess = WaitForReg<DWORD>(&CSDHCSlotBase::ReadDword, SDHC_PRESENT_STATE, STATE_CMD_INHIBIT, 0); if (!fSuccess) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("%s Timeout waiting for CMD Inhibit\r\n"), pszFname)); status = SD_API_STATUS_DEVICE_NOT_RESPONDING; goto EXIT; } // programming registers if (!TRANSFER_IS_COMMAND_ONLY(pRequest)) { WORD wRegTxnMode = 0; #ifdef _MMC_SPEC_42_ // To distinguish btween MMCmicro and MMCplus, we will issue MMC_CMD_SEND_EXT_CSD. // At that time, Dat line is 8bit. If the inserted card is MMCmicro, "Data timeout" error will be occurred. // Because MMCmicro does not supports 8bit DAT line but 4bit. To reduce the delay time on Data timeout error occurring, // we modify the timeout value. if ( (ReadByte(SDHC_TIMEOUT_CONTROL) != m_dwTimeoutControl) && (pRequest->CommandCode != MMC_CMD_SEND_EXT_CSD) ) { WriteByte(SDHC_TIMEOUT_CONTROL, (BYTE) m_dwTimeoutControl); } else if ( (ReadByte(SDHC_TIMEOUT_CONTROL) == m_dwTimeoutControl) && (pRequest->CommandCode == MMC_CMD_SEND_EXT_CSD) ) { WriteByte(SDHC_TIMEOUT_CONTROL, (BYTE)0x3); } #endif wRegCommand |= CMD_DATA_PRESENT; if (m_SlotDma && m_SlotDma->ArmDMA(*pRequest,TRANSFER_IS_WRITE(pRequest))) { wIntStatusEn |= NORMAL_INT_ENABLE_DMA; wRegTxnMode |= TXN_MODE_DMA; } else { if (TRANSFER_IS_WRITE(pRequest)) { wIntStatusEn |= NORMAL_INT_ENABLE_BUF_WRITE_RDY; } else { wIntStatusEn |= NORMAL_INT_ENABLE_BUF_READ_RDY; } } // BlockSize // Note that for DMA we are programming the buffer boundary for 4k DEBUGMSG(SDHC_SEND_ZONE,(TEXT("Sending command block size 0x%04X\r\n"), (WORD) pRequest->BlockSize)); ASSERT(PAGE_SIZE == 0x1000); WriteWord(SDHC_BLOCKSIZE, (WORD)(pRequest->BlockSize & 0xfff) | (0<<12)); // SDHC 2.2.2, CE is 4k-aligned page. // We always go into block mode even if there is only 1 block. // Otherwise the Pegasus will occaissionally hang when // writing a single block with DMA. wRegTxnMode |= (TXN_MODE_MULTI_BLOCK | TXN_MODE_BLOCK_COUNT_ENABLE); // BlockCount DEBUGMSG(SDHC_SEND_ZONE,(TEXT("Sending command block count 0x%04X\r\n"), (WORD) pRequest->NumBlocks)); WriteWord(SDHC_BLOCKCOUNT, (WORD) pRequest->NumBlocks); if (pRequest->Flags & SD_AUTO_ISSUE_CMD12) { wRegTxnMode |= TXN_MODE_AUTO_CMD12; } if (TRANSFER_IS_READ(pRequest)) { wRegTxnMode |= TXN_MODE_DATA_DIRECTION_READ; } // check dat inhibit, wait until okay fSuccess = WaitForReg<DWORD>(&CSDHCSlotBase::ReadDword, SDHC_PRESENT_STATE, STATE_DAT_INHIBIT, 0); if (!fSuccess) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("%s Timeout waiting for DAT Inhibit\r\n"), pszFname)); status = SD_API_STATUS_DEVICE_NOT_RESPONDING; goto EXIT; } DEBUGMSG(SDHC_SEND_ZONE,(TEXT("Sending Transfer Mode 0x%04X\r\n"),wRegTxnMode)); WriteWord(SDHC_TRANSFERMODE, wRegTxnMode); } else { // Command-only if (pRequest->CommandCode == SD_CMD_STOP_TRANSMISSION) { wRegCommand |= CMD_TYPE_ABORT; } else if (TransferIsSDIOAbort(pRequest)) { // Use R5b For CMD52, Function 0, I/O Abort DEBUGMSG(SDHC_SEND_ZONE, (TEXT("Sending Abort command \r\n"))); wRegCommand |= CMD_TYPE_ABORT | CMD_RESPONSE_R1B_R5B; } } DEBUGMSG(SDHC_SEND_ZONE,(TEXT("Sending command register 0x%04X\r\n"),wRegCommand)); DEBUGMSG(SDHC_SEND_ZONE,(TEXT("Sending command Argument 0x%08X\r\n"),pRequest->CommandArgument)); WriteDword(SDHC_ARGUMENT_0, pRequest->CommandArgument); // Enable transfer interrupt sources. WriteWord(SDHC_NORMAL_INT_STATUS_ENABLE, wIntStatusEn); // Status Busy bit checking for clearing the interrupt status register before "CMD ISSUE". fSuccess = WaitForReg<DWORD>(&CSDHCSlotBase::ReadDword, SDHC_CONTROL4, SDHC_CONTROL4_STABUSY, 0); if (!fSuccess) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("%s Timeout waiting for CMD operation finish\r\n"), pszFname)); status = SD_API_STATUS_DEVICE_NOT_RESPONDING; goto EXIT; } // Turn the clock on. It is turned off in IndicateBusRequestComplete(). SDClockOn(); // Turn the LED on. EnableLED(TRUE); // Writing the upper byte of the command register starts the command. // All register initialization must already be complete by this point. WriteWord(SDHC_COMMAND, wRegCommand); if (m_fCommandPolling ) { PollingForCommandComplete(); } status = SD_API_STATUS_PENDING; EXIT: return status; } BOOL CSDHCSlotBase::PollingForCommandComplete() { BOOL fContinue = TRUE; if (m_fFakeCardRemoval && m_fCardPresent) { m_fFakeCardRemoval = FALSE; HandleRemoval(TRUE); } else { // Assume we reading PCI register at 66 Mhz. for times of 100 us. it should be 10*1000 time for (DWORD dwIndex=0; fContinue && dwIndex<10*1000; dwIndex ++ ) { WORD wIntStatus = ReadWord(SDHC_NORMAL_INT_STATUS); if (wIntStatus != 0) { DEBUGMSG(SDHC_INTERRUPT_ZONE, (TEXT("PollingForCommandComplete (%u) - Normal Interrupt_Status=0x%02x\n"), m_dwSlot, wIntStatus)); // Error handling. Make sure to handle errors first. if ( wIntStatus & NORMAL_INT_STATUS_ERROR_INT ) { HandleErrors(); fContinue = FALSE; } // Command Complete handling. if ( wIntStatus & NORMAL_INT_STATUS_CMD_COMPLETE ) { // Clear status m_fCommandCompleteOccurred = TRUE; fContinue = FALSE; WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_CMD_COMPLETE); if (HandleCommandComplete()) { // If completed. WriteWord(SDHC_NORMAL_INT_STATUS, (wIntStatus & NORMAL_INT_STATUS_TRX_COMPLETE)); } } } } } ASSERT(!fContinue); return (!fContinue); } VOID CSDHCSlotBase::EnableSDIOInterrupts( BOOL fEnable ) { Validate(); if (fEnable) { m_fSDIOInterruptsEnabled = TRUE; DoEnableSDIOInterrupts(fEnable); } else { DoEnableSDIOInterrupts(fEnable); m_fSDIOInterruptsEnabled = FALSE; } } #ifndef _SMDK6410_CH2_EXTCD_ VOID CSDHCSlotBase::HandleInterrupt( ) #else // New Interrupt handler function can process factors on new card detect interrupt of HSMMC ch2 on SMDK6410. VOID CSDHCSlotBase::HandleInterrupt(SDSLOT_INT_TYPE intType) #endif { Validate(); #ifdef _SMDK6410_CH2_EXTCD_ // in case of it is occurred a card detect interrupt of HSMMC ch2 on SMDK6410 if (intType == SDSLOT_INT_CARD_DETECTED) { m_fCheckSlot = TRUE; } else { #endif WORD wIntStatus = 0; wIntStatus = ReadWord(SDHC_NORMAL_INT_STATUS); if (m_fFakeCardRemoval ) { m_fFakeCardRemoval = FALSE; if (m_fCardPresent) HandleRemoval(TRUE); m_fCheckSlot = TRUE; } else if (wIntStatus != 0) { DEBUGMSG(SDHC_INTERRUPT_ZONE, (TEXT("HandleInterrupt (%u) - Normal Interrupt_Status=0x%02x\n"), m_dwSlot, wIntStatus)); // Error handling. Make sure to handle errors first. if ( wIntStatus & NORMAL_INT_STATUS_ERROR_INT ) { HandleErrors(); } // Command Complete handling. if ( wIntStatus & NORMAL_INT_STATUS_CMD_COMPLETE ) { // Clear status m_fCommandCompleteOccurred = TRUE; WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_CMD_COMPLETE); if ( HandleCommandComplete() ) { wIntStatus &= ~NORMAL_INT_STATUS_TRX_COMPLETE; // this is command-only request. } } // Sometimes at the lowest clock rate, the Read/WriteBufferReady // interrupt actually occurs before the CommandComplete interrupt. // This confuses our debug validation code and could potentially // cause problems. This is why we will verify that the CommandComplete // occurred before processing any data transfer interrupts. if (m_fCommandCompleteOccurred) { if (wIntStatus & NORMAL_INT_STATUS_DMA) { WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_DMA); // get the current request PSD_BUS_REQUEST pRequest = GetAndLockCurrentRequest(); if (m_SlotDma && pRequest) m_SlotDma->DMANotifyEvent(*pRequest, DMA_COMPLETE); else { ASSERT(FALSE); } // do not break here. Continue to check TransferComplete. } // Buffer Read Ready handling if (wIntStatus & NORMAL_INT_STATUS_BUF_READ_RDY ) { // Clear status WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_BUF_READ_RDY); HandleReadReady(); // do not break here. Continue to check TransferComplete. } // Buffer Write Ready handling if (wIntStatus & NORMAL_INT_STATUS_BUF_WRITE_RDY ) { // Clear status WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_BUF_WRITE_RDY); HandleWriteReady(); // do not break here. Continue to check TransferComplete. } } else { // We received data transfer interrupt before command // complete interrupt. Wait for the command complete before // processing the data interrupt. } // Transfer Complete handling if ( wIntStatus & NORMAL_INT_STATUS_TRX_COMPLETE ) { // Clear status WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_TRX_COMPLETE | NORMAL_INT_STATUS_DMA); HandleTransferDone(); } // SDIO Interrupt Handling if ( wIntStatus & NORMAL_INT_STATUS_CARD_INT ) { DEBUGCHK(m_fSDIOInterruptsEnabled); DEBUGMSG(SDHC_INTERRUPT_ZONE, (_T("SDHCControllerIst: Card interrupt!\n"))); EnableSDIOInterrupts(FALSE); IndicateSlotStateChange(DeviceInterrupting); } // Card Detect Interrupt Handling if (wIntStatus & (NORMAL_INT_STATUS_CARD_INSERTION | NORMAL_INT_STATUS_CARD_REMOVAL)) { WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_CARD_INSERTION | NORMAL_INT_STATUS_CARD_REMOVAL); m_fCheckSlot = TRUE; } } #ifdef _SMDK6410_CH2_EXTCD_ } // The end of "if(intType == SDSLOT_INT_CARD_DETECTED)" #endif if (m_fCheckSlot) { m_fCheckSlot = FALSE; #ifdef _SMDK6410_CH2_EXTCD_ // At this time, we have to validate the card present status. if((IsCardPresent() == TRUE) && (m_fCardPresent != TRUE)) #else // check card inserted or removed DWORD dwPresentState = ReadDword(SDHC_PRESENT_STATE); if (dwPresentState & STATE_CARD_INSERTED) #endif { DEBUGMSG(SDHC_INTERRUPT_ZONE, (TEXT("SDHCControllerIst - Card is Inserted! \n"))); RETAILMSG(TRUE, (TEXT("[HSMMC2] SDHCControllerIst - Card is Inserted! \n"))); m_fFakeCardRemoval = FALSE; if (m_fCardPresent == FALSE ) { Start(); HandleInsertion(); } } #ifdef _SMDK6410_CH2_EXTCD_ else if((IsCardPresent() == FALSE)) #else else #endif { DEBUGMSG(SDHC_INTERRUPT_ZONE, (TEXT("SDHCControllerIst - Card is Removed! \n"))); RETAILMSG(TRUE, (TEXT("[HSMMC2] SDHCControllerIst - Card is Removed! \n"))); m_fFakeCardRemoval = FALSE; if (m_fCardPresent) { HandleRemoval(TRUE); } } } } #ifdef _SMDK6410_CH2_EXTCD_ // New function can detect whether card is presented of HSMMC ch2 on SMDK6410. BOOL CSDHCSlotBase::IsCardPresent() { BOOL fRetVal; #ifdef OMNIBOOK_VER fRetVal = FALSE; if (v_gBspArgs) fRetVal = v_gBspArgs->bSDMMCCH2CardDetect; #else //!OMNIBOOK_VER volatile S3C6410_GPIO_REG *pIOPreg = NULL; PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; ioPhysicalBase.LowPart = S3C6410_BASE_REG_PA_GPIO; pIOPreg = (volatile S3C6410_GPIO_REG *)MmMapIoSpace(ioPhysicalBase, sizeof(S3C6410_GPIO_REG), FALSE); if (pIOPreg == NULL) { RETAILMSG (1,(TEXT("GPIO registers not mapped\r\n"))); return FALSE; } if ( (pIOPreg->GPNDAT & (0x1<<15)) == 0 ) { fRetVal = TRUE; } else { fRetVal = FALSE; } MmUnmapIoSpace((PVOID)pIOPreg, sizeof(S3C6410_GPIO_REG)); #endif OMNIBOOK_VER return fRetVal; } #endif VOID CSDHCSlotBase::HandleRemoval( BOOL fCancelRequest ) { m_fCardPresent = FALSE; m_fIsPowerManaged = FALSE; m_fSleepsWithPower = FALSE; m_fPowerUpDisabledInts = FALSE; m_f4BitMode = FALSE; m_cpsCurrent = D0; // Wake on SDIO interrupt must be set by the client m_bWakeupControl &= ~WAKEUP_INTERRUPT; // To control the Data CRC error WORD wErrIntSignalEn = ReadWord(SDHC_ERROR_INT_SIGNAL_ENABLE); WORD wErrIntStatusEn = ReadWord(SDHC_ERROR_INT_STATUS_ENABLE); WORD wErrIntStatus = ReadWord(SDHC_ERROR_INT_STATUS); WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE, (wErrIntSignalEn & ~(0x20))); //Command and Data CRC error disable WriteWord(SDHC_ERROR_INT_STATUS_ENABLE, (wErrIntStatusEn & ~(0x20))); //Command and Data CRC error disable if (m_fSDIOInterruptsEnabled) { EnableSDIOInterrupts(FALSE); } IndicateSlotStateChange(DeviceEjected); // turn off clock and remove power from the slot SDClockOff(); WriteByte(SDHC_POWER_CONTROL, 0); if (fCancelRequest) { // get the current request PSD_BUS_REQUEST pRequest = GetAndLockCurrentRequest(); if (pRequest != NULL) { DEBUGMSG(SDCARD_ZONE_WARN, (TEXT("Card Removal Detected - Canceling current request: 0x%08X, command: %d\n"), pRequest, pRequest->CommandCode)); DumpRequest(pRequest, SDHC_SEND_ZONE || SDHC_RECEIVE_ZONE); DumpRequest(pRequest, 0); IndicateBusRequestComplete(pRequest, SD_API_STATUS_DEVICE_REMOVED); } } if (m_SlotDma) { delete m_SlotDma; m_SlotDma = NULL; // The Pegasus requires the following so that the next // insertion will work correctly. SoftwareReset(SOFT_RESET_CMD | SOFT_RESET_DAT); WriteDword(SDHC_SYSTEMADDRESS_LO, 0); WriteWord(SDHC_BLOCKSIZE, 0); WriteWord(SDHC_BLOCKCOUNT, 0); WriteWord(SDHC_NORMAL_INT_STATUS, NORMAL_INT_STATUS_DMA); // To diable the Data CRC error interrupt WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE,0); WriteWord(SDHC_ERROR_INT_STATUS,wErrIntStatus); WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE,wErrIntSignalEn); } #ifndef OMNIBOOK_VER v_gBspArgs->g_SDCardState = CARD_REMOVED; SetEvent( v_gBspArgs->g_SDCardDetectEvent ); #endif //!OMNIBOOK_VER } VOID CSDHCSlotBase::HandleInsertion( ) { DWORD dwClockRate = SD_DEFAULT_CARD_ID_CLOCK_RATE; // To control the Data CRC error WORD wErrIntSignalEn = ReadWord(SDHC_ERROR_INT_SIGNAL_ENABLE); WORD wErrIntStatusEn = ReadWord(SDHC_ERROR_INT_STATUS_ENABLE); m_fCardPresent = TRUE; // Apply the initial voltage to the card. SetVoltage(GetMaxVddWindow()); // Send at least 74 clocks to the card over the course of at least 1 ms // with allowance for power supply ramp-up time. (SD Phys Layer 6.4) // Note that power supply ramp-up time occurs in SetVoltage(). SetClockRate(&dwClockRate); SDClockOn(); DWORD dwSleepMs = (74 / (dwClockRate / 1000)) + 1; Sleep(dwSleepMs); SDClockOff(); if (m_SlotDma) { ASSERT(FALSE); delete m_SlotDma; m_SlotDma = NULL; } if (!m_fDisableDMA) { SSDHC_CAPABILITIES caps = GetCapabilities(); if (FALSE) { // Disable ADM2 support for now // caps.bits.ADMA2 m_SlotDma = new CSDHCSlotBase32BitADMA2(*this); } else if (caps.bits.SDMA) { m_SlotDma = new CSDHCSlotBaseSDMA(*this); } if (m_SlotDma && !m_SlotDma->Init()) { // failed. delete m_SlotDma; m_SlotDma = NULL; } ASSERT(!(caps.bits.ADMA2 || caps.bits.SDMA) || m_SlotDma!=NULL); } // Interrupts are not enabled on a newly inserted card. EnableSDIOInterrupts(FALSE); // Indicate device arrival IndicateSlotStateChange(DeviceInserted); // Disable the command and data CRC error WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE, (wErrIntSignalEn | (0x20))); WriteWord(SDHC_ERROR_INT_STATUS_ENABLE, (wErrIntStatusEn | (0x20))); #ifndef OMNIBOOK_VER v_gBspArgs->g_SDCardState = CARD_INSERTED; SetEvent( v_gBspArgs->g_SDCardDetectEvent ); #endif //!OMNIBOOK_VER } BOOL CSDHCSlotBase::HandleCommandComplete( ) { SETFNAME(); PSD_BUS_REQUEST pRequest; BOOL fRet = FALSE; // get the current request pRequest = GetAndLockCurrentRequest(); DEBUGCHK(m_dwReadyInts == 0); if (pRequest) { DEBUGCHK(pRequest->HCParam == 0); // INT_TRX_COMPLETE is not suitable for s3c6410, so I comment out below code. // therefore, in order to keep fastpath status, those code like just below is needed. SD_API_STATUS transferStatus = (m_FastPathStatus >= SD_API_STATUS_SUCCESS) ? SD_API_STATUS_SUCCESS : m_FastPathStatus; if (NoResponse != pRequest->CommandResponse.ResponseType) { // Copy response over to request structure. Note that this is a // bus driver buffer, so we do not need to SetProcPermissions // or __try/__except. UNALIGNED DWORD *pdwResponseBuffer = (PDWORD) (pRequest->CommandResponse.ResponseBuffer + 1); // Skip CRC WORD wCommand = ReadWord(SDHC_COMMAND); if ((wCommand & CMD_RESPONSE_R1B_R5B) == CMD_RESPONSE_R1B_R5B) { // Reset cmd and dat circuits SoftwareReset(SOFT_RESET_CMD | SOFT_RESET_DAT); } pdwResponseBuffer[0] = ReadDword(SDHC_R0); if (pRequest->CommandResponse.ResponseType == ResponseR2) { pdwResponseBuffer[1] = ReadDword(SDHC_R2); pdwResponseBuffer[2] = ReadDword(SDHC_R4); pdwResponseBuffer[3] = ReadDword(SDHC_R6); } } // check for command/response only if (TRANSFER_IS_COMMAND_ONLY(pRequest)) { IndicateBusRequestComplete(pRequest, transferStatus); fRet = TRUE; } else { // handle data phase transfer pRequest->HCParam = 0; fRet = FALSE; } } // else request must have been canceled due to an error return fRet; } VOID CSDHCSlotBase::HandleErrors( ) { SD_API_STATUS status = SD_API_STATUS_SUCCESS; // get the current request PSD_BUS_REQUEST pRequest = NULL; pRequest = GetAndLockCurrentRequest(); WORD wErrorStatus = 0; WORD RetryCount = 100; do { wErrorStatus = ReadWord(SDHC_ERROR_INT_STATUS); RetryCount--; } while ((wErrorStatus == 0) || (RetryCount != 0)); if (wErrorStatus == 0) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - ERROR INT STATUS=0x%02X\n"), wErrorStatus)); return; } DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - ERROR INT STATUS=0x%02X\n"), wErrorStatus)); if (pRequest) { DumpRequest(pRequest, SDCARD_ZONE_ERROR); // For simple debugging, we have to confirm the command number! RETAILMSG(TRUE, (TEXT("[HSMMC2] HandleErrors - ERR CMD:%d : "), pRequest->CommandCode)); } DEBUGCHK( (wErrorStatus & ERR_INT_STATUS_VENDOR) == 0 ); if (wErrorStatus) { if ( wErrorStatus & ERR_INT_STATUS_CMD_TIMEOUT ) { status = SD_API_STATUS_RESPONSE_TIMEOUT; switch(pRequest->CommandCode) { case 1 : RETAILMSG(TRUE, (TEXT("If the card is not a MMC, CMD 1 does not work in reason.\n"))); break; case 5 : RETAILMSG(TRUE, (TEXT("If the card is not a SDIO, CMD 5 does not work in reason.\n"))); #ifdef OMNIBOOK_VER if (NULL == g_hEventSDMMCCH2ERR) g_hEventSDMMCCH2ERR = OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("OMNIBOOK_EVENT_SDMMCCH2ERR")); if (g_hEventSDMMCCH2ERR) SetEvent(g_hEventSDMMCCH2ERR); #endif OMNIBOOK_VER break; case 8 : RETAILMSG(TRUE, (TEXT("If the card is not SD SPEC 2.0, CMD 8 does not work in reason.\n"))); break; default : RETAILMSG(TRUE, (TEXT("[HSMMC2] HandleErrors - CMD Timeout Error...\n"))); break; } } if ( wErrorStatus & ERR_INT_STATUS_CMD_CRC ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - CMD CRC Error...\r\n"))); status = SD_API_STATUS_CRC_ERROR; if ( wErrorStatus & ERR_INT_STATUS_CMD_TIMEOUT ) status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } if ( wErrorStatus & ERR_INT_STATUS_CMD_ENDBIT ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - CMD ENDBIT Error...\r\n"))); status = SD_API_STATUS_RESPONSE_TIMEOUT; } if ( wErrorStatus & ERR_INT_STATUS_CMD_INDEX ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - CMD INDEX Error...\r\n"))); status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } if ( wErrorStatus & ERR_INT_STATUS_DAT_TIMEOUT ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - DAT Timeout Error...\r\n"))); status = SD_API_STATUS_DATA_TIMEOUT; } if ( wErrorStatus & ERR_INT_STATUS_DAT_CRC ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - Data CRC Error...\r\n"))); status = SD_API_STATUS_CRC_ERROR; } if ( wErrorStatus & ERR_INT_STATUS_DAT_ENDBIT ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - DAT END BIT Error...\r\n"))); status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } if ( wErrorStatus & ERR_INT_STATUS_BUS_POWER ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - Bus Power Error...\r\n"))); status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } if ( wErrorStatus & ERR_INT_STATUS_AUTOCMD12 ) { RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - AUTOCMD12 Error...\r\n"))); status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } if (wErrorStatus & ERR_INT_STATUS_ADMA) { // ADMA Error RETAILMSG(TRUE,(TEXT("[HSMMC2] HandleErrors - ADMA Error...\r\n"))); if (m_SlotDma && pRequest ) { m_SlotDma->DMANotifyEvent(*pRequest, DMA_ERROR_OCCOR ); } else { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - ADMA Error without DMA Enabled (0x%x). Resetting CMD line.\r\n"), wErrorStatus)); } } // Perform basic error recovery WORD wErrIntSignal = ReadWord(SDHC_ERROR_INT_SIGNAL_ENABLE); WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE, 0); // Make sure that the value of "Error Interrupt Status Enable" is zero WORD wErrIntStatusEn = ReadWord(SDHC_ERROR_INT_STATUS_ENABLE); WriteWord(SDHC_ERROR_INT_STATUS_ENABLE,0); if (IS_CMD_LINE_ERROR(wErrorStatus)) { // Reset CMD line DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - Command line error (0x%x). Resetting CMD line.\r\n"), wErrorStatus)); SoftwareReset(SOFT_RESET_CMD); } if (IS_DAT_LINE_ERROR(wErrorStatus)) { // Reset DAT line DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - Data line error (0x%x). Resetting DAT line.\r\n"), wErrorStatus)); DWORD RetryCount = 5000; SoftwareReset(SOFT_RESET_DAT); do { WriteWord(SDHC_ERROR_INT_STATUS,wErrorStatus); if ((ReadWord(SDHC_NORMAL_INT_STATUS) & NORMAL_INT_STATUS_ERROR_INT)) { RetryCount--; } else { break; } if(RetryCount == 0) { DEBUGMSG(SDCARD_ZONE_ERROR, (TEXT("[HSMMC2] HandleErrors - DAT line error Recovery Timeout...\r\n"))); } } while(RetryCount != 0); } // clear all error status WriteWord(SDHC_ERROR_INT_STATUS, wErrorStatus); // re-enable error interrupt signals WriteWord(SDHC_ERROR_INT_STATUS_ENABLE, wErrIntStatusEn); WriteWord(SDHC_ERROR_INT_SIGNAL_ENABLE, wErrIntSignal); // complete the request if (pRequest) { IndicateBusRequestComplete(pRequest, status); } else { // If there is not a current request, the initialize of normal interrupt status enable is needed. WriteWord(SDHC_NORMAL_INT_STATUS_ENABLE, (ReadWord(SDHC_NORMAL_INT_STATUS_ENABLE)) | NORMAL_INT_ENABLE_CMD_COMPLETE | NORMAL_INT_ENABLE_TRX_COMPLETE); } } } VOID CSDHCSlotBase::HandleTransferDone( ) { PSD_BUS_REQUEST pRequest; SD_API_STATUS status = SD_API_STATUS_SUCCESS; // get the current request pRequest = GetAndLockCurrentRequest(); if (pRequest) { if (!TRANSFER_IS_COMMAND_ONLY(pRequest)) { if (m_SlotDma && !m_SlotDma->IsDMACompleted()) { m_SlotDma->DMANotifyEvent(*pRequest, TRANSFER_COMPLETED); } } if (pRequest->HCParam != TRANSFER_SIZE(pRequest)) { // This means that a Command Complete interrupt occurred before // a Buffer Ready interrupt. Hardware should not allow this. DEBUGCHK(FALSE); status = SD_API_STATUS_DEVICE_RESPONSE_ERROR; } // complete the request if (pRequest->Flags & SD_AUTO_ISSUE_CMD12) { m_fAutoCMD12Success = TRUE; } IndicateBusRequestComplete(pRequest, status); } // else request must have been canceled due to an error } VOID CSDHCSlotBase::HandleReadReady( ) { DEBUGMSG(SDHC_RECEIVE_ZONE, (TEXT("HandleReadReady - HandleReadReady!\n"))); // get the current request PSD_BUS_REQUEST pRequest = GetAndLockCurrentRequest(); if (pRequest) { DEBUGCHK(pRequest->NumBlocks > 0); DEBUGCHK(pRequest->HCParam < TRANSFER_SIZE(pRequest)); DEBUGCHK(TRANSFER_IS_READ(pRequest)); #ifdef DEBUG ++m_dwReadyInts; #endif __try { PDWORD pdwUserBuffer = (PDWORD) &pRequest->pBlockBuffer[pRequest->HCParam]; PDWORD pdwBuffer = pdwUserBuffer; DWORD rgdwIntermediateBuffer[SDHC_MAX_BLOCK_LENGTH / sizeof(DWORD)]; BOOL fUsingIntermediateBuffer = FALSE; DWORD cDwords = pRequest->BlockSize / 4; DWORD dwRemainder = pRequest->BlockSize % 4; PREFAST_DEBUGCHK(sizeof(rgdwIntermediateBuffer) >= pRequest->BlockSize); if (((DWORD) pdwUserBuffer) % 4 != 0) { // Buffer is not DWORD aligned so we must use an // intermediate buffer. pdwBuffer = rgdwIntermediateBuffer; fUsingIntermediateBuffer = TRUE; } DWORD dwDwordsRemaining = cDwords; pRequest->HCParam += dwDwordsRemaining * 4; // Read the data from the device while ( dwDwordsRemaining-- ) { *(pdwBuffer++) = ReadDword(SDHC_BUFFER_DATA_PORT_0); } if ( dwRemainder != 0 ) { DWORD dwLastWord = ReadDword(SDHC_BUFFER_DATA_PORT_0); memcpy(pdwBuffer, &dwLastWord, dwRemainder); pRequest->HCParam += dwRemainder; } if (fUsingIntermediateBuffer) { memcpy(pdwUserBuffer, rgdwIntermediateBuffer, pRequest->BlockSize); } } __except(SDProcessException(GetExceptionInformation())) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("Exception reading from client buffer!\r\n"))); IndicateBusRequestComplete(pRequest, SD_API_STATUS_ACCESS_VIOLATION); } DEBUGCHK(pRequest->HCParam == (m_dwReadyInts * pRequest->BlockSize)); } // else request must have been canceled due to an error } VOID CSDHCSlotBase::HandleWriteReady( ) { DEBUGMSG(SDHC_TRANSMIT_ZONE, (TEXT("HandleWriteReady - HandleWriteReady! \n"))); // get the current request PSD_BUS_REQUEST pRequest = GetAndLockCurrentRequest(); if (pRequest) { DEBUGCHK(TRANSFER_IS_WRITE(pRequest)); DEBUGCHK(pRequest->NumBlocks > 0); DEBUGCHK(pRequest->HCParam < TRANSFER_SIZE(pRequest)); #ifdef DEBUG ++m_dwReadyInts; #endif __try { PDWORD pdwUserBuffer = (PDWORD) &pRequest->pBlockBuffer[pRequest->HCParam]; PDWORD pdwBuffer = pdwUserBuffer; DWORD rgdwIntermediateBuffer[SDHC_MAX_BLOCK_LENGTH / sizeof(DWORD)]; BOOL fUsingIntermediateBuffer = FALSE; DWORD cDwords = pRequest->BlockSize / 4; DWORD dwRemainder = pRequest->BlockSize % 4; PREFAST_DEBUGCHK(sizeof(rgdwIntermediateBuffer) >= pRequest->BlockSize); if (((DWORD) pdwUserBuffer) % 4 != 0) { // Buffer is not DWORD aligned so we must use an // intermediate buffer. pdwBuffer = rgdwIntermediateBuffer; memcpy(rgdwIntermediateBuffer, pdwUserBuffer, pRequest->BlockSize); } DWORD dwDwordsRemaining = cDwords; pRequest->HCParam += dwDwordsRemaining * 4; // Write data to buffer data port while ( dwDwordsRemaining-- ) { WriteDword(SDHC_BUFFER_DATA_PORT_0, *(pdwBuffer++)); } if ( dwRemainder != 0 ) { DWORD dwLastWord = 0; memcpy(&dwLastWord, pdwBuffer, dwRemainder); WriteDword(SDHC_BUFFER_DATA_PORT_0, dwLastWord); pRequest->HCParam += dwRemainder; } } __except(SDProcessException(GetExceptionInformation())) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("Exception reading from client buffer!\r\n"))); IndicateBusRequestComplete(pRequest, SD_API_STATUS_ACCESS_VIOLATION); } DEBUGCHK(pRequest->HCParam == (m_dwReadyInts * pRequest->BlockSize)); } // else request must have been canceled due to an error } PVOID CSDHCSlotBase::AllocPhysBuffer( size_t cb, PDWORD pdwPhysAddr ) { PVOID pvUncached; PVOID pvRet = NULL; DWORD dwPhysAddr; pvUncached = AllocPhysMem(cb, PAGE_READWRITE, 0, 0, &dwPhysAddr); if (pvUncached) { *pdwPhysAddr = dwPhysAddr; pvRet = pvUncached; } return pvRet; } VOID CSDHCSlotBase::FreePhysBuffer( PVOID pv ) { BOOL fSuccess; DEBUGCHK(pv); fSuccess = FreePhysMem(pv); DEBUGCHK(fSuccess); } VOID CSDHCSlotBase::SetHardwarePowerState( CEDEVICE_POWER_STATE cpsNew ) { DEBUGCHK(VALID_DX(cpsNew)); DEBUGCHK(!DX_D1_OR_D2(cpsNew)); DEBUGCHK(m_cpsCurrent != cpsNew); CEDEVICE_POWER_STATE cpsCurrent = m_cpsCurrent; m_cpsCurrent = cpsNew; BYTE bWakeupControl = m_bWakeupControl; if (cpsCurrent == D0) { SDClockOff(); if (cpsNew == D3) { if ( m_fSDIOInterruptsEnabled && (bWakeupControl & WAKEUP_INTERRUPT) ) { DEBUGCHK(m_fCardPresent); m_fSleepsWithPower = TRUE; m_fPowerUpDisabledInts = FALSE; } else { // Wake on status changes only WriteByte(SDHC_POWER_CONTROL, 0); bWakeupControl &= ~WAKEUP_INTERRUPT; } // enable wakeup sources m_wIntSignals = ReadWord(SDHC_NORMAL_INT_SIGNAL_ENABLE); WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE, 0); WriteWord(SDHC_NORMAL_INT_STATUS, ReadWord(SDHC_NORMAL_INT_STATUS)); WriteByte(SDHC_WAKEUP_CONTROL, bWakeupControl); } else { DEBUGCHK(cpsNew == D4); WriteByte(SDHC_CLOCK_CONTROL, 0); WriteByte(SDHC_POWER_CONTROL, 0); } } else if (cpsCurrent == D3) { // Coming out of wakeup state if (cpsNew == D0) { WriteByte(SDHC_WAKEUP_CONTROL, 0); if (!m_fSleepsWithPower) { // Power was turned off to the socket. Re-enumerate card. if (m_fCardPresent) { HandleRemoval(TRUE); } m_fCheckSlot = TRUE; SetInterruptEvent(); } else { if (m_fCardPresent) { // Do not do this if the card was removed or // if power was not kept. if (m_fPowerUpDisabledInts) { EnableSDIOInterrupts(TRUE); } } } WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE, m_wIntSignals); } else { DEBUGCHK(cpsNew == D4); WriteByte(SDHC_CLOCK_CONTROL, 0); WriteByte(SDHC_WAKEUP_CONTROL, 0); WriteByte(SDHC_POWER_CONTROL, 0); WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE, m_wIntSignals); } m_fSleepsWithPower = FALSE; } else { DEBUGCHK(cpsCurrent == D4); // Coming out of unpowered state - signal card removal // so any card present will be re-enumerated. // // We do the same thing when we go to D3 as D0 because // the slot has lost power so it could have been removed // or changed. In other words, D3 is a meaningless state // after D4. m_cpsCurrent = D0; // Force to D0 // Do not call HandleRemoval here because it could cause // a context switch in a PowerUp callback. m_fFakeCardRemoval = TRUE; m_fCheckSlot = TRUE; SetInterruptEvent(); } } VOID CSDHCSlotBase::DoEnableSDIOInterrupts( BOOL fEnable ) { // To control the SDIO card interrupt on S3C6410, control the normal interrupt signal, too. WORD wIntSignalEn = ReadWord(SDHC_NORMAL_INT_SIGNAL_ENABLE); if (fEnable) { m_isSDIOInterrupt = FALSE; // SDIO card interrupt Enable. wIntSignalEn |= NORMAL_INT_SIGNAL_CARD_INT; } else { m_isSDIOInterrupt = TRUE; // SDIO card interrupt was occured. wIntSignalEn &= (~NORMAL_INT_SIGNAL_CARD_INT); } WriteWord(SDHC_NORMAL_INT_SIGNAL_ENABLE, wIntSignalEn); WORD wIntStatusEn = ReadWord(SDHC_NORMAL_INT_STATUS_ENABLE); if (fEnable) { wIntStatusEn |= NORMAL_INT_ENABLE_CARD_INT; } else { wIntStatusEn &= (~NORMAL_INT_ENABLE_CARD_INT); } WriteWord(SDHC_NORMAL_INT_STATUS_ENABLE, wIntStatusEn); } template<class T> BOOL CSDHCSlotBase::WaitForReg( T (CSDHCSlotBase::*pfnReadReg)(DWORD), DWORD dwRegOffset, T tMask, T tWaitForEqual, DWORD dwTimeout ) { SETFNAME(); const DWORD dwStart = GetTickCount(); T tValue; BOOL fRet = TRUE; DWORD dwIteration = 1; // Verify that reset has completed. do { tValue = (this->*pfnReadReg)(dwRegOffset); if ( (dwIteration % 16) == 0 ) { // Check time DWORD dwCurr = GetTickCount(); // Unsigned arithmetic handles rollover. DWORD dwTotal = dwCurr - dwStart; if (dwTotal > dwTimeout) { // Timeout fRet = FALSE; DEBUGMSG(SDCARD_ZONE_WARN, (_T("%s Timeout (%u ms) waiting for (ReadReg<%u>(0x%02x) & 0x%08x) == 0x%08x\r\n"), pszFname, dwTimeout, sizeof(T), dwRegOffset, tMask, tWaitForEqual)); break; } } ++dwIteration; } while ((tValue & tMask) != tWaitForEqual); return fRet; } BOOL CSDHCSlotBase::SoftwareReset( BYTE bResetBits ) { SETFNAME(); // Reset the controller WriteByte(SDHC_SOFT_RESET, bResetBits); BOOL fSuccess = WaitForReg<BYTE>(&CSDHCSlotBase::ReadByte, SDHC_SOFT_RESET, bResetBits, 0); if (!fSuccess) { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("%s Timeout waiting for controller reset - 0x%02x\r\n"), pszFname, bResetBits)); } // Command Conflict Mask Enable WriteDword(SDHC_CONTROL2, (ReadDword(SDHC_CONTROL2) | SDHC_CONTROL2_ENCMDCNFMSK)); return fSuccess; } VOID CSDHCSlotBase::EnableLED( BOOL fEnable ) { BYTE bHostControl = ReadByte(SDHC_HOST_CONTROL); if (fEnable) { bHostControl |= HOSTCTL_LED_CONTROL; } else { bHostControl &= ~HOSTCTL_LED_CONTROL; } WriteByte(SDHC_HOST_CONTROL, bHostControl); } VOID CSDHCSlotBase::IndicateSlotStateChange(SD_SLOT_EVENT sdEvent) { SDHCDIndicateSlotStateChange(m_pHCDContext, (UCHAR) m_dwSlot, sdEvent); } PSD_BUS_REQUEST CSDHCSlotBase::GetAndLockCurrentRequest() { return SDHCDGetAndLockCurrentRequest(m_pHCDContext, (UCHAR) m_dwSlot); } VOID CSDHCSlotBase::PowerUpDown(BOOL fPowerUp, BOOL fKeepPower) { SDHCDPowerUpDown(m_pHCDContext, fPowerUp, fKeepPower, (UCHAR) m_dwSlot); } VOID CSDHCSlotBase::IndicateBusRequestComplete( PSD_BUS_REQUEST pRequest, SD_API_STATUS status ) { const WORD c_wTransferIntSources = NORMAL_INT_STATUS_CMD_COMPLETE | NORMAL_INT_STATUS_TRX_COMPLETE | NORMAL_INT_STATUS_DMA | NORMAL_INT_STATUS_BUF_WRITE_RDY | NORMAL_INT_STATUS_BUF_READ_RDY; DEBUGCHK(pRequest); if ( (m_fSDIOInterruptsEnabled && m_f4BitMode) == FALSE ) { SDClockOff(); } // else need to leave clock on in order to receive interrupts in 4 bit mode // Turn off LED. EnableLED(FALSE); // Turn off interrupt sources WORD wIntStatusEn = ReadWord(SDHC_NORMAL_INT_STATUS_ENABLE); wIntStatusEn &= ~c_wTransferIntSources; WriteWord(SDHC_NORMAL_INT_STATUS_ENABLE, wIntStatusEn); // Clear any remaining spurious interrupts. WriteWord(SDHC_NORMAL_INT_STATUS, c_wTransferIntSources); #ifdef DEBUG m_dwReadyInts = 0; #endif m_fCommandCompleteOccurred = FALSE; ASSERT(m_pCurrentRequest!=NULL); m_pCurrentRequest = NULL; if (m_fCurrentRequestFastPath) { if (status == SD_API_STATUS_SUCCESS) { status = SD_API_STATUS_FAST_PATH_SUCCESS; } m_FastPathStatus = status; } else SDHCDIndicateBusRequestComplete(m_pHCDContext, pRequest, status); } BOOL CSDHCSlotBase::DetermineCommandPolling() { DWORD dwDivisor = (m_wRegClockControl>>8); DWORD dwMaxClockRate = (dwDivisor!=0? (m_dwMaxClockRate/2/dwDivisor): m_dwMaxClockRate); return (dwMaxClockRate >= (10^6)); // If bigger than 1 Mhz, we do the polling. } VOID CSDHCSlotBase::SetClockRate( PDWORD pdwRate ) { DEBUGCHK(m_dwMaxClockRate); const DWORD dwClockRate = *pdwRate; DWORD dwMaxClockRate = m_dwMaxClockRate; int i = 0; // 2^i is the divisor value DWORD dwControlValue = 0; // Command Conflict Mask Enable dwControlValue = SDHC_CONTROL2_ENCMDCNFMSK; // Write Status Clear Async Mode Enable // and, if this bit is enabled, it must be needed that Status Busy bit checking for clearing the interrupt status register before "CMD ISSUE"!! dwControlValue |= SDHC_CONTROL2_ENSTAASYNCCLR; if (dwClockRate < HSMMC_FULL_SPEED_RATE) { DEBUGMSG(SDHC_CLOCK_ZONE,(TEXT("[HSMMC2] Turn OFF the F/B delay control.\r\n"))); dwControlValue &= ~(0x3<<14); // Turn off the feedback clock delay } else { DEBUGMSG(SDHC_CLOCK_ZONE,(TEXT("[HSMMC2] Turn ON the F/B delay control.\r\n"))); dwControlValue = (dwControlValue & (~(0x3<<14))) | (0x1<<14); // Turn on the RX feedback clock delay WriteDword(SDHC_CONTROL3, (ReadDword(SDHC_CONTROL3) | (0x1<<15) | (0x1<<7))); } #ifdef _SRCCLK_48MHZ_ dwControlValue |= ((0x3<<9) | // Debounce Filter Count 0x3=64 iSDCLK (0x1<<8) | // SDCLK Hold Enable (0x3<<4)); // Base Clock Source = External Clock(USB_PHY) #else dwControlValue |= ((0x3<<9) | (0x1<<8) | (0x2<<4)); // Base Clock Source = EPLL out #endif // !_SRCCLK_48MHZ_ WriteDword(SDHC_CONTROL2, dwControlValue); // shift MaxClockRate until we find the closest frequency <= target while ( (dwClockRate < dwMaxClockRate) && ( i < 8 ) ) { dwMaxClockRate = dwMaxClockRate >> 1; i++; } // set the actual clock rate *pdwRate = dwMaxClockRate; m_wRegClockControl = CLOCK_INTERNAL_ENABLE; if (i != 0) { DWORD dwDivisor = 1 << (i - 1); m_wRegClockControl |= (dwDivisor << 8); } m_fCommandPolling = DetermineCommandPolling(); DEBUGMSG(SDHC_CLOCK_ZONE,(TEXT("SDHCSetRate - Clock Control Reg = %X\n"), m_wRegClockControl)); DEBUGMSG(SDHC_CLOCK_ZONE,(TEXT("SDHCSetRate - Actual clock rate = %d\n"), *pdwRate)); } VOID CSDHCSlotBase::SDClockOn( ) { SETFNAME(); // Must call SetClockRate() first to init m_wRegClockControl // We separate clock divisor calculation with ClockOn, so we can call // ClockOn without recalcuating the divisor. WriteWord(SDHC_CLOCK_CONTROL, m_wRegClockControl); // wait until clock stable BOOL fSuccess = WaitForReg<WORD>(&CSDHCSlotBase::ReadWord, SDHC_CLOCK_CONTROL, CLOCK_STABLE, CLOCK_STABLE); if (fSuccess) { // SD Clock Output PAD Drive Strength is needed as 9mA. WriteDword(SDHC_CONTROL4, ((ReadDword(SDHC_CONTROL4) | (0x3<<16)))); // enable it WriteWord(SDHC_CLOCK_CONTROL, m_wRegClockControl | CLOCK_ENABLE); } else { DEBUGMSG(SDCARD_ZONE_ERROR, (_T("%s Timeout waiting for CLOCK_STABLE\r\n"), pszFname)); RETAILMSG(TRUE, (_T("[HSMMC2] %s Timeout waiting for CLOCK_STABLE\r\n"), pszFname)); } } VOID CSDHCSlotBase::SDClockOff( ) { WriteWord(SDHC_CLOCK_CONTROL, m_wRegClockControl); } DWORD CSDHCSlotBase::DetermineVddWindows( ) { DWORD dwVddWindows = 0; // This is needed for supporting both SD Memory and MMC. dwVddWindows = SD_VDD_WINDOW_3_2_TO_3_3 | SD_VDD_WINDOW_3_3_TO_3_4; return dwVddWindows; } DWORD CSDHCSlotBase::GetDesiredVddWindow( ) { DEBUGCHK(m_dwVddWindows); DWORD dwDesiredVddWindow = 0; // Return lowest supportable voltage. if (m_dwVddWindows & SD_VDD_WINDOW_1_7_TO_1_8) { dwDesiredVddWindow = SD_VDD_WINDOW_1_7_TO_1_8; } else if (m_dwVddWindows & SD_VDD_WINDOW_2_9_TO_3_0) { dwDesiredVddWindow = SD_VDD_WINDOW_2_9_TO_3_0; } else if (m_dwVddWindows & SD_VDD_WINDOW_3_2_TO_3_3) { dwDesiredVddWindow = SD_VDD_WINDOW_3_2_TO_3_3; } return dwDesiredVddWindow; } DWORD CSDHCSlotBase::GetMaxVddWindow( ) { DEBUGCHK(m_dwVddWindows); DWORD dwMaxVddWindow = 0; if (m_dwVddWindows & SD_VDD_WINDOW_3_2_TO_3_3) { dwMaxVddWindow = SD_VDD_WINDOW_3_2_TO_3_3; } else if (m_dwVddWindows & SD_VDD_WINDOW_2_9_TO_3_0) { dwMaxVddWindow = SD_VDD_WINDOW_2_9_TO_3_0; } else if (m_dwVddWindows & SD_VDD_WINDOW_1_7_TO_1_8) { dwMaxVddWindow = SD_VDD_WINDOW_1_7_TO_1_8; } return dwMaxVddWindow; } BOOL CSDHCSlotBase::IsWriteProtected() { #ifdef _SMDK6410_CH2_WP_ // On the CPU B'd Rev 0.0 of SMDK6410 , Write protect is detected with GPIO_N[12] BOOL fRet = FALSE; volatile S3C6410_GPIO_REG *pIOPreg = NULL; PHYSICAL_ADDRESS ioPhysicalBase = {0,0}; ioPhysicalBase.LowPart = S3C6410_BASE_REG_PA_GPIO; pIOPreg = (volatile S3C6410_GPIO_REG *)MmMapIoSpace(ioPhysicalBase, sizeof(S3C6410_GPIO_REG), FALSE); if (pIOPreg == NULL) { RETAILMSG (1,(TEXT("[HSMMC2] GPIO registers is *NOT* mapped.\n"))); return FALSE; } fRet = (pIOPreg->GPNDAT & (0x1<<14)) ? 1 : 0; // It is always "0" because WP pin is not connected for now and the status of line is floating. MmUnmapIoSpace((PVOID)pIOPreg, sizeof(S3C6410_GPIO_REG)); return fRet; #else return ((ReadDword(SDHC_PRESENT_STATE) & STATE_WRITE_PROTECT) == 0); #endif } PVOID CSDHCSlotBase::SlotAllocDMABuffer(ULONG Length,PPHYSICAL_ADDRESS LogicalAddress,BOOLEAN CacheEnabled ) { CE_DMA_ADAPTER dmaAdapter = { sizeof(CE_DMA_ADAPTER), m_interfaceType, m_dwBusNumber, 0,0 }; dmaAdapter.BusMaster = TRUE; return OALDMAAllocBuffer(&dmaAdapter, Length, LogicalAddress,CacheEnabled); } BOOL CSDHCSlotBase::SlotFreeDMABuffer(ULONG Length,PHYSICAL_ADDRESS LogicalAddress,PVOID VirtualAddress,BOOLEAN CacheEnabled ) { CE_DMA_ADAPTER dmaAdapter = { sizeof(CE_DMA_ADAPTER), m_interfaceType, m_dwBusNumber, 0,0 }; dmaAdapter.BusMaster = TRUE; OALDMAFreeBuffer(&dmaAdapter,Length, LogicalAddress, VirtualAddress, CacheEnabled); return TRUE; } #ifdef DEBUG VOID CSDHCSlotBase::Validate( ) { DEBUGCHK(m_pregDevice && m_pregDevice->IsOK()); DEBUGCHK(m_dwSlot < SDHC_MAX_SLOTS); DEBUGCHK(m_pbRegisters); DEBUGCHK(m_pHCDContext); DEBUGCHK(VALID_DX(m_cpsCurrent)); DEBUGCHK(VALID_DX(m_cpsAtPowerDown)); } VOID CSDHCSlotBase::DumpRegisters( ) { BYTE rgbSdRegs[sizeof(SSDHC_REGISTERS)]; SSDHC_REGISTERS *pStdHCRegs = (SSDHC_REGISTERS *) rgbSdRegs; DEBUGCHK(sizeof(SSDHC_REGISTERS) % sizeof(DWORD) == 0); for (DWORD dwRegIndex = 0; dwRegIndex < dim(rgbSdRegs); ++dwRegIndex) { rgbSdRegs[dwRegIndex] = ReadByte(dwRegIndex); } DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("+DumpStdHCRegs - Slot %d -------------------------\n"), m_dwSlot)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SystemAddressLo: 0x%04X \n"), pStdHCRegs->SystemAddressLo)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SystemAddressHi: 0x%04X \n"), pStdHCRegs->SystemAddressHi)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("BlockSize: 0x%04X \n"), pStdHCRegs->BlockSize)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("BlockCount: 0x%04X \n"), pStdHCRegs->BlockCount)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("Argument0: 0x%04X \n"), pStdHCRegs->Argument0)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("Argument1: 0x%04X \n"), pStdHCRegs->Argument1)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("TransferMode: 0x%04X \n"), pStdHCRegs->TransferMode)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("Command: 0x%04X \n"), pStdHCRegs->Command)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R0: 0x%04X \n"), pStdHCRegs->R0)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R1: 0x%04X \n"), pStdHCRegs->R1)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R2: 0x%04X \n"), pStdHCRegs->R2)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R3: 0x%04X \n"), pStdHCRegs->R3)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R4: 0x%04X \n"), pStdHCRegs->R4)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R5: 0x%04X \n"), pStdHCRegs->R5)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R6: 0x%04X \n"), pStdHCRegs->R6)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("R7: 0x%04X \n"), pStdHCRegs->R7)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("BufferDataPort0: 0x%04X \n"), pStdHCRegs->BufferDataPort0)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("BufferDataPort1: 0x%04X \n"), pStdHCRegs->BufferDataPort1)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("PresentState: 0x%04X \n"), pStdHCRegs->PresentState)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("HostControl: 0x%04X \n"), pStdHCRegs->HostControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("PowerControl: 0x%04X \n"), pStdHCRegs->PowerControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("BlockGapControl: 0x%04X \n"), pStdHCRegs->BlockGapControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("WakeUpControl: 0x%04X \n"), pStdHCRegs->WakeUpControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("ClockControl: 0x%04X \n"), pStdHCRegs->ClockControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("TimeOutControl: 0x%04X \n"), pStdHCRegs->TimeOutControl)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SoftReset: 0x%04X \n"), pStdHCRegs->SoftReset)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("NormalIntStatus: 0x%04X \n"), pStdHCRegs->NormalIntStatus)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("ErrorIntStatus: 0x%04X \n"), pStdHCRegs->ErrorIntStatus)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("NormalIntStatusEnable: 0x%04X \n"), pStdHCRegs->NormalIntStatusEnable)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("ErrorIntStatusEnable: 0x%04X \n"), pStdHCRegs->ErrorIntStatusEnable)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("NormalIntSignalEnable: 0x%04X \n"), pStdHCRegs->NormalIntSignalEnable)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("ErrorIntSignalEnable: 0x%04X \n"), pStdHCRegs->ErrorIntSignalEnable)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("AutoCMD12ErrorStatus: 0x%04X \n"), pStdHCRegs->AutoCMD12ErrorStatus)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("Capabilities: 0x%04X \n"), pStdHCRegs->Capabilities)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("MaxCurrentCapabilites: 0x%04X \n"), pStdHCRegs->MaxCurrentCapabilites)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("SlotInterruptStatus: 0x%04X \n"), pStdHCRegs->SlotInterruptStatus)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("HostControllerVersion: 0x%04X \n"), pStdHCRegs->HostControllerVersion)); DEBUGMSG(SDCARD_ZONE_INIT, (TEXT("-DumpStdHCRegs-------------------------\n"))); } #endif // DO NOT REMOVE --- END EXTERNALLY DEVELOPED SOURCE CODE ID --- DO NOT REMOVE
[ "jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006" ]
[ [ [ 1, 2334 ] ] ]
d7d5da16b658b4a4476cb785843a2a2df9df92b5
49db059c239549a8691fda362adf0654c5749fb1
/2010/baboshina/task1/main.cpp
0c3bb542e9abafcbed71ac4dd7244e4ac5a9f765
[]
no_license
bondarevts/amse-qt
1a063f27c45a80897bb4751ae5c10f5d9d80de1b
2b9b76c7a5576bc1079fc037adcf039fed4dc848
refs/heads/master
2020-05-07T21:19:48.773724
2010-12-07T07:53:51
2010-12-07T07:53:51
35,804,478
0
0
null
null
null
null
UTF-8
C++
false
false
1,706
cpp
#include <QtGui/QApplication> #include <QVBoxLayout> #include <QDialog> #include <QLabel> #include <QPushButton> #include <QLineEdit> int main(int c, char ** v) { QApplication app(c, v); QDialog d(NULL); QVBoxLayout* layout = new QVBoxLayout; QHBoxLayout* surLayout = new QHBoxLayout; QLabel* surLabel = new QLabel; surLabel->setText("Surname"); QLineEdit* surLineEdit = new QLineEdit; surLayout->addWidget(surLabel); surLayout->addWidget(surLineEdit); layout->insertLayout(-1, surLayout); QHBoxLayout* nameLayout = new QHBoxLayout; QLabel* nameLabel = new QLabel; nameLabel->setText("Name"); QLineEdit* nameLineEdit = new QLineEdit; nameLayout->addWidget(nameLabel); nameLayout->addWidget(nameLineEdit); layout->insertLayout(-1, nameLayout); QHBoxLayout* emailLayout = new QHBoxLayout; QLabel* emailLabel = new QLabel; emailLabel->setText("E-mail"); QLineEdit* emailLineEdit = new QLineEdit; emailLayout->addWidget(emailLabel); emailLayout->addWidget(emailLineEdit); layout->insertLayout(-1, emailLayout); QHBoxLayout* phoneLayout = new QHBoxLayout; QLabel* phoneLabel = new QLabel; phoneLabel->setText("Phone"); QLineEdit* phoneLineEdit = new QLineEdit; phoneLayout->addWidget(phoneLabel); phoneLayout->addWidget(phoneLineEdit); layout->insertLayout(-1, phoneLayout); QPushButton* okButton = new QPushButton ("OK", &d); d.setLayout(layout); d.layout()->addWidget(okButton); QObject::connect(okButton, SIGNAL(clicked()), qApp, SLOT(quit())); d.show(); return app.exec(); }
[ "snowwlex@1a14799f-55e9-4979-7f51-533a2053511e" ]
[ [ [ 1, 65 ] ] ]
b28a6aec038230a86a61fbf391d861e1562245ab
011359e589f99ae5fe8271962d447165e9ff7768
/src/burn/misc/pre90s/d_epos.cpp
ff8d19770808e95989bdbf8aada7909808ea2a1a
[]
no_license
PS3emulators/fba-next-slim
4c753375fd68863c53830bb367c61737393f9777
d082dea48c378bddd5e2a686fe8c19beb06db8e1
refs/heads/master
2021-01-17T23:05:29.479865
2011-12-01T18:16:02
2011-12-01T18:16:02
2,899,840
1
0
null
null
null
null
UTF-8
C++
false
false
26,192
cpp
// FB Alpha Epos Tristar Hardware driver module // Based on MAME driver by Zsolt Vasvari #include "tiles_generic.h" #include "8255ppi.h" #include "bitswap.h" #include "driver.h" extern "C" { #include "ay8910.h" } static unsigned char *AllMem; static unsigned char *MemEnd; static unsigned char *AllRam; static unsigned char *RamEnd; static unsigned char *DrvZ80ROM; static unsigned char *DrvColPROM; static unsigned char *DrvZ80RAM; static unsigned char *DrvVidRAM; static unsigned int *Palette; static unsigned int *DrvPalette; static short* pAY8910Buffer[3]; static unsigned char DrvRecalc; static unsigned char DrvJoy1[8]; static unsigned char DrvJoy2[8]; static unsigned char DrvDips[2]; static unsigned char DrvInputs[2]; static unsigned char DrvReset; static unsigned char *DrvPaletteBank; static unsigned char *DealerZ80Bank; static unsigned char *DealerZ80Bank2; static struct BurnInputInfo MegadonInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 2, "p1 start" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 1, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 0, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 2, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 3, "p1 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, }; STDINPUTINFO(Megadon) static struct BurnInputInfo SuprglobInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy1 + 0, "p1 coin" }, {"P1 Start", BIT_DIGITAL, DrvJoy1 + 2, "p1 start" }, {"P1 Up", BIT_DIGITAL, DrvJoy2 + 4, "p1 up" }, {"P1 Down", BIT_DIGITAL, DrvJoy2 + 5, "p1 down" }, {"P1 Left", BIT_DIGITAL, DrvJoy2 + 1, "p1 left" }, {"P1 Right", BIT_DIGITAL, DrvJoy2 + 0, "p1 right" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 2, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 3, "p1 fire 2" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, }; STDINPUTINFO(Suprglob) static struct BurnInputInfo DealerInputList[] = { {"P1 Coin", BIT_DIGITAL, DrvJoy2 + 6, "p1 coin" }, {"P1 Button 1", BIT_DIGITAL, DrvJoy2 + 0, "p1 fire 1" }, {"P1 Button 2", BIT_DIGITAL, DrvJoy2 + 1, "p1 fire 2" }, {"P1 Button 3", BIT_DIGITAL, DrvJoy2 + 2, "p1 fire 3" }, {"P1 Button 4", BIT_DIGITAL, DrvJoy2 + 3, "p1 fire 4" }, {"P1 Button 5", BIT_DIGITAL, DrvJoy2 + 4, "p1 fire 5" }, {"P1 Button 6", BIT_DIGITAL, DrvJoy2 + 5, "p1 fire 6" }, {"Reset", BIT_DIGITAL, &DrvReset, "reset" }, {"Dip A", BIT_DIPSWITCH, DrvDips + 0, "dip" }, {"Dip B", BIT_DIPSWITCH, DrvDips + 1, "dip" }, }; STDINPUTINFO(Dealer) static struct BurnDIPInfo MegadonDIPList[]= { {0x07, 0xff, 0xff, 0x28, NULL }, {0x08, 0xff, 0xff, 0xfe, NULL }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x07, 0x01, 0x01, 0x00, "1 Coin 1 Credits " }, {0x07, 0x01, 0x01, 0x01, "1 Coin 2 Credits " }, {0 , 0xfe, 0 , 2, "Fuel Consumption" }, {0x07, 0x01, 0x02, 0x00, "Slow" }, {0x07, 0x01, 0x02, 0x02, "Fast" }, {0 , 0xfe, 0 , 2, "Rotation" }, {0x07, 0x01, 0x04, 0x04, "Slow" }, {0x07, 0x01, 0x04, 0x00, "Fast" }, {0 , 0xfe, 0 , 2, "ERG" }, {0x07, 0x01, 0x08, 0x08, "Easy" }, {0x07, 0x01, 0x08, 0x00, "Hard" }, {0 , 0xfe, 0 , 2, "Enemy Fire Rate" }, {0x07, 0x01, 0x20, 0x20, "Slow" }, {0x07, 0x01, 0x20, 0x00, "Fast" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x07, 0x01, 0x50, 0x00, "3" }, {0x07, 0x01, 0x50, 0x10, "4" }, {0x07, 0x01, 0x50, 0x40, "5" }, {0x07, 0x01, 0x50, 0x50, "6" }, {0 , 0xfe, 0 , 2, "Game Mode" }, {0x07, 0x01, 0x80, 0x00, "Arcade" }, {0x07, 0x01, 0x80, 0x80, "Contest" }, }; STDDIPINFO(Megadon) static struct BurnDIPInfo SuprglobDIPList[]= { // Default Values {0x09, 0xff, 0xff, 0x00, NULL }, {0x0A, 0xff, 0xff, 0xbe, NULL }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x09, 0x01, 0x01, 0x00, "1 Coin 1 Credits " }, {0x09, 0x01, 0x01, 0x01, "1 Coin 2 Credits " }, {0 , 0xfe, 0 , 2, "Bonus Life" }, {0x09, 0x01, 0x08, 0x00, "10000 + Difficulty * 10000" }, {0x09, 0x01, 0x08, 0x08, "90000 + Difficulty * 10000" }, {0 , 0xfe, 0 , 8, "Difficulty" }, {0x09, 0x01, 0x26, 0x00, "1" }, {0x09, 0x01, 0x26, 0x02, "2" }, {0x09, 0x01, 0x26, 0x20, "3" }, {0x09, 0x01, 0x26, 0x22, "4" }, {0x09, 0x01, 0x26, 0x04, "5" }, {0x09, 0x01, 0x26, 0x06, "6" }, {0x09, 0x01, 0x26, 0x24, "7" }, {0x09, 0x01, 0x26, 0x26, "8" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x09, 0x01, 0x50, 0x00, "3" }, {0x09, 0x01, 0x50, 0x10, "4" }, {0x09, 0x01, 0x50, 0x40, "5" }, {0x09, 0x01, 0x50, 0x50, "6" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x09, 0x01, 0x80, 0x80, "Off" }, {0x09, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Suprglob) static struct BurnDIPInfo IgmoDIPList[]= { {0x09, 0xff, 0xff, 0x00, NULL }, {0x0A, 0xff, 0xff, 0xfe, NULL }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x09, 0x01, 0x01, 0x00, "1 Coin 1 Credits " }, {0x09, 0x01, 0x01, 0x01, "1 Coin 2 Credits " }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x09, 0x01, 0x22, 0x00, "20000" }, {0x09, 0x01, 0x22, 0x02, "40000" }, {0x09, 0x01, 0x22, 0x20, "60000" }, {0x09, 0x01, 0x22, 0x22, "80000" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x09, 0x01, 0x50, 0x00, "3" }, {0x09, 0x01, 0x50, 0x10, "4" }, {0x09, 0x01, 0x50, 0x40, "5" }, {0x09, 0x01, 0x50, 0x50, "6" }, {0 , 0xfe, 0 , 8, "Difficulty" }, {0x09, 0x01, 0x8c, 0x00, "1" }, {0x09, 0x01, 0x8c, 0x04, "2" }, {0x09, 0x01, 0x8c, 0x08, "3" }, {0x09, 0x01, 0x8c, 0x0c, "4" }, {0x09, 0x01, 0x8c, 0x80, "5" }, {0x09, 0x01, 0x8c, 0x84, "6" }, {0x09, 0x01, 0x8c, 0x88, "7" }, {0x09, 0x01, 0x8c, 0x8c, "8" }, }; STDDIPINFO(Igmo) static struct BurnDIPInfo CatapultDIPList[]= { {0x09, 0xff, 0xff, 0x00, NULL }, {0x0A, 0xff, 0xff, 0xfe, NULL }, {0 , 0xfe, 0 , 2, "Coinage" }, {0x09, 0x01, 0x01, 0x00, "1 Coin 1 Credits " }, {0x09, 0x01, 0x01, 0x01, "1 Coin 2 Credits " }, {0 , 0xfe, 0 , 4, "Bonus Life" }, {0x09, 0x01, 0x0c, 0x00, "20000" }, {0x09, 0x01, 0x0c, 0x04, "40000" }, {0x09, 0x01, 0x0c, 0x08, "60000" }, {0x09, 0x01, 0x0c, 0x0c, "80000" }, {0 , 0xfe, 0 , 4, "Difficulty" }, {0x09, 0x01, 0x22, 0x00, "1" }, {0x09, 0x01, 0x22, 0x02, "2" }, {0x09, 0x01, 0x22, 0x20, "3" }, {0x09, 0x01, 0x22, 0x22, "4" }, {0 , 0xfe, 0 , 4, "Lives" }, {0x09, 0x01, 0x50, 0x00, "3" }, {0x09, 0x01, 0x50, 0x10, "4" }, {0x09, 0x01, 0x50, 0x40, "5" }, {0x09, 0x01, 0x50, 0x50, "6" }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x09, 0x01, 0x80, 0x80, "Off" }, {0x09, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Catapult) static struct BurnDIPInfo DealerDIPList[]= { {0x08, 0xff, 0xff, 0xfe, NULL }, {0x09, 0xff, 0xff, 0xff, NULL }, {0 , 0xfe, 0 , 2, "Demo Sounds" }, {0x08, 0x01, 0x01, 0x01, "Off" }, {0x08, 0x01, 0x01, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Free Play" }, {0x08, 0x01, 0x02, 0x02, "Off" }, {0x08, 0x01, 0x02, 0x00, "On" }, {0 , 0xfe, 0 , 2, "Cabinet" }, {0x08, 0x01, 0x40, 0x40, "Upright" }, {0x08, 0x01, 0x40, 0x00, "Cocktail" }, {0 , 0xfe, 0 , 2, "Flip Screen" }, {0x08, 0x01, 0x80, 0x80, "Off" }, {0x08, 0x01, 0x80, 0x00, "On" }, }; STDDIPINFO(Dealer) unsigned char __fastcall epos_read_port(unsigned short port) { switch (port & 0xff) { case 0x00: return DrvDips[0]; case 0x01: return DrvInputs[0]; case 0x02: return DrvInputs[1]; case 0x03: return 0; } return 0; } void __fastcall epos_write_port(unsigned short port, unsigned char data) { switch (port & 0xff) { case 0x00: break; case 0x01: *DrvPaletteBank = (data << 1) & 0x10; break; case 0x02: AY8910Write(0, 1, data); break; case 0x06: AY8910Write(0, 0, data); break; } } static void dealer_set_bank() { ZetMapArea(0x0000, 0x5fff, 0, DrvZ80ROM + (*DealerZ80Bank << 16)); ZetMapArea(0x0000, 0x5fff, 2, DrvZ80ROM + (*DealerZ80Bank << 16)); } static void dealer_bankswitch(int offset) { int nBank = *DealerZ80Bank; if (offset & 4) { nBank = (nBank + 1) & 3; } else { nBank = (nBank - 1) & 3; } *DealerZ80Bank = nBank; dealer_set_bank(); } static void dealer_bankswitch2(int data) { *DealerZ80Bank2 = data & 1; int nBank = 0x6000 + ((data & 1) << 12); ZetMapArea(0x6000, 0x6fff, 0, DrvZ80ROM + nBank); ZetMapArea(0x6000, 0x6fff, 2, DrvZ80ROM + nBank); } unsigned char __fastcall dealer_read_port(unsigned short port) { switch (port & 0xff) { case 0x10: case 0x11: case 0x12: case 0x13: return ppi8255_r(0, port & 3); case 0x38: return DrvDips[0]; } return 0; } void __fastcall dealer_write_port(unsigned short port, unsigned char data) { switch (port & 0xff) { case 0x10: case 0x11: case 0x12: case 0x13: ppi8255_w(0, port & 3, data); break; case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: dealer_bankswitch(port & 7); break; } } unsigned char DealerPPIReadA() { return DrvInputs[1]; } void DealerPPIWriteC(unsigned char data) { dealer_bankswitch2(data); } static int DrvDoReset() { DrvReset = 0; memset (AllRam, 0, RamEnd - AllRam); ZetOpen(0); ZetReset(); dealer_set_bank(); dealer_bankswitch2(0); ZetClose(); AY8910Reset(0); return 0; } static void DrvPaletteInit(int num) { unsigned char prom[32] = { // in case the set lacks a prom dump 0x00, 0xE1, 0xC3, 0xFC, 0xEC, 0xF8, 0x34, 0xFF, 0x17, 0xF0, 0xEE, 0xEF, 0xAC, 0xC2, 0x1C, 0x07, 0x00, 0xE1, 0xC3, 0xFC, 0xEC, 0xF8, 0x34, 0xFF, 0x17, 0xF0, 0xEE, 0xEF, 0xAC, 0xC2, 0x1C, 0x07 }; memcpy (DrvColPROM, prom, 32); BurnLoadRom(DrvColPROM, num, 1); for (int i = 0; i < 0x20; i++) { Palette[i] = BITSWAP24(DrvColPROM[i], 7,6,5,7,6,6,7,5,4,3,2,4,3,3,4,2,1,0,1,0,1,1,0,1); } } static void DealerDecode() { for (int i = 0;i < 0x8000;i++) DrvZ80ROM[i + 0x00000] = BITSWAP08(DrvZ80ROM[i] ^ 0xbd, 2,6,4,0,5,7,1,3); for (int i = 0;i < 0x8000;i++) DrvZ80ROM[i + 0x10000] = BITSWAP08(DrvZ80ROM[i] ^ 0x00, 7,5,4,6,3,2,1,0); for (int i = 0;i < 0x8000;i++) DrvZ80ROM[i + 0x20000] = BITSWAP08(DrvZ80ROM[i] ^ 0x01, 7,6,5,4,3,0,2,1); for (int i = 0;i < 0x8000;i++) DrvZ80ROM[i + 0x30000] = BITSWAP08(DrvZ80ROM[i] ^ 0x01, 7,5,4,6,3,0,2,1); } static int MemIndex() { unsigned char *Next; Next = AllMem; DrvZ80ROM = Next; Next += 0x040000; DrvColPROM = Next; Next += 0x000020; Palette = (unsigned int*)Next; Next += 0x0020 * sizeof(int); DrvPalette = (unsigned int*)Next; Next += 0x0020 * sizeof(int); pAY8910Buffer[0] = (short *)Next; Next += nBurnSoundLen * sizeof(short); pAY8910Buffer[1] = (short *)Next; Next += nBurnSoundLen * sizeof(short); pAY8910Buffer[2] = (short *)Next; Next += nBurnSoundLen * sizeof(short); AllRam = Next; DrvZ80RAM = Next; Next += 0x001000; DrvVidRAM = Next; Next += 0x008000; DrvPaletteBank = Next; Next += 0x000001; DealerZ80Bank = Next; Next += 0x000001; DealerZ80Bank2 = Next; Next += 0x000001; RamEnd = Next; MemEnd = Next; return 0; } static int DrvInit() { AllMem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(DrvZ80ROM + 0x0000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x1000, 1, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x2000, 2, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x3000, 3, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x4000, 4, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x5000, 5, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x6000, 6, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x7000, 7, 1)) return 1; DrvPaletteInit(8); } ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x77ff, 0, DrvZ80ROM); ZetMapArea(0x0000, 0x77ff, 2, DrvZ80ROM); ZetMapArea(0x7800, 0x7fff, 0, DrvZ80RAM); ZetMapArea(0x7800, 0x7fff, 1, DrvZ80RAM); ZetMapArea(0x7800, 0x7fff, 2, DrvZ80RAM); ZetMapArea(0x8000, 0xffff, 0, DrvVidRAM); ZetMapArea(0x8000, 0xffff, 1, DrvVidRAM); ZetMapArea(0x8000, 0xffff, 2, DrvVidRAM); ZetSetInHandler(epos_read_port); ZetSetOutHandler(epos_write_port); ZetMemEnd(); ZetClose(); AY8910Init(0, 2750000, nBurnSoundRate, NULL, NULL, NULL, NULL); GenericTilesInit(); DrvDoReset(); return 0; } static int DealerInit() { AllMem = NULL; MemIndex(); int nLen = MemEnd - (unsigned char *)0; if ((AllMem = (unsigned char *)malloc(nLen)) == NULL) return 1; memset(AllMem, 0, nLen); MemIndex(); { if (BurnLoadRom(DrvZ80ROM + 0x0000, 0, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x2000, 1, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x4000, 2, 1)) return 1; if (BurnLoadRom(DrvZ80ROM + 0x6000, 3, 1)) return 1; DrvPaletteInit(4); DealerDecode(); } ZetInit(1); ZetOpen(0); ZetMapArea(0x0000, 0x6fff, 0, DrvZ80ROM); ZetMapArea(0x0000, 0x6fff, 2, DrvZ80ROM); ZetMapArea(0x7000, 0x7fff, 0, DrvZ80RAM); ZetMapArea(0x7000, 0x7fff, 1, DrvZ80RAM); ZetMapArea(0x7000, 0x7fff, 2, DrvZ80RAM); ZetMapArea(0x8000, 0xffff, 0, DrvVidRAM); ZetMapArea(0x8000, 0xffff, 1, DrvVidRAM); ZetMapArea(0x8000, 0xffff, 2, DrvVidRAM); ZetSetInHandler(dealer_read_port); ZetSetOutHandler(dealer_write_port); ZetMemEnd(); ZetClose(); AY8910Init(0, 2750000, nBurnSoundRate, NULL, NULL, NULL, NULL); ppi8255_init(1); PPI0PortReadA = DealerPPIReadA; PPI0PortWriteC = DealerPPIWriteC; GenericTilesInit(); DrvDoReset(); return 0; } static int DrvExit() { GenericTilesExit(); AY8910Exit(0); ZetExit(); if (PPI0PortReadA) { ppi8255_exit(); } free (AllMem); AllMem = NULL; return 0; } static int DrvDraw() { if (DrvRecalc) { unsigned char r,g,b; for (int i = 0; i < 0x20; i++) { int rgb = Palette[i]; r = (rgb >> 16) & 0xff; g = (rgb >> 8) & 0xff; b = (rgb >> 0) & 0xff; DrvPalette[i] = BurnHighCol(r, g, b, 0); } } for (int i = 0; i < 0x8000; i++) { int x = (i % 136) << 1; int y = (i / 136); if (y > 235) break; pTransDraw[(y * nScreenWidth) + x + 0] = *DrvPaletteBank | ((DrvVidRAM[i] >> 0) & 0x0f); pTransDraw[(y * nScreenWidth) + x + 1] = *DrvPaletteBank | ((DrvVidRAM[i] >> 4) & 0x0f); } BurnTransferCopy(DrvPalette); return 0; } static int DrvFrame() { if (DrvReset) { DrvDoReset(); } { DrvInputs[0] = DrvDips[1]; DrvInputs[1] = 0xff; for (int i = 0; i < 8; i++) { DrvInputs[0] ^= (DrvJoy1[i] & 1) << i; DrvInputs[1] ^= (DrvJoy2[i] & 1) << i; } } ZetOpen(0); ZetRun(2750000 / 60); ZetRaiseIrq(0); ZetClose(); if (pBurnSoundOut) { int nSample; AY8910Update(0, &pAY8910Buffer[0], nBurnSoundLen); for (int n = 0; n < nBurnSoundLen; n++) { nSample = pAY8910Buffer[0][n]; nSample += pAY8910Buffer[1][n]; nSample += pAY8910Buffer[2][n]; nSample /= 4; if (nSample < -32768) { nSample = -32768; } else { if (nSample > 32767) { nSample = 32767; } } pBurnSoundOut[(n << 1) + 0] = nSample; pBurnSoundOut[(n << 1) + 1] = nSample; } } if (pBurnDraw) { DrvDraw(); } return 0; } static int DrvScan(int nAction,int *pnMin) { struct BurnArea ba; if (pnMin) { *pnMin = 0x029702; } if (nAction & ACB_VOLATILE) { memset(&ba, 0, sizeof(ba)); ba.Data = AllRam; ba.nLen = RamEnd - AllRam; ba.szName = "All Ram"; BurnAcb(&ba); ZetScan(nAction); AY8910Scan(nAction, pnMin); if (PPI0PortReadA) { ppi8255_scan(); if (nAction & ACB_WRITE) { dealer_set_bank(); dealer_bankswitch2(*DealerZ80Bank2); } } } return 0; } // Megadon static struct BurnRomInfo megadonRomDesc[] = { { "2732u10b.bin", 0x1000, 0xaf8fbe80, BRF_ESS | BRF_PRG }, // 0 Z80 code { "2732u09b.bin", 0x1000, 0x097d1e73, BRF_ESS | BRF_PRG }, // 1 { "2732u08b.bin", 0x1000, 0x526784da, BRF_ESS | BRF_PRG }, // 2 { "2732u07b.bin", 0x1000, 0x5b060910, BRF_ESS | BRF_PRG }, // 3 { "2732u06b.bin", 0x1000, 0x8ac8af6d, BRF_ESS | BRF_PRG }, // 4 { "2732u05b.bin", 0x1000, 0x052bb603, BRF_ESS | BRF_PRG }, // 5 { "2732u04b.bin", 0x1000, 0x9b8b7e92, BRF_ESS | BRF_PRG }, // 6 { "2716u11b.bin", 0x0800, 0x599b8b61, BRF_ESS | BRF_PRG }, // 7 { "74s288.bin", 0x0020, 0xc779ea99, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(megadon) STD_ROM_FN(megadon) struct BurnDriver BurnDrvMegadon = { "megadon", NULL, NULL, "1982", "Megadon\0", NULL, "Epos Corporation (Photar Industries License)", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, megadonRomInfo, megadonRomName, MegadonInputInfo, MegadonDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // Catapult static struct BurnRomInfo catapultRomDesc[] = { { "co3223.u10", 0x1000, 0x50abcfd2, BRF_ESS | BRF_PRG }, // 0 Z80 code { "co3223.u09", 0x1000, 0xfd5a9a1c, BRF_ESS | BRF_PRG }, // 1 { "co3223.u08", 0x1000, 0x4bfc36f3, BRF_ESS | BRF_PRG }, // 2 { "co3223.u07", 0x1000, 0x4113bb99, BRF_ESS | BRF_PRG }, // 3 { "co3223.u06", 0x1000, 0x966bb9f5, BRF_ESS | BRF_PRG }, // 4 { "co3223.u05", 0x1000, 0x65f9fb9a, BRF_ESS | BRF_PRG }, // 5 { "co3223.u04", 0x1000, 0x648453bc, BRF_ESS | BRF_PRG }, // 6 { "co3223.u11", 0x0800, 0x08fb8c28, BRF_ESS | BRF_PRG }, // 7 { "co3223.u66", 0x0020, 0xe7de76a7, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(catapult) STD_ROM_FN(catapult) struct BurnDriver BurnDrvCatapult = { "catapult", NULL, NULL, "1982", "Catapult\0", "Bad dump", "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, catapultRomInfo, catapultRomName, SuprglobInputInfo, CatapultDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // Super Glob static struct BurnRomInfo suprglobRomDesc[] = { { "u10", 0x1000, 0xc0141324, BRF_ESS | BRF_PRG }, // 0 Z80 code { "u9", 0x1000, 0x58be8128, BRF_ESS | BRF_PRG }, // 1 { "u8", 0x1000, 0x6d088c16, BRF_ESS | BRF_PRG }, // 2 { "u7", 0x1000, 0xb2768203, BRF_ESS | BRF_PRG }, // 3 { "u6", 0x1000, 0x976c8f46, BRF_ESS | BRF_PRG }, // 4 { "u5", 0x1000, 0x340f5290, BRF_ESS | BRF_PRG }, // 5 { "u4", 0x1000, 0x173bd589, BRF_ESS | BRF_PRG }, // 6 { "u11", 0x0800, 0xd45b740d, BRF_ESS | BRF_PRG }, // 7 { "82s123.u66", 0x0020, 0xf4f6ddc5, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(suprglob) STD_ROM_FN(suprglob) struct BurnDriver BurnDrvSuprglob = { "suprglob", NULL, NULL, "1983", "Super Glob\0", NULL, "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, suprglobRomInfo, suprglobRomName, SuprglobInputInfo, SuprglobDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // The Glob static struct BurnRomInfo theglobRomDesc[] = { { "globu10.bin", 0x1000, 0x08fdb495, BRF_ESS | BRF_PRG }, // 0 Z80 code { "globu9.bin", 0x1000, 0x827cd56c, BRF_ESS | BRF_PRG }, // 1 { "globu8.bin", 0x1000, 0xd1219966, BRF_ESS | BRF_PRG }, // 2 { "globu7.bin", 0x1000, 0xb1649da7, BRF_ESS | BRF_PRG }, // 3 { "globu6.bin", 0x1000, 0xb3457e67, BRF_ESS | BRF_PRG }, // 4 { "globu5.bin", 0x1000, 0x89d582cd, BRF_ESS | BRF_PRG }, // 5 { "globu4.bin", 0x1000, 0x7ee9fdeb, BRF_ESS | BRF_PRG }, // 6 { "globu11.bin", 0x0800, 0x9e05dee3, BRF_ESS | BRF_PRG }, // 7 { "82s123.u66", 0x0020, 0xf4f6ddc5, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(theglob) STD_ROM_FN(theglob) struct BurnDriver BurnDrvTheglob = { "theglob", "suprglob", NULL, "1983", "The Glob\0", NULL, "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, theglobRomInfo, theglobRomName, SuprglobInputInfo, SuprglobDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // The Glob (earlier) static struct BurnRomInfo theglob2RomDesc[] = { { "611293.u10", 0x1000, 0x870af7ce, BRF_ESS | BRF_PRG }, // 0 Z80 code { "611293.u9", 0x1000, 0xa3679782, BRF_ESS | BRF_PRG }, // 1 { "611293.u8", 0x1000, 0x67499d1a, BRF_ESS | BRF_PRG }, // 2 { "611293.u7", 0x1000, 0x55e53aac, BRF_ESS | BRF_PRG }, // 3 { "611293.u6", 0x1000, 0xc64ad743, BRF_ESS | BRF_PRG }, // 4 { "611293.u5", 0x1000, 0xf93c3203, BRF_ESS | BRF_PRG }, // 5 { "611293.u4", 0x1000, 0xceea0018, BRF_ESS | BRF_PRG }, // 6 { "611293.u11", 0x0800, 0x6ac83f9b, BRF_ESS | BRF_PRG }, // 7 { "82s123.u66", 0x0020, 0xf4f6ddc5, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(theglob2) STD_ROM_FN(theglob2) struct BurnDriver BurnDrvTheglob2 = { "theglob2", "suprglob", NULL, "1983", "The Glob (earlier)\0", NULL, "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, theglob2RomInfo, theglob2RomName, SuprglobInputInfo, SuprglobDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // The Glob (set 3) static struct BurnRomInfo theglob3RomDesc[] = { { "theglob3.u10", 0x1000, 0x969cfaf6, BRF_ESS | BRF_PRG }, // 0 Z80 code { "theglob3.u9", 0x1000, 0x8e6c010a, BRF_ESS | BRF_PRG }, // 1 { "theglob3.u8", 0x1000, 0x1c1ca5c8, BRF_ESS | BRF_PRG }, // 2 { "theglob3.u7", 0x1000, 0xa54b9d22, BRF_ESS | BRF_PRG }, // 3 { "theglob3.u6", 0x1000, 0x5a6f82a9, BRF_ESS | BRF_PRG }, // 4 { "theglob3.u5", 0x1000, 0x72f935db, BRF_ESS | BRF_PRG }, // 5 { "theglob3.u4", 0x1000, 0x81db53ad, BRF_ESS | BRF_PRG }, // 6 { "theglob3.u11", 0x0800, 0x0e2e6359, BRF_ESS | BRF_PRG }, // 7 { "82s123.u66", 0x0020, 0xf4f6ddc5, BRF_GRA }, // 8 Color PROM }; STD_ROM_PICK(theglob3) STD_ROM_FN(theglob3) struct BurnDriver BurnDrvTheglob3 = { "theglob3", "suprglob", NULL, "1983", "The Glob (set 3)\0", NULL, "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_CLONE | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, theglob3RomInfo, theglob3RomName, SuprglobInputInfo, SuprglobDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // IGMO static struct BurnRomInfo igmoRomDesc[] = { { "igmo-u10.732", 0x1000, 0xa9f691a4, BRF_ESS | BRF_PRG }, // 0 Z80 code { "igmo-u9.732", 0x1000, 0x3c133c97, BRF_ESS | BRF_PRG }, // 1 { "igmo-u8.732", 0x1000, 0x5692f8d8, BRF_ESS | BRF_PRG }, // 2 { "igmo-u7.732", 0x1000, 0x630ae2ed, BRF_ESS | BRF_PRG }, // 3 { "igmo-u6.732", 0x1000, 0xd3f20e1d, BRF_ESS | BRF_PRG }, // 4 { "igmo-u5.732", 0x1000, 0xe26bb391, BRF_ESS | BRF_PRG }, // 5 { "igmo-u4.732", 0x1000, 0x762a4417, BRF_ESS | BRF_PRG }, // 6 { "igmo-u11.716", 0x0800, 0x8c675837, BRF_ESS | BRF_PRG }, // 7 { "82s123.u66", 0x0020, 0x00000000, BRF_GRA | BRF_NODUMP }, // 8 Color Prom (missing) }; STD_ROM_PICK(igmo) STD_ROM_FN(igmo) struct BurnDriver BurnDrvIgmo = { "igmo", NULL, NULL, "1984", "IGMO\0", "Incorrect Colors", "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, igmoRomInfo, igmoRomName, SuprglobInputInfo, IgmoDIPInfo, DrvInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // The Dealer static struct BurnRomInfo dealerRomDesc[] = { { "u1.bin", 0x2000, 0xe06f3563, BRF_ESS | BRF_PRG }, // 0 Z80 code { "u2.bin", 0x2000, 0x726bbbd6, BRF_ESS | BRF_PRG }, // 1 { "u3.bin", 0x2000, 0xab721455, BRF_ESS | BRF_PRG }, // 2 { "u4.bin", 0x2000, 0xddb903e4, BRF_ESS | BRF_PRG }, // 3 { "82s123.u66", 0x0020, 0x00000000, BRF_GRA | BRF_NODUMP }, // 4 Color Prom (missing) }; STD_ROM_PICK(dealer) STD_ROM_FN(dealer) struct BurnDriver BurnDrvDealer = { "dealer", NULL, NULL, "198?", "The Dealer\0", "No Sound / Incorrect Colors", "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, dealerRomInfo, dealerRomName, DealerInputInfo, DealerDIPInfo, DealerInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 }; // Revenger static struct BurnRomInfo revengerRomDesc[] = { { "r06124.u1", 0x2000, 0xfad1a2a5, BRF_ESS | BRF_PRG }, // 0 Z80 code { "r06124.u2", 0x2000, 0xa8e0ee7b, BRF_ESS | BRF_PRG }, // 1 { "r06124.u3", 0x2000, 0xcca414a5, BRF_ESS | BRF_PRG }, // 2 { "r06124.u4", 0x2000, 0x0b81c303, BRF_ESS | BRF_PRG }, // 3 { "82s123.u66", 0x0020, 0x00000000, BRF_GRA | BRF_NODUMP }, // 4 Color Prom (missing) }; STD_ROM_PICK(revenger) STD_ROM_FN(revenger) struct BurnDriver BurnDrvRevenger = { "revenger", NULL, NULL, "1984", "Revenger\0", "Bad dump", "Epos Corporation", "EPOS Tristar", NULL, NULL, NULL, NULL, BDF_ORIENTATION_VERTICAL, 1, HARDWARE_MISC_MISC, NULL, revengerRomInfo, revengerRomName, DealerInputInfo, DealerDIPInfo, DealerInit, DrvExit, DrvFrame, DrvDraw, DrvScan, &DrvRecalc, 236, 272, 3, 4 };
[ [ [ 1, 926 ] ] ]
06a2ff8ad69bd0954c58c6ecca80a148f1e7af02
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Common/mobileyeInterface/mobileyeInterface.h
01593b639e24a2075062dfcebe85466115bb693c
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,680
h
#pragma once #include "..\network\udp_connection.h" #include "..\utility/fastdelegate.h" #ifdef __cplusplus_cli #pragma managed(push,off) #endif #define UDP_MOBILEYE_MULTICAST_PORT 30036 #define UDP_MOBILEYE_MULTICAST_ADDR "239.132.1.36" #define MOBILEYE_MAX_OBS 20 enum MobilEyeID:int { MOBILEYE_FL=0, MOBILEYE_FR=1, MOBILEYE_CTR=2, MOBILEYE_REAR=3 }; enum MobilEyeMessageID:int { ME_Info = 0, ME_RoadEnv= 1, ME_Obs = 3, ME_BAD = 99 }; enum PoseAvailable:int { POSE_None = 0x00, POSE_Vel = 0x04, POSE_Pitch= 0x02, POSE_Yaw = 0x01 }; enum LaneMarkType:int { LM_None, LM_Solid, LM_Dashed, LM_Virtual, LM_BottsDots, LM_RoadEdge, LM_DoubleSolid, LM_Reserved }; enum LatDistDir:int { LD_Left, LD_Right }; enum LaneCrossingFlag:int { LC_Unknown, LC_NoCrossing, LC_CrossingLeft, LC_CrossingRight }; enum StopLinePath:int { SL_Unknown, SL_InPath, SL_LeftPath, SL_RightPath }; enum VehiclePath:int { VP_NoSide, VP_Center, VP_Left, VP_Right }; #pragma pack(1) struct MobilEyeEnvironment { double carTime; int meTimestamp; int frameIndex; int FOEY; int FOEX; float CamHeight; float leftDangerZone; float rightDangerZone; }; #pragma pack() #pragma pack(1) struct MobilEyeRoadInformation { double carTime; LaneMarkType rightMarkType; LaneMarkType leftMarkType; float distToLeftMark; float distToRightMark; float roadModelSlope; float roadModelCurvature; float roadModelConst; int rightLaneConfidence; int leftLaneConfidence; float stopLineDistance; StopLinePath stopLinePath; int stopLineConf; float roadModelValidRange; LaneCrossingFlag laneCrossingFlag; float leftTimeToLaneCrossing; float rightTimeToLaneCrossing; bool isRoadModelValid; //new---------- //lanes--------------- LaneMarkType rightNeighborMarkType; LaneMarkType leftNeighborMarkType; int rightNeighborConfidence; int leftNeighborConfidence; float distToRightNeighborMark; float distToLeftNeighborMark; //edges-------------- LaneMarkType rightEdgeMarkType; LaneMarkType leftEdgeMarkType; int rightEdgeConfidence; int leftEdgeConfidence; float distToRightEdge; float distToLeftEdge; }; #pragma pack() #pragma pack(1) struct MobilEyeRoadEnv { MobilEyeID id; MobilEyeMessageID msgType; int sequenceNumber; MobilEyeRoadInformation road; MobilEyeEnvironment env; }; #pragma pack() #pragma pack(1) struct MobilEyeWorldObstacle { int obstacleID; float obstacleDistZ; int confidence; VehiclePath path; //0 no side, 1 center, 2 left, 3 right bool currentInPathVehicle; bool obstacleDistXDirection; // 0 left, 1 right float obstacleDistX; float obstacleWidth; float scaleChange; // (.5 to -.5) float velocity; int bottomRect; //pixels? int leftRect; int topRect; int rightRect; }; #pragma pack() #pragma pack(1) struct MobilEyeObstacles { MobilEyeID id; MobilEyeMessageID msgType; int sequenceNumber; double carTime; int numObstacles; MobilEyeWorldObstacle obstacles[MOBILEYE_MAX_OBS]; }; #pragma pack() class MobilEyeInterfaceSender; class MobilEyeInterfaceReceiver; typedef FastDelegate4<MobilEyeRoadEnv, MobilEyeInterfaceReceiver*, MobilEyeID, void*> mobilEye_RoadEnv_Msg_handler; typedef FastDelegate4<MobilEyeObstacles, MobilEyeInterfaceReceiver*, MobilEyeID, void*> mobilEye_Obstacle_Msg_handler; using namespace std; class MobilEyeInterfaceReceiver { private: udp_connection *conn; void UDPCallback(udp_message& msg, udp_connection* conn, void* arg); mobilEye_RoadEnv_Msg_handler roadenv_cbk; mobilEye_Obstacle_Msg_handler obs_cbk; void* roadenv_cbk_arg; void* obs_cbk_arg; public: MobilEyeInterfaceReceiver(); ~MobilEyeInterfaceReceiver(void); void SetRoadEnvInfoCallback(mobilEye_RoadEnv_Msg_handler handler, void* arg); void SetObstacleCallback(mobilEye_Obstacle_Msg_handler handler, void* arg); int sequenceNumber; int dropCount; int packetCount; }; class MobilEyeInterfaceSender { private: udp_connection *conn; void UDPCallback(udp_message msg, udp_connection* conn, void* arg); int sequenceNumber; public: MobilEyeInterfaceSender(); ~MobilEyeInterfaceSender(void); void SendRoadEnvInfo(MobilEyeRoadInformation* road, MobilEyeEnvironment* env, MobilEyeID id); void SendObstacles(MobilEyeObstacles* obs, MobilEyeID id); }; #ifdef __cplusplus_cli #pragma managed(pop) #endif
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 203 ] ] ]
251b6dbe261ee326dbb1e48dd46c0ed2edda6251
bdb1e38df8bf74ac0df4209a77ddea841045349e
/CapsuleSortor/Version 1.0 -2.0/CapsuleSortor-10-11-12/CapsuleSortor-10-11-12/ToolSrc/TLocker.h
eb9a2504d61616395d58c59330772bfa78875e6c
[]
no_license
Strongc/my001project
e0754f23c7818df964289dc07890e29144393432
07d6e31b9d4708d2ef691d9bedccbb818ea6b121
refs/heads/master
2021-01-19T07:02:29.673281
2010-12-17T03:10:52
2010-12-17T03:10:52
49,062,858
0
1
null
2016-01-05T11:53:07
2016-01-05T11:53:07
null
UTF-8
C++
false
false
1,007
h
// TLocker.h : Interface and Implement of the TLocker class // // Copyright (c) 2007 PACS Group Zibo Creative Computor CO.,LTD ////////////////////////////////////////////////////////////////////////// // Module : Common Tool // Create Date : 2007.01.09 // // A tool to use critical sections #ifndef TLOCKER_H #define TLOCKER_H // We want this to be compatible with MFC and non-MFC apps #ifdef _AFXDLL #include <afx.h> #else #include <windows.h> #endif class TLockObject { public: TLockObject() {} virtual ~TLockObject() {} virtual void Lock() = 0; virtual void Unlock() = 0; }; class TLocker { public: TLocker(TLockObject & object); ~TLocker(); private: TLocker(const TLocker& src); TLocker& operator= (const TLocker& src); private: TLockObject& m_lockObject; }; inline TLocker::TLocker(TLockObject & object) : m_lockObject(object) { m_lockObject.Lock(); } inline TLocker::~TLocker() { m_lockObject.Unlock(); } #endif //TCRITSECT_H
[ "vincen.cn@66f52ff4-a261-11de-b161-9f508301ba8e" ]
[ [ [ 1, 54 ] ] ]
c1e5bd5c092fcb0ec13fdc4a13ff828ba7243e46
cb318077a36ea2885b66ebdfb61cb37f9096b27d
/MT4ODBCBridge/cppodbc.cpp
33bc8a42c7edb6e979482d4ce6256376cc15fc37
[]
no_license
danmi1258/mt4-odbc-bridge
aede37e60959d60e0b524c0d25f7c4e24164113e
422d2ae4137886babdbf6dff17e594f8d729049f
refs/heads/master
2021-05-26T13:54:46.648670
2011-08-29T10:48:51
2011-08-29T10:48:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,518
cpp
#include "cppodbc.h" using namespace cppodbc; // ====================================================================== // Implementation of class ODBCException // ====================================================================== ODBCException::ODBCException(int nError, const TCHAR *sqlState, const TCHAR *errorMesg) { this->nativeError = nError; _tcsncpy_s(this->sqlState, sqlState, _TRUNCATE); _tcsncpy_s(this->errorMesg, errorMesg, _TRUNCATE); } ODBCException::~ODBCException() { } // ====================================================================== // Implementation of class Handler // ====================================================================== /** * Constructor of Handler class. * This allocate a handle by SQLAllocHandle. * The type of handle is distinguished by hType. */ Handler::Handler(SQLSMALLINT hType, SQLHANDLE parent) { this->hType = hType; process(SQLAllocHandle(hType, parent, &handle)); }; /** * Destructor of Handler class. * This makes the instance be free by SQLFreeHandle, corresponding to * the constructor. */ Handler::~Handler() { retcode = SQLFreeHandle(hType, handle); } /** * Checks every ODBC API call and throws an exception if necessary. */ SQLRETURN Handler::process(SQLRETURN rc) { retcode = rc; //TODO: Need to clarify when messages are available, even in non-error situation. switch (rc) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: break; case SQL_ERROR: case SQL_INVALID_HANDLE: throw makeException(); default: break; } return rc; } ODBCException *Handler::makeException() { //BUG: Seems to work in only MBCS mode, not in UNICODE mode. // Maybe http://stackoverflow.com/questions/829311/sqlgetdiagrec-causes-crash-in-unicode-release-build char sqlState[EX_SQLSTATE_LEN]; SQLINTEGER nativeError; char errorMesg[EX_ERRMESG_LEN]; SQLSMALLINT errorMesgLen; retcode = SQLGetDiagRecA(hType, handle, 1, (SQLCHAR *) sqlState, &nativeError, (SQLCHAR *) errorMesg, sizeof(errorMesg), &errorMesgLen); if (retcode == SQL_SUCCESS || retcode == SQL_SUCCESS_WITH_INFO) { //WORKAROUND: force to use MBCS even in UNICODE mode. #ifdef UNICODE wchar_t wSqlState[EX_SQLSTATE_LEN]; wchar_t wErrorMesg[EX_ERRMESG_LEN]; size_t dummy; mbstowcs_s(&dummy, wSqlState, sqlState, _TRUNCATE); if (errorMesgLen < EX_ERRMESG_LEN) mbstowcs_s(&dummy, wErrorMesg, errorMesg, _TRUNCATE); else mbstowcs_s(&dummy, wErrorMesg, "Error message buffer is not enough.", _TRUNCATE); return new ODBCException(nativeError, (TCHAR *) wSqlState, (TCHAR *) wErrorMesg); #else if (errorMesgLen >= EX_ERRMESG_LEN) strncpy_s(errorMesg, "Error message buffer is not enough.", _TRUNCATE); return new ODBCException(nativeError, (TCHAR *) sqlState, (TCHAR *) errorMesg); #endif } else { return new ODBCException(-1, _T(""), _T("Cannot get message.")); } } // ====================================================================== // Implementation of class Environment // ====================================================================== Environment::Environment() : Handler(SQL_HANDLE_ENV, SQL_NULL_HANDLE) { // allocated at the superclass } Environment::~Environment() { // freed at the superclass } void Environment::setAttribute(int aType, int value) { process(SQLSetEnvAttr(handle, aType, (SQLPOINTER) value, 0)); } int Environment::getAttribute(int aType) { int value; process(SQLGetEnvAttr(handle, aType, &value, 0, NULL)); return value; } // ====================================================================== // Implementation of class Connection // ====================================================================== Connection::Connection(Environment *env) : Handler(SQL_HANDLE_DBC, env->handle) { // allocated at the superclass } Connection::~Connection() { disconnect(); // freed at the suuperclass } void Connection::setAttribute(int aType, int value) { process(SQLSetConnectAttr(handle, aType, (SQLPOINTER) value, 0)); } int Connection::getAttribute(int aType) { int value; process(SQLGetConnectAttr(handle, aType, &value, 0, NULL)); return value; } void Connection::connect(const TCHAR *dsn, const TCHAR *username, const TCHAR *password) { if (!username && !password) process(SQLConnect(handle, (SQLTCHAR *) dsn, SQL_NTS, (SQLTCHAR *) username, SQL_NTS, (SQLTCHAR *) password, SQL_NTS)); else process(SQLConnect(handle, (SQLTCHAR *) dsn, SQL_NTS, (SQLTCHAR *) NULL, 0, (SQLTCHAR *) NULL, 0)); } void Connection::disconnect() { retcode = SQLDisconnect(handle); } int Connection::isDead() { return getAttribute(SQL_ATTR_CONNECTION_DEAD) == SQL_CD_TRUE; } void Connection::commit() { process(SQLEndTran(SQL_HANDLE_DBC, handle, SQL_COMMIT)); } void Connection::rollback() { process(SQLEndTran(SQL_HANDLE_DBC, handle, SQL_ROLLBACK)); } int Connection::getAutoCommit() { return getAttribute(SQL_ATTR_AUTOCOMMIT) == SQL_AUTOCOMMIT_ON; } void Connection::setAutoCommit(int autoCommit) { int val = autoCommit == 0 ? SQL_AUTOCOMMIT_OFF : SQL_AUTOCOMMIT_ON; setAttribute(SQL_ATTR_AUTOCOMMIT, val); } // ====================================================================== // Implementation of class Statement // ====================================================================== Statement::Statement(Connection *dbc) : Handler(SQL_HANDLE_STMT, dbc->handle) { // allocated at the superclass this->parameters = NULL; this->paramNum = 0; this->columns = NULL; this->colNum = 0; this->rowHandler = NULL; this->anyPointer = NULL; } Statement::~Statement() { free(); // about cursor, parameters, columns this may hold // freed at the superclass } void Statement::setAttribute(int aType, int value) { process(SQLSetStmtAttr(handle, aType, (SQLPOINTER) value, 0)); } int Statement::getAttribute(int aType) { int value; process(SQLGetStmtAttr(handle, aType, &value, 0, NULL)); return value; } void Statement::free() { for (std::vector<DataPointer*>::iterator ite = parameterHolder.begin(); ite != parameterHolder.end(); ite++) { if (*ite) { delete *ite; *ite = NULL; } } for (std::vector<DataPointer*>::iterator ite = columnHolder.begin(); ite != columnHolder.end(); ite++) { if (*ite) { delete *ite; *ite = NULL; } } // indirectDataPointers oesn't need to delete because thoese were deleted in one of aboves. retcode = SQLFreeStmt(handle, SQL_CLOSE); retcode = SQLFreeStmt(handle, SQL_UNBIND); retcode = SQLFreeStmt(handle, SQL_RESET_PARAMS); } int Statement::execute(const TCHAR *sql) { process(SQLExecDirect(handle, (SQLTCHAR *) sql, SQL_NTS)); return afterExecution(); } void Statement::prepare(const TCHAR *sql) { process(SQLPrepare(handle, (SQLTCHAR *) sql, SQL_NTS)); } void Statement::bindIntParameter(int slot, int *intp) { IntPointer *p = new IntPointer(intp); parameterHolder.push_back(p); // deleted at Statement:free bindParameter(slot, p); } void Statement::bindDoubleParameter(int slot, double *dblp) { DoublePointer *p = new DoublePointer(dblp); parameterHolder.push_back(p); // deleted at Statement:free bindParameter(slot, p); } void Statement::bindStringParameter(int slot, TCHAR *strp) { StringPointer *p = new StringPointer(strp, _tcslen(strp)); parameterHolder.push_back(p); // deleted at Statement:free bindParameter(slot, p); } void Statement::bindTimestampParameter(int slot, SQL_TIMESTAMP_STRUCT *tsp) { TimestampPointer *p = new TimestampPointer(tsp); parameterHolder.push_back(p); // deleted at Statement:free bindParameter(slot, p); } //void Statement::bindTimetParameter(int slot, time_t *tp) //{ // TimetPointer *p = new TimetPointer(tp); // parameterHolder.push_back(p); // deleted at Statement:free // indirectDataPointers.push_back(p); // bindParameter(slot, p); //} void Statement::bindUIntTimetParameter(int slot, unsigned int *tp) { UIntTimetPointer *p = new UIntTimetPointer(tp); parameterHolder.push_back(p); // deleted at Statement:free indirectDataPointers.push_back(p); bindParameter(slot, p); } void Statement::bindParameter(int slot, DataPointer *dp) { process(SQLBindParameter(handle, slot, SQL_PARAM_INPUT, dp->getCType(), dp->getSQLType(), dp->getColumnSize(), dp->getScale(), dp->getDataPointer(), dp->getDataSize(), dp->getLenOrInd())); } void Statement::bindParameters(DataPointer *dps, int size) { for (int i = 0; i < size; i++) bindParameter(i + 1, &dps[i]); parameters = dps; paramNum = size; } void Statement::bindIntColumn(int slot, int *intp) { IntPointer *p = new IntPointer(intp); columnHolder.push_back(p); // deleted at Statement:free bindColumn(slot, p); } void Statement::bindDoubleColumn(int slot, double *dblp) { DoublePointer *p = new DoublePointer(dblp); columnHolder.push_back(p); // deleted at Statement:free bindColumn(slot, p); } void Statement::bindStringColumn(int slot, TCHAR *strp) { StringPointer *p = new StringPointer(strp, _tcslen(strp)); columnHolder.push_back(p); // deleted at Statement:free bindColumn(slot, p); } void Statement::bindTimestampColumn(int slot, SQL_TIMESTAMP_STRUCT *tsp) { TimestampPointer *p = new TimestampPointer(tsp); columnHolder.push_back(p); // deleted at Statement:free bindColumn(slot, p); } //void Statement::bindTimetColumn(int slot, time_t *tp) //{ // TimetPointer *p = new TimetPointer(tp); // columnHolder.push_back(p); // deleted at Statement:free // indirectDataPointers.push_back(p); // bindColumn(slot, p); //} void Statement::bindUIntTimetColumn(int slot, unsigned int *tp) { UIntTimetPointer *p = new UIntTimetPointer(tp); columnHolder.push_back(p); // deleted at Statement:free indirectDataPointers.push_back(p); bindColumn(slot, p); } void Statement::bindColumn(int slot, DataPointer *dp) { process(SQLBindCol(handle, slot, dp->getCType(), dp->getDataPointer(), dp->getDataSize(), dp->getLenOrInd())); } void Statement::bindColumns(DataPointer *dps, int size) { for (int i = 0; i < size; i++) bindColumn(i + 1, &dps[i]); columns = dps; colNum = size; } void Statement::setRowHandler(void (*rowHandler)(int rowCnt, DataPointer *dps, int size, void *anyPointer), void *anyPointer) { this->rowHandler = rowHandler; this->anyPointer = anyPointer; } int Statement::execute() { return execute(true); } int Statement::execute(bool fetchImmediately) { // rebinding for indirectDataPointers to reflect the new value for (int i = 0, n = indirectDataPointers.size(); i < n; i++) { UIntTimetPointer *p = indirectDataPointers[i]; //TODO: use polymorphism! if (p) p->rebind(); } process(SQLExecute(handle)); if (fetchImmediately) { return afterExecution(); } else { SQLSMALLINT colNum; process(SQLNumResultCols(handle, &colNum)); return (int) colNum; } } int Statement::afterExecution() { int rc = -1; SQLSMALLINT colNum; process(SQLNumResultCols(handle, &colNum)); if (colNum == 0) { // Non-SELECT statement SQLINTEGER affectedRows; process(SQLRowCount(handle, &affectedRows)); rc = affectedRows; } else { // SELECT statement int rowCount = 0; try { while ((retcode = SQLFetch(handle)) != SQL_NO_DATA) { switch (retcode) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: rowCount++; if (rowHandler) (*rowHandler)(rowCount, columns, colNum, anyPointer); break; default: throw makeException(); } } } catch (ODBCException *e) { retcode = SQLCloseCursor(handle); throw e; } process(SQLCloseCursor(handle)); rc = rowCount; } return rc; } int Statement::fetch() { retcode = SQLFetch(handle); // refetching for indirectDataPointers to reflect the new value for (int i = 0, n = indirectDataPointers.size(); i < n; i++) { UIntTimetPointer *p = indirectDataPointers[i]; //TODO: use polymorphism! if (p) p->refetch(); } switch (retcode) { case SQL_SUCCESS: case SQL_SUCCESS_WITH_INFO: return 1; case SQL_NO_DATA: default: return 0; } } void Statement::fetchedAll() { SQLCloseCursor(handle); } // ====================================================================== // Implementation of class DataPointer // ====================================================================== DataPointer::DataPointer(SQLSMALLINT cType, SQLSMALLINT sqlType, SQLULEN columnSize, SQLSMALLINT scale, SQLPOINTER dataPointer, SQLLEN dataSize) { this->cType = cType; this->sqlType = sqlType; this->columnSize = columnSize; this->scale = scale; this->dataPointer = dataPointer; this->dataSize = dataSize; this->lenOrInd = &lengthOrIndicator; } DataPointer::~DataPointer() { } void DataPointer::setNull() { *lenOrInd = SQL_NULL_DATA; } int DataPointer::isNull() { return *lenOrInd == SQL_NULL_DATA; } int DataPointer::length() { return *lenOrInd; } // ====================================================================== // Implementation of class IntPointer // ====================================================================== IntPointer::IntPointer(int *intp) : DataPointer(SQL_C_SLONG, SQL_INTEGER, 0, 0, intp, 0) { lengthOrIndicator = NULL; } IntPointer::~IntPointer() { } // ====================================================================== // Implementation of class DoublePointer // ====================================================================== DoublePointer::DoublePointer(double *doublep) : DataPointer(SQL_C_DOUBLE, SQL_DOUBLE, 0, 0, doublep, 0) { lengthOrIndicator = NULL; } DoublePointer::~DoublePointer() { } // ====================================================================== // Implementation of class StringPointer // ====================================================================== StringPointer::StringPointer(TCHAR *stringp, int size) : DataPointer(SQL_C_TCHAR, SQL_VARCHAR, size, 0, stringp, size) { lengthOrIndicator = SQL_NTS; } StringPointer::~StringPointer() { } // ====================================================================== // Implementation of class TimestampPointer // ====================================================================== TimestampPointer::TimestampPointer(SQL_TIMESTAMP_STRUCT *timestamp) : DataPointer(SQL_C_TYPE_TIMESTAMP, SQL_TYPE_TIMESTAMP, 19, 0, timestamp, 0) { lengthOrIndicator = NULL; } TimestampPointer::TimestampPointer(SQL_TIMESTAMP_STRUCT *timestamp, int fractionScale) : DataPointer(SQL_C_TYPE_TIMESTAMP, SQL_TYPE_TIMESTAMP, 20 + fractionScale, fractionScale, timestamp, 0) { lengthOrIndicator = NULL; } TimestampPointer::~TimestampPointer() { } void TimestampPointer::structtm2timestamp(struct tm *in, SQL_TIMESTAMP_STRUCT *out) { out->year = in->tm_year + 1900; out->month = in->tm_mon + 1; out->day = in->tm_mday; out->hour = in->tm_hour; out->minute = in->tm_min; out->second = in->tm_sec; out->fraction = 0; } void TimestampPointer::timestamp2structtm(SQL_TIMESTAMP_STRUCT *in, struct tm *out) { out->tm_year = in->year - 1900; out->tm_mon = in->month - 1; out->tm_mday = in->day; out->tm_hour = in->hour; out->tm_min = in->minute; out->tm_sec = in->second; out->tm_isdst = -1; _mkgmtime(out); } void TimestampPointer::timet2timestamp(time_t *in, SQL_TIMESTAMP_STRUCT *out) { struct tm temp; gmtime_s(&temp, in); structtm2timestamp(&temp, out); } void TimestampPointer::timestamp2timet(SQL_TIMESTAMP_STRUCT *in, time_t *out) { struct tm temp; timestamp2structtm(in, &temp); *out = _mkgmtime(&temp); } // ====================================================================== // Implementation of class TimetPointer // ====================================================================== TimetPointer::TimetPointer(time_t *timet) : TimestampPointer(&timestamp) { timeType = timet; rebind(); } TimetPointer::~TimetPointer() { } void TimetPointer::rebind() { TimestampPointer::timet2timestamp(timeType, &timestamp); } void TimetPointer::refetch() { TimestampPointer::timestamp2timet(&timestamp, timeType); } // ====================================================================== // Implementation of class UIntTimetPointer // ====================================================================== UIntTimetPointer::UIntTimetPointer(unsigned int *uintTimet) : TimetPointer(&timet) { uintp = uintTimet; rebind(); } UIntTimetPointer::~UIntTimetPointer() { } void UIntTimetPointer::rebind() { timet = (time_t) *uintp; TimetPointer::rebind(); } void UIntTimetPointer::refetch() { TimetPointer::refetch(); *uintp = (unsigned int) timet; } // ====================================================================== // Implementation of class DatePointer // ====================================================================== DatePointer::DatePointer(SQL_DATE_STRUCT *datep) : DataPointer(SQL_C_TYPE_DATE, SQL_TYPE_DATE, 10, 0, datep, 0) { lengthOrIndicator = NULL; } DatePointer::~DatePointer() { } // ====================================================================== // Implementation of class TimePointer // ====================================================================== TimePointer::TimePointer(SQL_TIME_STRUCT *timep) : DataPointer(SQL_C_TYPE_TIME, SQL_TYPE_TIME, 8, 0, timep, 0) { lengthOrIndicator = NULL; } TimePointer::~TimePointer() { } // ====================================================================== // Implementation of class NumericPointer // ====================================================================== NumericPointer::NumericPointer(SQL_NUMERIC_STRUCT *numericp, int precision, int scale) : DataPointer(SQL_C_NUMERIC, SQL_NUMERIC, precision, scale, numericp, 0) { lengthOrIndicator = NULL; } NumericPointer::~NumericPointer() { } // http://support.microsoft.com/kb/222831 static long strtohextoval(const unsigned char *arr) { long val=0,value=0; int i=1,last=1,current; int a=0,b=0; for(i=0;i<16;i++) { current = (int) arr[i]; a= current % 16; //Obtain LSD b= current / 16; //Obtain MSD value += last* a; last = last * 16; value += last* b; last = last * 16; } return value; } void NumericPointer::numstruct2double(SQL_NUMERIC_STRUCT *nums, double *dbl) { int divisor = 1; for (int i = 0; i < nums->scale; i++) divisor *= 10; int sign = nums->sign == 0 ? -1 : 1; double dnum = sign * strtohextoval(nums->val) / (double) divisor; *dbl = dnum; } //TODO: complete writing double2numstruct() double NumericPointer::doubleValue() { double dbl; NumericPointer::numstruct2double((SQL_NUMERIC_STRUCT *) getDataPointer(), &dbl); return dbl; }
[ "onagano" ]
[ [ [ 1, 742 ] ] ]
ad81aba2f23cebb1334f1450924b6b0ea3412ba0
fcf03ead74f6dc103ec3b07ffe3bce81c820660d
/AppFramework/Apparc/Server Application/server_application/serv_app_minimal_main.cpp
139457fc23ba3c663f1c71aa1572be4d26ab6ea5
[]
no_license
huellif/symbian-example
72097c9aec6d45d555a79a30d576dddc04a65a16
56f6c5e67a3d37961408fc51188d46d49bddcfdc
refs/heads/master
2016-09-06T12:49:32.021854
2010-10-14T06:31:20
2010-10-14T06:31:20
38,062,421
2
0
null
null
null
null
UTF-8
C++
false
false
436
cpp
// serv_app_minimal_main.cpp // // Copyright (c) Symbian Software Ltd 2006. All rights reserved. // #include "serv_app_minimal.h" #include <eikstart.h> // Creates and returns an instance of the CApaApplication-derived class. static CApaApplication* NewApplication() { return new CExampleApplication; } // Standard entry point function. TInt E32Main() { return EikStart::RunApplication(NewApplication); }
[ "liuxk99@bdc341c6-17c0-11de-ac9f-1d9250355bca" ]
[ [ [ 1, 21 ] ] ]
651596b797fef93250ff3ed0fca66c8a37bdf199
854ee643a4e4d0b7a202fce237ee76b6930315ec
/arcemu_svn/src/arcemu-world/EyeOfTheStorm.h
d26dd4ac56e3e69d7164da07d0fcdd9fb2682337
[]
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
2,787
h
/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef _EOTS_H #define _EOTS_H #define EOTS_TOWER_COUNT 4 #define EOTS_BUFF_RESPAWN_TIME 90000 class EyeOfTheStorm : public CBattleground { public: EyeOfTheStorm(MapMgr * mgr, uint32 id, uint32 lgroup, uint32 t); ~EyeOfTheStorm(); void HookOnPlayerDeath(Player * plr); void HookFlagDrop(Player * plr, GameObject * obj); void HookFlagStand(Player * plr, GameObject * obj); void HookOnMount(Player * plr); void HookOnAreaTrigger(Player * plr, uint32 id); bool HookHandleRepop(Player * plr); void OnAddPlayer(Player * plr); void OnRemovePlayer(Player * plr); void OnCreate(); void HookOnPlayerKill(Player * plr, Unit * pVictim); void HookOnHK(Player * plr); void HookOnShadowSight(); void SpawnBuff(uint32 x); LocationVector GetStartingCoords(uint32 Team); static CBattleground * Create(MapMgr * m, uint32 i, uint32 l, uint32 t) { return new EyeOfTheStorm(m, i, l, t); } uint32 GetNameID() { return 44; } void OnStart(); void UpdateCPs(); void UpdateIcons(); void GeneratePoints(); // returns true if that team won bool GivePoints(uint32 team, uint32 points); void RespawnCPFlag(uint32 i, uint32 id); // 0 = Neutral, <0 = Leaning towards alliance, >0 Leaning towards horde bool HookSlowLockOpen(GameObject * pGo, Player * pPlayer, Spell * pSpell); void DropFlag(Player * plr); void EventResetFlag(); void RepopPlayersOfTeam(int32 team, Creature * sh); void SetIsWeekend(bool isweekend); protected: int32 m_CPStatus[EOTS_TOWER_COUNT]; uint32 m_flagHolder; GameObject * m_standFlag; GameObject * m_dropFlag; GameObject * m_CPStatusGO[EOTS_TOWER_COUNT]; GameObject * m_CPBanner[EOTS_TOWER_COUNT]; GameObject * m_bubbles[2]; GameObject * EOTSm_buffs[4]; typedef set<Player*> EOTSCaptureDisplayList; EOTSCaptureDisplayList m_CPDisplay[EOTS_TOWER_COUNT]; uint32 m_points[2]; Creature * m_spiritGuides[EOTS_TOWER_COUNT]; }; #endif // _EOTS_H
[ "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef", "[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef" ]
[ [ [ 1, 1 ], [ 5, 26 ], [ 29, 45 ], [ 47, 50 ], [ 52, 54 ], [ 56, 67 ], [ 70, 79 ], [ 81, 89 ] ], [ [ 2, 4 ], [ 27, 28 ], [ 46, 46 ], [ 51, 51 ], [ 55, 55 ], [ 68, 69 ], [ 80, 80 ] ] ]
a88c4572e42229b3cf6bbc04284d645256de9c3e
485c5413e1a4769516c549ed7f5cd4e835751187
/Source/Engine/plan.cpp
e21d44875c42ad51413a5abbe24ed1f96ffd3980
[]
no_license
FranckLetellier/rvstereogram
44d0a78c47288ec0d9fc88efac5c34088af88d41
c494b87ee8ebb00cf806214bc547ecbec9ad0ca0
refs/heads/master
2021-05-29T12:00:15.042441
2010-03-25T13:06:10
2010-03-25T13:06:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,637
cpp
#include "plan.h" #include "heightMapStripe.h" #include <iostream> #include <cmath> Plan::Plan() { //init(1,1,1); } Plan::Plan(unsigned int iDiscretization,unsigned int iWidth, unsigned int iHeight) { init(iDiscretization,iWidth,iHeight); } Plan::~Plan() { std::vector<HeightMapStripe*>::iterator iter = m_pStripes.begin(); for (iter = m_pStripes.begin(); iter != m_pStripes.end(); ++iter) delete (*iter); } void Plan::init(unsigned int iDiscretization,unsigned int iWidth, unsigned int iHeight) { m_iHeight = iHeight; m_iWidth = iWidth; float stepX = static_cast<float>(m_iWidth) / static_cast<float>(iDiscretization) ; float stepY = static_cast<float>(m_iHeight) / static_cast<float>(iDiscretization) ; //Index for Value float* vertexPosition; float* normal; float* texture; //HACK: Variables so that we need only one "for" unsigned int iForXCoord = 0; unsigned int iTex = 0; //Creating the stripes (one for each line) for (unsigned int j=0; j < iDiscretization ; ++j) { //* 2 (we are using TRIANGLE_STRIP)* 3 (X Y Z) vertexPosition = new float[(iDiscretization + 1)*2*3 ]; normal = new float[(iDiscretization + 1)*2*3 ]; texture = new float[(iDiscretization + 1)*2*2 ]; //Creating each square for (unsigned int i = 0; i<(iDiscretization+1) * 6; i+=6) { vertexPosition[i] = iForXCoord * stepX; // X1 vertexPosition[i+1] = j * stepY; // Y1 vertexPosition[i+2] = 0; vertexPosition[i+3] = iForXCoord * stepX; // X2 vertexPosition[i+4] = (j+1) * stepY; // Y2 vertexPosition[i+5] = 0; normal[i] = 0; // X1 normal[i+1] = 0; // Y1 normal[i+2] = 1; // Z1 normal[i+3] = 0; // X2 normal[i+4] = 0; // Y2 normal[i+5] = 1; // Z2 ++iForXCoord; } iForXCoord = 0; //For the texture coordinate (only 2 axes) for (unsigned int i = 0; i<(iDiscretization+1) * 4; i+=4) { texture[i] = static_cast<float>(iForXCoord * stepX) / static_cast<float>(m_iWidth); // X1 texture[i+1] = static_cast<float>(j * stepY) / static_cast<float>(m_iHeight); // Y1 texture[i+2] = static_cast<float>(iForXCoord * stepX) / static_cast<float>(m_iWidth); // X2 texture[i+3] = static_cast<float>((j+1) * stepY) / static_cast<float>(m_iHeight); // Y2 ++iForXCoord; } iForXCoord = 0; m_pStripes.push_back( new HeightMapStripe( ((iDiscretization +1)*2),vertexPosition ,normal,texture,NULL) ); } } void Plan::draw() { for (std::vector<HeightMapStripe*>::iterator iter = m_pStripes.begin(); iter != m_pStripes.end(); ++iter) (*iter)->draw(); }
[ [ [ 1, 95 ] ] ]
d74bbf936ecd4242e7405cbd2ed6ac283072cd19
12d558835322c0beafeeff98f99729aa7ee1a205
/QuartoApp/src/main.cpp
8f78da2220158dbc21677ecbb97af1e49db3d584
[]
no_license
douglyuckling/quarto
b3fae27a9e06be774dd4f12bf9cef67dada3b201
fc493b83c8c7a6964c334b32281850d1c659b394
refs/heads/master
2020-12-30T10:36:33.716568
2010-07-09T04:48:33
2010-07-09T04:48:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
/** * @file main.cpp */ #include "QuartoApp.hpp" using quarto::QuartoApp; /** Entry point for the program */ int main(int argc, char **argv) { QuartoApp app; app.run(); return 0; }
[ "douglyuckling@483a7388-aa76-4cae-9b69-882d6fd7d2f9" ]
[ [ [ 1, 15 ] ] ]
5b2b2387ecc67f4a8208f23835a3932ba6d20d9f
975d45994f670a7f284b0dc88d3a0ebe44458a82
/cliente/Source/HudSkin/CHudImageSkin.cpp
f53c20f7a93123af8b27dcc35034e51698fa029d
[]
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
UTF-8
C++
false
false
13,948
cpp
#include "CHudImageSkin.h" #include "IVideoDriver.h" #include "ITexture.h" #include "rect.h" using namespace irr; using namespace io; using namespace gui; using namespace core; using namespace video; namespace irr { //! Workaround for a bug in IVideoDriver::draw2DImage( ITexture* tex, rect<s32> dstRect, rect<s32> srcRect, rect<s32>* clip, SColor* colors, bool alpha ) //! It modifies dstRect and srcRect so the resulting dstRect is entirely inside the clipping rect. //! srcRect is scaled so the same part of the image is displayed. //! Returns false if dstRect is entirely outside clip, or true if at least some of it is inside. inline bool clipRects( rect<s32>& dstRect, rect<s32>& srcRect, const rect<s32>& clip ) { // Clip left side if ( dstRect.UpperLeftCorner.X < clip.UpperLeftCorner.X ) { s32 w = clip.UpperLeftCorner.X - dstRect.UpperLeftCorner.X; f32 percentRemoved = (f32)w / (f32)dstRect.getWidth(); dstRect.UpperLeftCorner.X = clip.UpperLeftCorner.X; srcRect.UpperLeftCorner.X += (s32)(percentRemoved * srcRect.getWidth()); } // Clip top side if ( dstRect.UpperLeftCorner.Y < clip.UpperLeftCorner.Y ) { s32 w = clip.UpperLeftCorner.Y - dstRect.UpperLeftCorner.Y; f32 percentRemoved = (f32)w / (f32)dstRect.getHeight(); dstRect.UpperLeftCorner.Y = clip.UpperLeftCorner.Y; srcRect.UpperLeftCorner.Y += (s32)(percentRemoved * srcRect.getHeight()); } // Clip right side if ( dstRect.LowerRightCorner.X > clip.LowerRightCorner.X ) { s32 w = dstRect.LowerRightCorner.X - clip.LowerRightCorner.X; f32 percentRemoved = (f32)w / (f32)dstRect.getWidth(); dstRect.LowerRightCorner.X = clip.LowerRightCorner.X; srcRect.LowerRightCorner.X -= (s32)(percentRemoved * srcRect.getWidth()); } // Clip bottom side if ( dstRect.LowerRightCorner.Y > clip.LowerRightCorner.Y ) { s32 w = dstRect.LowerRightCorner.Y - clip.LowerRightCorner.Y; f32 percentRemoved = (f32)w / (f32)dstRect.getHeight(); dstRect.LowerRightCorner.Y = clip.LowerRightCorner.Y; srcRect.LowerRightCorner.Y -= (s32)(percentRemoved * srcRect.getHeight()); } return ( dstRect.getWidth() > 0 && dstRect.getHeight() > 0 ); } namespace gui { CHudImageSkin::CHudImageSkin( IVideoDriver* driver, IGUISkin* fallbackSkin ) { VideoDriver = driver; FallbackSkin = fallbackSkin; FallbackSkin->grab(); } CHudImageSkin::~CHudImageSkin() { FallbackSkin->drop(); } void CHudImageSkin::loadConfig( const SImageGUISkinConfig& config ) { Config = config; } SColor CHudImageSkin::getColor(EGUI_DEFAULT_COLOR color) const { if ( color == EGDC_ACTIVE_CAPTION || color == EGDC_INACTIVE_CAPTION || color == EGDC_TOOLTIP ) { return SColor(255,0,0,0); } return FallbackSkin->getColor(color); } void CHudImageSkin::setColor( EGUI_DEFAULT_COLOR which, SColor newColor ) { FallbackSkin->setColor(which, newColor); } s32 CHudImageSkin::getSize(EGUI_DEFAULT_SIZE size) const { return FallbackSkin->getSize(size); } const wchar_t* CHudImageSkin::getDefaultText(EGUI_DEFAULT_TEXT text) const { return FallbackSkin->getDefaultText(text); } void CHudImageSkin::setDefaultText(EGUI_DEFAULT_TEXT which, const wchar_t* newText) { FallbackSkin->setDefaultText(which, newText); } void CHudImageSkin::setSize(EGUI_DEFAULT_SIZE which, s32 size) { FallbackSkin->setSize(which, size); } IGUIFont* CHudImageSkin::getFont(EGUI_DEFAULT_FONT defaultFont) const { return FallbackSkin->getFont(defaultFont); } void CHudImageSkin::setFont(IGUIFont* font, EGUI_DEFAULT_FONT defaultFont) { FallbackSkin->setFont(font, defaultFont); } IGUISpriteBank* CHudImageSkin::getSpriteBank() const { return FallbackSkin->getSpriteBank(); } void CHudImageSkin::setSpriteBank( IGUISpriteBank* bank ) { FallbackSkin->setSpriteBank(bank); } u32 CHudImageSkin::getIcon( EGUI_DEFAULT_ICON icon ) const { return FallbackSkin->getIcon(icon); } void CHudImageSkin::setIcon( EGUI_DEFAULT_ICON icon, u32 index ) { FallbackSkin->setIcon(icon, index); } void CHudImageSkin::draw3DButtonPaneStandard( IGUIElement* element, const rect<s32>& rect, const core::rect<s32>* clip ) { if ( !Config.Button.Texture ) { FallbackSkin->draw3DButtonPaneStandard( element, rect, clip ); return; } drawElementStyle( Config.Button, rect, clip ); } void CHudImageSkin::draw3DButtonPanePressed( IGUIElement* element, const core::rect<s32>& rect, const core::rect<s32>* clip ) { if ( !Config.Button.Texture ) { FallbackSkin->draw3DButtonPanePressed( element, rect, clip ); return; } drawElementStyle( Config.ButtonPressed, rect, clip ); } void CHudImageSkin::draw3DSunkenPane(IGUIElement* element, SColor bgcolor, bool flat, bool fillBackGround, const core::rect<s32>& rect, const core::rect<s32>* clip) { if ( !Config.SunkenPane.Texture ) { FallbackSkin->draw3DSunkenPane(element, bgcolor, flat, fillBackGround, rect, clip); return; } drawElementStyle( Config.SunkenPane, rect, clip ); } core::rect<s32> CHudImageSkin::draw3DWindowBackground(IGUIElement* element, bool drawTitleBar, SColor titleBarColor, const core::rect<s32>& rect, const core::rect<s32>* clip) { if ( !Config.Window.Texture ) { return FallbackSkin->draw3DWindowBackground(element, drawTitleBar, titleBarColor, rect, clip ); } drawElementStyle( Config.Window, rect, clip ); return core::rect<s32>( rect.UpperLeftCorner.X+Config.Window.DstBorder.Left, rect.UpperLeftCorner.Y, rect.LowerRightCorner.X-Config.Window.DstBorder.Right, rect.UpperLeftCorner.Y+Config.Window.DstBorder.Top ); } void CHudImageSkin::draw3DMenuPane(IGUIElement* element, const core::rect<s32>& rect, const core::rect<s32>* clip) { FallbackSkin->draw3DMenuPane(element,rect,clip); } void CHudImageSkin::draw3DToolBar(IGUIElement* element, const core::rect<s32>& rect, const core::rect<s32>* clip) { FallbackSkin->draw3DToolBar(element,rect,clip); } void CHudImageSkin::draw3DTabButton(IGUIElement* element, bool active, const core::rect<s32>& rect, const core::rect<s32>* clip, gui::EGUI_ALIGNMENT alignment) { FallbackSkin->draw3DTabButton(element, active, rect, clip); } void CHudImageSkin::draw3DTabBody(IGUIElement* element, bool border, bool background, const core::rect<s32>& rect, const core::rect<s32>* clip, s32 tabHeight, gui::EGUI_ALIGNMENT alignment ) { FallbackSkin->draw3DTabBody(element, border, background, rect, clip); } void CHudImageSkin::drawIcon(IGUIElement* element, EGUI_DEFAULT_ICON icon, const core::position2di position, u32 starttime, u32 currenttime, bool loop, const core::rect<s32>* clip) { FallbackSkin->drawIcon(element,icon,position,starttime,currenttime,loop,clip); } void CHudImageSkin::drawHorizontalProgressBar( IGUIElement* element, const core::rect<s32>& rectangle, const core::rect<s32>* clip, f32 filledRatio, SColor fillColor ) { if ( !Config.ProgressBar.Texture || !Config.ProgressBarFilled.Texture ) { return; } // Draw empty progress bar drawElementStyle( Config.ProgressBar, rectangle, clip ); // Draw filled progress bar on top if ( filledRatio < 0.0f ) filledRatio = 0.0f; else if ( filledRatio > 1.0f ) filledRatio = 1.0f; if ( filledRatio > 0.0f ) { s32 filledPixels = (s32)( filledRatio * rectangle.getSize().Width ); s32 height = rectangle.getSize().Height; core::rect<s32> clipRect = clip? *clip:rectangle; if ( filledPixels < height ) { if ( clipRect.LowerRightCorner.X > rectangle.UpperLeftCorner.X + filledPixels ) clipRect.LowerRightCorner.X = rectangle.UpperLeftCorner.X + filledPixels; filledPixels = height; } core::rect<s32> filledRect = core::rect<s32>( rectangle.UpperLeftCorner.X, rectangle.UpperLeftCorner.Y, rectangle.UpperLeftCorner.X + filledPixels, rectangle.LowerRightCorner.Y ); drawElementStyle( Config.ProgressBarFilled, filledRect, &clipRect, &fillColor ); } } void CHudImageSkin::drawElementStyle( const SImageGUIElementStyle& elem, const core::rect<s32>& rect, const core::rect<s32>* clip, SColor* pcolor ) { core::rect<s32> srcRect; core::rect<s32> dstRect; core::dimension2di tsize = elem.Texture->getSize(); ITexture* texture = elem.Texture; SColor color = elem.Color; if ( pcolor ) color = *pcolor; SColor faceColor = getColor(EGDC_3D_FACE); color.setRed( (u8)(color.getRed() * faceColor.getRed() / 255) ); color.setGreen( (u8)(color.getGreen() * faceColor.getGreen() / 255) ); color.setBlue( (u8)(color.getBlue() * faceColor.getBlue() / 255) ); color.setAlpha( (u8)(color.getAlpha() * faceColor.getAlpha() / 255 ) ); SColor colors [4] = { color, color, color, color }; core::dimension2di dstSize = rect.getSize(); // Scale the border if there is insufficient room SImageGUIElementStyle::SBorder dst = elem.DstBorder; f32 scale = 1.0f; if ( dstSize.Width < dst.Left + dst.Right ) { scale = dstSize.Width / (f32)( dst.Left + dst.Right ); } if ( dstSize.Height < dst.Top + dst.Bottom ) { f32 x = dstSize.Height / (f32)( dst.Top + dst.Bottom ); if ( x < scale ) { scale = x; } } if ( scale < 1.0f ) { dst.Left = (s32)( dst.Left * scale ); dst.Right = (s32)( dst.Right * scale ); dst.Top = (s32)( dst.Top * scale ); dst.Bottom = (s32)( dst.Bottom * scale ); } const SImageGUIElementStyle::SBorder& src = elem.SrcBorder; // Draw the top left corner srcRect = core::rect<s32>( 0, 0, src.Left, src.Top ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X, rect.UpperLeftCorner.Y, rect.UpperLeftCorner.X+dst.Left, rect.UpperLeftCorner.Y+dst.Top ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the top right corner srcRect = core::rect<s32>( tsize.Width-src.Right, 0, tsize.Width, src.Top ); dstRect = core::rect<s32>( rect.LowerRightCorner.X-dst.Right, rect.UpperLeftCorner.Y, rect.LowerRightCorner.X, rect.UpperLeftCorner.Y+dst.Top ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the top border srcRect = core::rect<s32>( src.Left, 0, tsize.Width-src.Right, src.Top ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X+dst.Left, rect.UpperLeftCorner.Y, rect.LowerRightCorner.X-dst.Right, rect.UpperLeftCorner.Y+dst.Top ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the left border srcRect = core::rect<s32>( 0, src.Top, src.Left, tsize.Height-src.Bottom ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X, rect.UpperLeftCorner.Y+dst.Top, rect.UpperLeftCorner.X+dst.Left, rect.LowerRightCorner.Y-dst.Bottom ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the right border srcRect = core::rect<s32>( tsize.Width-src.Right, src.Top, tsize.Width, tsize.Height-src.Bottom ); dstRect = core::rect<s32>( rect.LowerRightCorner.X-dst.Right, rect.UpperLeftCorner.Y+dst.Top, rect.LowerRightCorner.X, rect.LowerRightCorner.Y-dst.Bottom ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the middle section srcRect = core::rect<s32>( src.Left, src.Top, tsize.Width-src.Right, tsize.Height-src.Bottom ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X+dst.Left, rect.UpperLeftCorner.Y+dst.Top, rect.LowerRightCorner.X-dst.Right, rect.LowerRightCorner.Y-dst.Bottom ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the bottom left corner srcRect = core::rect<s32>( 0, tsize.Height-src.Bottom, src.Left, tsize.Height ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X, rect.LowerRightCorner.Y-dst.Bottom, rect.UpperLeftCorner.X+dst.Left, rect.LowerRightCorner.Y ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the bottom right corner srcRect = core::rect<s32>( tsize.Width-src.Right, tsize.Height-src.Bottom, tsize.Width, tsize.Height ); dstRect = core::rect<s32>( rect.LowerRightCorner.X-dst.Right, rect.LowerRightCorner.Y-dst.Bottom, rect.LowerRightCorner.X, rect.LowerRightCorner.Y ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); // Draw the bottom border srcRect = core::rect<s32>( src.Left, tsize.Height-src.Bottom, tsize.Width-src.Right, tsize.Height ); dstRect = core::rect<s32>( rect.UpperLeftCorner.X+dst.Left, rect.LowerRightCorner.Y-dst.Bottom, rect.LowerRightCorner.X-dst.Right, rect.LowerRightCorner.Y ); if ( !clip || clipRects( dstRect, srcRect, *clip ) ) VideoDriver->draw2DImage( texture, dstRect, srcRect, clip, colors, true ); } void CHudImageSkin::draw2DRectangle(IGUIElement* element, const SColor &color, const core::rect<s32>& pos, const core::rect<s32>* clip) { FallbackSkin->draw2DRectangle(element, color, pos, clip); } } }
[ [ [ 1, 385 ] ] ]
ccf99b4b6ff671d39a074752d6bf4e98f5116751
9ab5db1fbf99317fdf9fa327d3aae6e45493e993
/FramebufferBase.h
d7cc8e9960fbc68dbd101f487e5de4c3941af548
[]
no_license
SeanBoocock/simd-optimized-software-triangle-rasterizer
4c68a57da8a99284977252fe9f0c110193290809
abdf88e6871135b3fa2d04a2fd14c96a6fa66b49
refs/heads/master
2021-01-10T15:36:18.363163
2011-10-14T19:39:34
2011-10-14T19:39:34
52,691,253
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
#ifndef FRAMEBUFFER_BASE_H_ #define FRAMEBUFFER_BASE_H_ #include "Pixel.h" class FramebufferBase { public: FramebufferBase(){} virtual ~FramebufferBase(){} /*virtual void PutPixel(PixelBase&& pixel, unsigned int x, unsigned int y, bool directWrite = false) = 0;*/ virtual const float GetWidth() = 0; virtual const float GetHeight() = 0; virtual char* FlushBuffer() = 0; virtual unsigned int GetColorDepth() = 0; virtual void Reset() = 0; virtual void Resize(int xDim, int yDim) = 0; }; #endif
[ [ [ 1, 22 ] ] ]
40bcc124c3feec6ab3540cab10628fd58255d47d
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Halak/UIElement.h
e5e7023620068f5effa06dae97c1a1caf7d6d432
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UTF-8
C++
false
false
665
h
#pragma once #ifndef __HALAK_UIELEMENT_H__ #define __HALAK_UIELEMENT_H__ # include <Halak/FWD.h> # include <Halak/SharedObject.h> # include <Halak/Property.h> # include <Halak/String.h> namespace Halak { class UIElement : public SharedObject { HKThisIsNoncopyableClass(UIElement); public: UIElement(); virtual ~UIElement(); inline const String& GetName() const; inline void SetName(const String& value); private: String name; }; } # include <Halak/UIElement.inl> #endif
[ [ [ 1, 29 ] ] ]
17cd80f9fbad397ef8ae06eb28a862aa68e857fc
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daomax/Common/niutils.h
11fcd6e3e898da486541ec763ecdc15a95e11b40
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,913
h
/********************************************************************** *< FILE: NIUtils.h DESCRIPTION: Miscellaneous Utilities HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once #ifndef _WINDOWS_ # include <windows.h> #endif #include <tchar.h> #include <string> #include <map> #include <vector> #include <list> #include <set> // Max Headers #include <Max.h> #include <strclass.h> #include <color.h> #include "text.h" //#include "utility.h" #ifndef _countof #define _countof(x) (sizeof(x)/sizeof((x)[0])) #endif const unsigned int IntegerInf = 0x7f7fffff; const unsigned int IntegerNegInf = 0xff7fffff; const float FloatINF = *(float*)&IntegerInf; const float FloatNegINF = *(float*)&IntegerNegInf; typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > _tstring; typedef std::vector<_tstring> _tstringlist; typedef std::basic_stringstream<TCHAR, std::char_traits<char>, std::allocator<char> > _tstringstream; //typedef std::map<_tstring, _tstring, ltstr> NameValueCollection; typedef std::pair<_tstring, _tstring> KeyValuePair; typedef std::vector<_tstring> stringlist; typedef std::vector<_tstring> stringvector; #if 0 using std::string; // Case insensitive string equivalence but numbers are sorted together struct NumericStringEquivalence { bool operator()(const TCHAR* s1, const TCHAR* s2) const { return numstrcmp(s1, s2) < 0; } bool operator()(const std::string& s1, const TCHAR* s2) const { return numstrcmp(s1.c_str(), s2) < 0; } bool operator()(const TCHAR* s1, const std::string& s2) const { return numstrcmp(s1, s2.c_str()) < 0; } bool operator()(const std::string& s1, const std::string& s2) const { return numstrcmp(s1.c_str(), s2.c_str()) < 0; } static int numstrcmp(const TCHAR *str1, const TCHAR *str2) { TCHAR *p1, *p2; int c1, c2, lcmp; for(;;) { c1 = tolower(*str1), c2 = tolower(*str2); if ( c1 == 0 || c2 == 0 ) break; else if (isdigit(c1) && isdigit(c2)) { lcmp = strtol(str1, &p1, 10) - strtol(str2, &p2, 10); if ( lcmp == 0 ) lcmp = (p2 - str2) - (p1 - str1); if ( lcmp != 0 ) return (lcmp > 0 ? 1 : -1); str1 = p1, str2 = p2; } else { lcmp = (c1 - c2); if (lcmp != 0) return (lcmp > 0 ? 1 : -1); ++str1, ++str2; } } lcmp = (c1 - c2); return ( lcmp < 0 ) ? -1 : (lcmp > 0 ? 1 : 0); } }; // Common collections that I use typedef std::map<std::string, std::string, ltstr> NameValueCollection; typedef std::pair<std::string, std::string> KeyValuePair; typedef std::vector<std::string> stringlist; typedef std::set<std::string, ltstr> stringset; extern int wildcmp(const TCHAR *wild, const TCHAR *string); extern int wildcmpi(const TCHAR *wild, const TCHAR *string); inline bool strmatch(const string& lhs, const std::string& rhs) { return (0 == _tcsicmp(lhs.c_str(), rhs.c_str())); } inline bool strmatch(const TCHAR* lhs, const std::string& rhs) { return (0 == _tcsicmp(lhs, rhs.c_str())); } inline bool strmatch(const string& lhs, const TCHAR* rhs) { return (0 == _tcsicmp(lhs.c_str(), rhs)); } inline bool strmatch(const TCHAR* lhs, const TCHAR* rhs) { return (0 == _tcsicmp(lhs, rhs)); } bool wildmatch(const TCHAR* match, const TCHAR* value); bool wildmatch(const string& match, const std::string& value); bool wildmatch(const stringlist& matches, const TCHAR* value); bool wildmatch(const stringlist& matches, const std::string& value); #endif // Generic IniFile reading routine template<typename T> inline T GetIniValue(LPCTSTR Section, LPCTSTR Setting, T Default, LPCTSTR iniFileName){ T v = Default; TCHAR buffer[1024]; std::stringstream sstr; sstr << Default; buffer[0] = 0; if (0 < GetPrivateProfileString(Section, Setting, sstr.str().c_str(), buffer, sizeof(buffer), iniFileName)){ std::stringstream sstr(buffer); sstr >> v; return v; } return Default; } // Specific override for int values template<> inline int GetIniValue<int>(LPCTSTR Section, LPCTSTR Setting, int Default, LPCTSTR iniFileName){ return GetPrivateProfileInt(Section, Setting, Default, iniFileName); } // Specific override for int values template<> inline bool GetIniValue<bool>(LPCTSTR Section, LPCTSTR Setting, bool Default, LPCTSTR iniFileName){ return GetPrivateProfileInt(Section, Setting, Default, iniFileName) ? true : false; } // Specific override for string values template<> inline std::string GetIniValue<std::string>(LPCTSTR Section, LPCTSTR Setting, std::string Default, LPCTSTR iniFileName){ TCHAR buffer[1024]; buffer[0] = 0; if (0 < GetPrivateProfileString(Section, Setting, Default.c_str(), buffer, sizeof(buffer), iniFileName)){ return std::string(buffer); } return Default; } // Specific override for TSTR values template<> inline TSTR GetIniValue<TSTR>(LPCTSTR Section, LPCTSTR Setting, TSTR Default, LPCTSTR iniFileName){ TCHAR buffer[1024]; buffer[0] = 0; if (0 < GetPrivateProfileString(Section, Setting, Default.data(), buffer, sizeof(buffer), iniFileName)){ return TSTR(buffer); } return Default; } // Generic IniFile reading routine template<typename T> inline void SetIniValue(LPCTSTR Section, LPCTSTR Setting, T value, LPCTSTR iniFileName){ std::stringstream sstr; sstr << value; WritePrivateProfileString(Section, Setting, sstr.str().c_str(), iniFileName); } // Specific override for string values template<> inline void SetIniValue<std::string>(LPCTSTR Section, LPCTSTR Setting, std::string value, LPCTSTR iniFileName){ WritePrivateProfileString(Section, Setting, value.c_str(), iniFileName); } // Specific override for TSTR values template<> inline void SetIniValue<TSTR>(LPCTSTR Section, LPCTSTR Setting, TSTR value, LPCTSTR iniFileName){ WritePrivateProfileString(Section, Setting, value.data(), iniFileName); } template<> inline void SetIniValue<LPTSTR>(LPCTSTR Section, LPCTSTR Setting, LPTSTR value, LPCTSTR iniFileName){ WritePrivateProfileString(Section, Setting, value, iniFileName); } template<> inline void SetIniValue<LPCTSTR>(LPCTSTR Section, LPCTSTR Setting, LPCTSTR value, LPCTSTR iniFileName){ WritePrivateProfileString(Section, Setting, value, iniFileName); } //extern TSTR FormatTStr(const TCHAR* format,...); extern std::string FormatString(const TCHAR* format,...); extern stringlist TokenizeCommandLine(LPCTSTR str, bool trim); extern _tstring JoinCommandLine(stringlist args); extern _tstring GetIndirectValue(LPCSTR path); extern NameValueCollection ReadIniSection(LPCTSTR Section, LPCTSTR iniFileName); extern _tstring ExpandQualifiers(const _tstring& src, const NameValueCollection& map); extern _tstring ExpandEnvironment(const _tstring& src); extern void ReadEnvironment(LPCTSTR Section, LPCTSTR iniFileName, NameValueCollection& Environment); extern void FindImages(NameValueCollection& images, const _tstring& rootPath, const stringlist& searchpaths, const stringlist& extensions); extern void RenameNode(Interface *gi, LPCTSTR SrcName, LPCTSTR DstName); enum PosRotScale { prsPos = 0x1, prsRot = 0x2, prsScale = 0x4, prsDefault = prsPos | prsRot | prsScale, }; extern void PosRotScaleNode(INode *n, Point3 p, Quat& q, float s, PosRotScale prs = prsDefault, TimeValue t = 0); extern void PosRotScaleNode(Control *c, Point3 p, Quat& q, float s, PosRotScale prs = prsDefault, TimeValue t = 0); extern void PosRotScaleNode(INode *n, Point3 p, Quat& q, Point3 s, PosRotScale prs = prsDefault, TimeValue t = 0); extern void PosRotScaleNode(Control *c, Point3 p, Quat& q, Point3 s, PosRotScale prs = prsDefault, TimeValue t = 0); extern void PosRotScaleNode(INode *n, Matrix3& m3, PosRotScale prs = prsDefault, TimeValue t = 0); extern void PosRotScaleNode(Control *c, Matrix3& m3, PosRotScale prs = prsDefault, TimeValue t = 0); extern Matrix3 GetNodeLocalTM(INode *n, TimeValue t = 0); extern INode* FindINode(Interface *i, const _tstring& name); // Simple conversion helpers Text PrintMatrix3(Matrix3& m); extern Modifier *GetOrCreateSkin(INode *node); extern Modifier *GetSkin(INode *node); extern TriObject* GetTriObject(Object *o); extern Text GetFileVersion(const char *fileName); extern unsigned int ParseVersionString(_tstring version); extern _tstring PrintVersionString(unsigned int version); extern void ExpandFileList( stringlist& list ); extern NameValueCollection Environment; template<typename T> inline T GetSetting(std::string setting){ T v; NameValueCollection::iterator itr = Environment.find(setting); if (itr != Environment.end()){ stringstream sstr((*itr).second); sstr >> v; } return v; } template<> inline std::string GetSetting(std::string setting){ NameValueCollection::iterator itr = Environment.find(setting); if (itr != Environment.end()) return (*itr).second; return std::string(); } template<typename T> inline T GetSetting(std::string setting, T Default){ NameValueCollection::iterator itr = Environment.find(setting); if (itr != Environment.end()){ T v; stringstream sstr((*itr).second); sstr >> v; return v; } return Default; } template<> inline std::string GetSetting(std::string setting, std::string Default){ NameValueCollection::iterator itr = Environment.find(setting); if (itr != Environment.end()) return (*itr).second; return Default; }
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 294 ] ] ]
9dc69e28fcda92ae92f8641348fa146d419ba490
5dc78c30093221b4d2ce0e522d96b0f676f0c59a
/src/modules/sound/wrap_Sound.h
194abf04fe80099877074f6880b815af97f7dd6d
[ "Zlib" ]
permissive
JackDanger/love
f03219b6cca452530bf590ca22825170c2b2eae1
596c98c88bde046f01d6898fda8b46013804aad6
refs/heads/master
2021-01-13T02:32:12.708770
2009-07-22T17:21:13
2009-07-22T17:21:13
142,595
1
0
null
null
null
null
UTF-8
C++
false
false
1,303
h
/** * Copyright (c) 2006-2009 LOVE Development Team * * 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. **/ #ifndef LOVE_SOUND_WRAP_SOUND_H #define LOVE_SOUND_WRAP_SOUND_H // LOVE #include "Sound.h" #include "wrap_SoundData.h" #include "wrap_Decoder.h" namespace love { namespace sound { int _wrap_newSoundData(lua_State * L); int _wrap_newDecoder(lua_State * L); int wrap_Sound_open(lua_State * L); } // sound } // love #endif // LOVE_SOUND_WRAP_SOUND_H
[ "prerude@3494dbca-881a-0410-bd34-8ecbaf855390" ]
[ [ [ 1, 40 ] ] ]
813cc30245a8a4670b354aa38731c4aedd9dd914
8f8cc0ed96d272f1aee79becfc1138538abbefc9
/prototype/bdk/BDK/Data.h
d7cb38c685bcddefd613a768e474763a02b33185
[]
no_license
BackupTheBerlios/picdatcom-svn
0a417abb3b60df6aedb47c0eb52998d262e459b7
0696c6d6e0c7158ede88908257abea0e0a7e303c
refs/heads/master
2016-09-02T07:52:18.882862
2010-06-10T22:43:50
2010-06-10T22:43:50
40,800,263
0
0
null
null
null
null
UTF-8
C++
false
false
6,138
h
// Data.h // // This header file defines the interfaces to the class Data // // This file was generate from a Dia Diagram using the xslt script file dia-uml2cpp.xsl // which is copyright(c) Dave Klotzbach <[email protected]> // // The author asserts no additional copyrights on the derived product. Limitations // on the uses of this file are the right and responsibility of authors of the source // diagram. // // The dia-uml2cpp.xsl script 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. // // A copy of the GNU General Public License is available by writing to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, // MA 02111-1307, USA. // #ifndef __DATA_H__ #define __DATA_H__ #include <iostream> #include <cstdlib> #include "Arithmetic_entropy_encoder.h" #include "Arithmetic_entropy_decoder.h" #include "Filter97_decoder.h" #include "Filter97_encoder.h" using namespace std; namespace BDK { #define SIGNIFICANT_BIT 0x0100 #define ISCODED_BIT 0x0200 #define REFINEMENT_BIT 0x0400 #define D0_BIT 0x0080 #define D1_BIT 0x0040 #define D2_BIT 0x0020 #define D3_BIT 0x0010 #define H0_BIT 0x0008 #define H1_BIT 0x0004 #define V0_BIT 0x0002 #define V1_BIT 0x0001 #define H0_sign_BIT 0x8000 #define H1_sign_BIT 0x4000 #define V0_sign_BIT 0x2000 #define V1_sign_BIT 0x1000 #define SIGN_BIT 0x80000000 #define UNIFORM (unsigned char)0 #define RUNLENGTH (unsigned char)1 #define MAGNITUT_STATE1 (unsigned char)16 #define MAGNITUT_STATE2 (unsigned char)17 #define MAGNITUT_STATE3 (unsigned char)18 #define BITSTUFFING false typedef enum{SIGNIFICANCE_PROPAGATION_DECODING_PASS, MAGNITUDE_REFINEMENT_DECODING_PASS, CLEANUP_DECODING_PASS}Decodepass; class Data{ private: public: virtual ~Data(); private: unsigned __int16* state;// |H0 sign | H1 sign | V0 sign | V1 sign | X | refinement | iscoded | significant |D0|D1|D2|D3|H0|H1|V0|V1 unsigned int work_bitplane;// The next coding pass work on this bitplane unsigned int numb_bitplane; Decodepass decodepass; unsigned int nr_passes; Arithmetic_entropy_encoder *encoder; Arithmetic_entropy_decoder *decoder; bool initdecoder; ByteBuffer *codeword; //unsigned int pos_buffer; static unsigned char state_propagation[3][256]; static unsigned char state_signbit[256]; static unsigned char state_XORBit[256]; bool evenH, evenV; unsigned int SETBIT1; unsigned int SETBIT2; unsigned int UNSETBIT; public: ByteBuffer *d_buffer; ByteBuffer *cx_buffer; void* free_pointer;// If the memory free the free_pointer is used. float* data_float;// Use the date as float __int32* data_int;// Use the data as integer. unsigned __int32* data_uint; unsigned int total_size; unsigned int start_pointer; unsigned int end_pointer; unsigned int line_feed; unsigned int nr_subband; unsigned int total_sizeX;// The size of the complete memory area. unsigned int total_sizeY;// The size of the complete memory area. unsigned int work_x0;// Size of the working area. unsigned int work_x1;// Size of the working area. unsigned int work_y0;// Size of the working area. unsigned int work_y1;// Size of the working area. unsigned int size_x; unsigned int size_y; bool free_void;// If true, free the free_pointer with this deconstructor. int maximumValue_int; private: void significance_propagation_encoding_pass(); void significance_propagation_decoding_pass(); void sign_bit_encoding(); void sign_bit_decoding(); void magnitude_refinement_encoding_pass(); void magnitude_refinement_decoding_pass(); void cleanup_encoding_pass(); void cleanup_decoding_pass(); void set_state_zero(); void reset_is_coded(); void set_state(unsigned int sign,unsigned int x, unsigned int y, unsigned int run_pointer, unsigned int offset_D0, unsigned int offset_D1, unsigned int offset_D2, unsigned int offset_D3, unsigned int offset_H0, unsigned int offset_H1, unsigned int offset_V0, unsigned int offset_V1); void initDate(unsigned int sizeX, unsigned int sizeY, unsigned int x0, unsigned int x1, unsigned int y0, unsigned int y1); void initDate(Data *data, unsigned int x0, unsigned int x1, unsigned int y0, unsigned int y1); int npasses; public: Data(unsigned int sizeX, unsigned int sizeY); Data(unsigned int sizeX, unsigned int sizeY, unsigned int x0, unsigned int x1, unsigned int y0, unsigned int y1); Data(Data *data, unsigned int x0, unsigned int x1, unsigned int y0, unsigned int y1); void random_fill(); void random_fill_float(); void zero_fill(); void start_encode_Coefficient_bit_modeling(); void start_decode_Coefficient_bit_modeling(); void start_decode_Coefficient_bit_modeling(int passes); void inttocustomint(); void custominttoint(); void showData(); void showData_float(); void setmaximumValue(); void setnumb_bitplane(); void initBuffer(); void initBuffer(ByteBuffer*); void set_numb_bitplane(unsigned int); unsigned int get_numb_bitplane(); void set_subband(unsigned int); void compare(Data *); void fill_buffer(unsigned char* buffer, unsigned int width, unsigned int height); void setdecoder(ByteBuffer *codeword); void customint_to_float(float deltab); void filter_encode(Filter97_encoder *encoder); void filter_decode(Filter97_decoder *decoder); void set_even(int h, int v); void fill_RGBbuffer_Y(unsigned char* buffer); void fill_RGBbuffer_Cr(unsigned char* buffer); void fill_RGBbuffer_Cb(unsigned char* buffer); static void fill_RGBbuffer(Data *dataY, Data *dataCb, Data *dataCr, unsigned char *buffer); }; } #endif // defined __DATA_H__
[ "uwebr@161c6524-834b-0410-aead-e7223efaf009" ]
[ [ [ 1, 182 ] ] ]
fff197903b0c56733fdd9b7b71e6d53ffdf9873e
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/diroutln.hpp
7990627cdd7264df7cdecfbd0931528ba20fb1bf
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
4,768
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'DirOutln.pas' rev: 6.00 #ifndef DirOutlnHPP #define DirOutlnHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Menus.hpp> // Pascal unit #include <StdCtrls.hpp> // Pascal unit #include <Grids.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Outline.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Diroutln { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TTextCase { tcLowerCase, tcUpperCase, tcAsIs }; #pragma option pop typedef AnsiString __fastcall (*TCaseFunction)(const AnsiString AString); class DELPHICLASS TDirectoryOutline; class PASCALIMPLEMENTATION TDirectoryOutline : public Outline::TCustomOutline { typedef Outline::TCustomOutline inherited; private: char FDrive; AnsiString FDirectory; Classes::TNotifyEvent FOnChange; TTextCase FTextCase; TCaseFunction FCaseFunction; protected: void __fastcall SetDrive(char NewDrive); void __fastcall SetDirectory(const AnsiString NewDirectory); void __fastcall SetTextCase(TTextCase NewTextCase); void __fastcall AssignCaseProc(void); virtual void __fastcall BuildOneLevel(int RootItem); virtual void __fastcall BuildTree(void); virtual void __fastcall BuildSubTree(int RootItem); virtual void __fastcall Change(void); DYNAMIC void __fastcall Click(void); virtual void __fastcall CreateWnd(void); DYNAMIC void __fastcall Expand(int Index); int __fastcall FindIndex(Outline::TOutlineNode* RootNode, AnsiString SearchName); virtual void __fastcall Loaded(void); void __fastcall WalkTree(const AnsiString Dest); public: __fastcall virtual TDirectoryOutline(Classes::TComponent* AOwner); AnsiString __fastcall ForceCase(const AnsiString AString); __property char Drive = {read=FDrive, write=SetDrive, nodefault}; __property AnsiString Directory = {read=FDirectory, write=SetDirectory}; __property Lines = {stored=false}; __published: __property Align = {default=0}; __property Anchors = {default=3}; __property BorderStyle = {default=1}; __property Color = {default=-2147483643}; __property Constraints ; __property Ctl3D ; __property DragCursor = {default=-12}; __property DragKind = {default=0}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property ItemHeight ; __property Options = {default=6}; __property ParentColor = {default=0}; __property ParentCtl3D = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PictureClosed ; __property PictureLeaf ; __property PictureOpen ; __property PopupMenu ; __property ScrollBars = {default=3}; __property Style = {default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property TTextCase TextCase = {read=FTextCase, write=SetTextCase, default=0}; __property Visible = {default=1}; __property Classes::TNotifyEvent OnChange = {read=FOnChange, write=FOnChange}; __property OnClick ; __property OnCollapse ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnDrawItem ; __property OnEndDock ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnExpand ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDock ; __property OnStartDrag ; public: #pragma option push -w-inl /* TCustomOutline.Destroy */ inline __fastcall virtual ~TDirectoryOutline(void) { } #pragma option pop public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TDirectoryOutline(HWND ParentWindow) : Outline::TCustomOutline(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE bool __fastcall SameLetter(char Letter1, char Letter2); } /* namespace Diroutln */ using namespace Diroutln; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // DirOutln
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 143 ] ] ]
465f23919778a748e262995c3d6f73044972a583
e7c45d18fa1e4285e5227e5984e07c47f8867d1d
/SMDK/RTTS/TS/OSM_type.cpp
be54dd6155e59966ebd1ebb8b044b586b56ca77f
[]
no_license
abcweizhuo/Test3
0f3379e528a543c0d43aad09489b2444a2e0f86d
128a4edcf9a93d36a45e5585b70dee75e4502db4
refs/heads/master
2021-01-17T01:59:39.357645
2008-08-20T00:00:29
2008-08-20T00:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,686
cpp
//-- OSM_type.cpp ----------------------------------------------------------- // // Classes Implemented // // OSM_Type // OSM_HasType // // History: // // 31/01/2000 First version. // David T. // // 08/02/2000 Class name changes to avoid confusion between typing // David T. of OSM objects (for mutual compatibility) and Stream: // - OSM_Type (was StreamType) manages material properties // of multiple OSM objects in the current analysis // - OSM_HasType (was HasStreamType) brands an object // with a reference to its relevant OSM_Type) // // 09/02/2000 - Split OSM_type.cpp from OSM.cpp to separate the // David T. OSM basic type classes from the OSM Stream classes. // //-- External Definitions --------------------------------------------------- #include "stdafx.h" #include <stdlib.h> #include <math.h> #include "OSM.h" //--------------------------------------------------------------------------- // // OSM_Type IMPLEMENTATION // // Manages information associated with a type of stream // classification. Specifically looks after the number // of ore components represented by streams, the number // size fractions in the size distribution of each ore // component, and the sieve and nominal sizes of each // size fraction in those distributions. // // Sizing format is fractional %retained, with the first // fraction being the coarsest. It is assumed that the // smallest sieve size specified is zero, ie that the // finest size fraction is an undersize fraction. // // Members Defined: // // OSM_Type( ) // ~OSM_Type( ) // void setSizes( int, double* ) // void setSizes( OSM_Vector& ) // void makeNominalSizes( ) // //-- Uninitialized OSM_Type ------------------------------------------------- OSM_Type::OSM_Type( ) { numSize = 0; numComp = 0; } //-- Deallocate OSM_Type ---------------------------------------------------- OSM_Type::~OSM_Type( ) { /* void */ } //-- Set OSM_Type size distribution, specifying array of sieve numbers ------ void OSM_Type::setSizes( int numSizes, double* buffer ) { numSize = numSizes; sieveVec.dimension( numSizes, buffer ); makeNominalSizes( ); } //-- Set size distribution specifying Vector of sieve sizes ----------------- void OSM_Type::setSizes( OSM_Vector& sieveSizes ) { numSize = sieveSizes.count(); sieveVec = sieveSizes; makeNominalSizes( ); } //-- Create vector of nominal sizes from the current sieve sizes ------------ void OSM_Type::makeNominalSizes( ) { int count = sieveVec.count(); // Number of size fractions nominalVec.dimension( count ); // Resize nominal size Vector for( int size=0; size<count; size++ ) { if( size==0 ) { // Coarsest size nominalVec[size] // assume equal to sieve = sieveVec[size] * pow(2.0,0.25); // size * 2^(1/4) } else if( size==count-1 && size>=0 ) { // Finest size nominalVec[size] // assume half finest sieve = sieveVec[size-1] / 2; } else { // Intermediate sizes nominalVec[size] = sqrt( // use geometric mean size sieveVec[size-1] * sieveVec[size] ); } } } //--------------------------------------------------------------------------- // // OSM_HasType IMPLEMENTATION // // Represents the property of an object needing to know particular // OSM_Type properties. e.g. streams and connected models need to // agree on the number of components and size fractions represented. // Objects which inherit OSM_HasType and specify the same OSM_Type to // OSM_HasType() constructor will refer to the OSM_Type object, and // will agree on OSM_Type properties. // // OSM_HasType acts as a proxy to the specified remote OSM_Type // object by reimplementing much of the OSM_Type interface. // // Members Defined: // // OSM_HasType( StreamType& ) // ~OSM_HasType( ) // //-- Initialize with StreamType --------------------------------------------- OSM_HasType::OSM_HasType( OSM_Type& sType ) : myType( sType ) { /* void */ } //-- Deallocate ------------------------------------------------------------- OSM_HasType::~OSM_HasType( ) { /* void */ } //-- end OSM_type.cpp -------------------------------------------------------
[ [ [ 1, 158 ] ] ]
50936ea228a9ecde5dfba4d22e791b792e7f5997
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/mw/classicui/uifw/apps/S60_SDK3.0/bctestscreenclearer/src/bctestscreenclearerappui.cpp
c5fe32f9d7b4e703bff137973ae595e22d3ebb93
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
2,324
cpp
/* * Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: test bc for screenclearer control api(s) * */ #include <avkon.hrh> #include <aknsutils.h> #include "bctestscreenclearerappui.h" #include "bctestscreenclearer.hrh" #include "bctestscreenclearerview.h" // ======== MEMBER FUNCTIONS ======== // --------------------------------------------------------------------------- // ctro do nothing // --------------------------------------------------------------------------- // CBCTestScreenClearerAppUi::CBCTestScreenClearerAppUi() { } // --------------------------------------------------------------------------- // symbian 2nd phase ctor // --------------------------------------------------------------------------- // void CBCTestScreenClearerAppUi::ConstructL() { BaseConstructL(); AknsUtils::SetAvkonSkinEnabledL( ETrue ); // init view CBCTestScreenClearerView* view = CBCTestScreenClearerView::NewL(); CleanupStack::PushL( view ); AddViewL( view ); CleanupStack::Pop( view ); ActivateLocalViewL( view->Id() ); } // ---------------------------------------------------------------------------- // CBCTestScreenClearerAppUi::~CBCTestScreenClearerAppUi() // Destructor. // ---------------------------------------------------------------------------- // CBCTestScreenClearerAppUi::~CBCTestScreenClearerAppUi() { } // ---------------------------------------------------------------------------- // handle menu command events // ---------------------------------------------------------------------------- // void CBCTestScreenClearerAppUi::HandleCommandL( TInt aCommand ) { switch ( aCommand ) { case EAknSoftkeyBack: case EEikCmdExit: { Exit(); return; } default: break; } }
[ "none@none" ]
[ [ [ 1, 81 ] ] ]
9f1f5fc3eb9b2869079b6aa97f9f7dfcba84efae
ea2786bfb29ab1522074aa865524600f719b5d60
/MultimodalSpaceShooter/src/input/MultimodalManager.cpp
138eb6be8c663b7a4f1a3d2cc080c1fbb04d64ec
[]
no_license
jeremysingy/multimodal-space-shooter
90ffda254246d0e3a1e25558aae5a15fed39137f
ca6e28944cdda97285a2caf90e635a73c9e4e5cd
refs/heads/master
2021-01-19T08:52:52.393679
2011-04-12T08:37:03
2011-04-12T08:37:03
1,467,691
0
1
null
null
null
null
UTF-8
C++
false
false
2,578
cpp
#include "input/MultimodalManager.h" MultimodalManager::MultimodalManager() : myTrackingState(Tracking::NotInitialized) { myGestureManager.initialize(); if(sf::SoundRecorder::IsAvailable()) myVolumeRecorder.Start(11025); } MultimodalManager::~MultimodalManager() { myGestureManager.stopTracking(); myVolumeRecorder.Stop(); } void MultimodalManager::addListener(MultimodalListener* listener) { if(listener) myListeners.insert(listener); } void MultimodalManager::removeListener(MultimodalListener* listener) { myListeners.erase(listener); } bool MultimodalManager::isMultimodalityAvailable() { return myGestureManager.getState() != Tracking::NotInitialized && sf::SoundRecorder::IsAvailable(); } void MultimodalManager::startTracking() { myGestureManager.startTracking(); } Tracking::State MultimodalManager::getTrackingState() { return myGestureManager.getState(); } void MultimodalManager::update() { // Send notifications of volume changed if(myVolumeRecorder.hasLevelIncreased()) { Multimodal::Event event = Multimodal::VolumeChangedArmDown; if(myGestureManager.getRightHandPosition().y < myGestureManager.getBodyPosition().y) event = Multimodal::VolumeChangedArmUp; // Send other multimodal event to the listeners for(std::set<MultimodalListener*>::iterator i = myListeners.begin(); i != myListeners.end(); ++i) { (*i)->onMultimodalEvent(event); } } // Send notifications of gesture tracking state changed if(myGestureManager.getState() != myTrackingState) { myTrackingState = myGestureManager.getState(); // Send event to the listeners for(std::set<MultimodalListener*>::iterator i = myListeners.begin(); i != myListeners.end(); ++i) { (*i)->onTrackingStateChanged(myTrackingState); } } } const sf::Vector2f& MultimodalManager::getBodyPosition() const { return myGestureManager.getBodyPosition(); } const sf::Vector2f& MultimodalManager::getLeftHandPosition() const { return myGestureManager.getLeftHandPosition(); } const sf::Vector2f& MultimodalManager::getRightHandPosition() const { return myGestureManager.getRightHandPosition(); } float MultimodalManager::getMicroVolume() const { return myVolumeRecorder.getVolume(); } Volume::Level MultimodalManager::getMicroLevel() const { return myVolumeRecorder.getLevel(); }
[ [ [ 1, 97 ] ] ]
a5ae1df659098465dffb78cf3e03eaeabc08c61e
ffadac985f616b08e142033e7acb1aa240f82fd4
/src/Vector3.cpp
676ecb2f10b8b2a52a6dc35ef24b937a6590b3f3
[]
no_license
jfischoff/obido_math
9184aea6e975db4164b6e973d0e4fd5b21d024ba
5b892bf5c0615912613ef9719cb4e9944ab2c444
refs/heads/master
2016-09-06T06:18:49.577093
2011-10-11T14:53:37
2011-10-11T14:53:37
2,555,941
0
0
null
null
null
null
UTF-8
C++
false
false
4,969
cpp
#include "Vector3.h" #include <assert.h> #include <stdlib.h> #include <iostream> #include <assert.h> #include <float.h> #include <limits.h> using namespace std; void* Vector3::Constructor() { return new Vector3(); } Vector3::Vector3(Float x, Float y, Float z) { m_X = x; m_Y = y; m_Z = z; assert(isValid()); } Vector3::Vector3(const Vector2& vec2) { m_X = vec2.getX(); m_Y = vec2.getY(); m_Z = 0; assert(isValid()); } Vector3::Vector3() { m_X = 0.0; m_Y = 0.0; m_Z = 0.0; assert(isValid()); } Vector3::Vector3(const Vector3& other) { copy(other); assert(isValid()); } Vector3& Vector3::operator=(const Vector3& other) { copy(other); assert(isValid()); return *this; } void Vector3::copy(const Vector3& other) { m_X = other.m_X; m_Y = other.m_Y; m_Z = other.m_Z; assert(isValid()); } Vector3 Vector3::Zero() { return Vector3(); } bool Vector3::operator==(const Vector3& other) const { if(m_X == other.m_X && m_Y == other.m_Y && m_Z == other.m_Z) { return true; } else { return false; } } Float Vector3::getX() const { return m_X; } Float Vector3::getY() const { return m_Y; } Float Vector3::getZ() const { return m_Z; } void Vector3::setX(Float x) { m_X = x; assert(isValid()); } void Vector3::setY(Float y) { m_Y = y; assert(isValid()); } void Vector3::setZ(Float z) { m_Z = z; assert(isValid()); } Float Vector3::getIndex(int index) const { switch(index) { case 0: return m_X; case 1: return m_Y; case 2: return m_Z; } assert(0); return -1; } void Vector3::setIndex(int index, Float value) { switch(index) { case 0: m_X = value; return; case 1: m_Y = value; return; case 2: m_Z = value; return; } assert(isValid()); } Float Vector3::mag() const { return sqrt(m_X*m_X + m_Y*m_Y + m_Z*m_Z); } Vector3 Vector3::normalize() const { float m = mag(); Vector3 result(*this); if(m == 0) return result; result.m_X /= m; result.m_Y /= m; result.m_Z /= m; return result; } Vector3 Vector3 ::Cross(const Vector3& left, const Vector3& right) { Vector3 output; output.setX(left.getY()*right.getZ() - left.getZ()*right.getY()); output.setY(left.getZ()*right.getX() - left.getX()*right.getZ()); output.setZ(left.getX()*right.getY() - left.getY()*right.getX()); return output; } Float Vector3::angle(const Vector3& right) const { Float dotP = dot(right); Float angle = 0.0; if(dotP >= 1.0) { angle = 0; } else { angle = acos(dotP); } return angle; } Float Vector3::dot(const Vector3& right) const { return getX()*right.getX() + getY()*right.getY() + getZ()*right.getZ(); } float Vector3::operator*(const Vector3& right) const { return dot(right); } Vector3 Vector3::subtract(const Vector3& right) const { return Vector3(getX() - right.getX(), getY() - right.getY(), getZ() - right.getZ()); } Vector3 Vector3::operator+(const Vector3& right) const { return add(right); } Vector3 Vector3::add(const Vector3& right) const { return Vector3(getX() + right.getX(), getY() + right.getY(), getZ() + right.getZ()); } Vector3 Vector3::operator-(const Vector3& right) const { return subtract(right); } Vector3& Vector3::operator-=(const Vector3& right) { *this = subtract(right); return *this; } Float Vector3::distance(const Vector3& right) const { return (subtract(right)).mag(); } Vector3 Vector3::scale(double scale) const { return Vector3(getX() * scale, getY() * scale, getZ() * scale); } Vector3 Vector3::operator*(double scale) const { return Vector3::scale(scale); } Vector3 Vector3::operator/(double scale) const { return Vector3::scale(1.0 / scale); } bool Vector3::almostEqual(const Vector3& right) const { const Vector3& left = *this; const double epsilon = 0.000001; if(fabs(left.getX() - right.getX()) < epsilon && fabs(left.getY() - right.getY()) < epsilon && fabs(left.getZ() - right.getZ()) < epsilon) { return true; } else { return false; } } Vector3 Vector3::invert() const { Vector3 result; result.m_X *= -1; result.m_Y *= -1; result.m_Z *= -1; return result; } void Vector3::arbitrary() { *this = Vector3(((float)rand() / (float)INT_MAX) * 10.0, ((float)rand() / (float)INT_MAX) * 10.0, ((float)rand() / (float)INT_MAX) * 10.0); assert(isValid()); } bool Vector3::isValid() { if(isnan(m_X) == false && isnan(m_Y) == false && isnan(m_Z) == false) { return true; } else { return false; } }
[ [ [ 1, 300 ] ] ]
495fc9a41d923a435e17945d94cd4dc1805cf47e
9e4a5ffa0cdd3556730f82ffc4fe73c0d360ec8a
/Ray.h
78a96e6439bbbc2564db1702178fef4f83e426e7
[]
no_license
ANorwell/Graphics
fde4e946ab2d6f3cd7ddc6daab1a847a49665475
bbe73045b1fc83c2704a1881a7dd336f94388722
refs/heads/master
2021-01-19T13:53:07.549762
2010-09-06T04:49:02
2010-09-06T04:49:02
890,587
3
0
null
null
null
null
UTF-8
C++
false
false
167
h
#include "Vec.h" #include "TriangleMesh.h" class Ray { Vec start; Vec end; Ray(Vec s, Vec e) start(s), end(e) {}; intersect( TriangleFace face); }
[ [ [ 1, 11 ] ] ]
93cd7a9130b23b2bc6eaf0ddf396666f93625016
6dac9369d44799e368d866638433fbd17873dcf7
/src/branches/01032005/include/graphics/SceneGraphDB.h
b333a501ff403f538dc77da450d9d9017ef0a6aa
[]
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
708
h
#ifndef _SCENEGRAPHDB_H_ #define _SCENEGRAPHDB_H_ #include <graphics/SceneGraph.h> class SceneGraphDB: public FusionSubsystem{ protected: scenelist_t m_scenes; SceneGraph *m_scene_active; public: SceneGraphDB (); virtual ~SceneGraphDB (); virtual bool Initialise (void); virtual SceneGraph * operator[] (unsigned int index); virtual SceneGraph * AddScene (void); virtual void ReleaseAllScenes (void); virtual void ReleaseScene (unsigned int index); virtual void ActivateScene (unsigned int index); virtual void ActivateScene (SceneGraph *scene); virtual bool RenderScene (void); }; #endif // #ifndef _SCENEGRAPHDB_H_
[ "chris_a_thomas@1bf15c89-c11e-0410-aefd-b6ca7aeaabe7" ]
[ [ [ 1, 29 ] ] ]
48d77c42e04d7a59bb650d010827eed13d1a48e1
9e2c39ce4b2a226a6db1f5a5d361dea4b2f02345
/tools/LePlatz/DataModel/DataStructs/BgMutable.h
d4e9182b5b9cdc1f4606442ebc0020f235b81a34
[]
no_license
gonzalodelgado/uzebox-paul
38623933e0fb34d7b8638b95b29c4c1d0b922064
c0fa12be79a3ff6bbe70799f2e8620435ce80a01
refs/heads/master
2016-09-05T22:24:29.336414
2010-07-19T07:37:17
2010-07-19T07:37:17
33,088,815
0
0
null
null
null
null
UTF-8
C++
false
false
2,064
h
/* * LePlatz - A level editor for the Platz toolset (Uzebox - supports VIDEO_MODE 3) * Copyright (C) 2009 Paul McPhee * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef BGMUTABLE_H #define BGMUTABLE_H #include <PlatzEnums.h> #include "BgInner.h" class BgMutable : public BgInner { public: BgMutable(); BgMutable(const QList<QVariant> &data, BgInner *mutableLink = 0, WorldItem *parent = 0); ~BgMutable(); virtual WorldItem* validateState(); WorldItem* createItem(const QList<QVariant> &data, WorldItem *parent = 0); WorldItem::WorldItemType type() const; QVariant dataDecoration(int column) const; QString detailData() const; QRectF limitRect() const; qreal offsetX() const; QString mutableString() const { return mMutableString; } void setMutableString(const QString &mutableString) { mMutableString = mutableString; } bool isCustomPayload() { return customPayload; } const Platz::MutablePayload& payload() const { return mutablePayload; } void setPayload(const QRect &rect) { mutablePayload.fromRect(rect); customPayload = false; } void setCustomPayload(const Platz::MutablePayload& payload) { mutablePayload = payload; customPayload = true; } int mutableCount(int index = -1) const; private: Platz::MutablePayload mutablePayload; QString mMutableString; bool customPayload; }; #endif // BGMUTABLE_H
[ "[email protected]@08aac7ea-4340-11de-bfec-d9b18e096ff9" ]
[ [ [ 1, 53 ] ] ]
5b749851334e506f81af56500d302b93649ef1e0
b411e4861bc1478147bfc289c868b961a6136ead
/tags/DownhillRacing/Face.cpp
21c264ca1bef30a4b6becf3eeacfad6132a8f8bb
[]
no_license
mvm9289/downhill-racing
d05df2e12384d8012d5216bc0b976bc7df9ff345
038ec4875db17a7898282d6ced057d813a0243dc
refs/heads/master
2021-01-20T12:20:31.383595
2010-12-19T23:29:02
2010-12-19T23:29:02
32,334,476
0
0
null
null
null
null
UTF-8
C++
false
false
1,224
cpp
#include "Face.h" #include <gl/glut.h> Face::Face(void) {} Face::~Face(void) {} void Face::addVertex(int v) { indices.push_back(v); } void Face::computeNormal(vector<Vertex>& vertices) { Point a = vertices[indices[0]].coord; Point b = vertices[indices[1]].coord; Point c = vertices[indices[2]].coord; Vector v1 = b - a; Vector v2 = c - a; normal.x = (v1.y*v2.z) - (v1.z*v2.y); normal.y = -((v2.z*v1.x) - (v2.x*v1.z)); normal.z = (v1.x*v2.y) - (v1.y*v2.x); normal.normalize(); int n = indices.size(); for (int i = 0; i < n; i++) { vertices[indices[i]].normal.x += normal.x; vertices[indices[i]].normal.y += normal.y; vertices[indices[i]].normal.z += normal.z; vertices[indices[i]].normal.normalize(); } } void Face::render(const vector<Vertex>& vertices) { glMatrixMode(GL_MODELVIEW); glPushMatrix(); glBegin(GL_QUADS); int nVertices = indices.size(); for (int i = 0; i < nVertices; i++) { Vertex v = vertices[indices[i]]; glNormal3f(v.normal.x, v.normal.y, v.normal.z); glTexCoord2f(v.coord.x*TEX_REPEAT_FACTOR, v.coord.z*TEX_REPEAT_FACTOR); glVertex3f(v.coord.x, v.coord.y, v.coord.z); } glEnd(); glPopMatrix(); }
[ "mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1" ]
[ [ [ 1, 53 ] ] ]
fbc8ab22b1c13bb3b10eda218bfce18eac22507c
45c0d7927220c0607531d6a0d7ce49e6399c8785
/GlobeFactory/src/useful/command.hh
3ff5bb12a8369c9ae1b256044ce378712ad86bc2
[]
no_license
wavs/pfe-2011-scia
74e0fc04e30764ffd34ee7cee3866a26d1beb7e2
a4e1843239d9a65ecaa50bafe3c0c66b9c05d86a
refs/heads/master
2021-01-25T07:08:36.552423
2011-01-17T20:23:43
2011-01-17T20:23:43
39,025,134
0
0
null
null
null
null
UTF-8
C++
false
false
1,074
hh
//////////////////////////////////////////////////////////////////////////////// // Filename : command.hh // Authors : Creteur Clement // Last edit : 11/11/09 - 16h00 // Comment : //////////////////////////////////////////////////////////////////////////////// #ifndef USEFUL_COMMAND_HH #define USEFUL_COMMAND_HH #include <string> //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ class Command { public: inline const std::string& GetName() const {return MName;} virtual void Execute(); virtual void Execute(bool parArg); virtual void Execute(float parArg); virtual void Execute(const std::string& parArg); protected: Command(const std::string& parName); virtual ~Command(); private: std::string MName; }; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #endif
[ "creteur.c@8e971d8e-9cf3-0c36-aa0f-a7c54ab41ffc" ]
[ [ [ 1, 36 ] ] ]
6419f9aafadade97edd7a23f99578bc200ac3524
b7b58c5e83ae0e868414e8a6900b92fcfa87b4b1
/Tools/atlas/AtlasLogger.h
cf8a1a990da6dd36b5f2d970973df2ac516ff616
[]
no_license
dailongao/cheat-fusion
87df8bd58845f30808600b72167ff6c778a36245
ab7cd0fe56df0edabb9064da70b93a2856df7fac
refs/heads/master
2021-01-10T12:42:37.958692
2010-12-31T13:42:51
2010-12-31T13:42:51
51,513,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
h
#pragma once #include <string> #include <list> enum ErrorSeverity { FATALERROR = 0, WARNING }; typedef struct AtlasError { std::string Error; ErrorSeverity Severity; unsigned int LineNumber; } AtlasError; typedef std::list<AtlasError>::iterator ListErrorIt; class AtlasLogger { public: AtlasLogger(); ~AtlasLogger(); void ReportError(unsigned int ScriptLine, const char* FormatStr ...); void ReportWarning(unsigned int ScriptLine, const char* FormatStr ...); void Log(const char* FormatStr ...); void SetLogSource(FILE* OutputSource); void SetLogStatus(bool LoggingOn); void BugReportLine(unsigned int Line, const char* Filename, const char* Msg); void BugReport(unsigned int Line, const char* Filename, const char* FormatStr ...); std::list<AtlasError> Errors; private: FILE* output; static const unsigned int BufSize = 512; char buf[BufSize]; bool isLogging; }; extern AtlasLogger Logger; #define ReportBug(msg) Logger.BugReport(__LINE__, __FILE__, msg)
[ "forbbsneo@1e91e87a-c719-11dd-86c2-0f8696b7b6f9" ]
[ [ [ 1, 42 ] ] ]
9d36987eee0e74c5ae6b451203f33b2985e06664
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/_Common/patch.h
6cda45ba134851e4b87084f8b3feb228d532d7b2
[]
no_license
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UHC
C++
false
false
1,852
h
#ifndef PATCH_H #define PATCH_H class CLandscape; // 패치 클래스 // 랜드스케이프를 구성하는 일종의 타일 class CPatch { protected: FLOAT *m_pHeightMap; // 높이 맵 (이 패치에 사용될 주소) BOOL m_bDirty; // 버텍스 버퍼를 수정할 필요가 있을 경우 TRUE로 세트 BOOL m_bVisible; // 컬링된 결과 D3DXVECTOR3 m_avBounds[8]; // 컬링에 사용할 바운드 박스 벡터 D3DXPLANE m_aplaneBounds[6]; // 컬링에 사용할 바운드 박스 평면 D3DXVECTOR3 m_vCenter; // 컬링에 사용할 이 패치의 중심 public: int m_nWorldX,m_nWorldY; // 이 패치의 좌하단 월드좌표 int m_nLevel; // 이 패치의 LOD 레벨 int m_nTopLevel; // 이 패치 상단부의 LOD 레벨 int m_nLeftLevel; // 이 패치 좌단부의 LOD 레벨 int m_nRightLevel; // 이 패치 우단부의 LOD 레벨 int m_nBottomLevel; // 이 패치 하단부의 LOD 레벨 CPatch() { m_pHeightMap = NULL; m_nBottomLevel = m_nRightLevel = m_nLeftLevel = m_nTopLevel = m_nLevel = 0; } ~CPatch(); // void SetExPatch(BOOL bEnable); // 이거 이제 안쓴다. 전에 기능 추가했다가 삭제됐음. void Init( int heightX, int heightY, int worldX, int worldY, FLOAT *hMap ); // 패치 초기화. (전체 월드에서의 위치와 이 패치가 사용할 높이 맵의 주소를 지정한다.) BOOL isVisibile( ) { return m_bVisible; } // 컬링된 결과를 돌려준다. BOOL isDirty( ) { return m_bDirty; } // 하이트맵의 내용 등이 변경된 경우 버텍스 버퍼, 라이트맵을 수정한다. void SetDirty( BOOL bDirty ) { m_bDirty=bDirty; } void Render(LPDIRECT3DDEVICE9 pd3dDevice,int X,int Y); void CalculateBound(); void Cull(); void CalculateLevel(); }; #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 49 ] ] ]
49004cc8f801210fce2f341df49423a42230de86
23c0843109bcc469d7eaf369809a35e643491500
/Input/Input.cpp
b68e0ee167ec7963fb379f42816c723e3fdd6e7a
[]
no_license
takano32/d4r
eb2ab48b324c02634a25fc943e7a805fea8b93a9
0629af9d14035b2b768d21982789fc53747a1cdb
refs/heads/master
2021-01-19T00:46:58.672055
2009-01-07T01:28:38
2009-01-07T01:28:38
102,349
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,990
cpp
#pragma comment (lib, "msvcrt-ruby18.lib") #include <ruby.h> #include "Input.h" #include "InputClass.h" using namespace base; struct InputData { InputClass* klass; VALUE input_data; }; static void input_dfree( struct InputData* data ) { if( data->klass ) { //TODO: deleteすると落ちることがある delete data->klass; data->klass = NULL; } } static VALUE input_alloc(VALUE klass) { struct InputData *data = ALLOC(struct InputData); return Data_Wrap_Struct(klass, 0, input_dfree , data); } static VALUE input_initialize( VALUE self, VALUE window ) { struct InputData *data; HWND hWnd = (HWND)NUM2LONG(rb_funcall( window, rb_intern("handle") , 0 )); Data_Get_Struct(self, struct InputData, data); data->klass = new InputClass( hWnd ); return Qnil; } static VALUE input_update( VALUE self ) { struct InputData *data; Data_Get_Struct(self, struct InputData, data); return data->klass->Update() == TRUE?Qtrue:Qfalse; } static VALUE input_is_down( VALUE self, VALUE key ) { struct InputData *data; Data_Get_Struct(self, struct InputData, data); // key = 'joy 1', 'joy 2' // key = 'key a', 'key b' //char* RSTRING(str)->ptr //char* joy_head = "joy"; //char* key_head = "key"; return data->klass->IsDown( RSTRING(key)->ptr ) == TRUE?Qtrue:Qfalse; } static VALUE input_is_up( VALUE self, VALUE key ) { struct InputData *data; Data_Get_Struct(self, struct InputData, data); return data->klass->IsUp( RSTRING(key)->ptr ) == TRUE?Qtrue:Qfalse; } void Init_input() { VALUE Input; Input = rb_define_class("Input", rb_cObject); rb_define_alloc_func(Input, input_alloc); rb_define_private_method(Input, "initialize", (VALUE (*)(...))input_initialize, 1); rb_define_method(Input, "update", (VALUE (*)(...))input_update, 0); rb_define_method(Input, "down?", (VALUE (*)(...))input_is_down, 1); rb_define_method(Input, "up?", (VALUE (*)(...))input_is_up, 1); }
[ [ [ 1, 68 ] ] ]
07e1852bd123ebb3a8c34b0c0801e7b219e35a4e
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/input/DIKeyboard.h
aef1d3156118bb6e0297518cd456e1f51a9881cb
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
825
h
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #ifndef __DI_KEYBOARD_H #define __DI_KEYBOARD_H #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include "InputDevice.h" namespace dingus { class CDIKeyboard : public IInputDevice { private: enum { SAMPLE_BUFFER_SIZE = 8 }; enum { ASCII_BY_DIK_TABLE_SIZE = 256 }; public: CDIKeyboard( HWND hwnd, IDirectInput8& di8 ); virtual CInputEvents poll(); protected: int dik2ascii( int dik ); private: IDirectInputDevice8* mDIKeyboard; int mAsciiByDik[ASCII_BY_DIK_TABLE_SIZE]; BYTE mOldDiks[256]; }; }; // namespace #endif
[ [ [ 1, 38 ] ] ]
78e2ae1f392aa406b016937776c4ad4803bcf63c
7dd19b99378bc5ca4a7c669617a475f551015d48
/openclient/rtsp_stack/UsageEnvironment.h
51d00cf242151d262207b4aa8d79269320dc2121
[]
no_license
Locnath/openpernet
988a822eb590f8ed75f9b4e8c2aa7b783569b9da
67dad1ac4cfe7c336f8a06b8c50540f12407b815
refs/heads/master
2020-06-14T14:32:17.351799
2011-06-23T08:51:04
2011-06-23T08:51:04
41,778,769
0
0
null
null
null
null
UTF-8
C++
false
false
5,291
h
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // Copyright (c) 1996-2010 Live Networks, Inc. All rights reserved. // Usage Environment // C++ header #ifndef _USAGE_ENVIRONMENT_HH #define _USAGE_ENVIRONMENT_HH #ifndef _USAGEENVIRONMENT_VERSION_HH #include "UsageEnvironment_version.h" #endif #ifndef _NETCOMMON_H #include "NetCommon.h" #endif #ifndef _STRDUP_HH // "strDup()" is used often, so include this here, so everyone gets it: #include "strDup.h" #endif #ifndef NULL #define NULL 0 #endif #ifdef __BORLANDC__ #define _setmode setmode #define _O_BINARY O_BINARY #endif class TaskScheduler; // forward // An abstract base class, subclassed for each use of the library class UsageEnvironment { public: void reclaim(); // task scheduler: TaskScheduler& taskScheduler() const { return fScheduler;} // result message handling: typedef char const* MsgString; virtual MsgString getResultMsg() const = 0; virtual void setResultMsg(MsgString msg) = 0; virtual void setResultMsg(MsgString msg1, MsgString msg2) = 0; virtual void setResultMsg(MsgString msg1, MsgString msg2, MsgString msg3) = 0; virtual void setResultErrMsg(MsgString msg, int err = 0) = 0; // like setResultMsg(), except that an 'errno' message is appended. (If "err == 0", the "getErrno()" code is used instead.) virtual void appendToResultMsg(MsgString msg) = 0; virtual void reportBackgroundError() = 0; // used to report a (previously set) error message within // a background event // 'errno' virtual int getErrno() const = 0; // 'console' output: virtual UsageEnvironment& operator<<(char const* str) = 0; virtual UsageEnvironment& operator<<(int i) = 0; virtual UsageEnvironment& operator<<(unsigned u) = 0; virtual UsageEnvironment& operator<<(double d) = 0; virtual UsageEnvironment& operator<<(void* p) = 0; // a pointer to additional, optional, client-specific state void* liveMediaPriv; void* groupsockPriv; protected: UsageEnvironment(TaskScheduler& scheduler); // abstract base class virtual ~UsageEnvironment(); // we are deleted only by reclaim() private: TaskScheduler& fScheduler; }; typedef void TaskFunc(void* clientData); typedef void* TaskToken; class TaskScheduler { public: virtual ~TaskScheduler(); virtual TaskToken scheduleDelayedTask(int64_t microseconds, TaskFunc* proc, void* clientData) = 0; // Schedules a task to occur (after a delay) when we next // reach a scheduling point. // (Does not delay if "microseconds" <= 0) // Returns a token that can be used in a subsequent call to // unscheduleDelayedTask() virtual void unscheduleDelayedTask(TaskToken& prevTask) = 0; // (Has no effect if "prevTask" == NULL) // Sets "prevTask" to NULL afterwards. virtual void rescheduleDelayedTask(TaskToken& task, int64_t microseconds, TaskFunc* proc, void* clientData); // Combines "unscheduleDelayedTask()" with "scheduleDelayedTask()" // (setting "task" to the new task token). // For handling socket operations in the background (from the event loop): typedef void BackgroundHandlerProc(void* clientData, int mask); // Possible bits to set in "mask". (These are deliberately defined // the same as those in Tcl, to make a Tcl-based subclass easy.) #define SOCKET_READABLE (1<<1) #define SOCKET_WRITABLE (1<<2) #define SOCKET_EXCEPTION (1<<3) virtual void setBackgroundHandling(int socketNum, int conditionSet, BackgroundHandlerProc* handlerProc, void* clientData) = 0; void disableBackgroundHandling(int socketNum) { setBackgroundHandling(socketNum, 0, NULL, NULL); } virtual void moveSocketHandling(int oldSocketNum, int newSocketNum) = 0; // Changes any socket handling for "oldSocketNum" so that occurs with "newSocketNum" instead. virtual void doEventLoop(char* watchVariable = NULL) = 0; // Stops the current thread of control from proceeding, // but allows delayed tasks (and/or background I/O handling) // to proceed. // (If "watchVariable" is not NULL, then we return from this // routine when *watchVariable != 0) // The following two functions are deprecated, and are provided for backwards-compatibility only: void turnOnBackgroundReadHandling(int socketNum, BackgroundHandlerProc* handlerProc, void* clientData) { setBackgroundHandling(socketNum, SOCKET_READABLE, handlerProc, clientData); } void turnOffBackgroundReadHandling(int socketNum) { disableBackgroundHandling(socketNum); } protected: TaskScheduler(); // abstract base class }; #endif
[ [ [ 1, 149 ] ] ]
47beb5478b6f81af9c73bb2f19124820dd814f3a
184455acbcc5ee6b2ee0c77c66b436375e1171e9
/src/Rect.cpp
0cb9041c5dda3a393433b20bda2307f5d3627e66
[]
no_license
Karkasos/Core512
d996d40e57be899e6c4c9aec106e371356152b36
b83151ab284b7cf2e058fdd218dcc676946f43aa
refs/heads/master
2020-04-07T14:19:51.907224
2011-11-01T06:46:20
2011-11-01T06:46:20
2,753,621
0
0
null
null
null
null
UTF-8
C++
false
false
649
cpp
#include "Rect.h" Rect::Rect() : x1(0), y1(0), x2(0), y2(0), cx(0), cy(0), w(0), h(0) {} void Rect::SetByCenter(float cx, float cy, float w, float h) { this->x1 = cx - w / 2; this->y1 = cy - h / 2; this->x2 = this->x1 + w; this->y2 = this->y1 + h; this->cx = cx; this->cy = cy; this->w = w; this->h = h; } void Rect::SetByPoints(float x1, float y1, float x2, float y2) { this->x1 = x1; this->y1 = y1; this->x2 = x2; this->y2 = y2; this->w = x2 - x1; this->h = y2 - y1; this->cx = x1 + this->w / 2; this->cy = y1 + this->h / 2; } void Rect::Move(float cx, float cy) { SetByCenter(cx, cy, w, h); }
[ [ [ 1, 32 ] ] ]
a2069f9de8a02199630d51f4ece4c096413edf8a
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/CppGuiTest/swDirDialogManipulator.h
af3cba6fe19244770abc30131dcca4177a61bd60
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
1,147
h
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/CppGuiTest/swDirDialogManipulator.h // Author: Reinhold Füreder // Created: 2006 // Copyright: (c) 2006 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef SWDIRDIALOGMANIPULATOR_H #define SWDIRDIALOGMANIPULATOR_H #ifdef __GNUG__ #pragma interface "swDirDialogManipulator.h" #endif #include "swModalDialogInteractionInterface.h" class wxDirDialog; namespace swTst { /*! \class DirDialogManipulator \brief Manipulate DirDialog. */ class DirDialogManipulator : public ModalDialogInteractionInterface { public: /*! \fn DirDialogManipulator (wxDirDialog *dialog) \brief Constructor */ DirDialogManipulator (wxDirDialog *dialog); /*! \fn virtual void Execute () \brief Set the path of the DirDialog. */ virtual void Execute (); private: wxDirDialog *m_dialog; }; } // End namespace swTst #endif // SWDIRDIALOGMANIPULATOR_H
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 46 ] ] ]
decdd6384e626c85f721e853e9dd7b494d389a7e
ef8e875dbd9e81d84edb53b502b495e25163725c
/litewiz/src/user_interface/context_menu_info.cpp
608c8dae6b22512d15e2f4515aa77d904055e052
[]
no_license
panone/litewiz
22b9d549097727754c9a1e6286c50c5ad8e94f2d
e80ed9f9d845b08c55b687117acb1ed9b6e9a444
refs/heads/master
2021-01-10T19:54:31.146153
2010-10-01T13:29:38
2010-10-01T13:29:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,657
cpp
/******************************************************************************* *******************************************************************************/ #include <QSet> #include "utility.h" #include "context_menu_info.h" /******************************************************************************* *******************************************************************************/ ContextMenuInfo::ContextMenuInfo ( QIntList const & selection ) : selection( selection ) { } /******************************************************************************* *******************************************************************************/ QIntList ContextMenuInfo::getSelection ( void ) const { return selection; } /******************************************************************************* *******************************************************************************/ void ContextMenuInfo::addMenuEntry ( int const entry ) { entries.insert( entry ); } /******************************************************************************* *******************************************************************************/ bool ContextMenuInfo::hasMenuEntry ( int const entry ) const { return entries.contains( entry ); } /******************************************************************************* *******************************************************************************/ void ContextMenuInfo::clearMenuEntries ( void ) { entries.clear(); } /******************************************************************************/
[ [ [ 1, 60 ] ] ]
4d40829af193c39f5ebaec89b02c38688d736d08
b308f1edaab2be56eb66b7c03b0bf4673621b62f
/Code/CryEngine/CryCommon/CryHalf.inl
2725eb941edc1ce46f1da1020d0763c27b97cbba
[]
no_license
blockspacer/project-o
14e95aa2692930ee90d098980a7595759a8a1f74
403ec13c10757d7d948eafe9d0a95a7f59285e90
refs/heads/master
2021-05-31T16:46:36.814786
2011-09-16T14:34:07
2011-09-16T14:34:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,858
inl
#ifndef CRY_HALF_INL #define CRY_HALF_INL #pragma once typedef uint16 CryHalf; class ICrySizer; typedef union floatint_union {float f; uint32 i;} floatint_union; # if defined(WIN32) || defined(WIN64) || defined(LINUX) __forceinline CryHalf CryConvertFloatToHalf(const float Value) { #ifdef LINUX asm volatile("" ::: "memory"); #endif unsigned int Result; unsigned int IValue = ((unsigned int *)(&Value))[0]; unsigned int Sign = (IValue & 0x80000000U) >> 16U; IValue = IValue & 0x7FFFFFFFU; // Hack off the sign if (IValue > 0x47FFEFFFU) { // The number is too large to be represented as a half. Saturate to infinity. Result = 0x7FFFU; } else { if (IValue < 0x38800000U) { // The number is too small to be represented as a normalized half. // Convert it to a denormalized value. unsigned int Shift = 113U - (IValue >> 23U); IValue = (0x800000U | (IValue & 0x7FFFFFU)) >> Shift; } else { // Rebias the exponent to represent the value as a normalized half. IValue += 0xC8000000U; } Result = ((IValue + 0x0FFFU + ((IValue >> 13U) & 1U)) >> 13U)&0x7FFFU; } return (CryHalf)(Result|Sign); } __forceinline float CryConvertHalfToFloat(const CryHalf Value) { #ifdef LINUX asm volatile("" ::: "memory"); #endif unsigned int Mantissa; unsigned int Exponent; unsigned int Result; Mantissa = (unsigned int)(Value & 0x03FF); if ((Value & 0x7C00) != 0) // The value is normalized { Exponent = (unsigned int)((Value >> 10) & 0x1F); } else if (Mantissa != 0) // The value is denormalized { // Normalize the value in the resulting float Exponent = 1; do { Exponent--; Mantissa <<= 1; } while ((Mantissa & 0x0400) == 0); Mantissa &= 0x03FF; } else // The value is zero { Exponent = (unsigned int)-112; } Result = ((Value & 0x8000) << 16) | // Sign ((Exponent + 112) << 23) | // Exponent (Mantissa << 13); // Mantissa return *(float*)&Result; } # elif defined(XENON) __forceinline CryHalf CryConvertFloatToHalf(const float Value) { XMVECTOR ValueV; CryHalf Result; XMASSERT(((UINT_PTR)&Value & 3) == 0); ValueV = __lvlx(&Value, 0); ValueV = __vpkd3d(ValueV, ValueV, VPACK_FLOAT16_4, VPACK_64LO, 2); ValueV = __vsplth(ValueV, 0); __stvehx(ValueV, &Result, 0); return Result; } __forceinline float CryConvertHalfToFloat(const CryHalf Value) { XMVECTOR ValueV; float Result; XMASSERT(((UINT_PTR)&Value & 1) == 0); ValueV = __lvlx(&Value, 0); ValueV = __vsplth(ValueV, 0); ValueV = __vupkd3d(ValueV, VPACK_FLOAT16_4); __stvewx(ValueV, &Result, 0); return Result; } # elif defined(PS3) #include <CryHalf_branchfree.inl> #define HALF_FLOAT_USE_BRANCHFREE_CONVERSION ILINE CryHalf CryConvertFloatToHalf(const float val) { #if defined(HALF_FLOAT_USE_BRANCHFREE_CONVERSION) floatint_union u; u.f = val; return half_from_float(u.i); #else uint8 *tmp = (uint8*)&val; uint32 bits = ((uint32)tmp[0] << 24) | ((uint32)tmp[1] << 16) | ((uint32)tmp[2] << 8) |(uint32)tmp[3]; if(bits == 0) return 0; int e = ((bits & 0x7f800000) >> 23) - 127 + 15; if(e < 0) return 0; else if (e > 31) e = 31; uint32 s = bits & 0x80000000; uint32 m = bits & 0x007fffff; return ((s >> 16) & 0x8000) | ((e << 10) & 0x7c00) | ((m >> 13) & 0x03ff); #endif } ILINE float CryConvertHalfToFloat(const CryHalf val) { #if defined(HALF_FLOAT_USE_BRANCHFREE_CONVERSION) const uint32_t converted = half_to_float(val); floatint_union u; u.i = converted; return u.f; #else if(val == 0) return 0.0f; uint32 s = val & 0x8000; int e =((val & 0x7c00) >> 10) - 15 + 127; uint32 m = val & 0x03ff; uint32 floatVal = (s << 16) | ((e << 23) & 0x7f800000) | (m << 13); float result; uint8 *tmp = (uint8*)&result; tmp[0] = (floatVal >> 24) & 0xff; tmp[1] = (floatVal >> 16) & 0xff; tmp[2] = (floatVal >> 8) & 0xff; tmp[3] = floatVal & 0xff; return result; #endif } #if defined(HALF_FLOAT_USE_BRANCHFREE_CONVERSION) # undef HALF_FLOAT_USE_BRANCHFREE_CONVERSION #endif # endif struct CryHalf2 { CryHalf x; CryHalf y; CryHalf2() { } CryHalf2(CryHalf _x, CryHalf _y) : x(_x) , y(_y) { } CryHalf2(const CryHalf* const __restrict pArray) { x = pArray[0]; y = pArray[1]; } CryHalf2(float _x, float _y) { x = CryConvertFloatToHalf(_x); y = CryConvertFloatToHalf(_y); } CryHalf2(const float* const __restrict pArray) { x = CryConvertFloatToHalf(pArray[0]); y = CryConvertFloatToHalf(pArray[1]); } CryHalf2& operator= (const CryHalf2& Half2) { x = Half2.x; y = Half2.y; return *this; } void GetMemoryUsage(ICrySizer* pSizer) const {} AUTO_STRUCT_INFO }; struct CryHalf4 { CryHalf x; CryHalf y; CryHalf z; CryHalf w; CryHalf4() { } CryHalf4(CryHalf _x, CryHalf _y, CryHalf _z, CryHalf _w) : x(_x) , y(_y) , z(_z) , w(_w) { } CryHalf4(const CryHalf* const __restrict pArray) { x = pArray[0]; y = pArray[1]; z = pArray[2]; w = pArray[3]; } CryHalf4(float _x, float _y, float _z, float _w) { x = CryConvertFloatToHalf(_x); y = CryConvertFloatToHalf(_y); z = CryConvertFloatToHalf(_z); w = CryConvertFloatToHalf(_w); } CryHalf4(const float* const __restrict pArray) { x = CryConvertFloatToHalf(pArray[0]); y = CryConvertFloatToHalf(pArray[1]); z = CryConvertFloatToHalf(pArray[2]); w = CryConvertFloatToHalf(pArray[3]); } CryHalf4& operator= (const CryHalf4& Half4) { x = Half4.x; y = Half4.y; z = Half4.z; w = Half4.w; return *this; } void GetMemoryUsage(ICrySizer* pSizer) const {} AUTO_STRUCT_INFO }; #endif // #ifndef CRY_HALF_INL
[ [ [ 1, 274 ] ] ]
8d1c805df313247e35373ddaaf438a08c77adab1
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/sax/SAXException.hpp
58d83287a756cb8018b7ec5c6efc496f24758a71
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
8,448
hpp
/* * Copyright 1999-2000,2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Log: SAXException.hpp,v $ * Revision 1.7 2004/09/08 13:56:19 peiyongz * Apache License Version 2.0 * * Revision 1.6 2003/12/01 23:23:26 neilg * fix for bug 25118; thanks to Jeroen Witmond * * Revision 1.5 2003/08/13 15:43:24 knoaman * Use memory manager when creating SAX exceptions. * * Revision 1.4 2003/05/15 18:27:05 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.3 2002/12/06 13:17:29 tng * [Bug 9083] Make SAXNotSupportedException and SAXNotRecognizedException to be exportable * * Revision 1.2 2002/11/04 14:56:26 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:08 peiyongz * sane_include * * Revision 1.8 2000/09/07 23:55:02 andyh * Fix SAXException assignment operator. Now non-virtual, and * SAXParseException invokes base class operator. * * Revision 1.7 2000/08/09 22:06:04 jpolast * more functionality to SAXException and its children. * msgs are now functional for SAXNotSupportedEx and * SAXNotRecognizedEx * * Revision 1.6 2000/08/02 18:04:02 jpolast * include SAXNotSupportedException and * SAXNotRecognizedException needed for sax2 * * Revision 1.5 2000/02/24 20:12:55 abagchi * Swat for removing Log from API docs * * Revision 1.4 2000/02/09 19:15:17 abagchi * Inserted documentation for new APIs * * Revision 1.3 2000/02/06 07:47:58 rahulj * Year 2K copyright swat. * * Revision 1.2 1999/12/18 00:21:23 roddey * Fixed a small reported memory leak * * Revision 1.1.1.1 1999/11/09 01:07:47 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:02 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef SAXEXCEPTION_HPP #define SAXEXCEPTION_HPP #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUni.hpp> #include <xercesc/util/XMemory.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * Encapsulate a general SAX error or warning. * * <p>This class can contain basic error or warning information from * either the XML SAX parser or the application: a parser writer or * application writer can subclass it to provide additional * functionality. SAX handlers may throw this exception or * any exception subclassed from it.</p> * * <p>If the application needs to pass through other types of * exceptions, it must wrap those exceptions in a SAXException * or an exception derived from a SAXException.</p> * * <p>If the parser or application needs to include information * about a specific location in an XML document, it should use the * SAXParseException subclass.</p> * * @see SAXParseException#SAXParseException */ class SAX_EXPORT SAXException : public XMemory { public: /** @name Constructors and Destructor */ //@{ /** Default constructor * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXException(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) : fMsg(XMLString::replicate(XMLUni::fgZeroLenString, manager)) , fMemoryManager(manager) { } /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXException(const XMLCh* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) : fMsg(XMLString::replicate(msg, manager)) , fMemoryManager(manager) { } /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXException(const char* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager) : fMsg(XMLString::transcode(msg, manager)) , fMemoryManager(manager) { } /** * Copy constructor * * @param toCopy The exception to be copy constructed */ SAXException(const SAXException& toCopy) : fMsg(XMLString::replicate(toCopy.fMsg, toCopy.fMemoryManager)) , fMemoryManager(toCopy.fMemoryManager) { } /** Destructor */ virtual ~SAXException() { fMemoryManager->deallocate(fMsg);//delete [] fMsg; } //@} /** @name Public Operators */ //@{ /** * Assignment operator * * @param toCopy The object to be copied */ SAXException& operator=(const SAXException& toCopy) { if (this == &toCopy) return *this; fMemoryManager->deallocate(fMsg);//delete [] fMsg; fMsg = XMLString::replicate(toCopy.fMsg, toCopy.fMemoryManager); fMemoryManager = toCopy.fMemoryManager; return *this; } //@} /** @name Getter Methods */ //@{ /** * Get the contents of the message * */ virtual const XMLCh* getMessage() const { return fMsg; } //@} protected : // ----------------------------------------------------------------------- // Protected data members // // fMsg // This is the text of the error that is being thrown. // ----------------------------------------------------------------------- XMLCh* fMsg; MemoryManager* fMemoryManager; }; class SAX_EXPORT SAXNotSupportedException : public SAXException { public: SAXNotSupportedException(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXNotSupportedException(const XMLCh* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXNotSupportedException(const char* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Copy constructor * * @param toCopy The exception to be copy constructed */ SAXNotSupportedException(const SAXException& toCopy); }; class SAX_EXPORT SAXNotRecognizedException : public SAXException { public: SAXNotRecognizedException(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXNotRecognizedException(const XMLCh* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Create a new SAXException. * * @param msg The error or warning message. * @param manager Pointer to the memory manager to be used to * allocate objects. */ SAXNotRecognizedException(const char* const msg, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Copy constructor * * @param toCopy The exception to be copy constructed */ SAXNotRecognizedException(const SAXException& toCopy); }; XERCES_CPP_NAMESPACE_END #endif
[ [ [ 1, 282 ] ] ]
4dbee091ed03aad1d65c4c83dd90b957533f4982
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/mangalore/audio/soundfxhandler.cc
b864df5d5db81cb7ace9ae6aa3e17f0398501f2a
[]
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
1,526
cc
//------------------------------------------------------------------------------ // audio/soundfxhandler.cc // (C) 2003 RadonLabs GmbH //------------------------------------------------------------------------------ #include "audio/soundfxhandler.h" #include "audio/server.h" namespace Audio { ImplementRtti(Audio::SoundFxHandler, Message::Port); ImplementFactory(Audio::SoundFxHandler); //------------------------------------------------------------------------------ /** */ SoundFxHandler::SoundFxHandler() { // empty } //------------------------------------------------------------------------------ /** */ SoundFxHandler::~SoundFxHandler() { // empty } //------------------------------------------------------------------------------ /** */ bool SoundFxHandler::Accepts(Message::Msg* msg) { return msg->CheckId(Message::PlaySound::Id); } //------------------------------------------------------------------------------ /** */ void SoundFxHandler::HandleMessage(Message::Msg* msg) { if (msg->CheckId(Message::PlaySound::Id)) { Message::PlaySound* playSoundMsg = (Message::PlaySound*) msg; Audio::Server::Instance()->PlaySoundEffect(playSoundMsg->GetName(), playSoundMsg->GetPosition(), playSoundMsg->GetVelocity(), playSoundMsg->GetVolume()); } } } // namespace Audio
[ "BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 54 ] ] ]
2d2454da8033e53bb5d390d1faa7dd90ee24a9a1
9e2c39ce4b2a226a6db1f5a5d361dea4b2f02345
/tools/LePlatz/DataModel/DataStructs/Slice.cpp
b00d7ef0c7505f92e63201a02e5ea24bd9981e3f
[]
no_license
gonzalodelgado/uzebox-paul
38623933e0fb34d7b8638b95b29c4c1d0b922064
c0fa12be79a3ff6bbe70799f2e8620435ce80a01
refs/heads/master
2016-09-05T22:24:29.336414
2010-07-19T07:37:17
2010-07-19T07:37:17
33,088,815
0
0
null
null
null
null
UTF-8
C++
false
false
5,248
cpp
/* * LePlatz - A level editor for the Platz toolset (Uzebox - supports VIDEO_MODE 3) * Copyright (C) 2009 Paul McPhee * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <QList> #include "WorldItem.h" #include "Slice.h" Slice::Slice() : WorldItem(0), replica(0), locked(false), mBgoOrder(WorldItem::GameFlow) { sliceData = ""; WorldItem::worldStats.sliceCount++; setMutableCount(mutableCount(row())); } Slice::Slice(const QList<QVariant> &data, WorldItem* parent) : WorldItem(parent), replica(0), locked(false), mBgoOrder(WorldItem::GameFlow) { if (data.length() > 0) sliceData = data[0].toString(); else sliceData = ""; WorldItem::worldStats.sliceCount++; setMutableCount(mutableCount(row())); } WorldItem* Slice::createItem(const QList<QVariant> &data, WorldItem *parent) { Slice *slice = new Slice(data, (parent) ? parent : this->parent()); if (slice) { slice->setReplica(replica); slice->setLockedOrdering(locked); //slice->setBgoOrder(mBgoOrder); if (graphicalRepresentation()) slice->setGraphicalRepresentation(new PlatzGraphicsItem(slice, graphicalRepresentation()->mode())); } return slice; } QVariant Slice::data(int column) const { if (column == 0) return QVariant(sliceData + " " + QString::number(row())); else return QVariant(""); } QVariant Slice::dataDecoration(int) const { return QVariant(WorldItem::worldItemIcon(WorldItem::SliceIcon)); } QVariant Slice::tooltipData(int) const { return QVariant(data(0).toString() + "\nLocked: " + ((locked)?"Yes":"No") + "\nReplica Of: " + ((replica) ? replica->data(0).toString() : "None") + //"\nOrder: " + ((mBgoOrder == -1) ? "<---" : "--->") + "\nBgOuters: " + QString::number(outerProxy()->childCount()) + "\nBgObjects: " + QString::number(objectProxy()->childCount()) + "\nBgPlatformPaths: " + QString::number(platformProxy()->childCount())); } QString Slice::detailData() const { QString details((locked)?"Locked: Yes":"Locked: No"); details += "\nReplica Of: " + ((replica) ? replica->data(0).toString() : "None"); //details += "\nOrder: " + ((mBgoOrder == -1) ? QString("<---") : QString("--->")); return details; } WorldItem::WorldItemType Slice::type() const { return WorldItem::Slice; } bool Slice::validChild(const WorldItem::WorldItemType&) const { return false; } void Slice::setData(const QVariant &data) { sliceData = data.toString(); } /* void Slice::toggleBgoOrder() { setBgoOrder((mBgoOrder == 1) ? -1 : 1); } */ int Slice::validateBgoOrdering() { ProxyItem *proxy = outerProxy(); if (!proxy || !proxy->childCount()) return 0; qreal it = (mBgoOrder == 1) ? proxy->child(0)->relativeBoundingRect().left() : proxy->child(0)->relativeBoundingRect().right(); foreach (WorldItem *child, *proxy->children()) { if ((mBgoOrder == 1 && child->relativeBoundingRect().left() < it) || (mBgoOrder == -1 && child->relativeBoundingRect().right() > it)) return 0; it = (mBgoOrder == 1) ? child->relativeBoundingRect().left() : child->relativeBoundingRect().right(); } return mBgoOrder; } QRectF Slice::limitRect() const { return boundingRect(); } qreal Slice::offsetX() const { WorldItem *p = parent(); if (p) return p->offsetX() + row()*WorldItem::SliceSize.width(); else return 0.0; } ProxyItem* Slice::outerProxy() const { if (childCount()) return reinterpret_cast<ProxyItem*>(child(0)); else return 0; } ProxyItem* Slice::objectProxy() const { if (childCount() > 0) return reinterpret_cast<ProxyItem*>(child(1)); else return 0; } ProxyItem* Slice::platformProxy() const { if (childCount() > 1) return reinterpret_cast<ProxyItem*>(child(2)); else return 0; } Slice::~Slice() { // Resolve any potentially stray pointers if (parent()) { Slice *it; foreach (WorldItem *child, *parent()->children()) { it = static_cast<Slice*>(child); if (it->replicaOf() == this) it->setReplica(0); } } WorldItem::worldStats.sliceCount--; // Not managed by the scene. Also shared with proxy types. delete graphicalRepresentation(); setGraphicalRepresentation(0); }
[ "[email protected]@08aac7ea-4340-11de-bfec-d9b18e096ff9" ]
[ [ [ 1, 185 ] ] ]
69938e4c3bbd6f70bec7e3d600624588d74b7d6d
a7ead79a090d7d83eabc22d7ec633368de06b989
/client/CliTalk.cpp
72aa6a699ee7e3f650a4c120854a353e3413702f
[]
no_license
rjp/qUAck
0fd7a189c41cb30363bea5947816c9c234f40169
78216295097806938c792466eab509460f9cf33a
refs/heads/master
2020-06-06T14:34:41.579463
2010-08-25T11:01:29
2010-08-25T11:01:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,074
cpp
/* ** UNaXcess Conferencing System ** (c) 1998 Michael Wood ([email protected]) ** ** Concepts based on Bradford UNaXcess (c) 1984-87 Brandon S Allbery ** Extensions (c) 1989, 1990 Andrew G Minter ** Manchester UNaXcess extensions by Rob Partington, Gryn Davies, ** Michael Wood, Andrew Armitage, Francis Cook, Brian Widdas ** ** The look and feel was reproduced. No code taken from the original ** UA was someone else's inspiration. Copyright and 'nuff respect due ** ** CliTalk.cpp: Implementation of client side channel functions */ #include <stdio.h> #include <string.h> #include "EDF/EDF.h" #include "ua.h" #include "CliTalk.h" // Internal channel get method bool ChannelGet(EDF *pData, int *iChannelID, char **szChannelName, int iSearchType, bool bReset) { STACKTRACE int iChannelEDF = -1; char *szChannelEDF = NULL; bool bLoop = true, bFound = false, bGetCopy = false; if((iSearchType == 0 && (szChannelName == NULL || *szChannelName == NULL)) || (iSearchType == 1 && (iChannelID == NULL || *iChannelID <= 0))) { return false; } bGetCopy = pData->GetCopy(false); if(bReset == true) { pData->TempMark(); } // Position to first channel pData->Root(); pData->Child("channels"); bLoop = pData->Child("channel"); while(bFound == false && bLoop == true) { if(iSearchType == 0) { // Search by name pData->GetChild("name", &szChannelEDF); if(stricmp(*szChannelName, szChannelEDF) == 0) { // Set channel ID return (make a copy of the name) pData->Get(NULL, iChannelID); strcpy(*szChannelName, szChannelEDF); bFound = true; } } else { // Search by ID pData->Get(NULL, &iChannelEDF); if(*iChannelID == iChannelEDF) { if(szChannelName != NULL) { // Set channel name return (use a copy) pData->GetChild("name", &szChannelEDF); *szChannelName = strmk(szChannelEDF); } bFound = true; } } if(bFound == false) { bLoop = pData->Iterate("channel", "channels"); } } if(bReset == true) { pData->TempUnmark(); } pData->GetCopy(bGetCopy); return bFound; } // Get channel from name int ChannelGet(EDF *pData, char *&szChannelName, bool bReset) { STACKTRACE int iChannelID = -1; // debug("ChannelGet entry %s\n", szChannelName); ChannelGet(pData, &iChannelID, &szChannelName, 0, bReset); // debug("ChannelGet exit %d\n", iChannelID); return iChannelID; } // Get channel from ID bool ChannelGet(EDF *pData, int iChannelID, char **szChannelName, bool bReset) { STACKTRACE bool bReturn = false; // debug("ChannelGet entry %d\n", iChannelID); bReturn = ChannelGet(pData, &iChannelID, szChannelName, 1, bReset); // debug("ChannelGet exit %s\n", BoolStr(bReturn)); return bReturn; } bool MessageInChannel(EDF *pData, int iMsgID) { STACKTRACE bool bLoop = true, bFound = false; int iMsgEDF = 0; // debug("MessageInChannel entry %d\n", iMsgID); if(iMsgID == EDFElement::FIRST) { bFound = pData->Child("message"); } else if(iMsgID == EDFElement::LAST) { bFound = pData->GetChild("message", &iMsgID); while(pData->Child("message", EDFElement::LAST) == true) { pData->Last("message"); } // debug("Last child %s\n", BoolStr(bFound)); } else { bLoop = pData->Child("message"); } while(bFound == false && bLoop == true) { pData->Get(NULL, &iMsgEDF); if(iMsgID == iMsgEDF) { bFound = true; } else { bLoop = pData->Iterate("message", "channel", false); } } // debug("MessageInChannel exit %s, %d\n", BoolStr(bFound), iMsgEDF); return bFound; }
[ [ [ 1, 163 ] ] ]
261679249627905c785d63a8b53cc448676fd314
968aa9bac548662b49af4e2b873b61873ba6f680
/imgtools/romtools/rombuild/rombuild.cpp
bb8c22d1a786f5c3c4bcf23983b4227a811eca7b
[]
no_license
anagovitsyn/oss.FCL.sftools.dev.build
b3401a1ee3fb3c8f3d5caae6e5018ad7851963f3
f458a4ce83f74d603362fe6b71eaa647ccc62fee
refs/heads/master
2021-12-11T09:37:34.633852
2010-12-01T08:05:36
2010-12-01T08:05:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,331
cpp
// Copyright (c) 2007-2010 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of the License "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 <string.h> #include <stdlib.h> #include "h_utl.h" #include "h_ver.h" #include "r_global.h" #include "r_rom.h" #include "r_obey.h" #include "parameterfileprocessor.h" #include "r_dir.h" #include "r_coreimage.h" #include "logparser.h" const TInt KRomLoaderHeaderNone=0; const TInt KRomLoaderHeaderEPOC=1; const TInt KRomLoaderHeaderCOFF=2; static const TInt RombuildMajorVersion=2; static const TInt RombuildMinorVersion=20; static const TInt RombuildPatchVersion=0; static TBool SizeSummary=EFalse; static TPrintType SizeWhere=EAlways; static string compareROMName = ""; static TInt MAXIMUM_THREADS = 128; static TInt DEFAULT_THREADS = 8; static string romlogfile = "ROMBUILD.LOG"; string filename; // to store oby filename passed to Rombuild. TBool reallyHelp=EFalse; TInt gCPUNum = 0; TInt gThreadNum = 0; char* g_pCharCPUNum = NULL; TBool gGenDepGraph = EFalse; string gDepInfoFile = ""; TBool gGenSymbols = EFalse ; TBool gGenBsymbols = EFalse ; TBool gIsOBYUTF8 = EFalse; static string loginput = ""; void PrintVersion() { printf("\nROMBUILD - Rom builder"); printf(" V%d.%d.%d\n", RombuildMajorVersion, RombuildMinorVersion, RombuildPatchVersion); printf(Copyright); } char HelpText[] = "Syntax: ROMBUILD [options] obeyfilename\n" "Option: -v verbose, -? \n" " -type-safe-link \n" " -s[log|screen|both] size summary\n" " -r<FileName> compare a sectioned Rom image\n" " -no-header suppress the image loader header\n" " -gendep generate the dependence graph for paged part\n" " -coff-header use a PE-COFF header rather than an EPOC header\n" " -d<bitmask> set trace mask (DEB build only)\n" " -compress[[=]paged|unpaged] compress the ROM Image\n" " without any argumentum compress both sections\n" " paged compress paged section only\n" " unpaged compress unpaged section only\n\n" " -j<digit> do the main job with <digit> threads\n" " -symbols generate symbol file\n" " -bsymbols generate binary symbol file\n" " -compressionmethod <method> method one of none|inflate|bytepair to set the compression\n" " -no-sorted-romfs do not add sorted entries arrays (6.1 compatible)\n" " -oby-charset=<charset> used character set in which OBY was written\n" " -geninc to generate include file for licensee tools to use\n" " -loglevel<level> level of information to log (valid levels are 0,1,2,3,4).\n" //Tools like Visual ROM builder need the host/ROM filenames, size & if the file is hidden. " -wstdpath warn if destination path provided for a file is not a standard path\n" " -argfile=<fileName> specify argument-file name containing list of command-line arguments to rombuild\n" " -lowmem use memory-mapped file for image build to reduce physical memory consumption\n" " -coreimage=<core image file> to pass the core image as input for extension ROM image generation\n" " -k to enable keepgoing when duplicate files exist in oby\n" " -logfile=<fileName> specify log file\n" " -loginput=<log filename> specify as input a log file and produce as output symbol file.\n"; char ReallyHelpText[] = "Priorities:\n" " low background foreground high windowserver\n" " fileserver realtimeserver supervisor\n" "Languages:\n" " Test English French German Spanish Italian Swedish Danish\n" " Norwegian Finnish American SwissFrench SwissGerman Portuguese\n" " Turkish Icelandic Russian Hungarian Dutch BelgianFlemish\n" " Australian BelgianFrench\n" "Compression methods:\n" " none no compression on the individual executable image.\n" " inflate compress the individual executable image.\n" " bytepair compress the individual executable image.\n" "Log Level:\n" " 0 produce the default logs\n" " 1 produce file detail logs in addition to the default logs\n" " 2 logs e32 header attributes(same as default log) in addition to the level 1 details\n"; void processParamfile(const string& aFileName); // // Process the command line arguments, printing a helpful message if none are supplied // void processCommandLine(int argc, char *argv[], TBool paramFileFlag=EFalse) { // If "-argfile" option is passed to Rombuild, then process the parameters // specified in parameter-file first and then the options passed from the // command-line. string ParamFileArg("-argfile="); if(paramFileFlag == EFalse) { for (int count=1; count<argc; count++) { string paramFile; if(strnicmp(argv[count],ParamFileArg.c_str(),ParamFileArg.length())==0) { paramFile.assign(&argv[count][ParamFileArg.length()]); processParamfile(paramFile); } } } for (int i=1; i<argc; i++) { #ifdef __LINUX__ if (argv[i][0] == '-') #else if ((argv[i][0] == '-') || (argv[i][0] == '/')) #endif { // switch char* arg = argv[i] + 1; if (stricmp(arg, "symbols") == 0) gGenSymbols = ETrue; if (stricmp(arg, "bsymbols") == 0) gGenBsymbols = ETrue; else if (stricmp(arg, "v") == 0) H.iVerbose = ETrue; else if (stricmp(arg, "sl") == 0 || stricmp(arg, "slog") == 0) { SizeSummary = ETrue; SizeWhere = ELog; } else if (stricmp(arg, "ss") == 0 || stricmp(arg, "sscreen") == 0) { SizeSummary = ETrue; SizeWhere = EScreen; } else if(stricmp(arg, "sb") == 0 || stricmp(arg, "sboth") == 0) { SizeSummary = ETrue; SizeWhere = EAlways; } else if (stricmp(arg, "gendep")==0) gGenDepGraph = ETrue; else if (stricmp(arg, "k")==0) gKeepGoing = ETrue; else if ('j' == *arg || 'J' == *arg) { if(arg[1]) gThreadNum = atoi(arg + 1); else { Print(EWarning, "The option should be like '-j4'.\n"); gThreadNum = 0; } if(gThreadNum <= 0 || gThreadNum > MAXIMUM_THREADS) { if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS) { Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the number of processors %d will be used as the number of concurrent jobs.\n", gCPUNum); gThreadNum = gCPUNum; } else if(g_pCharCPUNum) { Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is invalid, so the default value %d will be used.\n", DEFAULT_THREADS); gThreadNum = DEFAULT_THREADS; } else { Print(EWarning, "The number of concurrent jobs set by -j should be between 1 and 128. And the NUMBER_OF_PROCESSORS is not available, so the default value %d will be used.\n", DEFAULT_THREADS); gThreadNum = DEFAULT_THREADS; } } } else if (strnicmp(argv[i],ParamFileArg.c_str(),ParamFileArg.length())==0) { // If "-argfile" option is specified within parameter-file then process it // otherwise ignore the option. if (paramFileFlag) { string paramFile; paramFile.assign(&argv[i][ParamFileArg.length()]); processParamfile(paramFile); } else { continue; } } else if ('t' == *arg || 'T' == *arg) TypeSafeLink=ETrue; else if (*arg == '?') reallyHelp=ETrue; else if ('r' == *arg || 'R' == *arg) compareROMName.assign(arg + 1); else if (stricmp(arg, "no-header")==0) gHeaderType=KRomLoaderHeaderNone; else if (stricmp(arg, "epoc-header")==0) gHeaderType=KRomLoaderHeaderEPOC; else if (stricmp(arg, "coff-header")==0) gHeaderType=KRomLoaderHeaderCOFF; else if ((stricmp(arg, "compress")==0) || (strnicmp(arg, "compress=", 9)==0)) { if((stricmp(arg, "compress")==0) && ((i+1) >= argc || argv[i+1][0] == '-')) { // No argument, compress both parts with default compression method // un-paged part compressed by Deflate gCompressUnpaged = ETrue; gCompressUnpagedMethod = KUidCompressionDeflate; // paged part compressed by the Bytepiar gEnableCompress=ETrue; gCompressionMethod = KUidCompressionBytePair; } else { const int paraMaxLen = 20; char* parameter = new char[paraMaxLen]; memset(parameter, 0, paraMaxLen); if(strncmp(arg, "compress=", 9)==0) { int paraLen = strlen(arg + 9); if (paraLen > paraMaxLen - 1) { delete[] parameter; parameter = new char[paraLen + 1]; memset(parameter, 0, paraLen + 1); } memcpy(parameter, arg + 9, paraLen); } else { int paraLen = strlen(argv[++i]); if (paraLen > paraMaxLen - 1) { delete[] parameter; parameter = new char[paraLen + 1]; memset(parameter, 0, paraLen + 1); } memcpy(parameter, argv[i], paraLen); } // An argument exists if( stricmp(parameter, "paged") == 0) { gEnableCompress=ETrue; gCompressionMethod = KUidCompressionBytePair; } else if( stricmp(parameter, "unpaged") == 0) { gCompressUnpaged=ETrue; gCompressUnpagedMethod = KUidCompressionDeflate; } else { Print (EError, "Unknown -compression argument! Set it to default (no compression)!"); gEnableCompress=EFalse; gCompressionMethod = 0; gCompressUnpaged = EFalse; gCompressUnpagedMethod = 0; } delete[] parameter; } } else if(strnicmp(argv[i], "-OBY-CHARSET=", 13) == 0) { if((stricmp(&argv[i][13], "UTF8")==0) || (stricmp(&argv[i][13], "UTF-8")==0)) gIsOBYUTF8 = ETrue; else Print(EError, "Invalid encoding %s, default system internal encoding will be used.\n", &argv[i][13]); } else if( stricmp(arg, "compressionmethod") == 0 ) { // next argument should be a method if( (i+1) >= argc || argv[i+1][0] == '-') { Print (EError, "Missing compression method! Set it to default (no compression)!"); gEnableCompress=EFalse; gCompressionMethod = 0; } else { i++; if( stricmp(argv[i], "inflate") == 0) { gEnableCompress=ETrue; gCompressionMethod = KUidCompressionDeflate; } else if( stricmp(argv[i], "bytepair") == 0) { gEnableCompress=ETrue; gCompressionMethod = KUidCompressionBytePair; } else { if( stricmp(argv[i], "none") != 0) { Print (EError, "Unknown compression method! Set it to default (no compression)!"); } gEnableCompress=EFalse; gCompressionMethod = 0; } } } else if (stricmp(arg, "no-sorted-romfs")==0) gSortedRomFs=EFalse; else if (stricmp(arg, "geninc")==0) gGenInc=ETrue; else if (stricmp(arg, "wstdpath")==0) // Warn if destination path provided for a file gEnableStdPathWarning=ETrue; // is not a standard path as per platsec else if( stricmp(arg, "loglevel") == 0) { // next argument should a be loglevel if( (i+1) >= argc || argv[i+1][0] == '-') { Print (EError, "Missing loglevel!"); gLogLevel = DEFAULT_LOG_LEVEL; } else { i++; if (stricmp(argv[i], "4") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO); else if (stricmp(argv[i], "3") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO); else if (stricmp(argv[i], "2") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES); else if (stricmp(argv[i], "1") == 0) gLogLevel = LOG_LEVEL_FILE_DETAILS; else if (stricmp(argv[i], "0") == 0) gLogLevel = DEFAULT_LOG_LEVEL; else Print(EError, "Only loglevel 0, 1, 2, 3 or 4 is allowed!"); } } else if( stricmp(arg, "loglevel4") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO | LOG_LEVEL_SMP_INFO); else if( stricmp(arg, "loglevel3") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES | LOG_LEVEL_COMPRESSION_INFO); else if( stricmp(arg, "loglevel2") == 0) gLogLevel = (LOG_LEVEL_FILE_DETAILS | LOG_LEVEL_FILE_ATTRIBUTES); else if( stricmp(arg, "loglevel1") == 0) gLogLevel = LOG_LEVEL_FILE_DETAILS; else if( stricmp(arg, "loglevel0") == 0) gLogLevel = DEFAULT_LOG_LEVEL; else if ('d' == *arg || 'D' == *arg) { TraceMask=strtoul(arg+1, 0, 0); } else if (stricmp(arg, "lowmem") == 0) gLowMem = ETrue; else if (strnicmp(arg, "coreimage=",10) ==0) { if(argv[i][11]) { gUseCoreImage = ETrue; gImageFilename.assign(arg + 10); } else { Print (EError, "Core ROM image file is missing\n"); } } else if (strnicmp(arg, "logfile=",8) ==0) { romlogfile = arg + 8; } else if (strnicmp(arg, "loginput=",9) ==0) { loginput = arg + 9; } else #ifdef WIN32 cout << "Unrecognised option " << argv[i] << "\n"; #else if(0 == access(argv[i],R_OK)){ filename.assign(argv[i]); } else { cout << "Unrecognised option " << argv[i] << "\n"; } #endif } else // Must be the obey filename filename.assign(argv[i]); } if (paramFileFlag) return; if( gGenSymbols && gGenBsymbols) { Print(EWarning, "Optiont symbols and bsymbols cannot be used at the same time, the common symbols file will be created this time!"); gGenBsymbols = EFalse; } if (filename.empty() && loginput.empty()) { PrintVersion(); cout << HelpText; if (reallyHelp) { ObeyFileReader::KeywordHelp(); cout << ReallyHelpText; } else Print(EError, "Obey filename is missing\n"); } } /** Function to process parameter-file. @param aFileName parameter-file name. */ void processParamfile(const string& aFileName) { CParameterFileProcessor parameterFile(aFileName); // Invoke fuction "ParameterFileProcessor" to process parameter-file. if(parameterFile.ParameterFileProcessor()) { TUint noOfParameters = parameterFile.GetNoOfArguments(); char** parameters = parameterFile.GetParameters(); TBool paramFileFlag=ETrue; // Invoke function "processCommandLine" to process parameters read from parameter-file. processCommandLine(noOfParameters, parameters, paramFileFlag); } } void GenerateIncludeFile(const char* aRomName, TInt aUnpagedSize, TInt aPagedSize ) { string incFileName(aRomName); int pos = -1 ; for(int i = incFileName.length() - 1 ; i >= 0 ; i--){ char ch = incFileName[i]; if(ch == '/' || ch == '\\') break ; else if(ch == '.'){ pos = i ; break ; } } if(pos > 0) incFileName.erase(pos,incFileName.length() - pos); incFileName += ".inc"; ofstream incFile(incFileName.c_str(),ios_base::trunc + ios_base::out); if(!incFile.is_open()) { Print(EError,"Cannot open include file %s for output\n", incFileName.c_str()); } else { const char incContent[] = "/** Size of the unpaged part of ROM.\n" "This part is at the start of the ROM image. */\n" "#define SYMBIAN_ROM_UNPAGED_SIZE 0x%08x\n" "\n" "/** Size of the demand paged part of ROM.\n" "This part is stored immediately after the unpaged part in the ROM image. */\n" "#define SYMBIAN_ROM_PAGED_SIZE 0x%08x\n"; // for place of two hex representated values and '\0' char* temp = new char[sizeof(incContent)+ 20]; size_t len = sprintf(temp,incContent, aUnpagedSize, aPagedSize); incFile.write(temp, len); incFile.close(); delete[] temp; } } int main(int argc, char *argv[]) { TInt r = 0; #ifdef __LINUX__ gCPUNum = sysconf(_SC_NPROCESSORS_CONF); #else g_pCharCPUNum = getenv("NUMBER_OF_PROCESSORS"); if(g_pCharCPUNum != NULL) gCPUNum = atoi(g_pCharCPUNum); #endif // initialise set of all capabilities ParseCapabilitiesArg(gPlatSecAllCaps, "all"); processCommandLine(argc, argv); if(filename.empty() && loginput.empty()) return KErrGeneral; if(gThreadNum == 0) { if(gCPUNum > 0 && gCPUNum <= MAXIMUM_THREADS >> 1) { printf("The double number of processors (%d) is used as the number of concurrent jobs.\n", gCPUNum * 2); gThreadNum = gCPUNum * 2; } else if(g_pCharCPUNum) { printf("The NUMBER_OF_PROCESSORS is invalid, and the default value %d will be used.\n", DEFAULT_THREADS); gThreadNum = DEFAULT_THREADS; } else { printf("The NUMBER_OF_PROCESSORS is not available, and the default value %d will be used.\n", DEFAULT_THREADS); gThreadNum = DEFAULT_THREADS; } } PrintVersion(); if(loginput.length() >= 1) { try { LogParser::GetInstance(ERomImage)->ParseSymbol(loginput.c_str()); } catch(LoggingException le) { printf("ERROR: %s\r\n", le.GetErrorMessage()); return 1; } return 0; } if (romlogfile.empty() || romlogfile[romlogfile.size()-1] == '\\' || romlogfile[romlogfile.size()-1] == '/') romlogfile += "ROMBUILD.LOG"; H.SetLogFile(romlogfile.c_str()); ObeyFileReader *reader=new ObeyFileReader(filename.c_str()); if (!reader->Open()) { delete reader; return KErrGeneral; } E32Rom* kernelRom=0; // for image from obey file CoreRomImage *core= 0; // for image from core image file MRomImage* imageInfo=0; CObeyFile *mainObeyFile=new CObeyFile(*reader); // need check if obey file has coreimage keyword char* file = mainObeyFile->ProcessCoreImage(); if (file) { // hase coreimage keyword but only use if command line option // for coreimage not already selected if (!gUseCoreImage) { gUseCoreImage = ETrue; gImageFilename = file; } delete []file ; } if (!gUseCoreImage) { r=mainObeyFile->ProcessKernelRom(); if (r==KErrNone) { // Build a kernel ROM using the description compiled into the // CObeyFile object kernelRom = new E32Rom(mainObeyFile); if (kernelRom == 0 || kernelRom->iData == 0) return KErrNoMemory; r=kernelRom->Create(); if (r!=KErrNone) { delete kernelRom; delete mainObeyFile; return r; } if (SizeSummary) kernelRom->DisplaySizes(SizeWhere); r=kernelRom->WriteImages(gHeaderType); if (r!=KErrNone) { delete kernelRom; delete mainObeyFile; return r; } if (compareROMName.length() > 0 ) { r=kernelRom->Compare(compareROMName.c_str(), gHeaderType); if (r!=KErrNone) { delete kernelRom; delete mainObeyFile; return r; } } imageInfo = kernelRom; mainObeyFile->Release(); } else if (r!=KErrNotFound) return r; } else { // need to use core image core = new CoreRomImage(gImageFilename.c_str()); if (!core) { return KErrNoMemory; } if (!core->ProcessImage(gLowMem)) { delete core; delete mainObeyFile; return KErrGeneral; } NumberOfVariants = core->VariantCount(); TVariantList::SetNumVariants(NumberOfVariants); TVariantList::SetVariants(core->VariantList()); core->SetRomAlign(mainObeyFile->iRomAlign); core->SetDataRunAddress(mainObeyFile->iDataRunAddress); gCompressionMethod = core->CompressionType(); if(gCompressionMethod) { gEnableCompress = ETrue; } imageInfo = core; if(!mainObeyFile->SkipToExtension()) { delete core; delete mainObeyFile; return KErrGeneral; } } if(gGenInc) { if(kernelRom != NULL) { Print(EAlways,"Generating include file for ROM image post-processors "); if( gPagedRom ) { Print(EAlways,"Paged ROM"); GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iPageableRomStart, kernelRom->iHeader->iPageableRomSize); } else { Print(EAlways,"Unpaged ROM"); int headersize=(kernelRom->iExtensionRomHeader ? sizeof(TExtensionRomHeader) : sizeof(TRomHeader)) - sizeof(TRomLoaderHeader); GenerateIncludeFile((char*)mainObeyFile->iRomFileName, kernelRom->iHeader->iCompressedSize + headersize, kernelRom->iHeader->iPageableRomSize); } } else { Print(EWarning,"Generating include file for ROM image igored because no Core ROM image generated.\n"); } } do { CObeyFile* extensionObeyFile = 0; E32Rom* extensionRom = 0; extensionObeyFile = new CObeyFile(*reader); r = extensionObeyFile->ProcessExtensionRom(imageInfo); if (r==KErrEof) { delete imageInfo; delete mainObeyFile; delete extensionObeyFile; return KErrNone; } if (r!=KErrNone) { delete extensionObeyFile; break; } extensionRom = new E32Rom(extensionObeyFile); r=extensionRom->CreateExtension(imageInfo); if (r!=KErrNone) { delete extensionRom; delete extensionObeyFile; break; } if (SizeSummary) extensionRom->DisplaySizes(SizeWhere); r=extensionRom->WriteImages(0); // always a raw image delete extensionRom; delete extensionObeyFile; } while (r==KErrNone); delete imageInfo; delete mainObeyFile; return r; }
[ [ [ 1, 28 ], [ 30, 35 ], [ 38, 42 ], [ 44, 52 ], [ 56, 56 ], [ 60, 77 ], [ 79, 80 ], [ 82, 87 ], [ 91, 140 ], [ 143, 269 ], [ 277, 355 ], [ 362, 378 ], [ 385, 467 ], [ 469, 470 ], [ 472, 472 ], [ 476, 477 ], [ 479, 481 ], [ 483, 487 ], [ 504, 599 ], [ 612, 613 ], [ 615, 656 ] ], [ [ 29, 29 ], [ 36, 37 ], [ 53, 53 ], [ 55, 55 ], [ 57, 59 ], [ 78, 78 ], [ 89, 90 ], [ 141, 142 ], [ 359, 361 ], [ 379, 384 ], [ 468, 468 ], [ 473, 475 ], [ 478, 478 ], [ 482, 482 ], [ 488, 503 ] ], [ [ 43, 43 ], [ 54, 54 ], [ 81, 81 ], [ 88, 88 ], [ 270, 276 ], [ 356, 358 ], [ 471, 471 ] ], [ [ 600, 611 ], [ 614, 614 ] ] ]
729898000aaf7a6ab32bc5f21a1bcd659b47a87d
fb43854c29e59c3186c9aad972f56dced1ea9b36
/InputLogger/InputLogger/stdafx.cpp
25fc430c6f80cbf22df2a206dad32ec4f8ee486a
[]
no_license
YSheldon/compare-view-vt
5b30ca9b01eadf336b2d3fc452fc6579bf1c6600
e84e7927588c72cf1b95054be90dbbcb26f47edd
refs/heads/master
2021-01-24T00:24:32.760744
2011-08-09T23:25:43
2011-08-09T23:25:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
211
cpp
// stdafx.cpp : source file that includes just the standard includes // InputLogger.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "bangnilz@ce3718d7-c667-c086-dfc9-3cc03c4e85f5" ]
[ [ [ 1, 7 ] ] ]
b643482e08e5b9e4f6ab14e26f8543a249b2ead5
57f014e835e566614a551f70f2da15145c7683ab
/src/color/colormap.h
5827c7da03a3cedd64396319649e591454ae5611
[]
no_license
vcer007/contour
d5c3a1bbd7f5c948fbda9d9bbc7d40333640568d
6917e4b4f24882df2111ca4af5634645cb2700eb
refs/heads/master
2020-05-30T05:35:15.107140
2011-05-23T12:59:00
2011-05-23T12:59:00
null
0
0
null
null
null
null
GB18030
C++
false
false
2,076
h
#ifndef COLORMAP_H #define COLORMAP_H #include <vector> #include <map> #include <cstring> #include <QDebug> struct Rgb { short r; short g; short b; int red() { return r; } int green() { return g; } int blue() { return b; } Rgb(){} Rgb(int r, int g, int b) { this->r= r; this->g= g; this->b= b; } }; class ColorMap { public: ColorMap(); ~ColorMap(); /* which color map to use */ void useMapOf(int mapIndex); void setRange(float minValue,float maxValue); /*由本先的个颜色进行插值,插值个数由倍数base指定,如果是则插值后的颜色为*/ void interpose(int base); /*给定一个key值(这个key值有可能不存在),返回一个与它相近的存在的key值(四舍五入法)对应的 颜色*/ Rgb findIndex(float key); inline void clear() { colorMap->clear(); colorindex.clear(); } inline Rgb* getColors() { return useMap; } inline void setColor(Rgb* colorMap) { memcpy((char*)useMap,(char*)colorMap,sizeof(useMap)); } public: static Rgb sebcolors[]; static Rgb gathercolors[]; static Rgb* maps[]; static int mapsize; /* mapsize is the size of maps */ static int currentMap; private: /*初始化基本的位颜色表*/ void initial(); /*快速排序算法,这个主要针对哈希表索引排序*/ void quicksort(std::vector<float> &a, int left, int right); /*快速排序算法的分割部分*/ int partition(std::vector<float> &a, int left,int right,int pivotIndex); void swap(std::vector<float> &a , int p, int q) { float tmp = a[p]; a[p]=a[q]; a[q]=tmp; } /*这个是key值和QRgb(用int表示)的哈希表,用哈希表的原因是因为速度快*/ std::map<float,Rgb> *colorMap; /*这个是哈希表key值得索引,因为需要key值是按顺序排列,但是哈希表是自由排序的*/ std::vector<float> colorindex; Rgb useMap[32]; /*key的范围*/ float max,min; /*初始增量*/ float step; }; #endif
[ [ [ 1, 114 ] ] ]
35b223c491d3dfb2eb42970b3353f4654d629026
bef7d0477a5cac485b4b3921a718394d5c2cf700
/testPerspShadows/src/demo/Shadows.cpp
c73c87b5085d07934384ff2fa7fcb14bbe5c9fff
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,445
cpp
#include "stdafx.h" #include "Shadows.h" #include "ShadowBufferRTManager.h" #include <dingus/gfx/GfxUtils.h> #include "Hull.h" extern bool gUseDSTShadows; // -------------------------------------------------------------------------- SceneEntityPtrs gScene; LightPtrs gLights; struct ObjectInfo { ObjectInfo( const CAABox& aabb_, SceneEntity& e ) : aabb(aabb_), entity(&e) { } CAABox aabb; // world space SceneEntity* entity; }; std::vector<ObjectInfo> gSceneReceivers; // objects in view frustum std::vector<ObjectInfo> gSceneCasters; // object extrusions in view frustum CAABox gSceneBounds, gCasterBounds, gReceiverBounds; static SVector3 gLightDir; static SVector3 gLightColor; static SMatrix4x4 gShadowTexProj; static SVector3 gInvShadowSize; // --------------------------------------------------------------------------- #define FLT_AS_INT(F) (*(DWORD*)&(F)) #define FLT_ALMOST_ZERO(F) ((FLT_AS_INT(F) & 0x7f800000L)==0) #define FLT_IS_SPECIAL(F) ((FLT_AS_INT(F) & 0x7f800000L)==0x7f800000L) struct Frustum { Frustum( const SMatrix4x4& matrix ); bool TestSphere ( const SVector3& pos, float radius ) const; //bool TestBox ( const CAABox& box ) const; bool TestSweptSphere( const SVector3& pos, float radius, const SVector3& sweepDir ) const; SPlane camPlanes[6]; SVector3 pntList[8]; int nVertexLUT[6]; }; // Computes the point where three planes intersect. Returns whether or not the point exists. static inline bool PlaneIntersection( SVector3* intersectPt, const SPlane& p0, const SPlane& p1, const SPlane& p2 ) { SVector3 n0( p0.a, p0.b, p0.c ); SVector3 n1( p1.a, p1.b, p1.c ); SVector3 n2( p2.a, p2.b, p2.c ); SVector3 n1_n2, n2_n0, n0_n1; D3DXVec3Cross( &n1_n2, &n1, &n2 ); D3DXVec3Cross( &n2_n0, &n2, &n0 ); D3DXVec3Cross( &n0_n1, &n0, &n1 ); float cosTheta = n0.dot(n1_n2); if( FLT_ALMOST_ZERO(cosTheta) || FLT_IS_SPECIAL(cosTheta) ) return false; float secTheta = 1.0f / cosTheta; n1_n2 = n1_n2 * p0.d; n2_n0 = n2_n0 * p1.d; n0_n1 = n0_n1 * p2.d; *intersectPt = -(n1_n2 + n2_n0 + n0_n1) * secTheta; return true; } Frustum::Frustum( const SMatrix4x4& matrix ) { // build a view frustum based on the current view & projection matrices... SVector4 column4( matrix._14, matrix._24, matrix._34, matrix._44 ); SVector4 column1( matrix._11, matrix._21, matrix._31, matrix._41 ); SVector4 column2( matrix._12, matrix._22, matrix._32, matrix._42 ); SVector4 column3( matrix._13, matrix._23, matrix._33, matrix._43 ); SVector4 planes[6]; planes[0] = column4 - column1; // left planes[1] = column4 + column1; // right planes[2] = column4 - column2; // bottom planes[3] = column4 + column2; // top planes[4] = column4 - column3; // near planes[5] = column4 + column3; // far int p; for (p=0; p<6; p++) // normalize the planes { float dot = planes[p].x*planes[p].x + planes[p].y*planes[p].y + planes[p].z*planes[p].z; dot = 1.0f / sqrtf(dot); planes[p] = planes[p] * dot; } for (p=0; p<6; p++) camPlanes[p] = SPlane( planes[p].x, planes[p].y, planes[p].z, planes[p].w ); // build a bit-field that will tell us the indices for the nearest and farthest vertices from each plane... for (int i=0; i<6; i++) nVertexLUT[i] = ((planes[i].x<0.f)?1:0) | ((planes[i].y<0.f)?2:0) | ((planes[i].z<0.f)?4:0); for( int i=0; i<8; ++i ) // compute extrema { const SPlane& p0 = (i&1)?camPlanes[4] : camPlanes[5]; const SPlane& p1 = (i&2)?camPlanes[3] : camPlanes[2]; const SPlane& p2 = (i&4)?camPlanes[0] : camPlanes[1]; PlaneIntersection( &pntList[i], p0, p1, p2 ); } } bool Frustum::TestSphere( const SVector3& pos, float radius ) const { bool inside = true; for( int i=0; (i<6) && inside; i++ ) inside &= ( (D3DXPlaneDotCoord(&camPlanes[i], &pos) + radius) >= 0.0f ); return inside; } // this function tests if the projection of a bounding sphere along the light direction intersects // the view frustum bool SweptSpherePlaneIntersect( float& t0, float& t1, const SPlane& plane, const SVector3& pos, float radius, const SVector3& sweepDir ) { float b_dot_n = D3DXPlaneDotCoord(&plane, &pos); float d_dot_n = D3DXPlaneDotNormal(&plane, &sweepDir); if (d_dot_n == 0.f) { if (b_dot_n <= radius) { // effectively infinity t0 = 0.f; t1 = 1e32f; return true; } else return false; } else { float tmp0 = ( radius - b_dot_n) / d_dot_n; float tmp1 = (-radius - b_dot_n) / d_dot_n; t0 = min(tmp0, tmp1); t1 = max(tmp0, tmp1); return true; } } bool Frustum::TestSweptSphere( const SVector3& pos, float radius, const SVector3& sweepDir ) const { // algorithm -- get all 12 intersection points of the swept sphere with the view frustum // for all points >0, displace sphere along the sweep direction. if the displaced sphere // is inside the frustum, return true. else, return false float displacements[12]; int cnt = 0; float a, b; bool inFrustum = false; for (int i=0; i<6; i++) { if (SweptSpherePlaneIntersect(a, b, camPlanes[i], pos, radius, sweepDir)) { if (a>=0.f) displacements[cnt++] = a; if (b>=0.f) displacements[cnt++] = b; } } for (int i=0; i<cnt; i++) { SVector3 displPos = pos + sweepDir * displacements[i]; float displRadius = radius * 1.1f; inFrustum |= TestSphere( displPos, displRadius ); } return inFrustum; } // -------------------------------------------------------------------------- void CalculateSceneBounds() { gSceneBounds.setNull(); size_t n = gScene.size(); for( size_t i = 0; i < n; ++i ) { CAABox b = gScene[i]->getAABB(); b.transform( gScene[i]->mWorldMat ); gSceneBounds.extend( b ); } } // Computes region-of-interest for the camera based on swept-sphere/frustum intersection. // If the swept sphere representing the extrusion of an object's bounding // sphere along the light direction intersects the view frustum, the object is added to // a list of interesting shadow casters. The field of view is the minimum cone containing // all eligible bounding spheres. void ComputeInterestingSceneParts( const SVector3& lightDir, const SMatrix4x4& cameraViewProj ) { bool hit = false; SVector3 sweepDir = lightDir; // camera frustum Frustum sceneFrustum( cameraViewProj ); gSceneReceivers.clear(); gSceneCasters.clear(); gCasterBounds.setNull(); gReceiverBounds.setNull(); size_t n = gScene.size(); for( size_t i = 0; i < n; ++i ) { SceneEntity& obj = *gScene[i]; CAABox aabb = obj.getAABB(); aabb.transform( obj.mWorldMat ); if( aabb.frustumCull( cameraViewProj ) ) { SVector3 spherePos = aabb.getCenter(); float sphereRadius = SVector3(aabb.getMax()-aabb.getMin()).length() / 2; if( sceneFrustum.TestSweptSphere( spherePos, sphereRadius, sweepDir ) ) { hit = true; gSceneCasters.push_back( ObjectInfo(aabb,obj) ); // originally in view space gCasterBounds.extend( aabb ); } } else { hit = true; gSceneCasters.push_back( ObjectInfo(aabb,obj) ); // originally in view space gSceneReceivers.push_back( ObjectInfo(aabb,obj) ); // originally in view space gCasterBounds.extend( aabb ); gReceiverBounds.extend( aabb ); } } } static void CalculateOrthoShadow( const CCameraEntity& cam, Light& light ) { SVector3 target = gCasterBounds.getCenter(); SVector3 size = gCasterBounds.getMax() - gCasterBounds.getMin(); float radius = size.length() * 0.5f; // figure out the light camera matrix that encloses whole scene light.mWorldMat.spaceFromAxisZ(); light.mWorldMat.getOrigin() = target - light.mWorldMat.getAxisZ() * radius; light.setOrthoParams( radius*2, radius*2, radius*0.1f, radius*2 ); light.setOntoRenderContext(); } static void CalculateLisPSM( const CCameraEntity& cam, Light& light ) { CalculateOrthoShadow( cam, light ); const SVector3& lightDir = light.mWorldMat.getAxisZ(); const SVector3& viewDir = cam.mWorldMat.getAxisZ(); double dotProd = lightDir.dot( viewDir ); if( fabs(dotProd) >= 0.999 ) { // degenerates to uniform shadow map return; } // calculate the hull of body B in world space HullFace bodyB; SMatrix4x4 invCamVP; D3DXMatrixInverse( &invCamVP, NULL, &cam.mWorldMat ); invCamVP *= cam.getProjectionMatrix(); D3DXMatrixInverse( &invCamVP, NULL, &invCamVP ); CalculateFocusedLightHull( invCamVP, lightDir, gCasterBounds, bodyB ); int zzz = bodyB.v.size(); int i, j; /* Frustum camFrustum( cam.getProjectionMatrix() ); std::vector<SVector3> bodyB; bodyB.reserve( gSceneCasters.size()*8 + 8 ); for( i = 0; i < 8; ++i ) bodyB.push_back( camFrustum.pntList[i] ); int ncasters = gSceneCasters.size(); for( i = 0; i < ncasters; ++i ) { const CAABox& aabb = gSceneCasters[i].aabb; for( j = 0; j < 8; ++j ) { SVector3 p; p.x = (j&1) ? aabb.getMin().x : aabb.getMax().x; p.y = (j&2) ? aabb.getMin().y : aabb.getMax().y; p.z = (j&4) ? aabb.getMin().z : aabb.getMax().z; bodyB.push_back( p ); } } */ // calculate basis of light space projection SVector3 ly = -lightDir; SVector3 lx = ly.cross( viewDir ).getNormalized(); SVector3 lz = lx.cross( ly ); SMatrix4x4 lightW; lightW.identify(); lightW.getAxisX() = lx; lightW.getAxisY() = ly; lightW.getAxisZ() = lz; SMatrix4x4 lightV; D3DXMatrixInverse( &lightV, NULL, &lightW ); // rotate bound body points from world into light projection space and calculate AABB there D3DXVec3TransformCoordArray( &bodyB.v[0], sizeof(SVector3), &bodyB.v[0], sizeof(SVector3), &lightV, bodyB.v.size() ); CAABox bodyLBounds; bodyLBounds.setNull(); for( i = 0; i < bodyB.v.size(); ++i ) bodyLBounds.extend( bodyB.v[i] ); float zextent = cam.getZFar() - cam.getZNear(); float zLextent = bodyLBounds.getMax().z - bodyLBounds.getMin().z; if( zLextent < zextent ) zextent = zLextent; // calculate free parameter N double sinGamma = sqrt( 1.0-dotProd*dotProd ); const double n = ( cam.getZNear() + sqrt(cam.getZNear() * (cam.getZNear() + zextent)) ) / sinGamma; // origin in this light space: looking at center of bounds, from distance n SVector3 lightSpaceO = bodyLBounds.getCenter(); lightSpaceO.z = bodyLBounds.getMin().z - n; // go through bound points in light space, and compute projected bound float maxx = 0.0f, maxy = 0.0f, maxz = 0.0f; for( i = 0; i < bodyB.v.size(); ++i ) { SVector3 tmp = bodyB.v[i] - lightSpaceO; assert( tmp.z > 0.0f ); maxx = max( maxx, fabsf(tmp.x / tmp.z) ); maxy = max( maxy, fabsf(tmp.y / tmp.z) ); maxz = max( maxz, tmp.z ); } SVector3 lpos; D3DXVec3TransformCoord( &lpos, &lightSpaceO, &lightW ); lightW.getOrigin() = lpos; SMatrix4x4 lightProj; D3DXMatrixPerspectiveLH( &lightProj, 2.0f*maxx*n, 2.0f*maxy*n, n, maxz ); SMatrix4x4 lsPermute, lsOrtho; lsPermute._11 = 1.f; lsPermute._12 = 0.f; lsPermute._13 = 0.f; lsPermute._14 = 0.f; lsPermute._21 = 0.f; lsPermute._22 = 0.f; lsPermute._23 =-1.f; lsPermute._24 = 0.f; lsPermute._31 = 0.f; lsPermute._32 = 1.f; lsPermute._33 = 0.f; lsPermute._34 = 0.f; lsPermute._41 = 0.f; lsPermute._42 = -0.5f; lsPermute._43 = 1.5f; lsPermute._44 = 1.f; D3DXMatrixOrthoLH( &lsOrtho, 2.f, 1.f, 0.5f, 2.5f ); lsPermute *= lsOrtho; lightProj *= lsPermute; G_RENDERCTX->getCamera().setCameraMatrix( lightW ); SMatrix4x4 lightFinal = G_RENDERCTX->getCamera().getViewMatrix() * lightProj; // unit cube clipping /* { // receiver hull std::vector<SVector3> receiverPts; receiverPts.reserve( gSceneReceivers.size() * 8 ); int nreceivers = gSceneReceivers.size(); for( i = 0; i < nreceivers; ++i ) { const CAABox& aabb = gSceneReceivers[i].aabb; for( j = 0; j < 8; ++j ) { SVector3 p; p.x = (j&1) ? aabb.getMin().x : aabb.getMax().x; p.y = (j&2) ? aabb.getMin().y : aabb.getMax().y; p.z = (j&4) ? aabb.getMin().z : aabb.getMax().z; receiverPts.push_back( p ); } } // transform to light post-perspective space D3DXVec3TransformCoordArray( &receiverPts[0], sizeof(SVector3), &receiverPts[0], sizeof(SVector3), &lightFinal, receiverPts.size() ); CAABox recvBounds; recvBounds.setNull(); for( i = 0; i < receiverPts.size(); ++i ) recvBounds.extend( receiverPts[i] ); recvBounds.getMax().x = min( 1.f, recvBounds.getMax().x ); recvBounds.getMin().x = max(-1.f, recvBounds.getMin().x ); recvBounds.getMax().y = min( 1.f, recvBounds.getMax().y ); recvBounds.getMin().y = max(-1.f, recvBounds.getMin().y ); float boxWidth = recvBounds.getMax().x - recvBounds.getMin().x; float boxHeight = recvBounds.getMax().y - recvBounds.getMin().y; if( !FLT_ALMOST_ZERO(boxWidth) && !FLT_ALMOST_ZERO(boxHeight) ) { float boxX = ( recvBounds.getMax().x + recvBounds.getMin().x ) * 0.5f; float boxY = ( recvBounds.getMax().y + recvBounds.getMin().y ) * 0.5f; SMatrix4x4 clipMatrix( 2.f/boxWidth, 0.f, 0.f, 0.f, 0.f, 2.f/boxHeight, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, -2.f*boxX/boxWidth, -2.f*boxY/boxHeight, 0.f, 1.f ); lightProj *= clipMatrix; } } */ G_RENDERCTX->getCamera().setProjectionMatrix( lightProj ); } void Light::PrepareAndSetOntoRenderContext( const CCameraEntity& cam, bool lispsm ) { SMatrix4x4 viewProj; D3DXMatrixInverse( &viewProj, NULL, &cam.mWorldMat ); viewProj *= cam.getProjectionMatrix(); ComputeInterestingSceneParts( mWorldMat.getAxisZ(), viewProj ); if( lispsm ) CalculateLisPSM( cam, *this ); else CalculateOrthoShadow( cam, *this ); m_DebugViewProjMatrix = G_RENDERCTX->getCamera().getViewProjMatrix(); // calculate the rest of matrices for shadow projections gfx::textureProjectionWorld( G_RENDERCTX->getCamera().getViewProjMatrix(), float(m_RTSize), float(m_RTSize), m_TextureProjMatrix ); } // -------------------------------------------------------------------------- const char* FX_NAMES[RMCOUNT] = { "object", "zfill", "caster", }; SceneEntity::SceneEntity( const std::string& name ) : mMesh(0) , m_CanAnimate(false) { assert( !name.empty() ); mMesh = RGET_MESH(name); if( name=="Teapot" || name=="Torus" || name=="Table" ) m_CanAnimate = true; for( int i = 0; i < RMCOUNT; ++i ) { CRenderableMesh* rr = new CRenderableMesh( *mMesh, CRenderableMesh::ALL_GROUPS, &mWorldMat.getOrigin(), 0 ); mRenderMeshes[i] = rr; rr->getParams().setEffect( *RGET_FX(FX_NAMES[i]) ); addMatricesToParams( rr->getParams() ); } CEffectParams& ep = mRenderMeshes[RM_NORMAL]->getParams(); ep.addVector3Ref( "vLightDir", gLightDir ); ep.addVector3Ref( "vLightColor", gLightColor ); ep.addMatrix4x4Ref( "mShadowProj", gShadowTexProj ); ep.addVector3Ref( "vInvShadowSize", gInvShadowSize ); ep.addVector3Ref( "vColor", m_Color ); } SceneEntity::~SceneEntity() { for( int i = 0; i < RMCOUNT; ++i ) delete mRenderMeshes[i]; } void SceneEntity::render( eRenderMode renderMode, bool updateWVP, bool direct ) { assert( mRenderMeshes[renderMode] ); if( updateWVP ) updateWVPMatrices(); if( direct ) G_RENDERCTX->directRender( *mRenderMeshes[renderMode] ); else G_RENDERCTX->attach( *mRenderMeshes[renderMode] ); } // -------------------------------------------------------------------------- void RenderSceneWithShadows( CCameraEntity& camera, CCameraEntity& actualCamera, float shadowQuality, bool lispsm ) { gShadowRTManager->BeginFrame(); size_t i, j; size_t nsceneobjs = gScene.size(); size_t nlights = gLights.size(); // Render the shadow buffers CD3DDevice& dx = CD3DDevice::getInstance(); if( gUseDSTShadows ) { const float kDepthBias = 0.0005f; const float kSlopeBias = 2.0f; dx.getStateManager().SetRenderState( D3DRS_COLORWRITEENABLE, 0 ); dx.getStateManager().SetRenderState( D3DRS_DEPTHBIAS, *(DWORD*)&kDepthBias ); dx.getStateManager().SetRenderState( D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&kSlopeBias ); } for( i = 0; i < nlights; ++i ) { Light& light = *gLights[i]; light.m_RTSize = 1 << int(shadowQuality); bool ok = gShadowRTManager->RequestBuffer( light.m_RTSize, &light.m_RTTexture, &light.m_RTSurface ); // set render target to this SB if( gUseDSTShadows ) { dx.setRenderTarget( gShadowRTManager->FindDepthBuffer( light.m_RTSize ) ); dx.setZStencil( light.m_RTSurface ); dx.clearTargets( false, true, false, 0xFFffffff, 1.0f ); } else { dx.setRenderTarget( light.m_RTSurface ); dx.setZStencil( gShadowRTManager->FindDepthBuffer( light.m_RTSize ) ); dx.clearTargets( true, true, false, 0xFFffffff, 1.0f ); } // calculate and set SB camera matrices light.PrepareAndSetOntoRenderContext( camera, lispsm ); G_RENDERCTX->applyGlobalEffect(); // render all casters G_RENDERCTX->directBegin(); size_t ncasters = gSceneCasters.size(); for( j = 0; j < ncasters; ++j ) gSceneCasters[j].entity->render( RM_CASTER, true, true ); G_RENDERCTX->directEnd(); } if( gUseDSTShadows ) { dx.getStateManager().SetRenderState( D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_RED|D3DCOLORWRITEENABLE_GREEN|D3DCOLORWRITEENABLE_BLUE|D3DCOLORWRITEENABLE_ALPHA ); const float temp = 0.0f; dx.getStateManager().SetRenderState( D3DRS_DEPTHBIAS, *(DWORD*)&temp ); dx.getStateManager().SetRenderState( D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&temp ); } // Render the main camera with all the shadows and lights and whatever dx.setDefaultRenderTarget(); dx.setDefaultZStencil(); dx.clearTargets( true, true, false, 0x606060, 1.0f ); actualCamera.setOntoRenderContext(); G_RENDERCTX->applyGlobalEffect(); // lay down depth for all visible objects G_RENDERCTX->directBegin(); size_t nreceivers = gSceneReceivers.size(); for( i = 0; i < nreceivers; ++i ) { gSceneReceivers[i].entity->render( RM_ZFILL, true, true ); } // additive lighting dx.getStateManager().SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE ); dx.getStateManager().SetRenderState( D3DRS_SRCBLEND, D3DBLEND_ONE ); dx.getStateManager().SetRenderState( D3DRS_DESTBLEND, D3DBLEND_ONE ); dx.getStateManager().SetRenderState( D3DRS_ZWRITEENABLE, FALSE ); dx.getStateManager().SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL ); // shadow map sampling if( gUseDSTShadows ) { dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MINFILTER, D3DTEXF_LINEAR ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MIPFILTER, D3DTEXF_NONE ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_ADDRESSU, D3DTADDRESS_CLAMP ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_ADDRESSV, D3DTADDRESS_CLAMP ); } else { dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MAGFILTER, D3DTEXF_POINT ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MINFILTER, D3DTEXF_POINT ); dx.getStateManager().SetSamplerState( kShaderShadowTextureIndex, D3DSAMP_MIPFILTER, D3DTEXF_POINT ); } // render all objects with shadows and lights for( i = 0; i < nreceivers; ++i ) { SceneEntity& obj = *gSceneReceivers[i].entity; // additively render all lights on this object for( size_t j = 0; j < nlights; ++j ) { Light& light = *gLights[j]; // set the SB dx.getStateManager().SetTexture( kShaderShadowTextureIndex, light.m_RTTexture->getObject() ); // set light constants gLightDir = light.mWorldMat.getAxisZ(); gLightColor = light.m_Color; gShadowTexProj = light.m_TextureProjMatrix; gInvShadowSize.x = 1.0f / light.m_RTSize; gInvShadowSize.y = 1.0f / light.m_RTSize; obj.render( RM_NORMAL, false, true ); } } dx.getStateManager().SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE ); dx.getStateManager().SetRenderState( D3DRS_ZWRITEENABLE, TRUE ); dx.getStateManager().SetRenderState( D3DRS_ZFUNC, D3DCMP_LESSEQUAL ); G_RENDERCTX->directEnd(); } // --------------------------------------------------------------------------
[ [ [ 1, 633 ] ] ]
cea85a299ea6d9114a33a7cd7d5255bb6588f845
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/vis/tasks/vis_create_liveview.h
dd261d87555592f19d971ac6b7517b83b4bc18eb
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,755
h
/************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2004,2005 by SwarmNet (www.swarmnet.de) ** ** and SWARMS (www.swarms.de) ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the GNU General Public License, version 2. ** ************************************************************************/ #ifndef __SHAWN_VIS_TASK_OPEN_LIVEVIEW_H #define __SHAWN_VIS_TASK_OPEN_LIVEVIEW_H #include "../buildfiles/_apps_enable_cmake.h" #ifdef ENABLE_VIS #ifdef HAVE_GLUT #include "apps/vis/base/vis_task.h" namespace vis { /** \brief Creates external Liveview window. * Creates the external Liveview output window. This window is used to * visualize the network state directly, while the simulation is * executed. It runs in an external thread in parallel to the shaun * simulation thread. */ class CreateLiveviewTask : public VisualizationTask { public: ///@name Constructor/Destructor ///@{ CreateLiveviewTask(); virtual ~CreateLiveviewTask(); ///@} ///@name Getter ///@{ /** * The name of the task. */ virtual std::string name( void ) const throw(); /** * A short description of the task. */ virtual std::string description( void ) const throw(); ///@} /** * Runs the task. This ist the task main method. */ virtual void run( shawn::SimulationController& sc ) throw( std::runtime_error ); }; } #endif #endif #endif
[ [ [ 1, 56 ] ] ]
3f280eea2783819660cd5d181e4400793a153b9d
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/tags/techdemo2/engine/ai/src/AgentManager.cpp
9de2be43831a91dd9a3e617c516a0638a0f0778a
[ "ClArtistic", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,904
cpp
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2006 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Perl Artistic License. * * 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 * Perl Artistic License for more details. * * You should have received a copy of the Perl Artistic License * along with this program; if not you can get it here * http://www.perldoc.com/perl5.6/Artistic.html. */ #include "AgentManager.h" #include "Agent.h" #include "PlayerVehicle.h" #include "Creature.h" using namespace Ogre; template<> rl::AgentManager* Singleton<rl::AgentManager>::ms_Singleton = 0; using namespace rl; AgentManager& AgentManager::getSingleton(void) { return Singleton<AgentManager>::getSingleton(); } AgentManager* AgentManager::getSingletonPtr(void) { return Singleton<AgentManager>::getSingletonPtr(); } AgentManager::AgentManager(void) : mAllNeighbors(), mAgents(), mPlayer(NULL) { } AgentManager::~AgentManager(void) { removeAllAgents(); } Agent* AgentManager::createAgent(AgentType type, Creature* character) { SteeringVehicle* vehicle = NULL; if(type == AGENT_PLAYER) { vehicle = new PlayerVehicle(character->getActor()); } Agent* agent = new Agent(character, vehicle); agent->setType(type); if(type == AGENT_PLAYER) { mPlayer = agent; } addAgent(agent); return agent; } Agent* AgentManager::createAgent(DialogCharacter* character) { Agent* agent = new Agent(character); addAgent(agent); return agent; } void AgentManager::addAgent(Agent* agent) { mAgents.push_back(agent); Logger::getSingleton().log( Logger::AI, Logger::LL_MESSAGE, "created AI Agent"); mAllNeighbors.push_back(agent->getVehicle()); } AgentManager::VehicleList AgentManager::getNeighbors(Agent* agent) { return mAllNeighbors; } /* void AgentManager::OnApplyForceAndTorque(PhysicalThing* thing) { // steerToAvoidNeighbors (10.0, const AVGroup& others); } */ void AgentManager::run( Ogre::Real elapsedTime ) { // update agents if(mPlayer != NULL) { mPlayer->update(elapsedTime); } /* for(AgentList::iterator itr = mAgents.begin(); itr != mAgents.end(); ++itr) { // update agents of type "player" only if((*itr)->getType() == AGENT_PLAYER) { (*itr)->update(elapsedTime); break; } }*/ } void AgentManager::removeAllAgents() { for(AgentList::iterator itr = mAgents.begin(); itr != mAgents.end(); ++itr) { delete (*itr); } mAgents.clear(); mAllNeighbors.clear(); mPlayer = NULL; }
[ "tanis@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 121 ] ] ]
197f88cca49b9b9d5776b2b0209bf18d27cb6e7e
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit/chromium/src/WebFrameImpl.cpp
d894a13d204fb06ec236375a35fe18b4123b9929
[ "BSD-2-Clause" ]
permissive
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
76,734
cpp
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // How ownership works // ------------------- // // Big oh represents a refcounted relationship: owner O--- ownee // // WebView (for the toplevel frame only) // O // | // Page O------- Frame (m_mainFrame) O-------O FrameView // || // || // FrameLoader O-------- WebFrame (via FrameLoaderClient) // // FrameLoader and Frame are formerly one object that was split apart because // it got too big. They basically have the same lifetime, hence the double line. // // WebFrame is refcounted and has one ref on behalf of the FrameLoader/Frame. // This is not a normal reference counted pointer because that would require // changing WebKit code that we don't control. Instead, it is created with this // ref initially and it is removed when the FrameLoader is getting destroyed. // // WebFrames are created in two places, first in WebViewImpl when the root // frame is created, and second in WebFrame::CreateChildFrame when sub-frames // are created. WebKit will hook up this object to the FrameLoader/Frame // and the refcount will be correct. // // How frames are destroyed // ------------------------ // // The main frame is never destroyed and is re-used. The FrameLoader is re-used // and a reference to the main frame is kept by the Page. // // When frame content is replaced, all subframes are destroyed. This happens // in FrameLoader::detachFromParent for each subframe. // // Frame going away causes the FrameLoader to get deleted. In FrameLoader's // destructor, it notifies its client with frameLoaderDestroyed. This calls // WebFrame::Closing and then derefs the WebFrame and will cause it to be // deleted (unless an external someone is also holding a reference). #include "config.h" #include "WebFrameImpl.h" #include "Chrome.h" #include "ChromiumBridge.h" #include "ClipboardUtilitiesChromium.h" #include "Console.h" #include "DOMUtilitiesPrivate.h" #include "DOMWindow.h" #include "Document.h" #include "DocumentFragment.h" // Only needed for ReplaceSelectionCommand.h :( #include "DocumentLoader.h" #include "DocumentMarker.h" #include "Editor.h" #include "EventHandler.h" #include "FormState.h" #include "FrameLoadRequest.h" #include "FrameLoader.h" #include "FrameTree.h" #include "FrameView.h" #include "GraphicsContext.h" #include "HTMLCollection.h" #include "HTMLFormElement.h" #include "HTMLFrameOwnerElement.h" #include "HTMLHeadElement.h" #include "HTMLInputElement.h" #include "HTMLLinkElement.h" #include "HTMLNames.h" #include "HistoryItem.h" #include "InspectorController.h" #include "Page.h" #include "PlatformContextSkia.h" #include "PluginDocument.h" #include "PrintContext.h" #include "RenderFrame.h" #include "RenderTreeAsText.h" #include "RenderView.h" #include "RenderWidget.h" #include "ReplaceSelectionCommand.h" #include "ResourceHandle.h" #include "ResourceRequest.h" #include "ScriptController.h" #include "ScriptSourceCode.h" #include "ScriptValue.h" #include "ScrollTypes.h" #include "ScrollbarTheme.h" #include "SelectionController.h" #include "Settings.h" #include "SkiaUtils.h" #include "SubstituteData.h" #include "TextAffinity.h" #include "TextIterator.h" #include "WebAnimationControllerImpl.h" #include "WebConsoleMessage.h" #include "WebDataSourceImpl.h" #include "WebDocument.h" #include "WebFindOptions.h" #include "WebFormElement.h" #include "WebFrameClient.h" #include "WebHistoryItem.h" #include "WebInputElement.h" #include "WebPasswordAutocompleteListener.h" #include "WebPlugin.h" #include "WebPluginContainerImpl.h" #include "WebRange.h" #include "WebRect.h" #include "WebScriptSource.h" #include "WebSecurityOrigin.h" #include "WebSize.h" #include "WebURLError.h" #include "WebVector.h" #include "WebViewImpl.h" #include "XPathResult.h" #include "markup.h" #include <algorithm> #include <wtf/CurrentTime.h> #if OS(DARWIN) #include "LocalCurrentGraphicsContext.h" #endif #if OS(LINUX) #include <gdk/gdk.h> #endif using namespace WebCore; namespace WebKit { static int frameCount = 0; // Key for a StatsCounter tracking how many WebFrames are active. static const char* const webFrameActiveCount = "WebFrameActiveCount"; static const char* const osdType = "application/opensearchdescription+xml"; static const char* const osdRel = "search"; // Backend for contentAsPlainText, this is a recursive function that gets // the text for the current frame and all of its subframes. It will append // the text of each frame in turn to the |output| up to |maxChars| length. // // The |frame| must be non-null. static void frameContentAsPlainText(size_t maxChars, Frame* frame, Vector<UChar>* output) { Document* doc = frame->document(); if (!doc) return; if (!frame->view()) return; // TextIterator iterates over the visual representation of the DOM. As such, // it requires you to do a layout before using it (otherwise it'll crash). if (frame->view()->needsLayout()) frame->view()->layout(); // Select the document body. RefPtr<Range> range(doc->createRange()); ExceptionCode exception = 0; range->selectNodeContents(doc->body(), exception); if (!exception) { // The text iterator will walk nodes giving us text. This is similar to // the plainText() function in TextIterator.h, but we implement the maximum // size and also copy the results directly into a wstring, avoiding the // string conversion. for (TextIterator it(range.get()); !it.atEnd(); it.advance()) { const UChar* chars = it.characters(); if (!chars) { if (it.length()) { // It appears from crash reports that an iterator can get into a state // where the character count is nonempty but the character pointer is // null. advance()ing it will then just add that many to the null // pointer which won't be caught in a null check but will crash. // // A null pointer and 0 length is common for some nodes. // // IF YOU CATCH THIS IN A DEBUGGER please let brettw know. We don't // currently understand the conditions for this to occur. Ideally, the // iterators would never get into the condition so we should fix them // if we can. ASSERT_NOT_REACHED(); break; } // Just got a null node, we can forge ahead! continue; } size_t toAppend = std::min(static_cast<size_t>(it.length()), maxChars - output->size()); output->append(chars, toAppend); if (output->size() >= maxChars) return; // Filled up the buffer. } } // The separator between frames when the frames are converted to plain text. const UChar frameSeparator[] = { '\n', '\n' }; const size_t frameSeparatorLen = 2; // Recursively walk the children. FrameTree* frameTree = frame->tree(); for (Frame* curChild = frameTree->firstChild(); curChild; curChild = curChild->tree()->nextSibling()) { // Ignore the text of non-visible frames. RenderView* contentRenderer = curChild->contentRenderer(); RenderPart* ownerRenderer = curChild->ownerRenderer(); if (!contentRenderer || !contentRenderer->width() || !contentRenderer->height() || (contentRenderer->x() + contentRenderer->width() <= 0) || (contentRenderer->y() + contentRenderer->height() <= 0) || (ownerRenderer && ownerRenderer->style() && ownerRenderer->style()->visibility() != VISIBLE)) { continue; } // Make sure the frame separator won't fill up the buffer, and give up if // it will. The danger is if the separator will make the buffer longer than // maxChars. This will cause the computation above: // maxChars - output->size() // to be a negative number which will crash when the subframe is added. if (output->size() >= maxChars - frameSeparatorLen) return; output->append(frameSeparator, frameSeparatorLen); frameContentAsPlainText(maxChars, curChild, output); if (output->size() >= maxChars) return; // Filled up the buffer. } } WebPluginContainerImpl* WebFrameImpl::pluginContainerFromFrame(Frame* frame) { if (!frame) return 0; if (!frame->document() || !frame->document()->isPluginDocument()) return 0; PluginDocument* pluginDocument = static_cast<PluginDocument*>(frame->document()); return static_cast<WebPluginContainerImpl *>(pluginDocument->pluginWidget()); } // Simple class to override some of PrintContext behavior. Some of the methods // made virtual so that they can be overriden by ChromePluginPrintContext. class ChromePrintContext : public PrintContext, public Noncopyable { public: ChromePrintContext(Frame* frame) : PrintContext(frame) , m_printedPageWidth(0) { } virtual void begin(float width) { ASSERT(!m_printedPageWidth); m_printedPageWidth = width; PrintContext::begin(m_printedPageWidth); } virtual void end() { PrintContext::end(); } virtual float getPageShrink(int pageNumber) const { IntRect pageRect = m_pageRects[pageNumber]; return m_printedPageWidth / pageRect.width(); } // Spools the printed page, a subrect of m_frame. Skip the scale step. // NativeTheme doesn't play well with scaling. Scaling is done browser side // instead. Returns the scale to be applied. // On Linux, we don't have the problem with NativeTheme, hence we let WebKit // do the scaling and ignore the return value. virtual float spoolPage(GraphicsContext& ctx, int pageNumber) { IntRect pageRect = m_pageRects[pageNumber]; float scale = m_printedPageWidth / pageRect.width(); ctx.save(); #if OS(LINUX) ctx.scale(WebCore::FloatSize(scale, scale)); #endif ctx.translate(static_cast<float>(-pageRect.x()), static_cast<float>(-pageRect.y())); ctx.clip(pageRect); m_frame->view()->paintContents(&ctx, pageRect); ctx.restore(); return scale; } virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight) { return PrintContext::computePageRects(printRect, headerHeight, footerHeight, userScaleFactor, outPageHeight); } virtual int pageCount() const { return PrintContext::pageCount(); } virtual bool shouldUseBrowserOverlays() const { return true; } private: // Set when printing. float m_printedPageWidth; }; // Simple class to override some of PrintContext behavior. This is used when // the frame hosts a plugin that supports custom printing. In this case, we // want to delegate all printing related calls to the plugin. class ChromePluginPrintContext : public ChromePrintContext { public: ChromePluginPrintContext(Frame* frame, int printerDPI) : ChromePrintContext(frame), m_pageCount(0), m_printerDPI(printerDPI) { // This HAS to be a frame hosting a full-mode plugin ASSERT(frame->document()->isPluginDocument()); } virtual void begin(float width) { } virtual void end() { WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(m_frame); if (pluginContainer && pluginContainer->supportsPaginatedPrint()) pluginContainer->printEnd(); else ASSERT_NOT_REACHED(); } virtual float getPageShrink(int pageNumber) const { // We don't shrink the page (maybe we should ask the widget ??) return 1.0; } virtual void computePageRects(const FloatRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, float& outPageHeight) { WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(m_frame); if (pluginContainer && pluginContainer->supportsPaginatedPrint()) m_pageCount = pluginContainer->printBegin(IntRect(printRect), m_printerDPI); else ASSERT_NOT_REACHED(); } virtual int pageCount() const { return m_pageCount; } // Spools the printed page, a subrect of m_frame. Skip the scale step. // NativeTheme doesn't play well with scaling. Scaling is done browser side // instead. Returns the scale to be applied. virtual float spoolPage(GraphicsContext& ctx, int pageNumber) { WebPluginContainerImpl* pluginContainer = WebFrameImpl::pluginContainerFromFrame(m_frame); if (pluginContainer && pluginContainer->supportsPaginatedPrint()) pluginContainer->printPage(pageNumber, &ctx); else ASSERT_NOT_REACHED(); return 1.0; } virtual bool shouldUseBrowserOverlays() const { return false; } private: // Set when printing. int m_pageCount; int m_printerDPI; }; static WebDataSource* DataSourceForDocLoader(DocumentLoader* loader) { return loader ? WebDataSourceImpl::fromDocumentLoader(loader) : 0; } // WebFrame ------------------------------------------------------------------- class WebFrameImpl::DeferredScopeStringMatches { public: DeferredScopeStringMatches(WebFrameImpl* webFrame, int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) : m_timer(this, &DeferredScopeStringMatches::doTimeout) , m_webFrame(webFrame) , m_identifier(identifier) , m_searchText(searchText) , m_options(options) , m_reset(reset) { m_timer.startOneShot(0.0); } private: void doTimeout(Timer<DeferredScopeStringMatches>*) { m_webFrame->callScopeStringMatches( this, m_identifier, m_searchText, m_options, m_reset); } Timer<DeferredScopeStringMatches> m_timer; RefPtr<WebFrameImpl> m_webFrame; int m_identifier; WebString m_searchText; WebFindOptions m_options; bool m_reset; }; // WebFrame ------------------------------------------------------------------- int WebFrame::instanceCount() { return frameCount; } WebFrame* WebFrame::frameForEnteredContext() { Frame* frame = ScriptController::retrieveFrameForEnteredContext(); return WebFrameImpl::fromFrame(frame); } WebFrame* WebFrame::frameForCurrentContext() { Frame* frame = ScriptController::retrieveFrameForCurrentContext(); return WebFrameImpl::fromFrame(frame); } WebFrame* WebFrame::fromFrameOwnerElement(const WebElement& element) { return WebFrameImpl::fromFrameOwnerElement( PassRefPtr<Element>(element).get()); } WebString WebFrameImpl::name() const { return m_frame->tree()->name(); } void WebFrameImpl::setName(const WebString& name) { m_frame->tree()->setName(name); } WebURL WebFrameImpl::url() const { const WebDataSource* ds = dataSource(); if (!ds) return WebURL(); return ds->request().url(); } WebURL WebFrameImpl::favIconURL() const { FrameLoader* frameLoader = m_frame->loader(); // The URL to the favicon may be in the header. As such, only // ask the loader for the favicon if it's finished loading. if (frameLoader->state() == FrameStateComplete) { const KURL& url = frameLoader->iconURL(); if (!url.isEmpty()) return url; } return WebURL(); } WebURL WebFrameImpl::openSearchDescriptionURL() const { FrameLoader* frameLoader = m_frame->loader(); if (frameLoader->state() == FrameStateComplete && m_frame->document() && m_frame->document()->head() && !m_frame->tree()->parent()) { HTMLHeadElement* head = m_frame->document()->head(); if (head) { RefPtr<HTMLCollection> children = head->children(); for (Node* child = children->firstItem(); child; child = children->nextItem()) { HTMLLinkElement* linkElement = toHTMLLinkElement(child); if (linkElement && linkElement->type() == osdType && linkElement->rel() == osdRel && !linkElement->href().isEmpty()) return linkElement->href(); } } } return WebURL(); } WebString WebFrameImpl::encoding() const { return frame()->loader()->writer()->encoding(); } WebSize WebFrameImpl::scrollOffset() const { FrameView* view = frameView(); if (view) return view->scrollOffset(); return WebSize(); } WebSize WebFrameImpl::contentsSize() const { return frame()->view()->contentsSize(); } int WebFrameImpl::contentsPreferredWidth() const { if (m_frame->document() && m_frame->document()->renderView()) return m_frame->document()->renderView()->minPrefWidth(); return 0; } int WebFrameImpl::documentElementScrollHeight() const { if (m_frame->document() && m_frame->document()->documentElement()) return m_frame->document()->documentElement()->scrollHeight(); return 0; } bool WebFrameImpl::hasVisibleContent() const { return frame()->view()->visibleWidth() > 0 && frame()->view()->visibleHeight() > 0; } WebView* WebFrameImpl::view() const { return viewImpl(); } WebFrame* WebFrameImpl::opener() const { Frame* opener = 0; if (m_frame) opener = m_frame->loader()->opener(); return fromFrame(opener); } WebFrame* WebFrameImpl::parent() const { Frame* parent = 0; if (m_frame) parent = m_frame->tree()->parent(); return fromFrame(parent); } WebFrame* WebFrameImpl::top() const { if (m_frame) return fromFrame(m_frame->tree()->top()); return 0; } WebFrame* WebFrameImpl::firstChild() const { return fromFrame(frame()->tree()->firstChild()); } WebFrame* WebFrameImpl::lastChild() const { return fromFrame(frame()->tree()->lastChild()); } WebFrame* WebFrameImpl::nextSibling() const { return fromFrame(frame()->tree()->nextSibling()); } WebFrame* WebFrameImpl::previousSibling() const { return fromFrame(frame()->tree()->previousSibling()); } WebFrame* WebFrameImpl::traverseNext(bool wrap) const { return fromFrame(frame()->tree()->traverseNextWithWrap(wrap)); } WebFrame* WebFrameImpl::traversePrevious(bool wrap) const { return fromFrame(frame()->tree()->traversePreviousWithWrap(wrap)); } WebFrame* WebFrameImpl::findChildByName(const WebString& name) const { return fromFrame(frame()->tree()->child(name)); } WebFrame* WebFrameImpl::findChildByExpression(const WebString& xpath) const { if (xpath.isEmpty()) return 0; Document* document = m_frame->document(); ExceptionCode ec = 0; PassRefPtr<XPathResult> xpathResult = document->evaluate(xpath, document, 0, // namespace XPathResult::ORDERED_NODE_ITERATOR_TYPE, 0, // XPathResult object ec); if (!xpathResult.get()) return 0; Node* node = xpathResult->iterateNext(ec); if (!node || !node->isFrameOwnerElement()) return 0; HTMLFrameOwnerElement* frameElement = static_cast<HTMLFrameOwnerElement*>(node); return fromFrame(frameElement->contentFrame()); } WebDocument WebFrameImpl::document() const { if (!m_frame || !m_frame->document()) return WebDocument(); return WebDocument(m_frame->document()); } void WebFrameImpl::forms(WebVector<WebFormElement>& results) const { if (!m_frame) return; RefPtr<HTMLCollection> forms = m_frame->document()->forms(); size_t formCount = 0; for (size_t i = 0; i < forms->length(); ++i) { Node* node = forms->item(i); if (node && node->isHTMLElement()) ++formCount; } WebVector<WebFormElement> temp(formCount); for (size_t i = 0; i < formCount; ++i) { Node* node = forms->item(i); // Strange but true, sometimes item can be 0. if (node && node->isHTMLElement()) temp[i] = static_cast<HTMLFormElement*>(node); } results.swap(temp); } WebAnimationController* WebFrameImpl::animationController() { return &m_animationController; } WebSecurityOrigin WebFrameImpl::securityOrigin() const { if (!m_frame || !m_frame->document()) return WebSecurityOrigin(); return WebSecurityOrigin(m_frame->document()->securityOrigin()); } void WebFrameImpl::grantUniversalAccess() { ASSERT(m_frame && m_frame->document()); if (m_frame && m_frame->document()) m_frame->document()->securityOrigin()->grantUniversalAccess(); } NPObject* WebFrameImpl::windowObject() const { if (!m_frame) return 0; return m_frame->script()->windowScriptNPObject(); } void WebFrameImpl::bindToWindowObject(const WebString& name, NPObject* object) { ASSERT(m_frame); if (!m_frame || !m_frame->script()->canExecuteScripts(NotAboutToExecuteScript)) return; String key = name; #if USE(V8) m_frame->script()->bindToWindowObject(m_frame, key, object); #else notImplemented(); #endif } void WebFrameImpl::executeScript(const WebScriptSource& source) { m_frame->script()->executeScript( ScriptSourceCode(source.code, source.url, source.startLine)); } void WebFrameImpl::executeScriptInIsolatedWorld( int worldId, const WebScriptSource* sourcesIn, unsigned numSources, int extensionGroup) { Vector<ScriptSourceCode> sources; for (unsigned i = 0; i < numSources; ++i) { sources.append(ScriptSourceCode( sourcesIn[i].code, sourcesIn[i].url, sourcesIn[i].startLine)); } m_frame->script()->evaluateInIsolatedWorld(worldId, sources, extensionGroup); } void WebFrameImpl::addMessageToConsole(const WebConsoleMessage& message) { ASSERT(frame()); MessageLevel webCoreMessageLevel; switch (message.level) { case WebConsoleMessage::LevelTip: webCoreMessageLevel = TipMessageLevel; break; case WebConsoleMessage::LevelLog: webCoreMessageLevel = LogMessageLevel; break; case WebConsoleMessage::LevelWarning: webCoreMessageLevel = WarningMessageLevel; break; case WebConsoleMessage::LevelError: webCoreMessageLevel = ErrorMessageLevel; break; default: ASSERT_NOT_REACHED(); return; } frame()->domWindow()->console()->addMessage( OtherMessageSource, LogMessageType, webCoreMessageLevel, message.text, 1, String()); } void WebFrameImpl::collectGarbage() { if (!m_frame) return; if (!m_frame->settings()->isJavaScriptEnabled()) return; // FIXME: Move this to the ScriptController and make it JS neutral. #if USE(V8) m_frame->script()->collectGarbage(); #else notImplemented(); #endif } #if USE(V8) v8::Handle<v8::Value> WebFrameImpl::executeScriptAndReturnValue( const WebScriptSource& source) { return m_frame->script()->executeScript( ScriptSourceCode(source.code, source.url, source.startLine)).v8Value(); } // Returns the V8 context for this frame, or an empty handle if there is none. v8::Local<v8::Context> WebFrameImpl::mainWorldScriptContext() const { if (!m_frame) return v8::Local<v8::Context>(); return V8Proxy::mainWorldContext(m_frame); } #endif bool WebFrameImpl::insertStyleText( const WebString& css, const WebString& id) { Document* document = frame()->document(); if (!document) return false; Element* documentElement = document->documentElement(); if (!documentElement) return false; ExceptionCode err = 0; if (!id.isEmpty()) { Element* oldElement = document->getElementById(id); if (oldElement) { Node* parent = oldElement->parent(); if (!parent) return false; parent->removeChild(oldElement, err); } } RefPtr<Element> stylesheet = document->createElement( HTMLNames::styleTag, false); if (!id.isEmpty()) stylesheet->setAttribute(HTMLNames::idAttr, id); stylesheet->setTextContent(css, err); ASSERT(!err); Node* first = documentElement->firstChild(); bool success = documentElement->insertBefore(stylesheet, first, err); ASSERT(success); return success; } void WebFrameImpl::reload(bool ignoreCache) { m_frame->loader()->history()->saveDocumentAndScrollState(); m_frame->loader()->reload(ignoreCache); } void WebFrameImpl::loadRequest(const WebURLRequest& request) { ASSERT(!request.isNull()); const ResourceRequest& resourceRequest = request.toResourceRequest(); if (resourceRequest.url().protocolIs("javascript")) { loadJavaScriptURL(resourceRequest.url()); return; } m_frame->loader()->load(resourceRequest, false); } void WebFrameImpl::loadHistoryItem(const WebHistoryItem& item) { RefPtr<HistoryItem> historyItem = PassRefPtr<HistoryItem>(item); ASSERT(historyItem.get()); // If there is no currentItem, which happens when we are navigating in // session history after a crash, we need to manufacture one otherwise WebKit // hoarks. This is probably the wrong thing to do, but it seems to work. RefPtr<HistoryItem> currentItem = m_frame->loader()->history()->currentItem(); if (!currentItem) { currentItem = HistoryItem::create(); currentItem->setLastVisitWasFailure(true); m_frame->loader()->history()->setCurrentItem(currentItem.get()); viewImpl()->setCurrentHistoryItem(currentItem.get()); } m_frame->loader()->history()->goToItem( historyItem.get(), FrameLoadTypeIndexedBackForward); } void WebFrameImpl::loadData(const WebData& data, const WebString& mimeType, const WebString& textEncoding, const WebURL& baseURL, const WebURL& unreachableURL, bool replace) { SubstituteData substData(data, mimeType, textEncoding, unreachableURL); ASSERT(substData.isValid()); // If we are loading substitute data to replace an existing load, then // inherit all of the properties of that original request. This way, // reload will re-attempt the original request. It is essential that // we only do this when there is an unreachableURL since a non-empty // unreachableURL informs FrameLoader::reload to load unreachableURL // instead of the currently loaded URL. ResourceRequest request; if (replace && !unreachableURL.isEmpty()) request = m_frame->loader()->originalRequest(); request.setURL(baseURL); m_frame->loader()->load(request, substData, false); if (replace) { // Do this to force WebKit to treat the load as replacing the currently // loaded page. m_frame->loader()->setReplacing(); } } void WebFrameImpl::loadHTMLString(const WebData& data, const WebURL& baseURL, const WebURL& unreachableURL, bool replace) { loadData(data, WebString::fromUTF8("text/html"), WebString::fromUTF8("UTF-8"), baseURL, unreachableURL, replace); } bool WebFrameImpl::isLoading() const { if (!m_frame) return false; return m_frame->loader()->isLoading(); } void WebFrameImpl::stopLoading() { if (!m_frame) return; // FIXME: Figure out what we should really do here. It seems like a bug // that FrameLoader::stopLoading doesn't call stopAllLoaders. m_frame->loader()->stopAllLoaders(); m_frame->loader()->stopLoading(UnloadEventPolicyNone); } WebDataSource* WebFrameImpl::provisionalDataSource() const { FrameLoader* frameLoader = m_frame->loader(); // We regard the policy document loader as still provisional. DocumentLoader* docLoader = frameLoader->provisionalDocumentLoader(); if (!docLoader) docLoader = frameLoader->policyDocumentLoader(); return DataSourceForDocLoader(docLoader); } WebDataSource* WebFrameImpl::dataSource() const { return DataSourceForDocLoader(m_frame->loader()->documentLoader()); } WebHistoryItem WebFrameImpl::previousHistoryItem() const { // We use the previous item here because documentState (filled-out forms) // only get saved to history when it becomes the previous item. The caller // is expected to query the history item after a navigation occurs, after // the desired history item has become the previous entry. return WebHistoryItem(viewImpl()->previousHistoryItem()); } WebHistoryItem WebFrameImpl::currentHistoryItem() const { // If we are still loading, then we don't want to clobber the current // history item as this could cause us to lose the scroll position and // document state. However, it is OK for new navigations. if (m_frame->loader()->loadType() == FrameLoadTypeStandard || !m_frame->loader()->activeDocumentLoader()->isLoadingInAPISense()) m_frame->loader()->history()->saveDocumentAndScrollState(); return WebHistoryItem(m_frame->page()->backForwardList()->currentItem()); } void WebFrameImpl::enableViewSourceMode(bool enable) { if (m_frame) m_frame->setInViewSourceMode(enable); } bool WebFrameImpl::isViewSourceModeEnabled() const { if (m_frame) return m_frame->inViewSourceMode(); return false; } void WebFrameImpl::setReferrerForRequest( WebURLRequest& request, const WebURL& referrerURL) { String referrer; if (referrerURL.isEmpty()) referrer = m_frame->loader()->outgoingReferrer(); else referrer = referrerURL.spec().utf16(); if (SecurityOrigin::shouldHideReferrer(request.url(), referrer)) return; request.setHTTPHeaderField(WebString::fromUTF8("Referer"), referrer); } void WebFrameImpl::dispatchWillSendRequest(WebURLRequest& request) { ResourceResponse response; m_frame->loader()->client()->dispatchWillSendRequest( 0, 0, request.toMutableResourceRequest(), response); } void WebFrameImpl::commitDocumentData(const char* data, size_t length) { m_frame->loader()->documentLoader()->commitData(data, length); } unsigned WebFrameImpl::unloadListenerCount() const { return frame()->domWindow()->pendingUnloadEventListeners(); } bool WebFrameImpl::isProcessingUserGesture() const { return frame()->loader()->isProcessingUserGesture(); } bool WebFrameImpl::willSuppressOpenerInNewFrame() const { return frame()->loader()->suppressOpenerInNewFrame(); } void WebFrameImpl::replaceSelection(const WebString& text) { RefPtr<DocumentFragment> fragment = createFragmentFromText( frame()->selection()->toNormalizedRange().get(), text); applyCommand(ReplaceSelectionCommand::create( frame()->document(), fragment.get(), false, true, true)); } void WebFrameImpl::insertText(const WebString& text) { frame()->editor()->insertText(text, 0); } void WebFrameImpl::setMarkedText( const WebString& text, unsigned location, unsigned length) { Editor* editor = frame()->editor(); editor->confirmComposition(text); Vector<CompositionUnderline> decorations; editor->setComposition(text, decorations, location, length); } void WebFrameImpl::unmarkText() { frame()->editor()->confirmCompositionWithoutDisturbingSelection(); } bool WebFrameImpl::hasMarkedText() const { return frame()->editor()->hasComposition(); } WebRange WebFrameImpl::markedRange() const { return frame()->editor()->compositionRange(); } bool WebFrameImpl::executeCommand(const WebString& name) { ASSERT(frame()); if (name.length() <= 2) return false; // Since we don't have NSControl, we will convert the format of command // string and call the function on Editor directly. String command = name; // Make sure the first letter is upper case. command.replace(0, 1, command.substring(0, 1).upper()); // Remove the trailing ':' if existing. if (command[command.length() - 1] == UChar(':')) command = command.substring(0, command.length() - 1); if (command == "Copy") { WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame()); if (pluginContainer) { pluginContainer->copy(); return true; } } bool rv = true; // Specially handling commands that Editor::execCommand does not directly // support. if (command == "DeleteToEndOfParagraph") { Editor* editor = frame()->editor(); if (!editor->deleteWithDirection(SelectionController::DirectionForward, ParagraphBoundary, true, false)) { editor->deleteWithDirection(SelectionController::DirectionForward, CharacterGranularity, true, false); } } else if (command == "Indent") frame()->editor()->indent(); else if (command == "Outdent") frame()->editor()->outdent(); else if (command == "DeleteBackward") rv = frame()->editor()->command(AtomicString("BackwardDelete")).execute(); else if (command == "DeleteForward") rv = frame()->editor()->command(AtomicString("ForwardDelete")).execute(); else if (command == "AdvanceToNextMisspelling") { // False must be passed here, or the currently selected word will never be // skipped. frame()->editor()->advanceToNextMisspelling(false); } else if (command == "ToggleSpellPanel") frame()->editor()->showSpellingGuessPanel(); else rv = frame()->editor()->command(command).execute(); return rv; } bool WebFrameImpl::executeCommand(const WebString& name, const WebString& value) { ASSERT(frame()); String webName = name; // moveToBeginningOfDocument and moveToEndfDocument are only handled by WebKit // for editable nodes. if (!frame()->editor()->canEdit() && webName == "moveToBeginningOfDocument") return viewImpl()->propagateScroll(ScrollUp, ScrollByDocument); if (!frame()->editor()->canEdit() && webName == "moveToEndOfDocument") return viewImpl()->propagateScroll(ScrollDown, ScrollByDocument); return frame()->editor()->command(webName).execute(value); } bool WebFrameImpl::isCommandEnabled(const WebString& name) const { ASSERT(frame()); return frame()->editor()->command(name).isEnabled(); } void WebFrameImpl::enableContinuousSpellChecking(bool enable) { if (enable == isContinuousSpellCheckingEnabled()) return; frame()->editor()->toggleContinuousSpellChecking(); } bool WebFrameImpl::isContinuousSpellCheckingEnabled() const { return frame()->editor()->isContinuousSpellCheckingEnabled(); } bool WebFrameImpl::hasSelection() const { WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame()); if (pluginContainer) return pluginContainer->plugin()->hasSelection(); // frame()->selection()->isNone() never returns true. return (frame()->selection()->start() != frame()->selection()->end()); } WebRange WebFrameImpl::selectionRange() const { return frame()->selection()->toNormalizedRange(); } WebString WebFrameImpl::selectionAsText() const { WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame()); if (pluginContainer) return pluginContainer->plugin()->selectionAsText(); RefPtr<Range> range = frame()->selection()->toNormalizedRange(); if (!range.get()) return WebString(); String text = range->text(); #if OS(WINDOWS) replaceNewlinesWithWindowsStyleNewlines(text); #endif replaceNBSPWithSpace(text); return text; } WebString WebFrameImpl::selectionAsMarkup() const { WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame()); if (pluginContainer) return pluginContainer->plugin()->selectionAsMarkup(); RefPtr<Range> range = frame()->selection()->toNormalizedRange(); if (!range.get()) return WebString(); return createMarkup(range.get(), 0); } void WebFrameImpl::selectWordAroundPosition(Frame* frame, VisiblePosition pos) { VisibleSelection selection(pos); selection.expandUsingGranularity(WordGranularity); if (frame->selection()->shouldChangeSelection(selection)) { TextGranularity granularity = selection.isRange() ? WordGranularity : CharacterGranularity; frame->selection()->setSelection(selection, granularity); } } bool WebFrameImpl::selectWordAroundCaret() { SelectionController* controller = frame()->selection(); ASSERT(!controller->isNone()); if (controller->isNone() || controller->isRange()) return false; selectWordAroundPosition(frame(), controller->selection().visibleStart()); return true; } int WebFrameImpl::printBegin(const WebSize& pageSize, int printerDPI, bool *useBrowserOverlays) { ASSERT(!frame()->document()->isFrameSet()); // If this is a plugin document, check if the plugin supports its own // printing. If it does, we will delegate all printing to that. WebPluginContainerImpl* pluginContainer = pluginContainerFromFrame(frame()); if (pluginContainer && pluginContainer->supportsPaginatedPrint()) m_printContext.set(new ChromePluginPrintContext(frame(), printerDPI)); else m_printContext.set(new ChromePrintContext(frame())); FloatRect rect(0, 0, static_cast<float>(pageSize.width), static_cast<float>(pageSize.height)); m_printContext->begin(rect.width()); float pageHeight; // We ignore the overlays calculation for now since they are generated in the // browser. pageHeight is actually an output parameter. m_printContext->computePageRects(rect, 0, 0, 1.0, pageHeight); if (useBrowserOverlays) *useBrowserOverlays = m_printContext->shouldUseBrowserOverlays(); return m_printContext->pageCount(); } float WebFrameImpl::getPrintPageShrink(int page) { // Ensure correct state. if (!m_printContext.get() || page < 0) { ASSERT_NOT_REACHED(); return 0; } return m_printContext->getPageShrink(page); } float WebFrameImpl::printPage(int page, WebCanvas* canvas) { // Ensure correct state. if (!m_printContext.get() || page < 0 || !frame() || !frame()->document()) { ASSERT_NOT_REACHED(); return 0; } #if OS(WINDOWS) || OS(LINUX) || OS(FREEBSD) || OS(SOLARIS) PlatformContextSkia context(canvas); GraphicsContext spool(&context); #elif OS(DARWIN) GraphicsContext spool(canvas); LocalCurrentGraphicsContext localContext(&spool); #endif return m_printContext->spoolPage(spool, page); } void WebFrameImpl::printEnd() { ASSERT(m_printContext.get()); if (m_printContext.get()) m_printContext->end(); m_printContext.clear(); } bool WebFrameImpl::isPageBoxVisible(int pageIndex) { return frame()->document()->isPageBoxVisible(pageIndex); } void WebFrameImpl::pageSizeAndMarginsInPixels(int pageIndex, WebSize& pageSize, int& marginTop, int& marginRight, int& marginBottom, int& marginLeft) { IntSize size(pageSize.width, pageSize.height); frame()->document()->pageSizeAndMarginsInPixels(pageIndex, size, marginTop, marginRight, marginBottom, marginLeft); pageSize = size; } bool WebFrameImpl::find(int identifier, const WebString& searchText, const WebFindOptions& options, bool wrapWithinFrame, WebRect* selectionRect) { WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); if (!options.findNext) frame()->page()->unmarkAllTextMatches(); else setMarkerActive(m_activeMatch.get(), false); // Active match is changing. // Starts the search from the current selection. bool startInSelection = true; // If the user has selected something since the last Find operation we want // to start from there. Otherwise, we start searching from where the last Find // operation left off (either a Find or a FindNext operation). VisibleSelection selection(frame()->selection()->selection()); bool activeSelection = !selection.isNone(); if (!activeSelection && m_activeMatch) { selection = VisibleSelection(m_activeMatch.get()); frame()->selection()->setSelection(selection); } ASSERT(frame() && frame()->view()); bool found = frame()->editor()->findString( searchText, options.forward, options.matchCase, wrapWithinFrame, startInSelection); if (found) { // Store which frame was active. This will come in handy later when we // change the active match ordinal below. WebFrameImpl* oldActiveFrame = mainFrameImpl->m_activeMatchFrame; // Set this frame as the active frame (the one with the active highlight). mainFrameImpl->m_activeMatchFrame = this; // We found something, so we can now query the selection for its position. VisibleSelection newSelection(frame()->selection()->selection()); IntRect currSelectionRect; // If we thought we found something, but it couldn't be selected (perhaps // because it was marked -webkit-user-select: none), we can't set it to // be active but we still continue searching. This matches Safari's // behavior, including some oddities when selectable and un-selectable text // are mixed on a page: see https://bugs.webkit.org/show_bug.cgi?id=19127. if (newSelection.isNone() || (newSelection.start() == newSelection.end())) m_activeMatch = 0; else { m_activeMatch = newSelection.toNormalizedRange(); currSelectionRect = m_activeMatch->boundingBox(); setMarkerActive(m_activeMatch.get(), true); // Active. // WebKit draws the highlighting for all matches. executeCommand(WebString::fromUTF8("Unselect")); } // Make sure no node is focused. See http://crbug.com/38700. frame()->document()->setFocusedNode(0); if (!options.findNext || activeSelection) { // This is either a Find operation or a Find-next from a new start point // due to a selection, so we set the flag to ask the scoping effort // to find the active rect for us so we can update the ordinal (n of m). m_locatingActiveRect = true; } else { if (oldActiveFrame != this) { // If the active frame has changed it means that we have a multi-frame // page and we just switch to searching in a new frame. Then we just // want to reset the index. if (options.forward) m_activeMatchIndex = 0; else m_activeMatchIndex = m_lastMatchCount - 1; } else { // We are still the active frame, so increment (or decrement) the // |m_activeMatchIndex|, wrapping if needed (on single frame pages). options.forward ? ++m_activeMatchIndex : --m_activeMatchIndex; if (m_activeMatchIndex + 1 > m_lastMatchCount) m_activeMatchIndex = 0; if (m_activeMatchIndex == -1) m_activeMatchIndex = m_lastMatchCount - 1; } if (selectionRect) { WebRect rect = frame()->view()->convertToContainingWindow(currSelectionRect); rect.x -= frameView()->scrollOffset().width(); rect.y -= frameView()->scrollOffset().height(); *selectionRect = rect; reportFindInPageSelection(rect, m_activeMatchIndex + 1, identifier); } } } else { // Nothing was found in this frame. m_activeMatch = 0; // Erase all previous tickmarks and highlighting. invalidateArea(InvalidateAll); } return found; } void WebFrameImpl::stopFinding(bool clearSelection) { if (!clearSelection) setFindEndstateFocusAndSelection(); cancelPendingScopingEffort(); // Remove all markers for matches found and turn off the highlighting. frame()->document()->markers()->removeMarkers(DocumentMarker::TextMatch); frame()->editor()->setMarkedTextMatchesAreHighlighted(false); // Let the frame know that we don't want tickmarks or highlighting anymore. invalidateArea(InvalidateAll); } void WebFrameImpl::scopeStringMatches(int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) { if (!shouldScopeMatches(searchText)) return; WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); if (reset) { // This is a brand new search, so we need to reset everything. // Scoping is just about to begin. m_scopingComplete = false; // Clear highlighting for this frame. if (frame()->editor()->markedTextMatchesAreHighlighted()) frame()->page()->unmarkAllTextMatches(); // Clear the counters from last operation. m_lastMatchCount = 0; m_nextInvalidateAfter = 0; m_resumeScopingFromRange = 0; mainFrameImpl->m_framesScopingCount++; // Now, defer scoping until later to allow find operation to finish quickly. scopeStringMatchesSoon( identifier, searchText, options, false); // false=we just reset, so don't do it again. return; } RefPtr<Range> searchRange(rangeOfContents(frame()->document())); ExceptionCode ec = 0, ec2 = 0; if (m_resumeScopingFromRange.get()) { // This is a continuation of a scoping operation that timed out and didn't // complete last time around, so we should start from where we left off. searchRange->setStart(m_resumeScopingFromRange->startContainer(), m_resumeScopingFromRange->startOffset(ec2) + 1, ec); if (ec || ec2) { if (ec2) // A non-zero |ec| happens when navigating during search. ASSERT_NOT_REACHED(); return; } } // This timeout controls how long we scope before releasing control. This // value does not prevent us from running for longer than this, but it is // periodically checked to see if we have exceeded our allocated time. const double maxScopingDuration = 0.1; // seconds int matchCount = 0; bool timedOut = false; double startTime = currentTime(); do { // Find next occurrence of the search string. // FIXME: (http://b/1088245) This WebKit operation may run for longer // than the timeout value, and is not interruptible as it is currently // written. We may need to rewrite it with interruptibility in mind, or // find an alternative. RefPtr<Range> resultRange(findPlainText(searchRange.get(), searchText, true, options.matchCase)); if (resultRange->collapsed(ec)) { if (!resultRange->startContainer()->isInShadowTree()) break; searchRange = rangeOfContents(frame()->document()); searchRange->setStartAfter( resultRange->startContainer()->shadowAncestorNode(), ec); continue; } // A non-collapsed result range can in some funky whitespace cases still not // advance the range's start position (4509328). Break to avoid infinite // loop. (This function is based on the implementation of // Frame::markAllMatchesForText, which is where this safeguard comes from). VisiblePosition newStart = endVisiblePosition(resultRange.get(), DOWNSTREAM); if (newStart == startVisiblePosition(searchRange.get(), DOWNSTREAM)) break; // Only treat the result as a match if it is visible if (frame()->editor()->insideVisibleArea(resultRange.get())) { ++matchCount; setStart(searchRange.get(), newStart); Node* shadowTreeRoot = searchRange->shadowTreeRootNode(); if (searchRange->collapsed(ec) && shadowTreeRoot) searchRange->setEnd(shadowTreeRoot, shadowTreeRoot->childNodeCount(), ec); // Catch a special case where Find found something but doesn't know what // the bounding box for it is. In this case we set the first match we find // as the active rect. IntRect resultBounds = resultRange->boundingBox(); IntRect activeSelectionRect; if (m_locatingActiveRect) { activeSelectionRect = m_activeMatch.get() ? m_activeMatch->boundingBox() : resultBounds; } // If the Find function found a match it will have stored where the // match was found in m_activeSelectionRect on the current frame. If we // find this rect during scoping it means we have found the active // tickmark. bool foundActiveMatch = false; if (m_locatingActiveRect && (activeSelectionRect == resultBounds)) { // We have found the active tickmark frame. mainFrameImpl->m_activeMatchFrame = this; foundActiveMatch = true; // We also know which tickmark is active now. m_activeMatchIndex = matchCount - 1; // To stop looking for the active tickmark, we set this flag. m_locatingActiveRect = false; // Notify browser of new location for the selected rectangle. resultBounds.move(-frameView()->scrollOffset().width(), -frameView()->scrollOffset().height()); reportFindInPageSelection( frame()->view()->convertToContainingWindow(resultBounds), m_activeMatchIndex + 1, identifier); } addMarker(resultRange.get(), foundActiveMatch); } m_resumeScopingFromRange = resultRange; timedOut = (currentTime() - startTime) >= maxScopingDuration; } while (!timedOut); // Remember what we search for last time, so we can skip searching if more // letters are added to the search string (and last outcome was 0). m_lastSearchString = searchText; if (matchCount > 0) { frame()->editor()->setMarkedTextMatchesAreHighlighted(true); m_lastMatchCount += matchCount; // Let the mainframe know how much we found during this pass. mainFrameImpl->increaseMatchCount(matchCount, identifier); } if (timedOut) { // If we found anything during this pass, we should redraw. However, we // don't want to spam too much if the page is extremely long, so if we // reach a certain point we start throttling the redraw requests. if (matchCount > 0) invalidateIfNecessary(); // Scoping effort ran out of time, lets ask for another time-slice. scopeStringMatchesSoon( identifier, searchText, options, false); // don't reset. return; // Done for now, resume work later. } // This frame has no further scoping left, so it is done. Other frames might, // of course, continue to scope matches. m_scopingComplete = true; mainFrameImpl->m_framesScopingCount--; // If this is the last frame to finish scoping we need to trigger the final // update to be sent. if (!mainFrameImpl->m_framesScopingCount) mainFrameImpl->increaseMatchCount(0, identifier); // This frame is done, so show any scrollbar tickmarks we haven't drawn yet. invalidateArea(InvalidateScrollbar); } void WebFrameImpl::cancelPendingScopingEffort() { deleteAllValues(m_deferredScopingWork); m_deferredScopingWork.clear(); m_activeMatchIndex = -1; } void WebFrameImpl::increaseMatchCount(int count, int identifier) { // This function should only be called on the mainframe. ASSERT(!parent()); m_totalMatchCount += count; // Update the UI with the latest findings. if (client()) client()->reportFindInPageMatchCount(identifier, m_totalMatchCount, !m_framesScopingCount); } void WebFrameImpl::reportFindInPageSelection(const WebRect& selectionRect, int activeMatchOrdinal, int identifier) { // Update the UI with the latest selection rect. if (client()) client()->reportFindInPageSelection(identifier, ordinalOfFirstMatchForFrame(this) + activeMatchOrdinal, selectionRect); } void WebFrameImpl::resetMatchCount() { m_totalMatchCount = 0; m_framesScopingCount = 0; } WebString WebFrameImpl::contentAsText(size_t maxChars) const { if (!m_frame) return WebString(); Vector<UChar> text; frameContentAsPlainText(maxChars, m_frame, &text); return String::adopt(text); } WebString WebFrameImpl::contentAsMarkup() const { return createFullMarkup(m_frame->document()); } WebString WebFrameImpl::renderTreeAsText() const { return externalRepresentation(m_frame); } WebString WebFrameImpl::counterValueForElementById(const WebString& id) const { if (!m_frame) return WebString(); Element* element = m_frame->document()->getElementById(id); if (!element) return WebString(); return counterValueForElement(element); } WebString WebFrameImpl::markerTextForListItem(const WebElement& webElement) const { return WebCore::markerTextForListItem(const_cast<Element*>(webElement.constUnwrap<Element>())); } int WebFrameImpl::pageNumberForElementById(const WebString& id, float pageWidthInPixels, float pageHeightInPixels) const { if (!m_frame) return -1; Element* element = m_frame->document()->getElementById(id); if (!element) return -1; FloatSize pageSize(pageWidthInPixels, pageHeightInPixels); return PrintContext::pageNumberForElement(element, pageSize); } WebRect WebFrameImpl::selectionBoundsRect() const { if (hasSelection()) return IntRect(frame()->selection()->bounds(false)); return WebRect(); } bool WebFrameImpl::selectionStartHasSpellingMarkerFor(int from, int length) const { if (!m_frame) return false; return m_frame->editor()->selectionStartHasSpellingMarkerFor(from, length); } // WebFrameImpl public --------------------------------------------------------- PassRefPtr<WebFrameImpl> WebFrameImpl::create(WebFrameClient* client) { return adoptRef(new WebFrameImpl(client)); } WebFrameImpl::WebFrameImpl(WebFrameClient* client) : m_frameLoaderClient(this) , m_client(client) , m_activeMatchFrame(0) , m_activeMatchIndex(-1) , m_locatingActiveRect(false) , m_resumeScopingFromRange(0) , m_lastMatchCount(-1) , m_totalMatchCount(-1) , m_framesScopingCount(-1) , m_scopingComplete(false) , m_nextInvalidateAfter(0) , m_animationController(this) { ChromiumBridge::incrementStatsCounter(webFrameActiveCount); frameCount++; } WebFrameImpl::~WebFrameImpl() { ChromiumBridge::decrementStatsCounter(webFrameActiveCount); frameCount--; cancelPendingScopingEffort(); clearPasswordListeners(); } void WebFrameImpl::initializeAsMainFrame(WebViewImpl* webViewImpl) { RefPtr<Frame> frame = Frame::create(webViewImpl->page(), 0, &m_frameLoaderClient); m_frame = frame.get(); // Add reference on behalf of FrameLoader. See comments in // WebFrameLoaderClient::frameLoaderDestroyed for more info. ref(); // We must call init() after m_frame is assigned because it is referenced // during init(). m_frame->init(); } PassRefPtr<Frame> WebFrameImpl::createChildFrame( const FrameLoadRequest& request, HTMLFrameOwnerElement* ownerElement) { RefPtr<WebFrameImpl> webframe(adoptRef(new WebFrameImpl(m_client))); // Add an extra ref on behalf of the Frame/FrameLoader, which references the // WebFrame via the FrameLoaderClient interface. See the comment at the top // of this file for more info. webframe->ref(); RefPtr<Frame> childFrame = Frame::create( m_frame->page(), ownerElement, &webframe->m_frameLoaderClient); webframe->m_frame = childFrame.get(); childFrame->tree()->setName(request.frameName()); m_frame->tree()->appendChild(childFrame); // Frame::init() can trigger onload event in the parent frame, // which may detach this frame and trigger a null-pointer access // in FrameTree::removeChild. Move init() after appendChild call // so that webframe->mFrame is in the tree before triggering // onload event handler. // Because the event handler may set webframe->mFrame to null, // it is necessary to check the value after calling init() and // return without loading URL. // (b:791612) childFrame->init(); // create an empty document if (!childFrame->tree()->parent()) return 0; m_frame->loader()->loadURLIntoChildFrame( request.resourceRequest().url(), request.resourceRequest().httpReferrer(), childFrame.get()); // A synchronous navigation (about:blank) would have already processed // onload, so it is possible for the frame to have already been destroyed by // script in the page. if (!childFrame->tree()->parent()) return 0; return childFrame.release(); } void WebFrameImpl::layout() { // layout this frame FrameView* view = m_frame->view(); if (view) view->updateLayoutAndStyleIfNeededRecursive(); } void WebFrameImpl::paintWithContext(GraphicsContext& gc, const WebRect& rect) { IntRect dirtyRect(rect); gc.save(); if (m_frame->document() && frameView()) { gc.clip(dirtyRect); frameView()->paint(&gc, dirtyRect); m_frame->page()->inspectorController()->drawNodeHighlight(gc); } else gc.fillRect(dirtyRect, Color::white, DeviceColorSpace); gc.restore(); } void WebFrameImpl::paint(WebCanvas* canvas, const WebRect& rect) { if (rect.isEmpty()) return; #if WEBKIT_USING_CG GraphicsContext gc(canvas); LocalCurrentGraphicsContext localContext(&gc); #elif WEBKIT_USING_SKIA PlatformContextSkia context(canvas); // PlatformGraphicsContext is actually a pointer to PlatformContextSkia GraphicsContext gc(reinterpret_cast<PlatformGraphicsContext*>(&context)); #else notImplemented(); #endif paintWithContext(gc, rect); } void WebFrameImpl::createFrameView() { ASSERT(m_frame); // If m_frame doesn't exist, we probably didn't init properly. Page* page = m_frame->page(); ASSERT(page); ASSERT(page->mainFrame()); bool isMainFrame = m_frame == page->mainFrame(); if (isMainFrame && m_frame->view()) m_frame->view()->setParentVisible(false); m_frame->setView(0); WebViewImpl* webView = viewImpl(); RefPtr<FrameView> view; if (isMainFrame) view = FrameView::create(m_frame, webView->size()); else view = FrameView::create(m_frame); m_frame->setView(view); if (webView->isTransparent()) view->setTransparent(true); // FIXME: The Mac code has a comment about this possibly being unnecessary. // See installInFrame in WebCoreFrameBridge.mm if (m_frame->ownerRenderer()) m_frame->ownerRenderer()->setWidget(view.get()); if (HTMLFrameOwnerElement* owner = m_frame->ownerElement()) view->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff); if (isMainFrame) view->setParentVisible(true); } WebFrameImpl* WebFrameImpl::fromFrame(Frame* frame) { if (!frame) return 0; return static_cast<FrameLoaderClientImpl*>(frame->loader()->client())->webFrame(); } WebFrameImpl* WebFrameImpl::fromFrameOwnerElement(Element* element) { if (!element || !element->isFrameOwnerElement() || (!element->hasTagName(HTMLNames::iframeTag) && !element->hasTagName(HTMLNames::frameTag))) return 0; HTMLFrameOwnerElement* frameElement = static_cast<HTMLFrameOwnerElement*>(element); return fromFrame(frameElement->contentFrame()); } WebViewImpl* WebFrameImpl::viewImpl() const { if (!m_frame) return 0; return WebViewImpl::fromPage(m_frame->page()); } WebDataSourceImpl* WebFrameImpl::dataSourceImpl() const { return static_cast<WebDataSourceImpl*>(dataSource()); } WebDataSourceImpl* WebFrameImpl::provisionalDataSourceImpl() const { return static_cast<WebDataSourceImpl*>(provisionalDataSource()); } void WebFrameImpl::setFindEndstateFocusAndSelection() { WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); if (this == mainFrameImpl->activeMatchFrame() && m_activeMatch.get()) { // If the user has set the selection since the match was found, we // don't focus anything. VisibleSelection selection(frame()->selection()->selection()); if (!selection.isNone()) return; // Try to find the first focusable node up the chain, which will, for // example, focus links if we have found text within the link. Node* node = m_activeMatch->firstNode(); while (node && !node->isFocusable() && node != frame()->document()) node = node->parent(); if (node && node != frame()->document()) { // Found a focusable parent node. Set focus to it. frame()->document()->setFocusedNode(node); return; } // Iterate over all the nodes in the range until we find a focusable node. // This, for example, sets focus to the first link if you search for // text and text that is within one or more links. node = m_activeMatch->firstNode(); while (node && node != m_activeMatch->pastLastNode()) { if (node->isFocusable()) { frame()->document()->setFocusedNode(node); return; } node = node->traverseNextNode(); } // No node related to the active match was focusable, so set the // active match as the selection (so that when you end the Find session, // you'll have the last thing you found highlighted) and make sure that // we have nothing focused (otherwise you might have text selected but // a link focused, which is weird). frame()->selection()->setSelection(m_activeMatch.get()); frame()->document()->setFocusedNode(0); } } void WebFrameImpl::didFail(const ResourceError& error, bool wasProvisional) { if (!client()) return; WebURLError webError = error; if (wasProvisional) client()->didFailProvisionalLoad(this, webError); else client()->didFailLoad(this, webError); } void WebFrameImpl::setCanHaveScrollbars(bool canHaveScrollbars) { m_frame->view()->setCanHaveScrollbars(canHaveScrollbars); } bool WebFrameImpl::registerPasswordListener( WebInputElement inputElement, WebPasswordAutocompleteListener* listener) { RefPtr<HTMLInputElement> element(inputElement.unwrap<HTMLInputElement>()); if (!m_passwordListeners.add(element, listener).second) { delete listener; return false; } return true; } void WebFrameImpl::notifiyPasswordListenerOfAutocomplete( const WebInputElement& inputElement) { const HTMLInputElement* element = inputElement.constUnwrap<HTMLInputElement>(); WebPasswordAutocompleteListener* listener = getPasswordListener(element); // Password listeners need to autocomplete other fields that depend on the // input element with autofill suggestions. if (listener) listener->performInlineAutocomplete(element->value(), false, false); } WebPasswordAutocompleteListener* WebFrameImpl::getPasswordListener( const HTMLInputElement* inputElement) { return m_passwordListeners.get(RefPtr<HTMLInputElement>(const_cast<HTMLInputElement*>(inputElement))); } // WebFrameImpl private -------------------------------------------------------- void WebFrameImpl::closing() { m_frame = 0; } void WebFrameImpl::invalidateArea(AreaToInvalidate area) { ASSERT(frame() && frame()->view()); FrameView* view = frame()->view(); if ((area & InvalidateAll) == InvalidateAll) view->invalidateRect(view->frameRect()); else { if ((area & InvalidateContentArea) == InvalidateContentArea) { IntRect contentArea( view->x(), view->y(), view->visibleWidth(), view->visibleHeight()); IntRect frameRect = view->frameRect(); contentArea.move(-frameRect.topLeft().x(), -frameRect.topLeft().y()); view->invalidateRect(contentArea); } if ((area & InvalidateScrollbar) == InvalidateScrollbar) { // Invalidate the vertical scroll bar region for the view. IntRect scrollBarVert( view->x() + view->visibleWidth(), view->y(), ScrollbarTheme::nativeTheme()->scrollbarThickness(), view->visibleHeight()); IntRect frameRect = view->frameRect(); scrollBarVert.move(-frameRect.topLeft().x(), -frameRect.topLeft().y()); view->invalidateRect(scrollBarVert); } } } void WebFrameImpl::addMarker(Range* range, bool activeMatch) { // Use a TextIterator to visit the potentially multiple nodes the range // covers. TextIterator markedText(range); for (; !markedText.atEnd(); markedText.advance()) { RefPtr<Range> textPiece = markedText.range(); int exception = 0; DocumentMarker marker = { DocumentMarker::TextMatch, textPiece->startOffset(exception), textPiece->endOffset(exception), "", activeMatch }; if (marker.endOffset > marker.startOffset) { // Find the node to add a marker to and add it. Node* node = textPiece->startContainer(exception); frame()->document()->markers()->addMarker(node, marker); // Rendered rects for markers in WebKit are not populated until each time // the markers are painted. However, we need it to happen sooner, because // the whole purpose of tickmarks on the scrollbar is to show where // matches off-screen are (that haven't been painted yet). Vector<DocumentMarker> markers = frame()->document()->markers()->markersForNode(node); frame()->document()->markers()->setRenderedRectForMarker( textPiece->startContainer(exception), markers[markers.size() - 1], range->boundingBox()); } } } void WebFrameImpl::setMarkerActive(Range* range, bool active) { WebCore::ExceptionCode ec; if (!range || range->collapsed(ec)) return; frame()->document()->markers()->setMarkersActive(range, active); } int WebFrameImpl::ordinalOfFirstMatchForFrame(WebFrameImpl* frame) const { int ordinal = 0; WebFrameImpl* mainFrameImpl = viewImpl()->mainFrameImpl(); // Iterate from the main frame up to (but not including) |frame| and // add up the number of matches found so far. for (WebFrameImpl* it = mainFrameImpl; it != frame; it = static_cast<WebFrameImpl*>(it->traverseNext(true))) { if (it->m_lastMatchCount > 0) ordinal += it->m_lastMatchCount; } return ordinal; } bool WebFrameImpl::shouldScopeMatches(const String& searchText) { // Don't scope if we can't find a frame or a view or if the frame is not visible. // The user may have closed the tab/application, so abort. if (!frame() || !frame()->view() || !hasVisibleContent()) return false; ASSERT(frame()->document() && frame()->view()); // If the frame completed the scoping operation and found 0 matches the last // time it was searched, then we don't have to search it again if the user is // just adding to the search string or sending the same search string again. if (m_scopingComplete && !m_lastSearchString.isEmpty() && !m_lastMatchCount) { // Check to see if the search string prefixes match. String previousSearchPrefix = searchText.substring(0, m_lastSearchString.length()); if (previousSearchPrefix == m_lastSearchString) return false; // Don't search this frame, it will be fruitless. } return true; } void WebFrameImpl::scopeStringMatchesSoon(int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) { m_deferredScopingWork.append(new DeferredScopeStringMatches( this, identifier, searchText, options, reset)); } void WebFrameImpl::callScopeStringMatches(DeferredScopeStringMatches* caller, int identifier, const WebString& searchText, const WebFindOptions& options, bool reset) { m_deferredScopingWork.remove(m_deferredScopingWork.find(caller)); scopeStringMatches(identifier, searchText, options, reset); // This needs to happen last since searchText is passed by reference. delete caller; } void WebFrameImpl::invalidateIfNecessary() { if (m_lastMatchCount > m_nextInvalidateAfter) { // FIXME: (http://b/1088165) Optimize the drawing of the tickmarks and // remove this. This calculation sets a milestone for when next to // invalidate the scrollbar and the content area. We do this so that we // don't spend too much time drawing the scrollbar over and over again. // Basically, up until the first 500 matches there is no throttle. // After the first 500 matches, we set set the milestone further and // further out (750, 1125, 1688, 2K, 3K). static const int startSlowingDownAfter = 500; static const int slowdown = 750; int i = (m_lastMatchCount / startSlowingDownAfter); m_nextInvalidateAfter += i * slowdown; invalidateArea(InvalidateScrollbar); } } void WebFrameImpl::clearPasswordListeners() { deleteAllValues(m_passwordListeners); m_passwordListeners.clear(); } void WebFrameImpl::loadJavaScriptURL(const KURL& url) { // This is copied from ScriptController::executeIfJavaScriptURL. // Unfortunately, we cannot just use that method since it is private, and // it also doesn't quite behave as we require it to for bookmarklets. The // key difference is that we need to suppress loading the string result // from evaluating the JS URL if executing the JS URL resulted in a // location change. We also allow a JS URL to be loaded even if scripts on // the page are otherwise disabled. if (!m_frame->document() || !m_frame->page()) return; String script = decodeURLEscapeSequences(url.string().substring(strlen("javascript:"))); ScriptValue result = m_frame->script()->executeScript(script, true); String scriptResult; if (!result.getString(scriptResult)) return; if (!m_frame->redirectScheduler()->locationChangePending()) m_frame->loader()->writer()->replaceDocument(scriptResult); } } // namespace WebKit
[ [ [ 1, 2202 ] ] ]
3afabe8c79ee60085dbb6d01cde8b48d9637f2d8
3aa746598879eaefa782bf732b444f51c22e5351
/NMozLib/Source/Browser.cpp
a8a6f16fc65f8761ad81342617d32eb4d85cb373
[]
no_license
tonytonyfly/nmozlib
0cdf5087815790d4cd98819de5e021e94eee8566
e71c7887816eb92713c049b749733c1ece550759
refs/heads/master
2021-01-01T04:57:33.819398
2008-02-11T02:26:02
2008-02-11T02:26:02
58,304,343
0
0
null
null
null
null
UTF-8
C++
false
false
6,164
cpp
/* This file is part of NMozLib, "Navi Mozilla Library", a wrapper for Mozilla Gecko Copyright (C) 2008 Adam J. Simmons http://code.google.com/p/nmozlib/ Portions Copyright (C) 2006 Callum Prentice and Linden Lab Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // Windows specific switches #ifdef WIN32 // appears to be required by LibXUL/Mozilla code to avoid crashes in debug versions of their code (undef'd at end of this file) #ifdef _DEBUG #define DEBUG 1 #endif #endif // WIN32 #include "Browser.h" #include "MozillaBrowserWindow.h" #ifdef WIN32 #pragma warning( disable : 4265 ) // "class has virtual functions, but destructor is not virtual" #pragma warning( disable : 4291 ) // (no matching operator delete found; memory will not be freed if initialization throws an exception) #endif // WIN32 #include "nsBuildID.h" #include "nsICacheService.h" #include "nsIPref.h" #include "nsNetCID.h" #include "nsProfileDirServiceProvider.h" #include "nsXULAppAPI.h" using namespace NMozLib; Browser* Browser::instance = 0; Browser::Browser(const std::string& runtimeDir, const std::string& profileDir) { nsCOMPtr<nsILocalFile> appDir; nsresult result = NS_NewNativeLocalFile(nsCString(runtimeDir.c_str()), PR_FALSE, getter_AddRefs(appDir)); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, invalid runtime directory specified."); result = XRE_InitEmbedding(appDir, appDir, nsnull, nsnull, 0); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, unable to initialize XULRunner using the specified runtime directory."); nsCOMPtr<nsILocalFile> appDataDir; NS_NewNativeLocalFile(nsCString(runtimeDir.c_str()), PR_TRUE, getter_AddRefs(appDataDir)); result = appDataDir->Append(NS_ConvertUTF8toUCS2(profileDir.c_str())); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, invalid profile directory specified."); nsCOMPtr<nsILocalFile> localAppDataDir(do_QueryInterface(appDataDir)); nsCOMPtr<nsProfileDirServiceProvider> locProvider; result = NS_NewProfileDirServiceProvider(PR_TRUE, getter_AddRefs(locProvider)); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, unable to instantiate ProfileDirServiceProvider."); result = locProvider->Register(); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, unable to register ProfileDirServiceProvider."); result = locProvider->SetProfileDir(localAppDataDir); if(NS_FAILED(result)) throw std::exception("NMozLib::Browser, unable to set profile directory."); // TODO: temporary fix - need to do this in the absence of the relevant dialogs setBooleanPref("security.warn_entering_secure", false); setBooleanPref("security.warn_entering_weak", false); setBooleanPref("security.warn_leaving_secure", false); setBooleanPref("security.warn_submit_insecure", false); instance = this; } Browser::~Browser() { for(WindowIter i = windows.begin(); i != windows.end();) { MozillaBrowserWindow* browserWin = static_cast<MozillaBrowserWindow*>(*i); i = windows.erase(i); browserWin->destroy(); } XRE_TermEmbedding(); instance = 0; } Browser& Browser::Get() { if(!instance) throw std::exception("In NMozLib::Browser::Get, singleton hasn't been instantiated yet!"); return *instance; } Browser* Browser::GetPointer() { return instance; } BrowserWindow* Browser::createBrowserWindow(void* nativeWindowHandle, int width, int height) { MozillaBrowserWindow* newBrowser = new MozillaBrowserWindow(nativeWindowHandle, width, height); windows.push_back(newBrowser); return newBrowser; } void Browser::destroyBrowserWindow(BrowserWindow* browserWindow) { for(WindowIter i = windows.begin(); i != windows.end(); i++) { if(*i == browserWindow) { windows.erase(i); break; } } //delete static_cast<MozillaBrowserWindow*>(browserWindow); static_cast<MozillaBrowserWindow*>(browserWindow)->destroy(); } bool Browser::setBooleanPref(const std::string& prefName, bool value) { nsresult result; nsCOMPtr<nsIPref> pref = do_CreateInstance(NS_PREF_CONTRACTID, &result); if(NS_FAILED(result)) return false; result = pref->SetBoolPref(prefName.c_str(), (PRBool)value); return NS_SUCCEEDED(result); } bool Browser::setIntegerPref(const std::string& prefName, int value) { nsresult result; nsCOMPtr<nsIPref> pref = do_CreateInstance(NS_PREF_CONTRACTID, &result); if(NS_FAILED(result)) return false; result = pref->SetIntPref(prefName.c_str(), (PRInt32)value); return NS_SUCCEEDED(result); } bool Browser::setStringPref(const std::string& prefName, const std::string& value) { nsresult result; nsCOMPtr<nsIPref> pref = do_CreateInstance(NS_PREF_CONTRACTID, &result); if(NS_FAILED(result)) return false; result = pref->SetCharPref(prefName.c_str(), value.c_str()); return NS_SUCCEEDED(result); } void Browser::clearCache() { nsresult result; nsCOMPtr<nsICacheService> cacheService = do_GetService(NS_CACHESERVICE_CONTRACTID, &result); if(NS_FAILED(result)) return; cacheService->EvictEntries(nsICache::STORE_ANYWHERE); } std::string Browser::getVersion() { return std::string(GRE_BUILD_ID); } // Windows specific switches #ifdef WIN32 // #define required by this file for LibXUL/Mozilla code to avoid crashes in their debug code #ifdef _DEBUG #undef DEBUG #endif #endif // WIN32
[ "ajs15822@be7176e2-5d45-0410-b9dd-a1b14b2f9e02" ]
[ [ [ 1, 201 ] ] ]
a211fa2d0444fba0fb2a2e0c22402b52bf9684ac
0c5fd443401312fafae18ea6a9d17bac9ee61474
/code/demos/Pong/PongState.h
1c8a1908a25c223f46e010fbbde94251414cdef5
[]
no_license
nurF/Brute-Force-Game-Engine
fcfebc997d6ab487508a5706b849e9d7bc66792d
b930472429ec6d6f691230e36076cd2c868d853d
refs/heads/master
2021-01-18T09:29:44.038036
2011-12-02T17:31:59
2011-12-02T17:31:59
2,877,061
1
0
null
null
null
null
UTF-8
C++
false
false
6,195
h
/* ___ _________ ____ __ / _ )/ __/ ___/____/ __/___ ___ _/_/___ ___ / _ / _// (_ //___/ _/ / _ | _ `/ // _ | -_) /____/_/ \___/ /___//_//_|_, /_//_//_|__/ /___/ This file is part of the Brute-Force Game Engine, BFG-Engine For the latest info, see http://www.brute-force-games.com Copyright (c) 2011 Brute-Force Games GbR The BFG-Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The BFG-Engine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the BFG-Engine. If not, see <http://www.gnu.org/licenses/>. */ #ifndef __PONG_STATE_H_ #define __PONG_STATE_H_ #include <EventSystem/Emitter.h> #include <EventSystem/EventFactory.h> #include <Core/ClockUtils.h> #include <Core/Path.h> #include <Core/Types.h> #include <Core/Utils.h> #include <Controller/ControllerEvents.h> #include <Controller/ControllerInterface.h> #include <Model/Loader/Types.h> #include <Model/Loader/Interpreter.h> #include <Model/Loader/GameObjectFactory.h> #include <Model/Environment.h> #include <Model/Property/SpacePlugin.h> #include <Physics/PhysicsManager.h> #include "Pong/PongDefinitions.h" #include "Pong/PongFactory.h" #include <Pong/PropertyPlugin.h> struct PongServerState : BFG::Emitter { PongServerState(BFG::GameHandle handle, EventLoop* loop) : Emitter(loop), mClock(new BFG::Clock::StopWatch(BFG::Clock::milliSecond)), mExitNextTick(false) { BFG::Path p; std::string level = p.Get(BFG::ID::P_SCRIPTS_LEVELS) + "pong/"; std::string def = p.Get(BFG::ID::P_SCRIPTS_LEVELS) + "default/"; BFG::Loader::LevelConfig lc; lc.mModules.push_back(def + "Object.xml"); lc.mAdapters.push_back(def + "Adapter.xml"); lc.mConcepts.push_back(def + "Concept.xml"); lc.mProperties.push_back(def + "Value.xml"); lc.mModules.push_back(level + "Object.xml"); lc.mAdapters.push_back(level + "Adapter.xml"); lc.mConcepts.push_back(level + "Concept.xml"); lc.mProperties.push_back(level + "Value.xml"); boost::shared_ptr<BFG::Environment> environment(new BFG::Environment); using BFG::Property::ValueId; using BFG::Property::PluginId; PluginId spId = ValueId::ENGINE_PLUGIN_ID; PluginId ppId = BFG::Property::generatePluginId<PluginId>(); boost::shared_ptr<BFG::SpacePlugin> sp(new BFG::SpacePlugin(spId)); boost::shared_ptr<PongPlugin> pp(new PongPlugin(ppId)); pm.insert(sp); pm.insert(pp); boost::shared_ptr<BFG::Loader::Interpreter> interpreter(new BFG::Loader::Interpreter(pm)); boost::shared_ptr<BFG::Loader::GameObjectFactory> gof; gof.reset(new BFG::Loader::GameObjectFactory(loop, lc, pm, interpreter, environment, handle)); // Hack: We don't use the SectorFactory directly, since there's still // race-related stuff inside BFG::Loader::ObjectParameter op; op.mHandle = BFG::generateHandle(); op.mName = "Ball"; op.mType = "Pong Ball"; op.mLocation = v3(0.0f, 0.0f, OBJECT_Z_POSITION); op.mLinearVelocity = BALL_START_VELOCITY; mBall = gof->createGameObject(op); op = BFG::Loader::ObjectParameter(); op.mHandle = 123; op.mName = "Lower Bar"; op.mType = "Pong Lower Bar"; op.mLocation = v3(0.0f, -BAR_Y_POSITION, OBJECT_Z_POSITION + SPECIAL_PACKER_MESH_OFFSET); mLowerBar = gof->createGameObject(op); op = BFG::Loader::ObjectParameter(); op.mHandle = 456; op.mName = "Upper Bar"; op.mType = "Pong Upper Bar"; op.mLocation.position = v3(0.0f, BAR_Y_POSITION, OBJECT_Z_POSITION + SPECIAL_PACKER_MESH_OFFSET); op.mLocation.orientation = BFG::qv4::IDENTITY; fromAngleAxis(op.mLocation.orientation, 180 * DEG2RAD, BFG::v3::UNIT_Z); mUpperBar = gof->createGameObject(op); mClock->start(); } void LoopEventHandler(LoopEvent* iLE) { if (mExitNextTick) { // Error happened, while doing stuff iLE->getData().getLoop()->setExitFlag(); } long timeSinceLastFrame = mClock->stop(); if (timeSinceLastFrame) mClock->start(); BFG::f32 timeInSeconds = static_cast<BFG::f32>(timeSinceLastFrame) / BFG::Clock::milliSecond; tick(timeInSeconds); } void tick(const BFG::f32 timeSinceLastFrame) { if (timeSinceLastFrame < BFG::EPSILON_F) return; quantity<si::time, BFG::f32> TSLF = timeSinceLastFrame * si::seconds; mBall->update(TSLF); mLowerBar->update(TSLF); mUpperBar->update(TSLF); emit<BFG::Physics::Event>(BFG::ID::PE_STEP, TSLF.value()); } boost::shared_ptr<BFG::GameObject> mBall; boost::shared_ptr<BFG::GameObject> mLowerBar; boost::shared_ptr<BFG::GameObject> mUpperBar; boost::scoped_ptr<BFG::Clock::StopWatch> mClock; BFG::Property::PluginMapT pm; bool mExitNextTick; }; struct PongClientState : BFG::Emitter { PongClientState(BFG::GameHandle handle, EventLoop* loop) : Emitter(loop), mExitNextTick(false), mPlayer(123) { } void ControllerEventHandler(BFG::Controller_::VipEvent* iCE) { switch(iCE->getId()) { // Using this as lower bar x-axis controller (Sending to: Lower Bar!) case A_SHIP_AXIS_Y: if (!mPlayer) return; emit<BFG::GameObjectEvent>(BFG::ID::GOE_CONTROL_YAW, boost::get<float>(iCE->getData()), mPlayer); break; case A_QUIT: { mExitNextTick = true; break; } case A_FPS: { emit<BFG::View::Event>(BFG::ID::VE_DEBUG_FPS, boost::get<bool>(iCE->getData())); break; } } } void LoopEventHandler(LoopEvent* iLE) { if (mExitNextTick) { // Error happened, while doing stuff iLE->getData().getLoop()->setExitFlag(); } } BFG::GameHandle mPlayer; bool mExitNextTick; }; #endif //__PONG_STATE_H_
[ [ [ 1, 217 ] ] ]
8b6600e6e2825cf67750ac849c42a709d30f29a2
a30b091525dc3f07cd7e12c80b8d168a0ee4f808
/EngineAll/Core/VectorSTLImpl.h
fbff9769fe8869c8b465747d5b840e162bce421a
[]
no_license
ghsoftco/basecode14
f50dc049b8f2f8d284fece4ee72f9d2f3f59a700
57de2a24c01cec6dc3312cbfe200f2b15d923419
refs/heads/master
2021-01-10T11:18:29.585561
2011-01-23T02:25:21
2011-01-23T02:25:21
47,255,927
0
0
null
null
null
null
UTF-8
C++
false
false
8,368
h
/* Vector.h Written by Matthew Fisher Template vector library. Extends functionality of std::vector */ #pragma once #include "..\\..\\Main.h" template <class type> class Vector { public: Vector(); explicit Vector(UINT _Size); Vector(const Vector<type> &V); ~Vector(); // // Memory // void FreeMemory(); // // Windows has claimed the nice name "ZeroMemory" for its own uses // void ZeroMem(); Vector<type>& operator = (const Vector<type> &V); void ReSize(UINT Size); void Reserve(UINT Size); void Allocate(UINT Size); // // Accessors // __forceinline type& operator [] (UINT k) { #ifdef VECTOR_DEBUG Assert(k < int(Data.size()), "Out-of-bounds vector access"); #endif return Data[k]; } __forceinline type& operator [] (int k) { #ifdef VECTOR_DEBUG Assert(k >= 0 && k < int(Data.size()), "Out-of-bounds vector access"); #endif return Data[k]; } __forceinline const type& operator [] (UINT k) const { #ifdef VECTOR_DEBUG Assert(k < int(Data.size()), "Out-of-bounds vector access"); #endif return Data[k]; } __forceinline const type& operator [] (int k) const { #ifdef VECTOR_DEBUG Assert(k >= 0 && k < int(Data.size()), "Out-of-bounds vector access"); #endif return Data[k]; } __forceinline UINT Length() const { return UINT(Data.size()); } __forceinline type* CArray() { #ifdef VECTOR_DEBUG Assert(Data.size() != 0, "CArray called on zero-length vector"); #endif return &(Data[0]); } __forceinline const type* CArray() const { #ifdef VECTOR_DEBUG Assert(Data.size() != 0, "CArray called on zero-length vector"); #endif return &(Data[0]); } __forceinline type& RandomElement() { Assert(Length() > 0, "RandomElement called with no elements."); return (*this)[rand() % Length()]; } __forceinline const type& RandomElement() const { Assert(Length() > 0, "RandomElement called with no elements."); return (*this)[rand() % Length()]; } __forceinline type& Last() { Assert(Length() > 0, "Last called with no elements."); return (*this)[Length() - 1]; } __forceinline const type& Last() const { Assert(Length() > 0, "Last called with no elements."); return (*this)[Length() - 1]; } __forceinline type& First() { Assert(Length() > 0, "First called with no elements."); return (*this)[0]; } __forceinline const type& First() const { Assert(Length() > 0, "Last called with no elements."); return (*this)[0]; } // // Modifiers // void Append(const Vector<type> &V); void PushEnd(const type &t); void PushEnd(); void PopEnd(); void PopFront(); void RemoveSlow(UINT Index); void RemoveSwap(UINT Index); void Randomize(); void Sort(); void Scale(const type &t); template<class orderingType> void Sort(orderingType Function) { std::sort(CArray(), CArray() + Length(), Function); } void Clear(const type &T); // // Query // type Sum() const; const type& MaxValue() const; UINT MaxIndex() const; const type& MinValue() const; UINT MinIndex() const; bool Contains(const type &t); UINT Hash32() const; UINT64 Hash64() const; protected: vector<type> Data; }; //#include "VectorSTLImpl.cpp" /* Vector.cpp Written by Matthew Fisher */ template <class type> Vector<type>::Vector() { } template <class type> Vector<type>::Vector(UINT _Size) { Data.resize(_Size); } template <class type> Vector<type>::Vector(const Vector<type> &V) { Data = V.Data; } template <class type> Vector<type>::~Vector() { FreeMemory(); } template <class type> void Vector<type>::FreeMemory() { if(Length() != 0) { Data.resize(0); Data.clear(); } } template <class type> void Vector<type>::ZeroMem() { memset(CArray(), 0, Length() * sizeof(type)); } template <class type> Vector<type>& Vector<type>::operator = (const Vector<type> &V) { Data = V.Data; return *this; } template <class type> void Vector<type>::ReSize(UINT Size) { Data.resize(Size); } template <class type> void Vector<type>::Reserve(UINT Size) { Data.reserve(Size); } template <class type> void Vector<type>::Allocate(UINT Size) { Data.clear(); Data.resize(Size); } template <class type> void Vector<type>::Clear(const type &T) { UINT Length = Data.size(); type *CPtr = CArray(); for(UINT i = 0; i < Length; i++) { CPtr[i] = T; } } template <class type> type Vector<type>::Sum() const { const UINT Length = Data.size(); const type *CPtr = CArray(); type Result = CPtr[0]; for(UINT Index = 1; Index < Length; Index++) { Result += CPtr[Index]; } return Result; } template <class type> UINT Vector<type>::MaxIndex() const { const UINT Length = Data.size(); const type *CPtr = CArray(); UINT LargestIndexSeen = 0; for(UINT Index = 1; Index < Length; Index++) { if(CPtr[Index] > CPtr[LargestIndexSeen]) { LargestIndexSeen = Index; } } return LargestIndexSeen; } template <class type> const type& Vector<type>::MaxValue() const { return Data[MaxIndex()]; } template <class type> UINT Vector<type>::MinIndex() const { const UINT Length = Data.size(); const type *CPtr = CArray(); UINT SmallestIndexSeen = 0; for(UINT Index = 1; Index < Length; Index++) { if(CPtr[Index] < CPtr[SmallestIndexSeen]) { SmallestIndexSeen = Index; } } return SmallestIndexSeen; } template <class type> const type& Vector<type>::MinValue() const { return Data[MinIndex()]; } template <class type> void Vector<type>::Sort() { std::sort(CArray(), CArray() + Length()); } //template <class type, class orderingType> void Vector<type>::Sort(orderingType Function) template <class type> UINT Vector<type>::Hash32() const { return Utility::Hash32((const BYTE *)CArray(), sizeof(type) * Length()); } template <class type> UINT64 Vector<type>::Hash64() const { return Utility::Hash64((const BYTE *)CArray(), sizeof(type) * Length()); } template <class type> void Vector<type>::Append(const Vector<type> &V) { Data.reserve(V.Length() + Length()); for(UINT Index = 0; Index < V.Length(); Index++) { Data.push_back(V[Index]); } } template <class type> void Vector<type>::PushEnd(const type &t) { Data.push_back(t); } template <class type> void Vector<type>::PushEnd() { Data.resize(Data.size() + 1); } template <class type> void Vector<type>::PopEnd() { #ifdef VECTOR_DEBUG Assert(Data.size() != 0, "PopEnd called on zero-length vector"); #endif Data.pop_back(); } template <class type> void Vector<type>::RemoveSlow(UINT Index) { #ifdef VECTOR_DEBUG Assert(Index < Length(), "Remove called on invalid index"); #endif for(UINT i = Index; i < Length() - 1; i++) { Data[i] = Data[i + 1]; } PopEnd(); } template <class type> void Vector<type>::Scale(const type &t) { const UINT Length = Data.size(); type *CPtr = CArray(); for(UINT Index = 0; Index < Length; Index++) { CPtr[Index] *= t; } } template <class type> void Vector<type>::RemoveSwap(UINT Index) { #ifdef VECTOR_DEBUG Assert(Index < Length(), "Remove called on invalid index"); #endif Utility::Swap(Data[Index], Data[Length() - 1]); PopEnd(); } template <class type> bool Vector<type>::Contains(const type &t) { UINT Len = Length(); for(UINT Index = 0; Index < Len; Index++) { if(Data[Index] == t) { return true; } } return false; } template <class type> void Vector<type>::Randomize() { UINT Len = Length(); for(UINT i = 0; i < Len; i++) { UINT RandomNumber = UINT(rand()); Utility::Swap(Data[i], Data[i + RandomNumber % (Len - i)]); } } template <class type> void Vector<type>::PopFront() { RemoveSlow(0); }
[ "zhaodongmpii@7e7f00ea-7cf8-66b5-cf80-f378872134d2" ]
[ [ [ 1, 379 ] ] ]
09918e5d42d525fdba6dc7a1e5f31f0294277b5d
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Utilities/VisualDebugger/Viewer/Dynamics/Constraint/Drawer/hkpPrismaticDrawer.h
e823af709a1d352b344729da2ee738a9924765f0
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_PRISMATICDRAWER_H #define HK_PRISMATICDRAWER_H #include <Physics/Utilities/VisualDebugger/Viewer/Dynamics/Constraint/Drawer/hkpConstraintDrawer.h> /// Displays information about the prismatic constraint. class hkpPrismaticDrawer : public hkpConstraintDrawer { public: HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_VDB, hkpPrismaticDrawer ); void drawConstraint( hkpConstraintInstance* constraint, hkDebugDisplayHandler* displayHandler, int tag); }; #endif //HK_PRISMATICDRAWER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 39 ] ] ]
98d156dc3d0650635abb49096074a311ef75c7f9
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgViewer/api/Carbon/GraphicsWindowCarbon
b63bf5201294120533e301163b0a1efbcd7d53b4
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
6,559
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ /* Note, elements of GraphicsWindowX11 have used Prodcer/RenderSurface_X11.cpp as both * a guide to use of X11/GLX and copiying directly in the case of setBorder(). * These elements are license under OSGPL as above, with Copyright (C) 2001-2004 Don Burns. */ #ifndef OSGVIEWER_GRAPHICSWINDOWCARBON #define OSGVIEWER_GRAPHICSWINDOWCARBON 1 #if defined (__APPLE__) && (!__LP64__) #include <osgViewer/GraphicsWindow> #include <osgViewer/api/Carbon/GraphicsHandleCarbon> namespace osgViewer { class GraphicsWindowCarbon : public osgViewer::GraphicsWindow, public osgViewer::GraphicsHandleCarbon { public: GraphicsWindowCarbon(osg::GraphicsContext::Traits* traits): _valid(false), _initialized(false), _realized(false), _ownsWindow(true), _currentCursor(RightArrowCursor) { _traits = traits; init(); if (valid()) { setState( new osg::State ); getState()->setGraphicsContext(this); if (_traits.valid() && _traits->sharedContext) { getState()->setContextID( _traits->sharedContext->getState()->getContextID() ); incrementContextIDUsageCount( getState()->getContextID() ); } else { getState()->setContextID( osg::GraphicsContext::createNewContextID() ); } } } virtual bool isSameKindAs(const Object* object) const { return dynamic_cast<const GraphicsWindowCarbon*>(object)!=0; } virtual const char* libraryName() const { return "osgViewer"; } virtual const char* className() const { return "GraphicsWindowCarbon"; } virtual bool valid() const { return _valid; } /** Realise the GraphicsContext.*/ virtual bool realizeImplementation(); /** Return true if the graphics context has been realised and is ready to use.*/ virtual bool isRealizedImplementation() const { return _realized; } /** Close the graphics context.*/ virtual void closeImplementation(); /** Make this graphics context current.*/ virtual bool makeCurrentImplementation(); /** Release the graphics context.*/ virtual bool releaseContextImplementation(); /** Swap the front and back buffers.*/ virtual void swapBuffersImplementation(); /** Check to see if any events have been generated.*/ virtual void checkEvents(); /** Set the window's position and size.*/ virtual bool setWindowRectangleImplementation(int x, int y, int width, int height); /** Set Window decoration.*/ virtual bool setWindowDecorationImplementation(bool flag); // Override from GUIActionAdapter virtual void requestWarpPointer( float x, float y); /** Get focus.*/ virtual void grabFocus(); /** Get focus on if the pointer is in this window.*/ virtual void grabFocusIfPointerInWindow(); void requestClose() { _closeRequested = true; } virtual void resizedImplementation(int x, int y, int width, int height); virtual void setWindowName (const std::string & name); virtual void useCursor(bool cursorOn); virtual void setCursor(MouseCursor mouseCursor); WindowRef getNativeWindowRef() { return _window; } bool handleMouseEvent(EventRef theEvent); bool handleKeyboardEvent(EventRef theEvent); bool handleModifierKeys(EventRef theEvent); /** WindowData is used to pass in the Carbon window handle attached the GraphicsContext::Traits structure. */ class WindowData : public osg::Referenced { public: WindowData(WindowRef window, AGLDrawable* drawable=NULL ): //ADEGLI _window(window), _AGLDrawable(drawable) ,_installEventHandler(false) {} //ADEGLI WindowRef getNativeWindowRef() { return _window; } void setInstallEventHandler(bool flag) { _installEventHandler = flag; } bool installEventHandler() { return _installEventHandler; } AGLDrawable* getAGLDrawable() { return _AGLDrawable; } //ADEGLI private: WindowRef _window; AGLDrawable* _AGLDrawable; //ADEGLI bool _installEventHandler; }; /// install the standard os-eventhandler void installEventHandler(); // get the pixelformat AGLPixelFormat getAGLPixelFormat() { return _pixelFormat; } void adaptResize(int x, int y, int w, int h); protected: void init(); void transformMouseXY(float& x, float& y); bool _valid; bool _initialized; bool _realized; bool _useWindowDecoration; bool _ownsWindow; WindowRef _window; AGLPixelFormat _pixelFormat; int _windowTitleHeight; private: /// computes the window attributes WindowAttributes computeWindowAttributes(bool useWindowDecoration, bool supportsResize); void handleModifierKey(UInt32 modifierKey, UInt32 modifierMask, osgGA::GUIEventAdapter::KeySymbol keySymbol); bool _closeRequested; UInt32 _lastModifierKeys; MouseCursor _currentCursor; }; } #endif #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 176 ] ] ]
3fd225a5186d5dbb7ae11cfdc4937815a7e29682
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/Game/wheel/NetWheelController/src/WinDataPrototype.cpp
84d6cebfae43976c44aa6f8a92b21d32a2844f14
[]
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
3,342
cpp
#include "NetWheelControllerStableHeaders.h" #include "WinDataPrototype.h" #include "WinData.h" #include <boost/random.hpp> using namespace Orz; // //// =r =h =g //// 1 6 6 6 //// 2 10 10 10 //// 3 15 15 15 //// 4 31 31 31 // // //// +r -h =g //// 1 7 5 6 //// 2 11 8 10 //// 3 17 14 15 //// 4 35 28 31 // // //// +r =h -g //// 1 7 6 5 //// 2 11 10 8 //// 3 17 15 14 //// 4 35 31 28 // // //// -r +h =g //// 1 5 7 6 //// 2 8 11 10 //// 3 14 17 15 //// 4 28 35 31 // // //// =r +h -g //// 1 6 7 5 //// 2 10 11 8 //// 3 15 17 14 //// 4 31 35 28 // //static const int RATE[] = //{ // 6, 6, 6, // 10, 10, 10, // 15, 15, 15, // 31, 31, 31, // // // +r -h =g // 7, 5, 6, // 11, 8, 10, // 17, 14, 15, // 35, 28, 31, // // // // +r =h -g // 7, 6, 5, // 11, 10, 8, // 17, 15, 14, // 35, 31, 28, // // // // -r +h =g // 5, 7, 6, // 8, 11, 10, // 14, 17, 15, // 28, 35, 31, // // // // =r +h -g // 6, 7, 5, // 10, 11, 8, // 15, 17, 14, // 31, 35, 28, // // // // -r ++h -g // 5, 8, 5, // 8, 13, 8, // 14, 20, 14, // 28, 40, 28 //}; //static int getRate() //{ // //} //WinDataPrototype::WinDataPrototype(Orz::WheelEnum::WIN_MODE winMode):_winMode(winMode) //{ // /*Orz::IInputManager::getSingleton().addKeyListener(this);*/ //} //int WinDataPrototype::getRate(const WheelEnum::AnimalItem & animalItem, const WheelEnum::RATE mode) //{ // int i = (mode * 12+animalItem.first * 3 + animalItem.second); // int rate = RATE[i]; // return rate; //} // //void WinDataPrototype::setBonus(int bonus) //{ // if(bonus == -1) // { // using namespace boost; // // // boost::mt19937 engine(time(NULL)); // boost::uniform_int<> distribution(3000,19999); // // variate_generator<mt19937, uniform_int<> > myrandom (engine, distribution); // bonus = myrandom(); // } // // WinData::getInstance().setBonus(bonus); //} // //WinDataPrototypePtr WinDataPrototype::gatBonusData(void) const //{ // // assert(_winMode == Orz::WheelEnum::NONE); // WinDataPrototypePtr data(new WinDataPrototype(Orz::WheelEnum::GOLD)); // BOOST_FOREACH(const WheelEnum::AnimalItem & animalItem, _animals) // { // data->push_back(animalItem); // } // return data; //} // //void WinDataPrototype::submit(const WheelEnum::RATE mode) const //{ // WinData::getInstance().clear(); // WinData::getInstance().setWinMode(_winMode); // BOOST_FOREACH(const WheelEnum::AnimalItem & animalItem, _animals) // { // WinData::getInstance().push_back(animalItem, getRate(animalItem, mode)); // } // //} //const WheelEnum::WIN_MODE WinDataPrototype::getWinMode(void) const //{ // return _winMode; //} //size_t WinDataPrototype::calculate(const WheelEnum::AnimalItem & animalItem, const WheelEnum::RATE mode) const //{ // // size_t n = 0; // BOOST_FOREACH( WheelEnum::AnimalItem ai, _animals) // { // if(ai == animalItem) // { // n = getRate(ai, mode); // break; // // } // // } // // if(_winMode == WheelEnum::DOUBLE) // n *= 2; // else if(_winMode == WheelEnum::TREBLE) // n *= 3; // return n; //} //void WinDataPrototype::push_back(const WheelEnum::AnimalItem & animalItem) //{ // _animals.push_back(animalItem); //}
[ [ [ 1, 166 ] ] ]
c490cf290ee333510cdb3d01e780f4ba9e018deb
f89e32cc183d64db5fc4eb17c47644a15c99e104
/pcsx2-rr/pcsx2/x86/microVU_Misc.h
0a5377d353027d66cc71e3023a54817b66cf521a
[]
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
13,159
h
/* 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/>. */ #pragma once using namespace x86Emitter; typedef xRegisterSSE xmm; typedef xRegister32 x32; struct microVU; //------------------------------------------------------------------ // Global Variables //------------------------------------------------------------------ struct mVU_Globals { u32 absclip[4], signbit[4], minvals[4], maxvals[4]; u32 one[4]; u32 Pi4[4]; u32 T1[4], T2[4], T3[4], T4[4], T5[4], T6[4], T7[4], T8[4]; u32 S2[4], S3[4], S4[4], S5[4]; u32 E1[4], E2[4], E3[4], E4[4], E5[4], E6[4]; float FTOI_4[4], FTOI_12[4], FTOI_15[4]; float ITOF_4[4], ITOF_12[4], ITOF_15[4]; }; extern const __aligned(32) mVU_Globals mVUglob; static const uint _Ibit_ = 1 << 31; static const uint _Ebit_ = 1 << 30; static const uint _Mbit_ = 1 << 29; static const uint _Dbit_ = 1 << 28; static const uint _Tbit_ = 1 << 27; static const uint _DTbit_ = 0; //( _Dbit_ | _Tbit_ ) // ToDo: Implement this stuff... static const uint divI = 0x1040000; static const uint divD = 0x2080000; //------------------------------------------------------------------ // Helper Macros //------------------------------------------------------------------ #define _Ft_ ((mVU->code >> 16) & 0x1F) // The ft part of the instruction register #define _Fs_ ((mVU->code >> 11) & 0x1F) // The fs part of the instruction register #define _Fd_ ((mVU->code >> 6) & 0x1F) // The fd part of the instruction register #define _It_ ((mVU->code >> 16) & 0xF) // The it part of the instruction register #define _Is_ ((mVU->code >> 11) & 0xF) // The is part of the instruction register #define _Id_ ((mVU->code >> 6) & 0xF) // The id part of the instruction register #define _X ((mVU->code>>24) & 0x1) #define _Y ((mVU->code>>23) & 0x1) #define _Z ((mVU->code>>22) & 0x1) #define _W ((mVU->code>>21) & 0x1) #define _X_Y_Z_W (((mVU->code >> 21 ) & 0xF)) #define _XYZW_SS (_X+_Y+_Z+_W==1) #define _XYZW_SS2 (_XYZW_SS && (_X_Y_Z_W != 8)) #define _XYZW_PS (_X_Y_Z_W == 0xf) #define _XYZWss(x) ((x==8) || (x==4) || (x==2) || (x==1)) #define _bc_ (mVU->code & 0x3) #define _bc_x ((mVU->code & 0x3) == 0) #define _bc_y ((mVU->code & 0x3) == 1) #define _bc_z ((mVU->code & 0x3) == 2) #define _bc_w ((mVU->code & 0x3) == 3) #define _Fsf_ ((mVU->code >> 21) & 0x03) #define _Ftf_ ((mVU->code >> 23) & 0x03) #define _Imm5_ (mVU->Imm5()) #define _Imm11_ (mVU->Imm11()) #define _Imm12_ (mVU->Imm12()) #define _Imm15_ (mVU->Imm15()) #define _Imm24_ (mVU->Imm24()) #define isCOP2 (mVU->cop2 != 0) #define isVU1 (mVU->index != 0) #define isVU0 (mVU->index == 0) #define getIndex (isVU1 ? 1 : 0) #define getVUmem(x) (((isVU1) ? (x & 0x3ff) : ((x >= 0x400) ? (x & 0x43f) : (x & 0xff))) * 16) #define offsetSS ((_X) ? (0) : ((_Y) ? (4) : ((_Z) ? 8: 12))) #define offsetReg ((_X) ? (0) : ((_Y) ? (1) : ((_Z) ? 2: 3))) #define xmmT1 xmm0 // Used for regAlloc #define xmmT2 xmm1 // Used for regAlloc #define xmmT3 xmm2 // Used for regAlloc #define xmmT4 xmm3 // Used for regAlloc #define xmmT5 xmm4 // Used for regAlloc #define xmmT6 xmm5 // Used for regAlloc #define xmmT7 xmm6 // Used for regAlloc #define xmmPQ xmm7 // Holds the Value and Backup Values of P and Q regs #define gprT1 eax // eax - Temp Reg #define gprT2 ecx // ecx - Temp Reg #define gprT3 edx // edx - Temp Reg #define gprT1b ax // Low 16-bit of gprT1 (eax) #define gprT2b cx // Low 16-bit of gprT2 (ecx) #define gprT3b dx // Low 16-bit of gprT3 (edx) #define gprF0 ebx // Status Flag 0 #define gprF1 ebp // Status Flag 1 #define gprF2 esi // Status Flag 2 #define gprF3 edi // Status Flag 3 // Function Params #define mP microVU* mVU, int recPass #define mV microVU* mVU #define mF int recPass #define mX mVU, recPass typedef void __fastcall Fntype_mVUrecInst( microVU* mVU, int recPass ); typedef Fntype_mVUrecInst* Fnptr_mVUrecInst; // Recursive Inline #ifndef __LINUX__ #define __recInline __ri #else #define __recInline inline #endif // Function/Template Stuff #define mVUx (vuIndex ? &microVU1 : &microVU0) #define mVUop(opName) static void __fastcall opName (mP) #define _mVUt template<int vuIndex> #define _r static __recInline // Define Passes #define pass1 if (recPass == 0) #define pass2 if (recPass == 1) #define pass3 if (recPass == 2) #define pass4 if (recPass == 3) // Upper Opcode Cases #define opCase1 if (opCase == 1) // Normal Opcodes #define opCase2 if (opCase == 2) // BC Opcodes #define opCase3 if (opCase == 3) // I Opcodes #define opCase4 if (opCase == 4) // Q Opcodes //------------------------------------------------------------------ // Define mVUquickSearch //------------------------------------------------------------------ #ifndef __LINUX__ extern __pagealigned u8 mVUsearchXMM[__pagesize]; typedef u32 (__fastcall *mVUCall)(void*, void*); #define mVUquickSearch(dest, src, size) ((((mVUCall)((void*)mVUsearchXMM))(dest, src)) == 0xf) #define mVUemitSearch() { mVUcustomSearch(); } #else // Note: GCC builds crash with custom search function, because // they're not guaranteeing 16-byte alignment on the structs :( // #define mVUquickSearch(dest, src, size) (!memcmp(dest, src, size)) #define mVUquickSearch(dest, src, size) (!memcmp_mmx(dest, src, size)) #define mVUemitSearch() #endif //------------------------------------------------------------------ // Misc Macros... #define __four(val) { val, val, val, val } #define mVUcurProg mVU->prog.cur[0] #define mVUblocks mVU->prog.cur->block #define mVUir mVU->prog.IRinfo #define mVUbranch mVU->prog.IRinfo.branch #define mVUcycles mVU->prog.IRinfo.cycles #define mVUcount mVU->prog.IRinfo.count #define mVUpBlock mVU->prog.IRinfo.pBlock #define mVUblock mVU->prog.IRinfo.block #define mVUregs mVU->prog.IRinfo.block.pState #define mVUregsTemp mVU->prog.IRinfo.regsTemp #define iPC mVU->prog.IRinfo.curPC #define mVUsFlagHack mVU->prog.IRinfo.sFlagHack #define mVUconstReg mVU->prog.IRinfo.constReg #define mVUstartPC mVU->prog.IRinfo.startPC #define mVUinfo mVU->prog.IRinfo.info[iPC / 2] #define mVUstall mVUinfo.stall #define mVUup mVUinfo.uOp #define mVUlow mVUinfo.lOp #define sFLAG mVUinfo.sFlag #define mFLAG mVUinfo.mFlag #define cFLAG mVUinfo.cFlag #define mVUrange (mVUcurProg.ranges[0])[0] #define isEvilBlock (mVUpBlock->pState.blockType == 2) #define isBadOrEvil (mVUlow.badBranch || mVUlow.evilBranch) #define xPC ((iPC / 2) * 8) #define curI ((u32*)mVU->regs().Micro)[iPC] //mVUcurProg.data[iPC] #define setCode() { mVU->code = curI; } #define incPC(x) (mVU->advancePC(x)) #define branchAddr mVU->getBranchAddr() #define branchAddrN mVU->getBranchAddrN() #define incPC2(x) { iPC = ((iPC + (x)) & mVU->progMemMask); } #define bSaveAddr (((xPC + 16) & (mVU->microMemSize-8)) / 8) #define shufflePQ (((mVU->p) ? 0xb0 : 0xe0) | ((mVU->q) ? 0x01 : 0x04)) #define cmpOffset(x) ((u8*)&(((u8*)x)[it[0].start])) #define Rmem &mVU->regs().VI[REG_R].UL #define aWrap(x, m) ((x > m) ? 0 : x) #define shuffleSS(x) ((x==1)?(0x27):((x==2)?(0xc6):((x==4)?(0xe1):(0xe4)))) #define clampE CHECK_VU_EXTRA_OVERFLOW #define elif else if // Flag Info (Set if next-block's first 4 ops will read current-block's flags) #define __Status (mVUregs.needExactMatch & 1) #define __Mac (mVUregs.needExactMatch & 2) #define __Clip (mVUregs.needExactMatch & 4) // Pass 3 Helper Macros (Used for program logging) #define _Fsf_String ((_Fsf_ == 3) ? "w" : ((_Fsf_ == 2) ? "z" : ((_Fsf_ == 1) ? "y" : "x"))) #define _Ftf_String ((_Ftf_ == 3) ? "w" : ((_Ftf_ == 2) ? "z" : ((_Ftf_ == 1) ? "y" : "x"))) #define xyzwStr(x,s) (_X_Y_Z_W == x) ? s : #define _XYZW_String (xyzwStr(1, "w") (xyzwStr(2, "z") (xyzwStr(3, "zw") (xyzwStr(4, "y") (xyzwStr(5, "yw") (xyzwStr(6, "yz") (xyzwStr(7, "yzw") (xyzwStr(8, "x") (xyzwStr(9, "xw") (xyzwStr(10, "xz") (xyzwStr(11, "xzw") (xyzwStr(12, "xy") (xyzwStr(13, "xyw") (xyzwStr(14, "xyz") "xyzw")))))))))))))) #define _BC_String (_bc_x ? "x" : (_bc_y ? "y" : (_bc_z ? "z" : "w"))) #define mVUlogFtFs() { mVUlog(".%s vf%02d, vf%02d", _XYZW_String, _Ft_, _Fs_); } #define mVUlogFd() { mVUlog(".%s vf%02d, vf%02d", _XYZW_String, _Fd_, _Fs_); } #define mVUlogACC() { mVUlog(".%s ACC, vf%02d", _XYZW_String, _Fs_); } #define mVUlogFt() { mVUlog(", vf%02d", _Ft_); } #define mVUlogBC() { mVUlog(", vf%02d%s", _Ft_, _BC_String); } #define mVUlogI() { mVUlog(", I"); } #define mVUlogQ() { mVUlog(", Q"); } #define mVUlogCLIP() { mVUlog("w.xyz vf%02d, vf%02dw", _Fs_, _Ft_); } // Program Logging... #ifdef mVUlogProg #define mVUlog ((isVU1) ? __mVULog<1> : __mVULog<0>) #define mVUdumpProg __mVUdumpProgram<vuIndex> #else #define mVUlog(...) if (0) {} #define mVUdumpProg(...) if (0) {} #endif //------------------------------------------------------------------ // Optimization Options //------------------------------------------------------------------ // Reg Alloc static const bool doRegAlloc = 1; // Set to 0 to flush every 32bit Instruction // This turns off reg alloc for the most part, but reg alloc will still // be done within instructions... Also on doSwapOp() regAlloc is needed between // Lower and Upper instructions, so in this case it flushes after the full // 64bit instruction (lower and upper) // No Flag Optimizations static const bool noFlagOpts = 0; // Set to 1 to disable all flag setting optimizations // Note: The flag optimizations this disables should all be harmless, so // this option is mainly just for debugging... it effectively forces mVU // to always update Mac and Status Flags (both sticky and non-sticky) whenever // an Upper Instruction updates them. It also always transfers the 4 possible // flag instances between blocks... // Constant Propagation static const bool doConstProp = 0; // Set to 1 to turn on vi15 const propagation // Enables Constant Propagation for Jumps based on vi15 'link-register' // allowing us to know many indirect jump target addresses. // Makes GoW a lot slower due to extra recompilation time and extra code-gen! //------------------------------------------------------------------ // Speed Hacks (can cause infinite loops, SPS, Black Screens, etc...) //------------------------------------------------------------------ // Status Flag Speed Hack #define CHECK_VU_FLAGHACK (EmuConfig.Speedhacks.vuFlagHack) // This hack only updates the Status Flag on blocks that will read it. // Most blocks do not read status flags, so this is a big speedup. // Block Flag Instance No-Propagation Hack #define CHECK_VU_BLOCKHACK (EmuConfig.Speedhacks.vuBlockHack) // There are times when it is unknown if future blocks will need old // flag instance data (due to indirect jumps). This hack assumes // that they won't need old flag data. This effectively removes a lot // of end-of-block flag instance shuffling, causing nice speedups. // Min/Max Speed Hack #define CHECK_VU_MINMAXHACK (EmuConfig.Speedhacks.vuMinMax) // This hack uses SSE min/max instructions instead of emulated "logical min/max" // The PS2 does not consider denormals as zero on the mini/max opcodes. // This speedup is minor, but on AMD X2 CPUs it can be a 1~3% speedup //------------------------------------------------------------------ // Unknown Data //------------------------------------------------------------------ // XG Kick Transfer Delay Amount #define mVU_XGKICK_CYCLES ((CHECK_XGKICKHACK) ? 3 : 1) // Its unknown at recompile time how long the xgkick transfer will take // so give it a value that makes games happy :) (SO3 is fine at 1 cycle delay) //------------------------------------------------------------------ // Cache Limit Check #define mVUcacheCheck(ptr, start, limit) { \ uptr diff = ptr - start; \ if (diff >= limit) { \ DevCon.WriteLn("microVU%d: Program cache limit reached. Size = 0x%x", mVU->index, diff); \ mVUresizeCache(mVU, mVU->cacheSize + mVUcacheGrowBy); \ } \ } extern void mVUmergeRegs(const xmm& dest, const xmm& src, int xyzw, bool modXYZW=false); extern void mVUsaveReg(const xmm& reg, xAddressVoid ptr, int xyzw, bool modXYZW); extern void mVUloadReg(const xmm& reg, xAddressVoid ptr, int xyzw);
[ "koeiprogenitor@bfa1b011-20a7-a6e3-c617-88e5d26e11c5" ]
[ [ [ 1, 312 ] ] ]
7b10292253037cca1793cf4d3c315eccefc09e19
969987a50394a9ebab0f8cce0ff22f6e2cfd7fb2
/devel/traydict/kana_table.h
6c7e5bc35913f5a40b5aa762fa910697b94122ec
[]
no_license
jeeb/aegisub-historical
67bd9cf24e05926f1979942594e04d6b1ffce40c
b81be20fd953bd61be80bfe4c8944f1757605995
refs/heads/master
2021-05-28T03:49:26.880613
2011-09-02T00:03:40
2011-09-02T00:03:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
h
// Copyright (c) 2006, Rodrigo Braz Monteiro // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the TrayDict Group 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. // // ----------------------------------------------------------------------------- // // TRAYDICT // // Website: http://aegisub.cellosoft.com // Contact: mailto:[email protected] // #pragma once /////////// // Headers #include <vector> #include <wx/wxprec.h> /////////////////////////// // Hiragana/katakana entry class KanaEntry { public: wxString hiragana; wxString katakana; wxString hepburn; wxString group; int level; KanaEntry(wxString hira,wxString kata,wxString hep) { hiragana = hira; katakana = kata; hepburn = hep; } }; /////////////////////////// // Hiragana/Katakana table class KanaTable { private: std::vector<KanaEntry> entries; void Insert(wchar_t *hira,wchar_t *kata,wchar_t *hep); void BeginGroup(); wxString curGroup; int groups[2]; int level; public: KanaTable(); ~KanaTable(); int GetNumberEntries(int level=-1) const; int GetLevels(int table) const; const KanaEntry &GetEntry(int i) const; const KanaEntry *FindByRomaji(wxString romaji) const; const KanaEntry *FindByKana(wxString kana) const; wxString KanaToRomaji(wxString kana,int type=1); };
[ "archmagezeratul@93549f3f-7f0a-0410-a4b3-e966c9c94f04" ]
[ [ [ 1, 86 ] ] ]
2022c31d44d61628da86481af35dded1fa562905
44890f9b95a8c77492bf38514d26c0da51d2fae5
/Gif/MotionFont/drawing.cpp
a45e32a214db910607b33fe4fb2495b690d3917e
[]
no_license
winnison/huang-cpp
fd9cd57bd0b97870ae1ca6427d2fc8191cf58a77
989fe1d3fdc1c9eae33e0f11fcd6d790e866e4c5
refs/heads/master
2021-01-19T18:07:38.882211
2008-04-14T16:42:48
2008-04-14T16:42:48
34,250,385
0
0
null
null
null
null
UTF-8
C++
false
false
12,021
cpp
#include "drawing.h" #include "common.h" #include <math.h> COLORREF GetRGBbyHSB(float hue, float saturation, float brightness) { int r, g, b; HSBtoRGB(hue, saturation, brightness, r, g, b); return RGB(r,g,b); } void GetHSBbyRGB(COLORREF rgb, float& hue, float& saturation, float& brightness) { RGBtoHSB(GetRValue(rgb), GetGValue(rgb), GetBValue(rgb), hue, saturation, brightness); } /** * Converts the components of a color, as specified by the HSB * model, to an equivalent set of values for the default RGB model. * <p> * The <code>saturation</code> and <code>brightness</code> components * should be floating-point values between zero and one * (numbers in the range 0.0-1.0). The <code>hue</code> component * can be any floating-point number. The floor of this number is * subtracted from it to create a fraction between 0 and 1. This * fractional number is then multiplied by 360 to produce the hue * angle in the HSB color model. * <p> * The integer that is returned by <code>HSBtoRGB</code> encodes the * value of a color in bits 0-23 of an integer value that is the same * format used by the method {@link #getRGB() <code>getRGB</code>}. * This integer can be supplied as an argument to the * <code>Color</code> constructor that takes a single integer argument. * @param hue the hue component of the color * @param saturation the saturation of the color * @param brightness the brightness of the color * @return the RGB value of the color with the indicated hue, * saturation, and brightness. * @see java.awt.Color#getRGB() * @see java.awt.Color#Color(int) * @see java.awt.image.ColorModel#getRGBdefault() * @since JDK1.0 */ inline void HSBtoRGB(float hue, float saturation, float brightness, int& r, int& g, int& b) { r = 0; g = 0; b = 0; if (saturation == 0) { r = g = b = (int) (brightness * 255.0f + 0.5f); } else { float h = (hue - (float)floor(hue)) * 6.0f; float f = h - (float)floor(h); float p = brightness * (1.0f - saturation); float q = brightness * (1.0f - saturation * f); float t = brightness * (1.0f - (saturation * (1.0f - f))); switch ((int) h) { case 0: r = (int) (brightness * 255.0f + 0.5f); g = (int) (t * 255.0f + 0.5f); b = (int) (p * 255.0f + 0.5f); break; case 1: r = (int) (q * 255.0f + 0.5f); g = (int) (brightness * 255.0f + 0.5f); b = (int) (p * 255.0f + 0.5f); break; case 2: r = (int) (p * 255.0f + 0.5f); g = (int) (brightness * 255.0f + 0.5f); b = (int) (t * 255.0f + 0.5f); break; case 3: r = (int) (p * 255.0f + 0.5f); g = (int) (q * 255.0f + 0.5f); b = (int) (brightness * 255.0f + 0.5f); break; case 4: r = (int) (t * 255.0f + 0.5f); g = (int) (p * 255.0f + 0.5f); b = (int) (brightness * 255.0f + 0.5f); break; case 5: r = (int) (brightness * 255.0f + 0.5f); g = (int) (p * 255.0f + 0.5f); b = (int) (q * 255.0f + 0.5f); break; } } } /** * Converts the components of a color, as specified by the default RGB * model, to an equivalent set of values for hue, saturation, and * brightness that are the three components of the HSB model. * <p> * If the <code>hsbvals</code> argument is <code>null</code>, then a * new array is allocated to return the result. Otherwise, the method * returns the array <code>hsbvals</code>, with the values put into * that array. * @param r the red component of the color * @param g the green component of the color * @param b the blue component of the color * @param hsbvals the array used to return the * three HSB values, or <code>null</code> * @return an array of three elements containing the hue, saturation, * and brightness (in that order), of the color with * the indicated red, green, and blue components. * @see java.awt.Color#getRGB() * @see java.awt.Color#Color(int) * @see java.awt.image.ColorModel#getRGBdefault() * @since JDK1.0 */ inline void RGBtoHSB(int r, int g, int b, float& hue, float& saturation, float& brightness) { int cmax = (r > g) ? r : g; if (b > cmax) cmax = b; int cmin = (r < g) ? r : g; if (b < cmin) cmin = b; brightness = ((float) cmax) / 255.0f; if (cmax != 0) saturation = ((float) (cmax - cmin)) / ((float) cmax); else saturation = 0; if (saturation == 0) hue = 0; else { float redc = ((float) (cmax - r)) / ((float) (cmax - cmin)); float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin)); float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin)); if (r == cmax) hue = bluec - greenc; else if (g == cmax) hue = 2.0f + redc - bluec; else hue = 4.0f + greenc - redc; hue = hue / 6.0f; if (hue < 0) hue = hue + 1.0f; } } void myStrechConvert(CDC& dcDst,int cxDst,int cyDst,CDC& dcSrc,int cxSrc,int cySrc) { int w1 = cxSrc, h1 = cySrc, wd = 0, hd = 0; if (w1*cyDst>cxDst*h1) { //wd = (w1*cyDst*7/8>cxDst*h1)?(w1/8):(w1 - cxDst*h1/cyDst); wd = (w1 - cxDst*h1/cyDst); w1 -= wd; wd /= 2; } else { //hd = (w1*cyDst<cxDst*h1*7/8)?(h1/8):(h1 - w1*cyDst/cxDst); hd = (h1 - w1*cyDst/cxDst); h1 -= hd; hd /= 2; } //Bitmap ret = new Bitmap(width, height); for (int i=cxDst - 1; i >= 0; i--) { for (int j=cyDst - 1; j >= 0; j--) { int r = 0,g=0,b=0,n=0; for (int ii=i*w1/cxDst, iiend = (i+1)*w1/cxDst; ii<iiend||n==0; ii++) { for (int jj=j*h1/cyDst,jjend = (j+1)*h1/cyDst; jj<jjend||n==0; jj++) { n++; COLORREF clr = dcSrc.GetPixel(ii+wd,jj+hd); r+=GetRValue(clr);g +=GetGValue(clr);b+=GetBValue(clr); } } r = (r+n/2)/n; g = (g+n/2)/n; b = (b+n/2)/n; dcDst.SetPixel(i,j, RGB(r,g,b)); //n = (r*3+g*6+b)/10/n; //ret.SetPixel(i,j, RGB(n,n,n)); } } for (int i=cxDst - 1; i >= 0; i--) { for (int j=cyDst - 1; j >= 0; j--) { int r = 0,g=0,b=0,n=0; COLORREF clr = dcDst.GetPixel(i,j); } } //for (int i=cxDst - 1; i >= 0; i--) //{ // for (int j=cyDst - 1; j >= 0; j--) // { // int r = 0,g=0,b=0,n=0; // for (int ii=i*w1/cxDst, iiend = (i+1)*w1/cxDst, iistart=ii; ii<iiend||n==0; ii++) // { // int idis = min(ii-iistart, iiend-ii-1); // for (int jj=j*h1/cyDst,jjend = (j+1)*h1/cyDst, jjstart=jj; jj<jjend||n==0; jj++) // { // int dis = 1+idis+min(jj-jjstart, jjend-jj-1); // n+=dis; // COLORREF clr = dcSrc.GetPixel(ii+wd,jj+hd); // r+=dis*GetRValue(clr);g +=dis*GetGValue(clr);b+=dis*GetBValue(clr); // } // } // dcDst.SetPixel(i,j, RGB(r/n,g/n,b/n)); // //n = (r*3+g*6+b)/10/n; // //ret.SetPixel(i,j, RGB(n,n,n)); // } //} //int w1 = cxSrc, h1 = cySrc, wd = 0, hd = 0; //if (w1*cyDst>cxDst*h1) //{ // wd = (w1 - cxDst*h1/cyDst); // w1 -= wd; // wd /= 2; //} //else //{ // hd = (h1 - w1*cyDst/cxDst); // h1 -= hd; // hd /= 2; //} //for (int i=cxDst - 1; i >= 0; i--) //{ // for (int j=cyDst - 1; j >= 0; j--) // { // int r = 0,g=0,b=0,n=0; // for (int ii=i*cxSrc/cxDst, iiend = (i+1)*cxSrc/cxDst; ii<iiend||n==0; ii++) // { // for (int jj=j*cySrc/cyDst,jjend = (j+1)*cySrc/cyDst; jj<jjend||n==0; jj++) // { // COLORREF clr = dcSrc.GetPixel(ii,jj); // n++; // r+=GetRValue(clr);g +=GetGValue(clr);b+=GetBValue(clr); // } // } // dcDst.SetPixel(i,j, RGB(r/n,g/n,b/n)); // } //} } HBITMAP StretchBitmap(HBITMAP hbmpSrc,int cxDst,int cyDst) { CDCHandle dcScreen = GetDC(NULL); CDC dcTemp,dcMem; dcMem.CreateCompatibleDC(dcScreen); dcTemp.CreateCompatibleDC(dcScreen); BITMAP bmpInfo; ::GetObject(hbmpSrc,sizeof(BITMAP),&bmpInfo); CBitmap bmpRet; bmpRet.CreateCompatibleBitmap(dcScreen,cxDst,cyDst); HBITMAP hBmpOldRet = dcMem.SelectBitmap(bmpRet); HBITMAP hBmpOldSrc = dcTemp.SelectBitmap(hbmpSrc); myStrechConvert(dcMem,cxDst,cyDst,dcTemp,bmpInfo.bmWidth,bmpInfo.bmHeight); dcTemp.SelectBitmap(hBmpOldSrc); dcMem.SelectBitmap(hBmpOldRet); ::ReleaseDC(NULL,dcScreen.m_hDC); return bmpRet.Detach(); } void GrayAdjust(HBITMAP hBitmap) { CBitmapHandle bmpSrc( hBitmap ); if( bmpSrc.IsNull() ) return; CDC dcScreen = GetDC( NULL ); BITMAP bm; bmpSrc.GetBitmap(&bm); CDC dc;dc.CreateCompatibleDC( dcScreen.m_hDC ); CBitmapHandle hOld = dc.SelectBitmap( bmpSrc ); int p[25500]; memset(p, 0, 25500*sizeof(int)); for (int i=0; i<bm.bmWidth; i++) { for (int j=0; j<bm.bmHeight; j++) { COLORREF clr = dc.GetPixel(i,j); int v = GetRValue(clr)*30 + GetGValue(clr)*59 + GetBValue(clr)*11; p[v]++; } } int all = 0; for (int i=0; i<25500; i++) { all += p[i]; p[i] = all - p[i]/2; } for (int i=0; i<bm.bmWidth; i++) { for (int j=0; j<bm.bmHeight; j++) { COLORREF clr = dc.GetPixel(i,j); int r = GetRValue(clr), g = GetGValue(clr), b = GetBValue(clr); int v = r*30 + g*59 + b*11; if (v) { int vv = (p[v] * 25500 / all); r = vv*r*30/v/30; if (r>255) { r=255; } g = vv*g*59/v/59; if (g>255) { g=255; } b = vv*b*11/v/11; if (b>255) { b=255; } dc.SetPixel(i,j,RGB(r,g,b)); } } } dc.SelectBitmap( hOld ); ::ReleaseDC(NULL,dcScreen.m_hDC); } HBITMAP Transform( HBITMAP hBitmap , float matrix[3][3]) { CBitmapHandle bmpSrc( hBitmap ); if( bmpSrc.IsNull() ) return NULL; CDC dcScreen = GetDC( NULL ); BITMAP bm; bmpSrc.GetBitmap(&bm); CDC dcTmp;dcTmp.CreateCompatibleDC( dcScreen.m_hDC ); CBitmapHandle hOld = dcTmp.SelectBitmap( bmpSrc ); CDC dcMem;dcMem.CreateCompatibleDC( dcScreen.m_hDC ); CBitmap bmpRet ; bmpRet.CreateCompatibleBitmap( dcScreen.m_hDC , bm.bmWidth , bm.bmHeight ); CBitmapHandle hOldMem = dcMem.SelectBitmap( bmpRet ); for (int nX=0; nX <bm.bmWidth; nX++) { dcMem.SetPixel(nX,0,dcTmp.GetPixel(nX,0)); dcMem.SetPixel(nX,bm.bmHeight-1, dcTmp.GetPixel(nX,bm.bmHeight-1)); } for (int nY=0; nY<bm.bmHeight; nY++) { dcMem.SetPixel(0,nY,dcTmp.GetPixel(0,nY)); dcMem.SetPixel(bm.bmWidth-1,nY, dcTmp.GetPixel(bm.bmWidth-1,nY)); } float f = 0; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { f += matrix[i][j]; } } if (f != 0) { for (int nX = 1; nX < bm.bmWidth-1; nX++) { for (int nY = 1; nY < bm.bmHeight-1; nY++) { float r = 0, g = 0, b = 0; for (int i=0; i<3; i++) { for (int j=0; j<3; j++) { COLORREF clr = dcTmp.GetPixel( nX-1+i, nY-1+j ); float w = matrix[i][j]; r += w*GetRValue(clr); g += w*GetGValue(clr); b += w*GetBValue(clr); } } int R = INTROUND(r/f), G = INTROUND(g/f), B = INTROUND(b/f); CHECKRANGE(R, 0, 255); CHECKRANGE(G, 0, 255); CHECKRANGE(B, 0, 255); dcMem.SetPixel( nX, nY , RGB(R,G,B) ); } } } dcMem.SelectBitmap( hOldMem ); dcTmp.SelectBitmap( hOld ); ::ReleaseDC(NULL,dcScreen.m_hDC); return bmpRet.Detach(); } void DrawTextOuter(CDC& dc, string& text, CSize& size, int x, int y, COLORREF outer) { RECT r; // 1 // 402 // 3 const int xs[4]={1,2,1,0}, ys[4]={0,1,2,1}; dc.SetTextColor(outer); for (int i=3; i>=0; i--) { r.left = x+xs[i]; r.top = y+ys[i]; r.right = x+size.cx+xs[i]; r.bottom = y+size.cy+ys[i]; dc.DrawText(text.c_str(), text.length(), &r, DT_SINGLELINE | DT_LEFT | DT_VCENTER); } } void DrawTextWithOuter(CDC& dc, string& text, CSize& size, int x, int y, COLORREF clr, COLORREF outer) { DrawTextOuter(dc, text, size, x, y, outer); RECT r; dc.SetTextColor(clr); r.left = x+1; r.top = y+1; r.right = x+size.cx+1; r.bottom = y+size.cy+1; dc.DrawText(text.c_str(), text.length(), &r, DT_SINGLELINE | DT_LEFT | DT_VCENTER); };
[ "mr.huanghuan@48bf5850-ed27-0410-9317-b938f814dc16" ]
[ [ [ 1, 445 ] ] ]
eec166579a726674dbade39d480f18e655feba48
2d2e8f07bf92bb395993bfcdf7917c17674ac8cd
/fub001/src/006FBO/ofFBOTexture.h
2cf377251c629ab65ddf9897ba77e21f6621b313
[]
no_license
olekristensen/fuckyoubody
0a8a2b446c57f2e190eb61bee8ae56fcf5e10b7c
e6c656ff2cd02473d9252c036381c32a34b279f8
refs/heads/master
2020-03-31T00:16:08.127306
2010-02-20T21:15:59
2010-02-20T21:15:59
32,136,171
0
0
null
null
null
null
UTF-8
C++
false
false
819
h
/* * ofFBOTexture.h * openFrameworks * * Created by Zach Gage on 3/28/08. * Copyright 2008 STFJ.NET. All rights reserved. * */ #ifndef _FBO_TEX #define _FBO_TEX #include "ofMain.h" #include <iostream> class ofFBOTexture : public ofTexture { public: void allocate(int w, int h, bool autoC); void swapIn(); void swapOut(); void setupScreenForMe(); void setupScreenForThem(); void clear(); //---------------------------------------------------------- void draw(float x, float y){ draw(x,y,texData.width, texData.height); } void draw(float x, float y, float w, float h); protected: GLuint fbo; // Our handle to the FBO GLuint depthBuffer; // Our handle to the depth render buffer bool autoClear; void clean(); }; #endif
[ "[email protected]@e8aa6d0e-c866-11de-ba9a-9db95b2bc6c5" ]
[ [ [ 1, 49 ] ] ]
e676a233f7b2fce37e3b4b5b4642aeaa67d0e943
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/contnrs.hpp
965f80496f5c8661a168f68b65a99a575803f76c
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
11,351
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'Contnrs.pas' rev: 6.00 #ifndef ContnrsHPP #define ContnrsHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Contnrs { //-- type declarations ------------------------------------------------------- class DELPHICLASS TObjectList; class PASCALIMPLEMENTATION TObjectList : public Classes::TList { typedef Classes::TList inherited; public: System::TObject* operator[](int Index) { return Items[Index]; } private: bool FOwnsObjects; protected: virtual void __fastcall Notify(void * Ptr, Classes::TListNotification Action); System::TObject* __fastcall GetItem(int Index); void __fastcall SetItem(int Index, System::TObject* AObject); public: __fastcall TObjectList(void)/* overload */; __fastcall TObjectList(bool AOwnsObjects)/* overload */; HIDESBASE int __fastcall Add(System::TObject* AObject); HIDESBASE System::TObject* __fastcall Extract(System::TObject* Item); HIDESBASE int __fastcall Remove(System::TObject* AObject); HIDESBASE int __fastcall IndexOf(System::TObject* AObject); int __fastcall FindInstanceOf(TMetaClass* AClass, bool AExact = true, int AStartAt = 0x0); HIDESBASE void __fastcall Insert(int Index, System::TObject* AObject); HIDESBASE System::TObject* __fastcall First(void); HIDESBASE System::TObject* __fastcall Last(void); __property bool OwnsObjects = {read=FOwnsObjects, write=FOwnsObjects, nodefault}; __property System::TObject* Items[int Index] = {read=GetItem, write=SetItem/*, default*/}; public: #pragma option push -w-inl /* TList.Destroy */ inline __fastcall virtual ~TObjectList(void) { } #pragma option pop }; class DELPHICLASS TComponentList; class PASCALIMPLEMENTATION TComponentList : public TObjectList { typedef TObjectList inherited; public: Classes::TComponent* operator[](int Index) { return Items[Index]; } private: Classes::TComponent* FNexus; protected: virtual void __fastcall Notify(void * Ptr, Classes::TListNotification Action); Classes::TComponent* __fastcall GetItems(int Index); void __fastcall SetItems(int Index, Classes::TComponent* AComponent); void __fastcall HandleFreeNotify(System::TObject* Sender, Classes::TComponent* AComponent); public: __fastcall virtual ~TComponentList(void); HIDESBASE int __fastcall Add(Classes::TComponent* AComponent); HIDESBASE Classes::TComponent* __fastcall Extract(Classes::TComponent* Item); HIDESBASE int __fastcall Remove(Classes::TComponent* AComponent); HIDESBASE int __fastcall IndexOf(Classes::TComponent* AComponent); HIDESBASE Classes::TComponent* __fastcall First(void); HIDESBASE Classes::TComponent* __fastcall Last(void); HIDESBASE void __fastcall Insert(int Index, Classes::TComponent* AComponent); __property Classes::TComponent* Items[int Index] = {read=GetItems, write=SetItems/*, default*/}; public: #pragma option push -w-inl /* TObjectList.Create */ inline __fastcall TComponentList(void)/* overload */ : TObjectList() { } #pragma option pop }; class DELPHICLASS TClassList; class PASCALIMPLEMENTATION TClassList : public Classes::TList { typedef Classes::TList inherited; public: TMetaClass* operator[](int Index) { return Items[Index]; } protected: TMetaClass* __fastcall GetItems(int Index); void __fastcall SetItems(int Index, TMetaClass* AClass); public: HIDESBASE int __fastcall Add(TMetaClass* AClass); HIDESBASE TMetaClass* __fastcall Extract(TMetaClass* Item); HIDESBASE int __fastcall Remove(TMetaClass* AClass); HIDESBASE int __fastcall IndexOf(TMetaClass* AClass); HIDESBASE TMetaClass* __fastcall First(void); HIDESBASE TMetaClass* __fastcall Last(void); HIDESBASE void __fastcall Insert(int Index, TMetaClass* AClass); __property TMetaClass* Items[int Index] = {read=GetItems, write=SetItems/*, default*/}; public: #pragma option push -w-inl /* TList.Destroy */ inline __fastcall virtual ~TClassList(void) { } #pragma option pop public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TClassList(void) : Classes::TList() { } #pragma option pop }; class DELPHICLASS TOrderedList; class PASCALIMPLEMENTATION TOrderedList : public System::TObject { typedef System::TObject inherited; private: Classes::TList* FList; protected: virtual void __fastcall PushItem(void * AItem) = 0 ; virtual void * __fastcall PopItem(void); virtual void * __fastcall PeekItem(void); __property Classes::TList* List = {read=FList}; public: __fastcall TOrderedList(void); __fastcall virtual ~TOrderedList(void); int __fastcall Count(void); bool __fastcall AtLeast(int ACount); void * __fastcall Push(void * AItem); void * __fastcall Pop(void); void * __fastcall Peek(void); }; class DELPHICLASS TStack; class PASCALIMPLEMENTATION TStack : public TOrderedList { typedef TOrderedList inherited; protected: virtual void __fastcall PushItem(void * AItem); public: #pragma option push -w-inl /* TOrderedList.Create */ inline __fastcall TStack(void) : TOrderedList() { } #pragma option pop #pragma option push -w-inl /* TOrderedList.Destroy */ inline __fastcall virtual ~TStack(void) { } #pragma option pop }; class DELPHICLASS TObjectStack; class PASCALIMPLEMENTATION TObjectStack : public TStack { typedef TStack inherited; public: HIDESBASE System::TObject* __fastcall Push(System::TObject* AObject); HIDESBASE System::TObject* __fastcall Pop(void); HIDESBASE System::TObject* __fastcall Peek(void); public: #pragma option push -w-inl /* TOrderedList.Create */ inline __fastcall TObjectStack(void) : TStack() { } #pragma option pop #pragma option push -w-inl /* TOrderedList.Destroy */ inline __fastcall virtual ~TObjectStack(void) { } #pragma option pop }; class DELPHICLASS TQueue; class PASCALIMPLEMENTATION TQueue : public TOrderedList { typedef TOrderedList inherited; protected: virtual void __fastcall PushItem(void * AItem); public: #pragma option push -w-inl /* TOrderedList.Create */ inline __fastcall TQueue(void) : TOrderedList() { } #pragma option pop #pragma option push -w-inl /* TOrderedList.Destroy */ inline __fastcall virtual ~TQueue(void) { } #pragma option pop }; class DELPHICLASS TObjectQueue; class PASCALIMPLEMENTATION TObjectQueue : public TQueue { typedef TQueue inherited; public: HIDESBASE System::TObject* __fastcall Push(System::TObject* AObject); HIDESBASE System::TObject* __fastcall Pop(void); HIDESBASE System::TObject* __fastcall Peek(void); public: #pragma option push -w-inl /* TOrderedList.Create */ inline __fastcall TObjectQueue(void) : TQueue() { } #pragma option pop #pragma option push -w-inl /* TOrderedList.Destroy */ inline __fastcall virtual ~TObjectQueue(void) { } #pragma option pop }; #pragma pack(push, 4) struct TBucketItem { void *Item; void *Data; } ; #pragma pack(pop) typedef DynamicArray<TBucketItem > TBucketItemArray; #pragma pack(push, 4) struct TBucket { int Count; DynamicArray<TBucketItem > Items; } ; #pragma pack(pop) typedef DynamicArray<TBucket > TBucketArray; typedef void __fastcall (*TBucketProc)(void * AInfo, void * AItem, void * AData, /* out */ bool &AContinue); class DELPHICLASS TCustomBucketList; class PASCALIMPLEMENTATION TCustomBucketList : public System::TObject { typedef System::TObject inherited; public: void * operator[](void * AItem) { return Data[AItem]; } private: DynamicArray<TBucket > FBuckets; int FBucketCount; bool FListLocked; void * __fastcall GetData(void * AItem); void __fastcall SetData(void * AItem, const void * AData); void __fastcall SetBucketCount(const int Value); protected: __property TBucketArray Buckets = {read=FBuckets}; __property int BucketCount = {read=FBucketCount, write=SetBucketCount, nodefault}; virtual int __fastcall BucketFor(void * AItem) = 0 ; virtual bool __fastcall FindItem(void * AItem, /* out */ int &ABucket, /* out */ int &AIndex); virtual void * __fastcall AddItem(int ABucket, void * AItem, void * AData); virtual void * __fastcall DeleteItem(int ABucket, int AIndex); public: __fastcall virtual ~TCustomBucketList(void); void __fastcall Clear(void); void * __fastcall Add(void * AItem, void * AData); void * __fastcall Remove(void * AItem); bool __fastcall ForEach(TBucketProc AProc, void * AInfo = (void *)(0x0)); void __fastcall Assign(TCustomBucketList* AList); bool __fastcall Exists(void * AItem); bool __fastcall Find(void * AItem, /* out */ void * &AData); __property void * Data[void * AItem] = {read=GetData, write=SetData/*, default*/}; public: #pragma option push -w-inl /* TObject.Create */ inline __fastcall TCustomBucketList(void) : System::TObject() { } #pragma option pop }; #pragma option push -b- enum TBucketListSizes { bl2, bl4, bl8, bl16, bl32, bl64, bl128, bl256 }; #pragma option pop class DELPHICLASS TBucketList; class PASCALIMPLEMENTATION TBucketList : public TCustomBucketList { typedef TCustomBucketList inherited; private: Byte FBucketMask; protected: virtual int __fastcall BucketFor(void * AItem); public: __fastcall TBucketList(TBucketListSizes ABuckets); public: #pragma option push -w-inl /* TCustomBucketList.Destroy */ inline __fastcall virtual ~TBucketList(void) { } #pragma option pop }; class DELPHICLASS TObjectBucketList; class PASCALIMPLEMENTATION TObjectBucketList : public TBucketList { typedef TBucketList inherited; public: System::TObject* operator[](System::TObject* AItem) { return Data[AItem]; } protected: HIDESBASE System::TObject* __fastcall GetData(System::TObject* AItem); HIDESBASE void __fastcall SetData(System::TObject* AItem, const System::TObject* AData); public: HIDESBASE System::TObject* __fastcall Add(System::TObject* AItem, System::TObject* AData); HIDESBASE System::TObject* __fastcall Remove(System::TObject* AItem); __property System::TObject* Data[System::TObject* AItem] = {read=GetData, write=SetData/*, default*/}; public: #pragma option push -w-inl /* TBucketList.Create */ inline __fastcall TObjectBucketList(TBucketListSizes ABuckets) : TBucketList(ABuckets) { } #pragma option pop public: #pragma option push -w-inl /* TCustomBucketList.Destroy */ inline __fastcall virtual ~TObjectBucketList(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE void __fastcall RaiseListError(const AnsiString ATemplate, const System::TVarRec * AData, const int AData_Size); } /* namespace Contnrs */ using namespace Contnrs; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // Contnrs
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 358 ] ] ]
f00fdb4c7857ce35c7b59197e6692a1ff06a7036
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/win95/GSPRCHNK.HPP
440a5bb26e596f5fe29bd3bf8ae69cc190eba0b2
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
1,498
hpp
#ifndef _included_gsprchnk_hpp_ #define _included_gsprchnk_hpp_ #include "chunk.hpp" #include "mishchnk.hpp" class AllSprites_Header_Chunk; class AllSprites_Chunk : public Lockable_Chunk_With_Children { public: // empty constructor AllSprites_Chunk (Chunk_With_Children * parent); // constructor from buffer AllSprites_Chunk (Chunk_With_Children * const parent,const char *, size_t const); AllSprites_Header_Chunk * get_header(); // functions for the locking functionality BOOL file_equals (HANDLE &); const char * get_head_id(); void set_lock_user(char *); void post_input_processing(); private: friend class File_Chunk; friend class GodFather_Chunk; }; /////////////////////////////////////////////// class AllSprites_Header_Chunk : public Chunk { public: // constructor from buffer AllSprites_Header_Chunk (Chunk_With_Children * parent, const char * pdata, size_t psize); virtual size_t size_chunk () { chunk_size = 36; return chunk_size; } virtual BOOL output_chunk (HANDLE &); virtual void fill_data_block (char * data_start); void prepare_for_output(); private: friend class AllSprites_Chunk; friend class File_Chunk; int flags; int version_no; char lock_user[17]; // constructor from parent AllSprites_Header_Chunk (AllSprites_Chunk * parent) : Chunk (parent, "ASPRHEAD"), flags (0), version_no (0) {} }; #endif // _included_gsprchnk_hpp_
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 82 ] ] ]
63ce22346f29ca7c48ef7e27c0cd22d0ea0657f0
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/editintf.hpp
93e303cd8b00648a3813638a9cf5b51bd566fe5b
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
17,746
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'EditIntf.pas' rev: 6.00 #ifndef EditIntfHPP #define EditIntfHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <VirtIntf.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Editintf { //-- type declarations ------------------------------------------------------- #pragma pack(push, 1) struct TEditPos { short Col; int Line; } ; #pragma pack(pop) #pragma pack(push, 1) struct TCharPos { short CharIndex; int Line; } ; #pragma pack(pop) class DELPHICLASS TIEditReader; class PASCALIMPLEMENTATION TIEditReader : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual int __stdcall GetText(int Position, char * Buffer, int Count) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIEditReader(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIEditReader(void) { } #pragma option pop }; class DELPHICLASS TIEditWriter; class PASCALIMPLEMENTATION TIEditWriter : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual bool __stdcall CopyTo(int Pos) = 0 ; virtual bool __stdcall DeleteTo(int Pos) = 0 ; virtual bool __stdcall Insert(char * Text) = 0 ; virtual int __stdcall Position(void) = 0 ; virtual TCharPos __stdcall GetCurrentPos(void) = 0 ; __property TCharPos CurrentPos = {read=GetCurrentPos}; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIEditWriter(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIEditWriter(void) { } #pragma option pop }; class DELPHICLASS TIEditView; class PASCALIMPLEMENTATION TIEditView : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual TEditPos __stdcall GetPos(int Index) = 0 ; virtual void __stdcall SetPos(int Index, const TEditPos Value) = 0 ; virtual tagSIZE __stdcall GetViewSize(void) = 0 ; virtual TCharPos __stdcall PosToCharPos(int Pos) = 0 ; virtual int __stdcall CharPosToPos(const TCharPos CharPos) = 0 ; virtual void __stdcall ConvertPos(bool EdPosToCharPos, TEditPos &EditPos, TCharPos &CharPos) = 0 ; virtual void __stdcall GetAttributeAtPos(const TEditPos &EdPos, int &Element, int &LineFlag) = 0 ; __property TEditPos CursorPos = {read=GetPos, write=SetPos, index=0}; __property TEditPos TopPos = {read=GetPos, write=SetPos, index=1}; __property tagSIZE ViewSize = {read=GetViewSize}; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIEditView(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIEditView(void) { } #pragma option pop }; #pragma option push -b- enum TSyntaxHighlighter { shNone, shPascal, shC, shSQL, shQuery }; #pragma option pop #pragma option push -b- enum TBlockType { btInclusive, btLine, btColumn, btNonInclusive, btUnknown }; #pragma option pop class DELPHICLASS TIEditorInterface; class PASCALIMPLEMENTATION TIEditorInterface : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual TIEditReader* __stdcall CreateReader(void) = 0 ; virtual TIEditWriter* __stdcall CreateWriter(void) = 0 ; virtual AnsiString __stdcall FileName(void) = 0 ; virtual int __stdcall LinesInBuffer(void) = 0 ; virtual bool __stdcall BufferModified(void) = 0 ; virtual bool __stdcall MarkModified(void) = 0 ; virtual TSyntaxHighlighter __stdcall SetSyntaxHighlighter(TSyntaxHighlighter SyntaxHighlighter) = 0 ; virtual int __stdcall GetViewCount(void) = 0 ; virtual TIEditView* __stdcall GetView(int Index) = 0 ; virtual TIEditWriter* __stdcall CreateUndoableWriter(void) = 0 ; virtual TCharPos __stdcall GetBlockAfter(void) = 0 ; virtual TCharPos __stdcall GetBlockStart(void) = 0 ; virtual TBlockType __stdcall GetBlockType(void) = 0 ; virtual bool __stdcall GetBlockVisible(void) = 0 ; virtual void __stdcall SetBlockAfter(const TCharPos Value) = 0 ; virtual void __stdcall SetBlockStart(const TCharPos Value) = 0 ; virtual void __stdcall SetBlockType(TBlockType Value) = 0 ; virtual void __stdcall SetBlockVisible(bool Value) = 0 ; __property TCharPos BlockStart = {read=GetBlockStart, write=SetBlockStart}; __property TCharPos BlockAfter = {read=GetBlockAfter, write=SetBlockAfter}; __property TBlockType BlockType = {read=GetBlockType, write=SetBlockType, nodefault}; __property bool BlockVisible = {read=GetBlockVisible, write=SetBlockVisible, nodefault}; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIEditorInterface(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIEditorInterface(void) { } #pragma option pop }; #pragma option push -b- enum TPropertyType { ptUnknown, ptInteger, ptChar, ptEnumeration, ptFloat, ptString, ptSet, ptClass, ptMethod, ptWChar, ptLString, ptLWString, ptVariant }; #pragma option pop class DELPHICLASS TIComponentInterface; typedef bool __stdcall (*TGetChildCallback)(void * Param, TIComponentInterface* ComponentInterface); class PASCALIMPLEMENTATION TIComponentInterface : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual AnsiString __stdcall GetComponentType(void) = 0 ; virtual void * __stdcall GetComponentHandle(void) = 0 ; virtual TIComponentInterface* __stdcall GetParent(void) = 0 ; virtual bool __stdcall IsTControl(void) = 0 ; virtual int __stdcall GetPropCount(void) = 0 ; virtual AnsiString __stdcall GetPropName(int Index) = 0 ; virtual TPropertyType __stdcall GetPropType(int Index) = 0 ; virtual TPropertyType __stdcall GetPropTypeByName(const AnsiString Name) = 0 ; virtual bool __stdcall GetPropValue(int Index, void *Value) = 0 ; virtual bool __stdcall GetPropValueByName(const AnsiString Name, void *Value) = 0 ; virtual bool __stdcall SetProp(int Index, const void *Value) = 0 ; virtual bool __stdcall SetPropByName(const AnsiString Name, const void *Value) = 0 ; virtual bool __stdcall GetChildren(void * Param, TGetChildCallback Proc) = 0 ; virtual int __stdcall GetControlCount(void) = 0 ; virtual TIComponentInterface* __stdcall GetControl(int Index) = 0 ; virtual int __stdcall GetComponentCount(void) = 0 ; virtual TIComponentInterface* __stdcall GetComponent(int Index) = 0 ; virtual bool __stdcall Select(void) = 0 ; virtual bool __stdcall Focus(void) = 0 ; virtual bool __stdcall Delete(void) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIComponentInterface(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIComponentInterface(void) { } #pragma option pop }; class DELPHICLASS TIFormInterface; class PASCALIMPLEMENTATION TIFormInterface : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual AnsiString __stdcall FileName(void) = 0 ; virtual bool __stdcall FormModified(void) = 0 ; virtual bool __stdcall MarkModified(void) = 0 ; virtual TIComponentInterface* __stdcall GetFormComponent(void) = 0 ; virtual TIComponentInterface* __stdcall FindComponent(const AnsiString Name) = 0 ; virtual TIComponentInterface* __stdcall GetComponentFromHandle(void * ComponentHandle) = 0 ; virtual int __stdcall GetSelCount(void) = 0 ; virtual TIComponentInterface* __stdcall GetSelComponent(int Index) = 0 ; virtual TIComponentInterface* __stdcall GetCreateParent(void) = 0 ; virtual TIComponentInterface* __stdcall CreateComponent(TIComponentInterface* Container, const AnsiString TypeName, int X, int Y, int W, int H) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIFormInterface(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIFormInterface(void) { } #pragma option pop }; #pragma option push -b- enum TResHeaderValue { hvFlags, hvLanguage, hvDataVersion, hvVersion, hvCharacteristics }; #pragma option pop class DELPHICLASS TIResourceEntry; class PASCALIMPLEMENTATION TIResourceEntry : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual char * __stdcall GetResourceType(void) = 0 ; virtual char * __stdcall GetResourceName(void) = 0 ; virtual bool __stdcall Change(char * NewType, char * NewName) = 0 ; virtual bool __stdcall GetHeaderValue(TResHeaderValue HeaderValue, int &Value) = 0 ; virtual bool __stdcall SetHeaderValue(TResHeaderValue HeaderValue, int Value) = 0 ; virtual void * __stdcall GetData(void) = 0 ; virtual int __stdcall GetDataSize(void) = 0 ; virtual bool __stdcall SetDataSize(int NewSize) = 0 ; virtual void * __stdcall GetEntryHandle(void) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIResourceEntry(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIResourceEntry(void) { } #pragma option pop }; class DELPHICLASS TIResourceFile; class PASCALIMPLEMENTATION TIResourceFile : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual AnsiString __stdcall FileName(void) = 0 ; virtual int __stdcall GetEntryCount(void) = 0 ; virtual TIResourceEntry* __stdcall GetEntry(int Index) = 0 ; virtual TIResourceEntry* __stdcall GetEntryFromHandle(void * EntryHandle) = 0 ; virtual TIResourceEntry* __stdcall FindEntry(char * ResType, char * Name) = 0 ; virtual bool __stdcall DeleteEntry(void * EntryHandle) = 0 ; virtual TIResourceEntry* __stdcall CreateEntry(char * ResType, char * Name, Word Flags, Word LanguageId, int DataVersion, int Version, int Characteristics) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIResourceFile(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIResourceFile(void) { } #pragma option pop }; #pragma option push -b- enum TNotifyCode { ncModuleDeleted, ncModuleRenamed, ncEditorModified, ncFormModified, ncEditorSelected, ncFormSelected, ncBeforeSave, ncAfterSave, ncFormSaving, ncProjResModified }; #pragma option pop class DELPHICLASS TIModuleNotifier; class PASCALIMPLEMENTATION TIModuleNotifier : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual void __stdcall Notify(TNotifyCode NotifyCode) = 0 ; virtual void __stdcall ComponentRenamed(const Classes::TComponent* AComponent, const AnsiString OldName, const AnsiString NewName) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIModuleNotifier(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIModuleNotifier(void) { } #pragma option pop }; class DELPHICLASS TIModuleInterface; class PASCALIMPLEMENTATION TIModuleInterface : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual TIEditorInterface* __stdcall GetEditorInterface(void) = 0 ; virtual TIFormInterface* __stdcall GetFormInterface(void) = 0 ; virtual TIModuleInterface* __stdcall GetAncestorModule(void) = 0 ; virtual TIResourceFile* __stdcall GetProjectResource(void) = 0 ; virtual bool __stdcall IsProjectModule(void) = 0 ; virtual bool __stdcall Close(void) = 0 ; virtual bool __stdcall Save(bool ForceSave) = 0 ; virtual bool __stdcall Rename(const AnsiString NewName) = 0 ; virtual bool __stdcall GetFileSystem(AnsiString &FileSystem) = 0 ; virtual bool __stdcall SetFileSystem(const AnsiString FileSystem) = 0 ; virtual bool __stdcall ShowSource(void) = 0 ; virtual bool __stdcall ShowForm(void) = 0 ; virtual bool __stdcall AddNotifier(TIModuleNotifier* AModuleNotifier) = 0 ; virtual bool __stdcall RemoveNotifier(TIModuleNotifier* AModuleNotifier) = 0 ; virtual TIEditorInterface* __stdcall GetAuxEditorInterface(void) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIModuleInterface(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIModuleInterface(void) { } #pragma option pop }; class DELPHICLASS TIProjectCreator; class PASCALIMPLEMENTATION TIProjectCreator : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual bool __stdcall Existing(void) = 0 ; virtual AnsiString __stdcall GetFileName(void) = 0 ; virtual AnsiString __stdcall GetFileSystem(void) = 0 ; virtual AnsiString __stdcall NewProjectSource(const AnsiString ProjectName) = 0 ; virtual void __stdcall NewDefaultModule(void) = 0 ; virtual void __stdcall NewProjectResource(TIModuleInterface* Module) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIProjectCreator(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIProjectCreator(void) { } #pragma option pop }; class DELPHICLASS TIProjectCreatorEx; class PASCALIMPLEMENTATION TIProjectCreatorEx : public TIProjectCreator { typedef TIProjectCreator inherited; public: virtual AnsiString __stdcall GetOptionName(void) = 0 ; virtual AnsiString __stdcall NewOptionSource(const AnsiString ProjectName) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIProjectCreatorEx(void) : TIProjectCreator() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIProjectCreatorEx(void) { } #pragma option pop }; class DELPHICLASS TIModuleCreator; class PASCALIMPLEMENTATION TIModuleCreator : public Virtintf::TInterface { typedef Virtintf::TInterface inherited; public: virtual bool __stdcall Existing(void) = 0 ; virtual AnsiString __stdcall GetAncestorName(void) = 0 ; virtual AnsiString __stdcall GetFileName(void) = 0 ; virtual AnsiString __stdcall GetFileSystem(void) = 0 ; virtual AnsiString __stdcall GetFormName(void) = 0 ; virtual AnsiString __stdcall NewModuleSource(const AnsiString UnitIdent, const AnsiString FormIdent, const AnsiString AncestorIdent) = 0 ; virtual void __stdcall FormCreated(TIFormInterface* Form) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIModuleCreator(void) : Virtintf::TInterface() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIModuleCreator(void) { } #pragma option pop }; class DELPHICLASS TIModuleCreatorEx; class PASCALIMPLEMENTATION TIModuleCreatorEx : public TIModuleCreator { typedef TIModuleCreator inherited; public: virtual AnsiString __stdcall GetIntfName(void) = 0 ; virtual AnsiString __stdcall NewIntfSource(const AnsiString UnitIdent, const AnsiString FormIdent, const AnsiString AncestorIdent) = 0 ; public: #pragma option push -w-inl /* TInterface.Create */ inline __fastcall TIModuleCreatorEx(void) : TIModuleCreator() { } #pragma option pop public: #pragma option push -w-inl /* TObject.Destroy */ inline __fastcall virtual ~TIModuleCreatorEx(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- static const int cursorPos = 0x0; static const int ViewTopPos = 0x1; static const Shortint atWhiteSpace = 0x0; static const Shortint atComment = 0x1; static const Shortint atReservedWord = 0x2; static const Shortint atIdentifier = 0x3; static const Shortint atSymbol = 0x4; static const Shortint atString = 0x5; static const Shortint atNumber = 0x6; static const Shortint atFloat = 0x7; static const Shortint atOctal = 0x8; static const Shortint atHex = 0x9; static const Shortint atCharacter = 0xa; static const Shortint atPreproc = 0xb; static const Shortint atIllegal = 0xc; static const Shortint atAssembler = 0xd; static const Shortint SyntaxOff = 0xe; static const Shortint MarkedBlock = 0xf; static const Shortint SearchMatch = 0x10; static const Shortint lfCurrentCSIP = 0x1; static const Shortint lfBreakpointEnabled = 0x2; static const Shortint lfBreakpointDisabled = 0x4; static const Shortint lfBreakpointInvalid = 0x8; static const Shortint lfErrorLine = 0x10; static const Shortint lfBreakpointVerified = 0x20; } /* namespace Editintf */ using namespace Editintf; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // EditIntf
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 482 ] ] ]
c2cd2b7e3238277ad8cd87c6fb8d61b710e38667
ed6f03c2780226a28113ba535d3e438ee5d70266
/src/eljcaret.cpp
72b0f7b9d25edd08235795a219a18315947325df
[]
no_license
snmsts/wxc
f06c0306d0ff55f0634e5a372b3a71f56325c647
19663c56e4ae2c79ccf647d687a9a1d42ca8cb61
refs/heads/master
2021-01-01T05:41:20.607789
2009-04-08T09:12:08
2009-04-08T09:12:08
170,876
4
1
null
null
null
null
UTF-8
C++
false
false
1,160
cpp
#include "wrapper.h" extern "C" { EWXWEXPORT(wxCaret*,wxCaret_Create)(wxWindow* _wnd,int _wth,int _hgt) { return new wxCaret(_wnd, _wth, _hgt); } EWXWEXPORT(bool,wxCaret_IsOk)(wxCaret* self) { return self->IsOk(); } EWXWEXPORT(bool,wxCaret_IsVisible)(wxCaret* self) { return self->IsVisible(); } EWXWEXPORT(wxPoint*,wxCaret_GetPosition)(wxCaret* self) { return new wxPoint(self->GetPosition()); } EWXWEXPORT(wxSize*,wxCaret_GetSize)(wxCaret* self) { return new wxSize(self->GetSize()); } EWXWEXPORT(wxWindow*,wxCaret_GetWindow)(wxCaret* self) { return self->GetWindow(); } EWXWEXPORT(void,wxCaret_SetSize)(wxCaret* self,int width,int height) { self->SetSize(width, height); } EWXWEXPORT(void,wxCaret_Move)(wxCaret* self,int x,int y) { self->Move(x, y); } EWXWEXPORT(void,wxCaret_Show)(wxCaret* self) { self->Show(); } EWXWEXPORT(void,wxCaret_Hide)(wxCaret* self) { self->Hide(); } EWXWEXPORT(int,wxCaret_GetBlinkTime)() { return wxCaret::GetBlinkTime(); } EWXWEXPORT(void,wxCaret_SetBlinkTime)(int milliseconds) { wxCaret::SetBlinkTime(milliseconds); } }
[ [ [ 1, 66 ] ] ]
286dd7536e5046e43d8b801a8fea1591f2c8b6e3
57574cc7192ea8564bd630dbc2a1f1c4806e4e69
/Poker/Servidor/OpComprarFichas.h
76c97040fc940e6f5089c964aeeab9c420321267
[]
no_license
natlehmann/taller-2010-2c-poker
3c6821faacccd5afa526b36026b2b153a2e471f9
d07384873b3705d1cd37448a65b04b4105060f19
refs/heads/master
2016-09-05T23:43:54.272182
2010-11-17T11:48:00
2010-11-17T11:48:00
32,321,142
0
0
null
null
null
null
UTF-8
C++
false
false
259
h
#pragma once #include "operacion.h" class OpComprarFichas : public Operacion { protected: virtual bool ejecutarAccion(Socket* socket); public: OpComprarFichas(int idCliente, vector<string> parametros); virtual ~OpComprarFichas(void); };
[ "flrago78538@a9434d28-8610-e991-b0d0-89a272e3a296" ]
[ [ [ 1, 12 ] ] ]
bd8b782b10f21d2ab8dcaa49ef4fbd13448bb944
41371839eaa16ada179d580f7b2c1878600b718e
/SPOJ/obi/CAIXEIRB.cpp
a3eb58591bd4060b7ef2e6f4262f3df3890244a3
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
684
cpp
#include <cstdio> #include <cstring> bool must[300], vis[300]; int adj[300][300], deg[300]; int a, b, c, v, i; int dfs(int k){ int s = 0; vis[k] = 1; for(int w = 0; w < deg[k]; w++){ int x = adj[k][w]; if(!vis[x]) s += dfs(x); } return( (s || must[k]) ? (k ? s + 1: s) : 0); } int main(void){ for(int t = 1; scanf("%d%d",&c,&v) && c; t++){ memset(must,0,c); memset(vis,0,c); memset(deg,0,(c<<2)); for(i = 1; i < c; i++){ scanf("%d%d",&a,&b); adj[--a][deg[a]++] = --b; adj[b][deg[b]++] = a; } for(i = 0; i < v; i++){ scanf("%d",&a); must[--a] = 1; } printf("Teste %d\n%d\n\n",t,2*dfs(0)); } return 0; }
[ [ [ 1, 34 ] ] ]
b398539b0e0c7be170e0d1d61dc1bd76ba1970f4
032ea9816579a9869070a285d0224f95ba6a767b
/3dProject/trunk/Wall.cpp
be668c5ada65047e1887aae75a362b3c456e6dbb
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
sennheiser1986/oglproject
3577bae81c0e0b75001bde57b8628d59c8a5c3cf
d975ed5a4392036dace4388e976b88fc4280a116
refs/heads/master
2021-01-13T17:05:14.740056
2010-06-01T15:48:38
2010-06-01T15:48:38
39,767,324
0
0
null
null
null
null
UTF-8
C++
false
false
3,980
cpp
/* * 3dProject * Geert d'Hoine * (c) 2010 */ #include "Wall.h" #include "Map.h" #ifdef __APPLE__ #include <OpenGL/OpenGL.h> #include <GLUT/glut.h> #else #include <GL/glut.h> #endif Wall::Wall() { } Wall::Wall(float xIn, float yIn, float zIn, float inWidth, float inLength, float inHeight, int inTexture, bool inMark) : StaticObject(xIn, yIn, zIn) { width = inWidth; length = inLength; height = inHeight; wallTexture = inTexture; mark = inMark; if(mark) { Map * instance = Map::getInstance(); int cellSide = instance->getCellSide(); int * minMapCoord = instance->convertWorldCoordToMapCoord(x-width/2-cellSide,z-length/2-cellSide); int minRow = minMapCoord[0]; int minCol = minMapCoord[1]; int * maxMapCoord = instance->convertWorldCoordToMapCoord(x+width/2+cellSide,z+length/2+cellSide); int maxRow = maxMapCoord[0]; int maxCol = maxMapCoord[1]; int markWidth = maxCol - minCol; int markHeight = maxRow - minRow; instance->markBlock(minRow, minCol, markHeight, markWidth, 9); } } Wall::~Wall(void) { } void Wall::draw() { glPushMatrix(); glTranslatef(x, y + height/2, z); bool drawfront = true; bool drawback = true; bool drawleft = true; bool drawright = true; bool drawtop = true; bool drawbottom = true; glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, wallTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); float w = width/2; float h = height/2; float l = length/2; if(drawfront) { //front glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f,0.0f); glVertex3f(-w, -h, l); //bottom left glTexCoord2f(1.0f,0.0f); glVertex3f( w, -h, l); //bottom right glTexCoord2f(1.0f,1.0f); glVertex3f( w, h, l); //top right glTexCoord2f(0.0f,1.0f); glVertex3f(-w, h, l); //top left glEnd(); } if(drawleft) { //left glBegin(GL_QUADS); glNormal3f(-1.0f, 0.0f, 0.0f); glTexCoord2f(0,0); glVertex3f(-width/2, -height/2, -length/2); //bottom left glTexCoord2f(1,0); glVertex3f(-width/2, -height/2, length/2); //bottom right glTexCoord2f(1,1); glVertex3f(-width/2, height/2, length/2); //top right glTexCoord2f(0,1); glVertex3f(-width/2, height/2, -length/2); //top left glEnd(); } if(drawright) { //right glBegin(GL_QUADS); glNormal3f(1.0f, 0.0f, 0.0f); glTexCoord2f(1,0); glVertex3f(width/2, -height/2, -length/2); //BR glTexCoord2f(1,1); glVertex3f(width/2, height/2, -length/2); //TR glTexCoord2f(0,1); glVertex3f(width/2, height/2, length/2); //TL glTexCoord2f(0,0); glVertex3f(width/2, -height/2, length/2); //BL glEnd(); } if(drawback) { //back glBegin(GL_QUADS); glNormal3f(0.0f, 0.0f, -1.0f); glTexCoord2f(0,1); glVertex3f( width/2, height/2, -length/2); glTexCoord2f(1,1); glVertex3f(-width/2, height/2, -length/2); glTexCoord2f(1,0); glVertex3f(-width/2, -height/2, -length/2); glTexCoord2f(0,0); glVertex3f( width/2, -height/2, -length/2); glEnd(); } //top if(drawtop) { glBegin(GL_QUADS); glNormal3f(0.0f, 1.0f, 0.0f); glTexCoord2f(0,1); glVertex3f(-width/2, height/2, -length/2); glTexCoord2f(1,1); glVertex3f( width/2, height/2, -length/2); glTexCoord2f(1,0); glVertex3f( width/2, height/2, length/2); glTexCoord2f(0,0); glVertex3f(-width/2, height/2, length/2); glEnd(); } if(drawbottom) { //bottom glBegin(GL_QUADS); glNormal3f(0.0f, -1.0f, 0.0f); glTexCoord2f(0,1); glVertex3f( width/2, -height/2, length/2); glTexCoord2f(1,1); glVertex3f(-width/2, -height/2, length/2); glTexCoord2f(1,0); glVertex3f(-width/2, -height/2, -length/2); glTexCoord2f(0,0); glVertex3f( width/2, -height/2, -length/2); glEnd(); } glDisable(GL_TEXTURE_2D); glPopMatrix(); }
[ "fionnghall@444a4038-2bd8-11df-954b-21e382534593" ]
[ [ [ 1, 155 ] ] ]
684f011a9fe3d021f7aecc3345ab629c649be92c
c8d7d94a0bffd444ffbf4d2bbeb1868bda156653
/Misc/RWLock/RWLock.cpp
02509585d553f5ac6c8ae759a91ddafd0853b48c
[]
no_license
yongce/tyc-code-set
7c5d12fdf2bb9eb406e0972fdaee8106b424aa19
6255357322a6054cbd451a4969dde304099097e0
refs/heads/master
2021-01-22T10:17:45.484492
2010-04-20T16:17:37
2010-04-20T16:17:37
861,474
1
0
null
null
null
null
UTF-8
C++
false
false
2,593
cpp
/*! * @file RWLock.cpp * @brief Implementation file for class RWLock * @date 2010-04-17 20:36:54 * @author Tu Yongce <[email protected]> * @version $Id$ */ #include <cassert> #include "RWLock.h" RWLock::RWLock() : m_waitingReaders(0), m_waitingWriters(0), m_refCount(0) { ::InitializeCriticalSection(&m_cs); m_readersEvent = ::CreateEvent(NULL, TRUE, FALSE, NULL); // manual reset event m_writersEvent = ::CreateEvent(NULL, FALSE, FALSE, NULL); // auto reset event } RWLock::~RWLock() { assert(m_waitingReaders == 0); assert(m_waitingWriters == 0); assert(m_refCount == 0); ::CloseHandle(m_readersEvent); ::CloseHandle(m_writersEvent); ::DeleteCriticalSection(&m_cs); } void RWLock::ReadLock() { ::EnterCriticalSection(&m_cs); // Writers have higher priority than readers while (m_refCount < 0 || m_waitingWriters > 0) { ++m_waitingReaders; ::LeaveCriticalSection(&m_cs); ::WaitForSingleObject(m_readersEvent, INFINITE); ::EnterCriticalSection(&m_cs); --m_waitingReaders; } ++m_refCount; ::LeaveCriticalSection(&m_cs); } void RWLock::ReadUnlock() { ::EnterCriticalSection(&m_cs); assert(m_refCount > 0); --m_refCount; if (m_refCount == 0) { // Now, no readers are using the lock // Check if there are writers waiting on the lock if (m_waitingWriters > 0) { // Signal one of the waiting writers ::SetEvent(m_writersEvent); } } ::LeaveCriticalSection(&m_cs); } void RWLock::WriteLock() { ::EnterCriticalSection(&m_cs); // Stop all incoming readers ::ResetEvent(m_readersEvent); while (m_refCount != 0) { ++m_waitingWriters; ::LeaveCriticalSection(&m_cs); ::WaitForSingleObject(m_writersEvent, INFINITE); ::EnterCriticalSection(&m_cs); --m_waitingWriters; } m_refCount = -1; ::LeaveCriticalSection(&m_cs); } void RWLock::WriteUnlock() { ::EnterCriticalSection(&m_cs); assert(m_refCount == -1); m_refCount = 0; // Writers have higher priority than readers if (m_waitingWriters > 0) { // Signal one of the waiting writers ::SetEvent(m_writersEvent); } else if (m_waitingReaders > 0) { // Signal all waiting readers ::SetEvent(m_readersEvent); } ::LeaveCriticalSection(&m_cs); }
[ [ [ 1, 124 ] ] ]
3b879f3adcaca0c52a1be7a5e27fc15e2a88e18c
96e96a73920734376fd5c90eb8979509a2da25c0
/C3DE/Plane.cpp
74b6439cb2c49f9955bf2a9c5a859e4c46fd231b
[]
no_license
lianlab/c3de
9be416cfbf44f106e2393f60a32c1bcd22aa852d
a2a6625549552806562901a9fdc083c2cacc19de
refs/heads/master
2020-04-29T18:07:16.973449
2009-11-15T10:49:36
2009-11-15T10:49:36
32,124,547
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
#include "Plane.h" #include "PerPixelLighting.h" #include "PerVertexLighting.h" #include "D3DRenderer.h" #include "ResourceManager.h" #include "DebugMemory.h" Plane::Plane(float width, float height) { m_vertices = new vector<VertexPos>; m_indices = new vector<int>; m_vertices->push_back(VertexPos(-(width /2), 0.0f, -(height/2), 0.0f, 1.0f, 0.0f, 0.0f, 1.0f)); m_vertices->push_back(VertexPos(-(width /2), 0.0f, (height/2), 0.0f, 1.0f, 0.0f, 0.0f, 0.0f)); m_vertices->push_back(VertexPos( (width/2), 0.0f, (height/2), 0.0f, 1.0f, 0.0f, 1.0f, 0.0f)); m_vertices->push_back(VertexPos( (width/2), 0.0f, -(height/2), 0.0f, 1.0f, 0.0f, 1.0f, 1.0f)); m_indices->push_back(0); m_indices->push_back(1); m_indices->push_back(2); m_indices->push_back(0); m_indices->push_back(2); m_indices->push_back(3); D3DImage * d3dImage = new D3DImage(ResourceManager::GetInstance()->GetTextureByID(IMAGE_CRATE_ID)); AddTexture((Image *) d3dImage); Material *t_material = new Material( D3DXCOLOR(1.0f, 1.0f, 1.0f,1.0f),D3DXCOLOR(1.0f, 1.0f, 1.0f,1.0f), D3DXCOLOR(1.0f, 1.0f, 1.0f,1.0f), 16.0f); AddMaterial(t_material); CreateXMesh(D3DRenderer::GetDevice()); m_effect = ShaderManager::GetInstance()->GetFXByID(SHADER_LIGHTS_PER_VERTEX_TEXTURES_ID); PerVertexLighting *t_effect = (PerVertexLighting *) m_effect; t_effect->SetAlpha(1.0f); } Plane::~Plane() { ReleaseCOM(m_vertexDeclaration); } void Plane::SetShaderHandlers() { PerVertexLighting *t_effect = (PerVertexLighting *) m_effect; t_effect->SetObjectMaterials( m_currentMaterial->GetAmbient(), m_currentMaterial->GetDiffuse(), m_currentMaterial->GetSpecular(), m_currentMaterial->GetSpecularPower()); D3DImage *t_d3dText = (D3DImage *) m_currentTexture; t_effect->SetObjectTexture(t_d3dText->GetTexture()); t_effect->SetTransformMatrix(GetTransformMatrix()); }
[ "caiocsabino@7e2be596-0d54-0410-9f9d-cf4183935158" ]
[ [ [ 1, 62 ] ] ]
68c1381f5c91bf2405fc21c7f5263082f7e74eb3
1e299bdc79bdc75fc5039f4c7498d58f246ed197
/App/SSSubSystem.h
3f212ceaeb027ca70d44ad93451292666009f14b
[]
no_license
moosethemooche/Certificate-Server
5b066b5756fc44151b53841482b7fa603c26bf3e
887578cc2126bae04c09b2a9499b88cb8c7419d4
refs/heads/master
2021-01-17T06:24:52.178106
2011-07-13T13:27:09
2011-07-13T13:27:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,819
h
//-------------------------------------------------------------------------------- // // Copyright (c) 2000 MarkCare Solutions // // Programming by Rich Schonthal // //-------------------------------------------------------------------------------- #ifndef _SSSUBSYSTEM_H_ #define _SSSUBSYSTEM_H_ //-------------------------------------------------------------------------------- #include "SecuritySystem.h" class CSSIOSubSystem; class CDBSubSystem; class CClientSubSystem; class CSecuritySystem; //-------------------------------------------------------------------------------- template<class BASECLASS> class CSSSubSystem : public BASECLASS { private: CSSIOSubSystem* m_pIO; CDBSubSystem* m_pDB; CClientSubSystem* m_pClient; public: CSSSubSystem(CSecuritySystem* pSystem) : BASECLASS(pSystem), m_pIO(NULL) , m_pDB(NULL) , m_pClient(NULL) {} CSecuritySystem* GetSystem() { return (CSecuritySystem*) BASECLASS::GetSystem(); } CSSIOSubSystem* GetIO() { if(m_pIO == NULL) m_pIO = GetSystem()->GetIOSubSystem(); return m_pIO; } CDBSubSystem* GetDB() { if(m_pDB == NULL) m_pDB = GetSystem()->GetDBSubSystem(); return m_pDB; } CClientSubSystem* GetClientSubSystem() { if(m_pClient == NULL) m_pClient = GetSystem()->GetClientSubSystem(); return m_pClient; } }; /* //-------------------------------------------------------------------------------- class CSSLBSubSystem : public CLoadBalancedSubSystem { private: CSSIOSubSystem* m_pIO; CDBSubSystem* m_pDB; CClientSubSystem* m_pClient; public: CSSLBSubSystem(CSecuritySystem*); CSSIOSubSystem* GetIO(); CDBSubSystem* GetDB(); CClientSubSystem* GetClientSubSystem(); }; */ #endif // _SSSubSystem_H_
[ [ [ 1, 75 ] ] ]
d3e5fd1561ed42ad11a04316da6a6acce1751d4c
317f62189c63646f81198d1692bed708d8f18497
/contrib/orion/Allocator/RRArbiter.h
7f3fe1fb504e3a938b89ac2143a416f7835815d4
[ "MIT" ]
permissive
mit-carbon/Graphite-Cycle-Level
8fb41d5968e0a373fd4adbf0ad400a9aa5c10c90
db3f1e986ddc10f3e5f3a5d4b68bd6a9885969b3
refs/heads/master
2021-01-25T07:08:46.628355
2011-11-23T08:53:18
2011-11-23T08:53:18
1,930,686
1
0
null
null
null
null
UTF-8
C++
false
false
751
h
#ifndef __RRARBITER_H__ #define __RRARBITER_H__ #include "Type.h" #include "Arbiter.h" class TechParameter; class RRArbiter : public Arbiter { public: RRArbiter( const string& ff_model_str_, uint32_t req_width_, double len_in_wire_, const TechParameter* tech_param_ptr_ ); ~RRArbiter(); public: double calc_dynamic_energy(double num_req_, bool is_max_) const; private: void init(const string& ff_model_str_); double calc_req_cap(); double calc_pri_cap(); double calc_grant_cap(); double calc_carry_cap(); double calc_carry_in_cap(); double calc_i_static(); private: double m_e_chg_carry; double m_e_chg_carry_in; }; #endif
[ [ [ 1, 37 ] ] ]
fc11d96f78754fd1d189ed45d29d3270a63e0b10
b3b0c727bbafdb33619dedb0b61b6419692e03d3
/Source/WinHTTPTestUI/WinHTTPTestUIDlg.cpp
2292df84d2b69c953096fe8d5d797d6ec65956bc
[]
no_license
testzzzz/hwccnet
5b8fb8be799a42ef84d261e74ee6f91ecba96b1d
4dbb1d1a5d8b4143e8c7e2f1537908cb9bb98113
refs/heads/master
2021-01-10T02:59:32.527961
2009-11-04T03:39:39
2009-11-04T03:39:39
45,688,112
0
1
null
null
null
null
GB18030
C++
false
false
10,527
cpp
////////////////////////////////////////////////////////// /// /// @file WinHTTPTestUIDlg.cpp /// /// @brief 定义程序所需要的函数 /// /// @version 1.0 /// /// @author 甘先志 /// /// @date 2009-07-28 /// /// <修改日期> <修改者> <修改描述>\n /// /// 2009-07-29 游枭 增加了对多线程和定时器的处理 /// 2009-07-30 游枭 增加了对资源的释放操作 //////////////////////////////////////////////////////////// #include "stdafx.h" #include "WinHTTPLW.h" #include "WinHTTPTestUI.h" #include "WinHTTPTestUIDlg.h" #include "PromptDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif CRITICAL_SECTION g_cs; ///< 定义关键代码段,保证线程同步 bool StatusFlag = false; ///< 服务器是否返回1 volatile bool g_endThread = false; ///< 是否终止线程 // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialog { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CWinHTTPTestUIDlg 对话框 CWinHTTPTestUIDlg::CWinHTTPTestUIDlg(CWnd* pParent /*=NULL*/) : CDialog(CWinHTTPTestUIDlg::IDD, pParent) , m_pDlg(NULL) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CWinHTTPTestUIDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CWinHTTPTestUIDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_MESSAGE(WM_SHOWTASK,OnShowTask) ON_WM_TIMER() // ON_WM_DESTROY() ON_WM_DESTROY() END_MESSAGE_MAP() // CWinHTTPTestUIDlg 消息处理程序 BOOL CWinHTTPTestUIDlg::OnInitDialog() { CDialog::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 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); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 InitializeCriticalSection(&g_cs); SetTimer( IDT_TIMER_CHECK ,8000 ,NULL ); AfxBeginThread( reinterpret_cast<AFX_THREADPROC>(pfnThreadProc), NULL ); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CWinHTTPTestUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); if (nID == SC_MINIMIZE) { ToTray(); //添加最小化到系统托盘的函数响应命令 } } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CWinHTTPTestUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 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; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CWinHTTPTestUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } //////////////////////////////////////////////////////////// /// /// @brief 完成在最小化到系统栏功能 /// /// @param 无 /// /// @return 无 /// //////////////////////////////////////////////////////////// void CWinHTTPTestUIDlg::ToTray(void) { NOTIFYICONDATA Notifyid; Notifyid.cbSize = (DWORD)sizeof(NOTIFYICONDATA); Notifyid.hWnd = this->m_hWnd; Notifyid.uID = IDR_MAINFRAME; Notifyid.uFlags = NIF_ICON|NIF_MESSAGE | NIF_TIP ; Notifyid.uCallbackMessage = WM_SHOWTASK; //自定义的消息名称 Notifyid.hIcon = LoadIcon( AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME )); lstrcpy(Notifyid.szTip,L"WinHTTPLW"); //信息提示条 Shell_NotifyIcon(NIM_ADD,&Notifyid); //在托盘区添加图标 ShowWindow(SW_HIDE); //隐藏主窗口 } //////////////////////////////////////////////////////////// /// /// @brief 完成在系统栏显示点击右键和双击功能 /// /// @param WPARAM wParam /// /// @param LPARAM lParam /// /// @return 返回状态 /// /// @retval 1 返回当前 /// /// @retval 0 返回系统 /// //////////////////////////////////////////////////////////// LRESULT CWinHTTPTestUIDlg::OnShowTask(WPARAM wParam, LPARAM lParam) { if (wParam != IDR_MAINFRAME) { return 1; } switch(lParam) { case WM_RBUTTONUP: //右键起来时弹出快捷菜单,这里只有一个“关闭” { LPPOINT lPoint = new tagPOINT; ::GetCursorPos(lPoint); //获得鼠标位置 CMenu menu; menu.CreatePopupMenu(); //声明一个弹出式菜单 menu.AppendMenu(MF_STRING,WM_DESTROY,L"关闭"); //确定菜单 menu.TrackPopupMenu(TPM_LEFTALIGN,lPoint->x,lPoint->y,this); HMENU hmenu=menu.Detach(); menu.DestroyMenu(); delete lPoint; break; } case WM_LBUTTONDBLCLK: { this->ShowWindow(SW_SHOWNORMAL); //显示主窗口位于原来的位置 DeleteTray(); break; } default: break; } return 0; } //////////////////////////////////////////////////////////// /// /// @brief 完成在删除系统栏图标功能 /// /// @param 无 /// /// @return 无 /// //////////////////////////////////////////////////////////// void CWinHTTPTestUIDlg::DeleteTray(void) { NOTIFYICONDATA Notifyid; Notifyid.cbSize = (DWORD)sizeof(NOTIFYICONDATA); Notifyid.hWnd = this->m_hWnd; Notifyid.uID = IDR_MAINFRAME; Notifyid.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP ; Notifyid.uCallbackMessage = WM_SHOWTASK; //自定义的消息名称 Notifyid.hIcon=LoadIcon( AfxGetInstanceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME)); lstrcpy( Notifyid.szTip,L"WinHTTPLW" ); //信息提示条为“计划任务提醒” Shell_NotifyIcon( NIM_DELETE,&Notifyid ); //在托盘区删除图标 } //////////////////////////////////////////////////////////// /// /// @brief 定时检查StatusFlag,如果为true既弹出提示对话框 /// /// @param UINT_PTR nIDEvent WM_TIMER消息ID /// /// @return void /// //////////////////////////////////////////////////////////// void CWinHTTPTestUIDlg::OnTimer(UINT_PTR nIDEvent) { switch (nIDEvent) { case IDT_TIMER_CHECK: EnterCriticalSection(&g_cs); if (StatusFlag) { m_pDlg = new CPromptDlg(); m_pDlg->Create(IDD_PROMPT); m_pDlg->ShowWindow(SW_SHOW); StatusFlag = false; LeaveCriticalSection(&g_cs); } break; default: break; } CDialog::OnTimer(nIDEvent); } //////////////////////////////////////////////////////////// /// /// @brief 监视服务器是否返回1 /// /// @param void /// /// @return void /// //////////////////////////////////////////////////////////// void pfnThreadProc() { HRESULT Error = S_OK; char* Buf=new char[1]; WinHTTPLW::Initialize(); WinHTTPLW* p = new WinHTTPLW(); Error = p->Connect(L"www.52xianjian.com"); if (FAILED(Error)) { AfxEndThread(0); } while(true) { Error = p->Request(L"GET", L"/ip.php"); if (FAILED(Error)) { AfxEndThread(0); } Error = p->GetData(Buf,1); if (FAILED(Error)) { AfxEndThread(0); } if (*Buf == '1') { EnterCriticalSection(&g_cs); StatusFlag = true; LeaveCriticalSection(&g_cs); } else { EnterCriticalSection(&g_cs); StatusFlag = false; LeaveCriticalSection(&g_cs); } } delete p; p = NULL; } //////////////////////////////////////////////////////////// /// /// @brief 对资源进行释放 /// /// @param void /// /// @return void /// //////////////////////////////////////////////////////////// void CWinHTTPTestUIDlg::OnDestroy() { CDialog::OnDestroy(); WinHTTPLW::Uninitialize(); DeleteCriticalSection(&g_cs); delete m_pDlg; m_pDlg = NULL; }
[ [ [ 1, 382 ] ] ]
75a46e9d540967400d1e71eedf86abc447642713
f0da2c3ab8426f8bcdd8c3625c805a25f04aa89d
/armagic/Card.h
4c35a16c137c650d5dd887a74c2923221a299e00
[]
no_license
sanyaade-augmented-reality/armagic
81e557978936c396333be0261e45d869da680e6d
eb5132d280685e2f8db4ae1f3fbe624b1876bf73
refs/heads/master
2016-09-06T17:12:20.458558
2010-07-06T22:57:18
2010-07-06T22:57:18
34,191,493
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
h
#ifndef ARMAGIC_CARD_H_ #define ARMAGIC_CARD_H_ #include <string> #include <vector> #include <irrlicht.h> using namespace irr; using irr::core::vector3df; class Card { public: enum Color { COLOR_WHITE, COLOR_BLACK, COLOR_GREEN, COLOR_BLUE, COLOR_RED }; enum Type { CARD_LAND, CARD_CREATURE }; Card(const Color color, const std::string& marker, const std::string& name, irr::scene::IAnimatedMeshSceneNode* node); Card(); virtual ~Card(); inline Color getColor() { return color_; } inline std::string getMarker() const { return marker_; } inline std::string getName() const { return name_; } inline core::vector3df getPosition() const { return node_->getAbsolutePosition(); } inline Type getType() const { return type_; } inline irr::scene::IAnimatedMeshSceneNode* getNode() const { return node_; } inline bool isInGame() const { return inGame_; } inline void setInGame(const bool b) { inGame_ = b; } protected: Color color_; Type type_; std::string name_; std::string marker_; bool inGame_; irr::scene::IAnimatedMeshSceneNode* node_; }; #endif
[ "leochatain@22892e45-cd4f-0d29-0166-6a0decb81ae3", "pmdusso@22892e45-cd4f-0d29-0166-6a0decb81ae3" ]
[ [ [ 1, 4 ], [ 6, 8 ], [ 10, 31 ], [ 33, 33 ], [ 35, 36 ], [ 39, 43 ], [ 48, 51 ] ], [ [ 5, 5 ], [ 9, 9 ], [ 32, 32 ], [ 34, 34 ], [ 37, 38 ], [ 44, 47 ] ] ]
c760d170d2df05be936b408d24c4adc3b4c15ec6
8c54d89af1800c4c06959a3b7b62d04f883a11c0
/cs752/RTC/Code/.svn/text-base/Camera.cpp.svn-base
02134e3b4cdd4d55549dcc826ae21780070aee48
[]
no_license
dknutsen/dokray
567c79e7a69c80a97cd73bead151a12ad2d34f23
92acd2967542865963462aaf2299ab2427b89f31
refs/heads/master
2020-12-24T13:29:01.740250
2011-10-23T23:09:49
2011-10-23T23:09:49
2,639,353
0
0
null
null
null
null
UTF-8
C++
false
false
1,110
/* Author: Daniel Knutsen, Trevor Gerhardt Date: Spring 2010 Course: CS 752 */ #include "Camera.h" #include "Point.h" #include "Ray.h" #include "Vector.h" namespace RT { Point PinholeCamera::getEye() { return this->eye; } PinholeCamera::PinholeCamera( Point eye, Point lat, Vector up, float fov ) : eye( eye ), lat( lat ), up( up ), fov( fov ) { } void PinholeCamera::preprocess( float aspect ) { this->L = (this->lat - this->eye).normal(); Vector Ut = cross( this->L, this->up ); Vector Vt = cross( Ut, this->L ); //Vector U = (tan(deg2rad*fov*0.5f)) * Ut.normal(); //Vector V = ((1/aspect)*tan(deg2rad*fov*0.5f)) * Vt.normal(); this->U = Ut.normal(); this->U = this->U * tan( deg2rad * this->fov * 0.5f ); this->V = Vt.normal(); this->V = this->V * ( ( 1/aspect ) * tan( deg2rad * this->fov * 0.5f ) ); } Ray PinholeCamera::generateRay( float x, float y ) const { return Ray( this->eye, (this->L + (x * this->U) + (y * this->V) ).normal() ); } } // namespace RT
[ [ [ 1, 41 ] ] ]
ac22dd81e082e5741bea2f421ee7f7ebb72e8216
6fa6532d530904ba3704da72327072c24adfc587
/SCoder/QtGUI/sources/main.cpp
ee4564a9b2abd6af49ed59b90e2f3ae7c3fb5d60
[]
no_license
photoguns/code-hnure
277b1c0a249dae75c66e615986fb1477e6e0f938
92d6ab861a9de3f409c5af0a46ed78c2aaf13c17
refs/heads/master
2020-05-20T08:56:07.927168
2009-05-29T16:49:34
2009-05-29T16:49:34
35,911,792
0
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
#include <QtGui/QApplication> #include <QTranslator> #include "scoderwizard.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); QTranslator translator; translator.load("scoder_ru"); a.installTranslator(&translator); SCoderWizard w; w.show(); return a.exec(); }
[ "[email protected]@8592428e-0b6d-11de-9036-69e38a880166", "cutwatercore@8592428e-0b6d-11de-9036-69e38a880166" ]
[ [ [ 1, 1 ], [ 3, 8 ], [ 15, 18 ] ], [ [ 2, 2 ], [ 9, 14 ] ] ]
51491ea6da65e0c1d8595b953fa1722c0034c57a
bfcc0f6ef5b3ec68365971fd2e7d32f4abd054ed
/samples/csvedit/csvedit.cpp
ec42b3d816655e6a82708b0c2c3bdd2b59d6d354
[]
no_license
cnsuhao/kgui-1
d0a7d1e11cc5c15d098114051fabf6218f26fb96
ea304953c7f5579487769258b55f34a1c680e3ed
refs/heads/master
2021-05-28T22:52:18.733717
2011-03-10T03:10:47
2011-03-10T03:10:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,681
cpp
/*********************************************************************************/ /* CSVEdit - kGUI sample program showing: */ /* */ /* Tables */ /* Load/Save requestor */ /* Printing reports */ /* Load/Save XML preferences */ /* Sample Font added to internal bigfile */ /* */ /* Programmed by Kevin Pickell */ /* 02-Jun-2008 */ /* */ /*********************************************************************************/ #include "kgui.h" #include "kguicsv.h" #include "kguireport.h" #include "kguireq.h" #define APPNAME "CSVEdit Sample" #if defined(WIN32) || defined(MINGW) #include "resource.h" #endif #include "kguisys.cpp" class CSVTableRow : public kGUITableRowObj { public: CSVTableRow(); int GetNumObjects(void) {return m_numcells;} kGUIObj **GetObjectList(void) {return m_objectlist.GetArrayPtr();} void SetCell(int col,kGUIString *s) {m_cells.GetEntryPtr(col)->SetString(s);} kGUIString *GetCell(int col) {return m_cells.GetEntryPtr(col);} private: int m_numcells; Array<kGUIObj *>m_objectlist; ClassArray<kGUIInputBoxObj>m_cells; }; class CSVEditSample { public: CSVEditSample(); ~CSVEditSample(); int GetNumCols(void) {return m_table.GetNumCols();} int GetNumRows(void) {return m_table.GetNumRows();} kGUIString *GetCellPtr(int row,int col) {return static_cast<kGUIInputBoxObj *>(m_table.GetRow(row)->GetObjectList()[col]);} private: CALLBACKGLUEPTR(CSVEditSample,ButtonEvent,kGUIEvent); /* make a static connection to the callback */ void ButtonEvent(kGUIEvent *event); CALLBACKGLUEPTR(CSVEditSample,OpenMenuEvent,kGUIEvent); /* make a static connection to the callback */ void OpenMenuEvent(kGUIEvent *event); CALLBACKGLUEPTR(CSVEditSample,MenuEvent,kGUIEvent); /* make a static connection to the callback */ void MenuEvent(kGUIEvent *event); CALLBACKGLUEPTR(CSVEditSample,ColMenuEvent,kGUIEvent); /* make a static connection to the callback */ void ColMenuEvent(kGUIEvent *event); CALLBACKGLUEPTR(CSVEditSample,TableEvent,kGUIEvent); /* make a static connection to the callback */ void TableEvent(kGUIEvent *event); CALLBACKGLUEPTRVAL(CSVEditSample,LoadCSV,kGUIFileReq,int); /* make a static connection to the callback */ void LoadCSV(kGUIFileReq *req,int status); CALLBACKGLUEPTRVAL(CSVEditSample,SaveCSV,kGUIFileReq,int); /* make a static connection to the callback */ void SaveCSV(kGUIFileReq *req,int status); static int SortEntry(const void *o1,const void *o2); kGUITextObj m_menucaption; kGUIMenuColObj m_popmenu; kGUIMenuColObj m_colmenu; unsigned int m_numsortcols; Array<int>m_sortcols; Array<bool>m_sortrevs; /* reverse flag */ /* todo, had header flag */ /* todo: font size for use in the table */ kGUITableObj m_table; }; /* my report */ class MyReport : public kGUIReport { public: MyReport(int pid); ~MyReport(); private: int GetPPI(void) {return 125;} /* pixels per inch */ double GetPageWidth(void) {return -1.0f;} /* inches */ double GetPageHeight(void) {return -1.0f;} /* inches */ double GetLeftMargin(void) {return 0.25f;} /* inches */ double GetRightMargin(void) {return 0.25f;} /* inches */ double GetTopMargin(void) {return 0.25f;} /* inches */ double GetBottomMargin(void) {return 0.25f;} /* inches */ void Setup(void); void Setup(int page); const char *GetName(void) {return "My Report Title";} /********************************/ /* put uset controls that will appear in the print preview page here */ kGUITextObj m_tnumlines; kGUIInputBoxObj m_inumlines; kGUITextObj m_tfontsize; kGUIInputBoxObj m_ifontsize; /* this will be duplicated at the top of EACH page */ kGUIReportTextObj m_pagenofn; kGUIReportTextObj m_pagetitle; kGUIReportTextObj m_pagedatetime; /* this is int the body */ ClassArray<kGUIReportTextObj>m_lines; kGUIReportRowHeaderObj m_rowheader; }; CSVEditSample *g_csv; void AppInit(void) { kGUI::LoadFont("font.ttf",false); /* use default font inside kgui for regulsr */ kGUI::LoadFont("font.ttf",true); /* use default font inside kgui for bold */ kGUI::SetDefFontSize(15); kGUI::SetDefReportFontSize(20); new CSVEditSample(); } void AppClose(void) { delete g_csv; } enum { MENU_LOADCSV, MENU_SAVECSV, MENU_PRINT, MENU_EXIT, MENU_NUMENTRIES }; enum { COLMENU_INSERTCOLBEFORE, COLMENU_INSERTCOLAFTER, COLMENU_DELETECOL, COLMENU_SORTASC, COLMENU_SORTDESC, COLMENU_SORTASC2, COLMENU_SORTDESC2, COLMENU_NUMENTRIES}; CSVEditSample::CSVEditSample() { int i; kGUIWindowObj *background; g_csv=this; background=kGUI::GetBackground(); background->SetTitle("CSVEdit"); /* this is static text that when clicked on opens the popup menu */ m_menucaption.SetFontSize(20); m_menucaption.SetString("Menu"); m_menucaption.SetEventHandler(this,CALLBACKNAME(OpenMenuEvent)); background->AddObject(&m_menucaption); /* let's populate the popup menu */ m_popmenu.SetNumEntries(MENU_NUMENTRIES); m_popmenu.SetEntry(MENU_LOADCSV,"Load CSV"); m_popmenu.SetEntry(MENU_SAVECSV,"Save CSV"); m_popmenu.SetEntry(MENU_PRINT,"Print"); m_popmenu.SetEntry(MENU_EXIT,"Exit"); m_popmenu.SetEventHandler(this,CALLBACKNAME(MenuEvent)); /* the menu when right clicking on a column */ m_colmenu.SetNumEntries(COLMENU_NUMENTRIES); m_colmenu.SetEntry(COLMENU_INSERTCOLBEFORE,"Insert Column Before"); m_colmenu.SetEntry(COLMENU_INSERTCOLAFTER,"Insert Column After"); m_colmenu.SetEntry(COLMENU_DELETECOL,"Delete Column"); m_colmenu.SetEntry(COLMENU_SORTASC,"Sort Ascending"); m_colmenu.SetEntry(COLMENU_SORTDESC,"Sort Descending"); m_colmenu.SetEntry(COLMENU_SORTASC2,"Secondaty Sort Ascending"); m_colmenu.SetEntry(COLMENU_SORTDESC2,"Secondaty Sort Descending"); m_colmenu.SetEventHandler(this,CALLBACKNAME(ColMenuEvent)); /* default to 4 columns */ m_table.SetNumCols(4); for(i=0;i<4;++i) { m_table.GetColHeaderTextPtr(i)->Sprintf("Col #%d",i); m_table.SetColWidth(i,150); } m_table.SetAllowAddNewRow(true); /* allow user to add new row */ m_table.SetPos(0,30); m_table.SetSize(background->GetChildZoneW(),background->GetChildZoneH()-30); m_table.SetEventHandler(this,CALLBACKNAME(TableEvent)); background->AddObject(&m_table); m_sortcols.Init(3,1); m_sortrevs.Init(3,1); m_numsortcols=0; /* add 20 rows to the table, added by table event handler */ for(i=0;i<20;++i) m_table.AddNewRow(); kGUI::ShowWindow(); } void CSVEditSample::TableEvent(kGUIEvent *event) { switch(event->GetEvent()) { case EVENT_ADDROW: CSVTableRow *row; row=new CSVTableRow(); m_table.AddRow(row); break; case EVENT_COL_RIGHTCLICK: m_colmenu.Activate(kGUI::GetMouseX(),kGUI::GetMouseY()); break; } } void CSVEditSample::OpenMenuEvent(kGUIEvent *event) { if(event->GetEvent()==EVENT_LEFTCLICK) m_popmenu.Activate(kGUI::GetMouseX(),kGUI::GetMouseY()); } void CSVEditSample::MenuEvent(kGUIEvent *event) { if(event->GetEvent()==EVENT_SELECTED) { switch(event->m_value[0].i) { case MENU_LOADCSV: { kGUIFileReq *loadreq; loadreq=new kGUIFileReq(FILEREQ_OPEN,"",".csv",this,CALLBACKNAME(LoadCSV)); } break; case MENU_SAVECSV: { kGUIFileReq *savereq; savereq=new kGUIFileReq(FILEREQ_SAVE,"",".csv",this,CALLBACKNAME(SaveCSV)); } break; case MENU_PRINT: break; case MENU_EXIT: kGUI::CloseApp(); break; } } } void CSVEditSample::ColMenuEvent(kGUIEvent *event) { if(event->GetEvent()==EVENT_SELECTED) { switch(event->m_value[0].i) { case COLMENU_INSERTCOLBEFORE: break; case COLMENU_INSERTCOLAFTER: break; case COLMENU_DELETECOL: break; case COLMENU_SORTASC: m_numsortcols=1; m_sortcols.SetEntry(0,m_table.GetColOrder(m_table.GetCursorCol())); m_sortrevs.SetEntry(0,false); m_table.Sort(SortEntry); break; case COLMENU_SORTDESC: m_numsortcols=1; m_sortcols.SetEntry(0,m_table.GetColOrder(m_table.GetCursorCol())); m_sortrevs.SetEntry(0,true); m_table.Sort(SortEntry); break; case COLMENU_SORTASC2: m_sortcols.SetEntry(m_numsortcols,m_table.GetColOrder(m_table.GetCursorCol())); m_sortrevs.SetEntry(m_numsortcols,false); ++m_numsortcols; m_table.Sort(SortEntry); break; case COLMENU_SORTDESC2: m_sortcols.SetEntry(m_numsortcols,m_table.GetColOrder(m_table.GetCursorCol())); m_sortrevs.SetEntry(m_numsortcols,true); ++m_numsortcols; m_table.Sort(SortEntry); break; } } } int CSVEditSample::SortEntry(const void *o1,const void *o2) { unsigned int s; int sc; int res; bool sr; CSVTableRow *r1=*(static_cast<CSVTableRow **>((void *)o1)); CSVTableRow *r2=*(static_cast<CSVTableRow **>((void *)o2)); for(s=0;s<g_csv->m_numsortcols;++s) { sc=g_csv->m_sortcols.GetEntry(s); sr=g_csv->m_sortrevs.GetEntry(s); res=strcmp(r1->GetCell(sc)->GetString(),r2->GetCell(sc)->GetString()); if(res) { if(sr==false) return(res); return(-res); } } /* tie */ return(0); } /* you can have a unique event handler for each object, or you can have one to handle many objects */ void CSVEditSample::ButtonEvent(kGUIEvent *event) { switch(event->GetEvent()) { case EVENT_PRESSED: { MyReport *rep; rep=new MyReport(kGUI::GetDefPrinterNum()); rep->Preview(); } break; } } void CSVEditSample::LoadCSV(kGUIFileReq *req,int status) { if(status==MSGBOX_OK) { kGUICSV csvfile; unsigned int r,numrows; unsigned int c,numcols; csvfile.SetFilename(req->GetFilename()); if(csvfile.Load()==true) { numrows=csvfile.GetNumRows(); numcols=csvfile.GetNumCols(); m_table.DeleteChildren(); m_table.SetNumCols(numcols); for(r=0;r<numrows;++r) { m_table.AddNewRow(); for(c=0;c<numcols;++c) csvfile.GetField(r,c,GetCellPtr(r,c)); } } } } void CSVEditSample::SaveCSV(kGUIFileReq *req,int status) { if(status==MSGBOX_OK) { int row,col; int numrows; int numcols; kGUIString *cell; bool stop; kGUICSV csvfile; numrows=GetNumRows(); numcols=GetNumCols(); /* decrement numcols if empty columns found */ stop=false; while(numcols>1 && stop==false) { row=0; while(row<numrows && stop==false) { cell=GetCellPtr(row,numcols-1); if(cell->GetLen()) stop=true; ++row; } if(stop==false) --numcols; } /* decrement numrows if empty rows found */ stop=false; while(numrows>1 && stop==false) { col=0; while(col<numcols && stop==false) { cell=GetCellPtr(numrows-1,col); if(cell->GetLen()) stop=true; ++col; } if(stop==false) --numrows; } /* ok we got a numrows and numcols to save */ csvfile.SetFilename(req->GetFilename()); csvfile.Init(numrows,numcols); for(row=0;row<numrows;++row) { for(col=0;col<numcols;++col) csvfile.SetField(row,col,GetCellPtr(row,col)); } csvfile.Save(); } } CSVEditSample::~CSVEditSample() { m_table.DeleteChildren(); } /*********************************************************************************/ CSVTableRow::CSVTableRow() { int i; /* get number of columns from the table */ m_numcells=g_csv->GetNumCols(); m_objectlist.Init(m_numcells,1); m_cells.Init(m_numcells,1); for(i=0;i<m_numcells;++i) m_objectlist.SetEntry(i,m_cells.GetEntryPtr(i)); SetRowHeight(20); } /*********************************************************************************/ MyReport::MyReport(int pid) { //printer to use SetPID(pid); /* add custom controls to the print preview panel */ m_tnumlines.SetString("Number of Lines:"); AddUserControl(&m_tnumlines); m_inumlines.SetString("25"); m_inumlines.SetSize(100,m_tnumlines.GetZoneH()); AddUserControl(&m_inumlines); m_tfontsize.SetString("Starting Font Size:"); AddUserControl(&m_tfontsize); m_ifontsize.SetString("50"); m_ifontsize.SetSize(100,m_tfontsize.GetZoneH()); AddUserControl(&m_ifontsize); m_lines.Init(16,16); } void MyReport::Setup(void) { int ppw,pph; int i,fs,y,numlines,fontsize; kGUIDate date; kGUIString timestring; kGUIReportTextObj *t; numlines=m_inumlines.GetInt(); fontsize=m_ifontsize.GetInt(); /* get page size in pixels */ GetPageSizePixels(&ppw,&pph); m_pagenofn.SetPos(0,0); /* text will be overwritten during the Setup code for each page */ m_pagenofn.SetString("Page x of x"); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagenofn); m_pagetitle.SetPos(0,0); m_pagetitle.SetString("My Page Title!"); m_pagetitle.SetZoneW(ppw); m_pagetitle.SetHAlign(FT_CENTER); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagetitle); /* generate a string for date/time */ date.SetToday(); date.LongDate(&m_pagedatetime); date.Time(&timestring); m_pagedatetime.ASprintf(" %s",timestring.GetString()); m_pagedatetime.SetPos(0,0); m_pagedatetime.SetZoneW(ppw); m_pagedatetime.SetHAlign(FT_RIGHT); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_pagedatetime); fs=fontsize; y=0; for(i=0;i<numlines;++i) { t=m_lines.GetEntryPtr(i); /* get a report text object */ t->SetPos(0,y); t->SetFontSize(fs); t->SetString("Hello World!"); t->SetSize(t->GetWidth()+6,t->GetLineHeight()+6); y+=t->GetZoneH(); /* attach to the page */ AddObjToSection(REPORTSECTION_BODY,t); ++fs; } #if 0 int i,ne,x,y,w,xcol; GPXRow *row; GridLine *line; int oldsize; oldsize=kGUI::GetDefReportFontSize(); kGUI::SetDefReportFontSize(gpx->GetTableFontSize()); // SetBitmapMode(true); /* send to printer as a bitmap */ /* count number of visible columns */ ne=0; for(i=0;i<m_table->GetNumCols();++i) { if(m_table->GetColShow(i)==true) ++ne; } m_rowheader.SetNumColumns(m_table->GetNumCols()); x=0; y=0; for(i=0;i<m_table->GetNumCols();++i) { xcol=m_table->GetColOrder(i); if(m_table->GetColShow(xcol)==true) { w=m_table->GetColWidth(xcol)+12; m_rowheader.SetColX(y,x); m_rowheader.SetColWidth(y,w); m_rowheader.SetColName(y,wpcolnames[xcol]); x+=w; ++y; } } m_rowheader.SetZoneH(20); AddObjToSection(REPORTSECTION_PAGEHEADER,&m_rowheader,false); ne=m_table->GetNumChildren(); y=0; for(i=0;i<ne;++i) { row=static_cast<GPXRow *>(m_table->GetChild(i)); line=new GridLine(&m_rowheader,m_table,row,(i&1)==1); line->SetZoneY(y); AddObjToSection(REPORTSECTION_BODY,line,true); y+=line->GetZoneH(); } kGUI::SetDefReportFontSize(oldsize); #endif } /* this is called before printing each page */ void MyReport::Setup(int page) { m_pagenofn.Sprintf("Page %d of %d",page,GetNumPages()); } MyReport::~MyReport() { //save selected printer for using as the default next time // gpx->m_MyReport.SetString(kGUI::GetPrinterObj(GetPID())->GetName()); }
[ "[email protected]@4b35e2fd-144d-0410-91a6-811dcd9ab31d" ]
[ [ [ 1, 594 ] ] ]
6ea54159dc292dfa80a7f635989505c0c767529c
b4d726a0321649f907923cc57323942a1e45915b
/CODE/UI/UI.H
1fa5f0ed251cc1ab840763b56c1327de54a5d98a
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
33,322
h
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ /* * $Logfile: /Freespace2/code/Ui/UI.H $ * $Revision: 1.1.1.1 $ * $Date: 2004/08/13 22:47:43 $ * $Author: Spearhawk $ * * Include file for our user interface. * * $Log: UI.H,v $ * Revision 1.1.1.1 2004/08/13 22:47:43 Spearhawk * no message * * Revision 1.1.1.1 2004/08/13 21:01:45 Darkhill * no message * * Revision 2.3 2004/03/10 18:45:09 Kazan * partially complete IRC - so i can work on it on my laptop * * Revision 2.2 2002/08/06 03:50:48 penguin * inserted "class" keyword on "friend" definitions (ANSI C++ ) * * Revision 2.1 2002/08/01 01:41:10 penguin * The big include file move * * Revision 2.0 2002/06/03 04:02:29 penguin * Warpcore CVS sync * * Revision 1.1 2002/05/02 18:03:13 mharris * Initial checkin - converted filenames and includes to lower case * * * 20 8/16/99 9:45a Jefff * changes to cursor management to allow a 2nd temporary cursor * * 19 8/11/99 3:21p Jefff * set_bmaps clarification by daveb * * 18 8/11/99 12:18p Jefff * added option to slider2 class to not force slider reset on * set_numberItems * * 17 8/10/99 6:54p Dave * Mad optimizations. Added paging to the nebula effect. * * 16 8/05/99 2:44p Jefff * added disabled callback to UI_BUTTON * * 15 6/25/99 11:59a Dave * Multi options screen. * * 14 6/22/99 7:03p Dave * New detail options screen. * * 13 5/21/99 6:45p Dave * Sped up ui loading a bit. Sped up localization disk access stuff. Multi * start game screen, multi password, and multi pxo-help screen. * * 12 5/04/99 5:20p Dave * Fixed up multiplayer join screen and host options screen. Should both * be at 100% now. * * 11 5/03/99 8:33p Dave * New version of multi host options screen. * * 10 4/29/99 2:15p Neilk * fixed slider so there is an extra callback for mouse locks * * 9 4/16/99 5:22p Neilk * Added UI_SLIDER2 class * * 8 2/21/99 6:02p Dave * Fixed standalone WSS packets. * * 7 2/11/99 3:08p Dave * PXO refresh button. Very preliminary squad war support. * * 6 2/01/99 5:55p Dave * Removed the idea of explicit bitmaps for buttons. Fixed text * highlighting for disabled gadgets. * * 5 12/18/98 1:13a Dave * Rough 1024x768 support for Direct3D. Proper detection and usage through * the launcher. * * 4 12/02/98 5:47p Dave * Put in interface xstr code. Converted barracks screen to new format. * * 3 11/30/98 1:07p Dave * 16 bit conversion, first run. * * 2 10/07/98 10:54a Dave * Initial checkin. * * 1 10/07/98 10:51a Dave * * 71 5/12/98 11:59p Dave * Put in some more functionality for Parallax Online. * * 70 5/11/98 5:29p Hoffoss * Added mouse button mapped to joystick button support. * * 69 5/05/98 1:49a Lawrance * Add member function to disable processing for all gadgets in a window * * 68 5/03/98 1:55a Lawrance * Add function call that forces button code to skip first callback for * highlighing * * 67 4/17/98 12:22a Dave * Bumped up MAX_TOOLTIPS from 350 to 500 so Freespace will start. * * 66 4/14/98 5:07p Dave * Don't load or send invalid pilot pics. Fixed chatbox graphic errors. * Made chatbox display team icons in a team vs. team game. Fixed up pause * and endgame sequencing issues. * * 65 4/14/98 4:27p Hoffoss * Changed the way tooltips render as requested. * * 64 4/13/98 4:30p Hoffoss * Fixed a bunch of stupid little bugs in options screen. Also changed * forced_draw() to work like it used to. * * 63 4/12/98 2:09p Dave * Make main hall door text less stupid. Make sure inputbox focus in the * multi host options screen is managed more intelligently. * * 62 4/10/98 5:36p Dave * Put in user notification of illegal values in multi host options * screen. Fixed server respawn ship class problem. * * 61 4/10/98 4:51p Hoffoss * Made several changes related to tooltips. * * 60 4/09/98 7:14p Hoffoss * Did some cool changes for tooltips. * * 59 4/09/98 5:57p Hoffoss * Added custom tooltip handler functionality for callback. * * 58 4/09/98 12:12p Mike * Separate versioning for demo and full versions. * Fix inputbox bugs. * * 57 3/30/98 6:24p Hoffoss * Added the tooltip (foreign language translation of text) system. * * 56 3/23/98 5:48p Hoffoss * Improved listbox handling. Most notibly the scrollbar arrows work now. * * 55 3/22/98 10:50p Lawrance * Allow sliders to not have end-buttons. * * 54 3/10/98 4:06p Hoffoss * Removed unused variables. * * 53 3/09/98 5:55p Dave * Fixed stats to take asteroid hits into account. Polished up UI stuff in * team select. Finished up pilot info popup. Tracked down and fixed * double click bug. * * 52 3/02/98 3:54p Lawrance * make button draw function public * * 51 2/26/98 4:21p Dave * More robust multiplayer voice. * * 50 2/11/98 6:24p Hoffoss * Fixed bug where disabled and hidden buttons give failed sound when * pressed. Shouldn't happen when they are hidden. * * 49 2/09/98 10:03a Hoffoss * Made first_time variable public so I can clear the stupid thing in code * that I want it to be cleared in. * * 48 1/26/98 6:28p Lawrance * Add ability to for a button press event externally. * * 47 1/23/98 5:43p Dave * Finished bringing standalone up to speed. Coded in new host options * screen. * * 46 1/16/98 7:57p Lawrance * support animating input box cursor * * 45 1/15/98 5:10p Allender * ton of interface changes. chatbox in multiplayer now behaves * differently than before. It's always active in any screen that uses * it. Only non-printatble characters will get passed back out from * chatbox * * 44 1/14/98 6:44p Hoffoss * Massive changes to UI code. A lot cleaner and better now. Did all * this to get the new UI_DOT_SLIDER to work properly, which the old code * wasn't flexible enough to handle. * * 43 1/02/98 9:11p Lawrance * Add button_hot() function * * 42 12/22/97 5:08p Hoffoss * Changed inputbox class to be able to accept only certain keys, changed * pilot screens to utilize this feature. Added to assert with pilot file * saving. * * 41 12/11/97 8:15p Dave * Put in network options screen. Xed out olf protocol selection screen. * * 40 12/10/97 3:14p Dave * Added an overloaded set_mask_bmap(int) function for the UI_WINDOW * * 39 12/08/97 6:22p Lawrance * blink cursor on inputbox * * 38 12/06/97 4:27p Dave * Another load of interface and multiplayer bug fixes. * * 37 11/25/97 3:51p Hoffoss * Changed edit background rect position slightly. * * 36 11/19/97 8:32p Hoffoss * Changed UI buttons so they go back to unpressed when they are disabled. * * 35 10/29/97 7:25p Hoffoss * Added crude support for UI button double click checking. * * 34 10/24/97 10:58p Hoffoss * Made some changes to the UI code to do some things I need it to do. * * 33 10/01/97 4:40p Lawrance * allow process() to have key input * * 32 9/18/97 10:31p Lawrance * allow listbox to change text * * 31 9/09/97 4:32p Dave * Added sel_changed() function to UI_LISTBOX to check is the selection * has changed. * * 30 9/07/97 10:05p Lawrance * add icon class * * 29 8/30/97 12:23p Lawrance * add button function to reset the status of a button * * 28 8/29/97 7:33p Lawrance * move cleanup code from destructor to destroy() method * * 27 8/24/97 5:25p Lawrance * improve drawing of buttons * * 26 8/21/97 12:13p Dave * Made it possible for input box to ignore esc to lose focus. * * 25 8/19/97 1:27p Dave * Modified input box to allow character limitation by pixel width. * Changed list box so that you can create an empty box and add items as * you need to. * * 24 8/18/97 5:28p Lawrance * integrating sounds for when mouse goes over an active control * * 23 8/17/97 2:42p Lawrance * add code to have selected bitmap for buttons linger for a certain time * * 22 8/15/97 8:21p Dave * Modified UI_INPUTBOX so that it is possible to draw it invisibly. That * is, only the text is displayed. * * 21 8/14/97 5:23p Dave * Added clear_all_items() to the UI_LISTBOX * * 20 6/13/97 5:51p Lawrance * add in support for repeating buttons * * 19 6/11/97 1:32p Allender * externed sort_filelist * * 18 5/26/97 10:26a Lawrance * get slider control working 100% * * 17 5/22/97 5:36p Lawrance * allowing custom art for scrollbars * * 16 5/21/97 11:07a Lawrance * integrate masks and custom bitmaps * * 15 4/28/97 2:19p Lawrance * added clear_focus() function * * 14 4/22/97 10:11a John * Added checkbox lists to listboxes * * 13 4/15/97 3:47p Allender * moved type selection of list box items into actual UI code. Made it * behave more like windows listboxes do * * 12 1/28/97 4:58p Lawrance * allowing hidden UI components * * 11 12/23/96 2:42p Lawrance * allowing keys to select list box items in the mission load screen * * 10 12/04/96 3:00p John * Added code to allow adjusting of HUD colors and saved it to the player * config file. * * 9 12/03/96 3:46p Lawrance * added ability to set contents of input box * * 8 12/03/96 11:29a John * Made scroll buttons on listbox scroll once, then delay, then repeat * when the buttons are held down. * * 7 12/02/96 2:17p John * Made right button drag UI gadgets around and * Ctrl+Shift+Alt+F12 dumps out where they are. * * 6 12/01/96 3:48a Lawrance * added function set_current to UI_LISTBOX * * 5 11/29/96 6:08p Lawrance * enabled check-boxes to be set to a specific value outside of the * create() function * * 4 11/21/96 10:58a John * Started adding code to drag buttons. * * 3 11/18/96 4:28p Jasen * making class member process return an int * * 2 11/15/96 11:42a John * * 1 11/14/96 6:55p John * * $NoKeywords: $ */ #ifndef _UI_H #define _UI_H #include "graphics/2d.h" #define UI_KIND_BUTTON 1 #define UI_KIND_KEYTRAP 2 #define UI_KIND_CHECKBOX 3 #define UI_KIND_RADIO 4 #define UI_KIND_SCROLLBAR 5 #define UI_KIND_LISTBOX 6 #define UI_KIND_INPUTBOX 7 #define UI_KIND_SLIDER 8 #define UI_KIND_ICON 9 #define UI_KIND_DOT_SLIDER 10 #define UI_KIND_SLIDER2 11 #define UI_KIND_DOT_SLIDER_NEW 12 #define MAX_KEY_BUFFER 32 // for listboxes #define MAX_BMAPS_PER_GADGET 15 #define UI_INPUTBOX_FLAG_INVIS (1 << 0) // don't draw the input box boarders #define UI_INPUTBOX_FLAG_KEYTHRU (1 << 1) // pass all keypresses through to parent #define UI_INPUTBOX_FLAG_ESC_CLR (1 << 2) // allow escape key to clear input box #define UI_INPUTBOX_FLAG_ESC_FOC (1 << 3) // escape loses focus for the input box #define UI_INPUTBOX_FLAG_PASSWD (1 << 4) // display all characters as special "password" characters #define UI_INPUTBOX_FLAG_EAT_USED (1 << 5) // don't return any characters actually used by inputbox #define UI_INPUTBOX_FLAG_LETTER_FIRST (1 << 6) // require input string to begin with a letter. #define UI_INPUTBOX_FLAG_NO_LETTERS (1 << 7) // don't allow [a-z,A-Z] at all, no matter what #define UI_INPUTBOX_FLAG_NO_NUMERALS (1 << 8) // don't allow [0-9] at all, no matter what #define UI_INPUTBOX_FLAG_TEXT_CEN (1 << 9) // always draw text centered in the inputbox #define UI_INPUTBOX_FLAG_NO_BACK (1 << 10) // don't draw a black background rectangle #define UI_GF_MOUSE_CAPTURED (1 << 31) // gadget has all rights to the mouse class UI_WINDOW; class UI_BUTTON; class UI_KEYTRAP; class UI_CHECKBOX; class UI_RADIO; class UI_SCROLLBAR; class UI_LISTBOX; class UI_INPUTBOX; // class UI_SLIDER; class UI_DOT_SLIDER; class UI_DOT_SLIDER_NEW; class UI_GADGET { friend class UI_WINDOW; friend class UI_BUTTON; friend class UI_KEYTRAP; friend class UI_CHECKBOX; friend class UI_RADIO; friend class UI_SCROLLBAR; friend class UI_LISTBOX; friend class UI_INPUTBOX; // friend class UI_SLIDER; friend class UI_DOT_SLIDER; friend class UI_DOT_SLIDER_NEW; protected: char *bm_filename; int kind; int hotkey; int x, y, w, h; int m_flags; void (*user_function)(void); int disabled_flag; int base_dragging; int base_drag_x, base_drag_y; int base_start_x, base_start_y; int hidden; // Data for supporting linking controls to hotspots int linked_to_hotspot; int hotspot_num; // Data for supporting bitmaps associated with different states of the control int uses_bmaps; int m_num_frames; // ubyte *bmap_storage[MAX_BMAPS_PER_GADGET]; void drag_with_children( int dx, int dy ); void start_drag_with_children(); void stop_drag_with_children(); UI_GADGET *parent; UI_GADGET *children; UI_GADGET *prev; UI_GADGET *next; int is_mouse_on_children(); void remove_from_family(); void set_parent(UI_GADGET *_parent); UI_GADGET *get_next(); UI_GADGET *get_prev(); UI_WINDOW *my_wnd; virtual void process(int focus = 0); virtual void destroy(); int check_move(); public: int bmap_ids[MAX_BMAPS_PER_GADGET]; UI_GADGET(); // constructor ~UI_GADGET(); // destructor void base_create( UI_WINDOW *wnd, int kind, int x, int y, int w, int h ); virtual void draw(); void set_focus(); void clear_focus(); int has_focus(); void set_hotkey(int keycode); void set_callback(void (*user_function)(void)); void disable(); void enable(int n = 1); void capture_mouse(); int mouse_captured(UI_GADGET *gadget = NULL); int disabled(); int enabled(); virtual void hide(int n = 1); virtual void unhide(); void update_dimensions(int x, int y, int w, int h); void get_dimensions(int *x, int *y, int *w, int *h); int is_mouse_on(); void get_mouse_pos(int *x, int *y); void link_hotspot(int num); int get_hotspot(); int bmaps_used() { return uses_bmaps; } // loads nframes bitmaps, starting at index start_frame. // anything < start_frame will not be loaded. // this keeps the loading code from trying to load bitmaps which don't exist // and taking an unnecessary disk hit. int set_bmaps(char *ani_filename, int nframes = 3, int start_frame = 1); // extracts MAX_BMAPS_PER_GADGET from .ani file void reset(); // zero out m_flags int is_hidden() { return hidden; } }; // xstrings for a window #define UI_NUM_XSTR_COLORS 2 #define UI_XSTR_COLOR_GREEN 0 // shades of green/gray < its more of a white/blue now but i don't feel like changing everything #define UI_XSTR_COLOR_PINK 1 // pinkish hue typedef struct UI_XSTR { char *xstr; // base string int xstr_id; // xstring id int x, y; // coords of the string int clr; // color to use int font_id; // font id UI_GADGET *assoc; // the associated gadget } UI_XSTR; #define MAX_UI_XSTRS 100 // Button terminology: // Up = button is in up state (also called pressed) // Down = button is in down state (also called released) // Just pressed = button has just gone from up to down state // Just released = button has just gone from down to up state // Clicked = a trigger type effect caused by 'just pressed' event or repeat while 'down' // Double clicked = 2 'just pressed' events occuring within a short amount of time // Button flags #define BF_UP (1<<0) #define BF_DOWN (1<<1) #define BF_JUST_PRESSED (1<<2) #define BF_JUST_RELEASED (1<<3) #define BF_CLICKED (1<<4) #define BF_DOUBLE_CLICKED (1<<5) #define BF_HIGHLIGHTED (1<<6) // button is not highlighted (ie mouse is not over) #define BF_JUST_HIGHLIGHTED (1<<7) // button has just been highlighted, true for 1 frame #define BF_IGNORE_FOCUS (1<<8) // button should not use focus to accept space/enter keypresses #define BF_HOTKEY_JUST_PRESSED (1<<9) // button hotkey was just pressed #define BF_REPEATS (1<<10) // if held down, generates repeating presses #define BF_SKIP_FIRST_HIGHLIGHT_CALLBACK (1<<11) // skip first callback for mouse over event class UI_BUTTON : public UI_GADGET { friend class UI_SCROLLBAR; // friend class UI_SLIDER; friend class UI_DOT_SLIDER; friend class UI_DOT_SLIDER_NEW; char *text; int position; // indicates position of button (0 - up, 1 - down by mouse click 2 - down by keypress int next_repeat; // timestamp for next repeat if held down int m_press_linger; // timestamp for hold a pressed state animation int hotkey_if_focus; // hotkey for button that only works if it has focus int force_draw_frame; // frame number to draw next time (override default) int first_callback; // true until first time callback function is called for button highlight // Used to index into bmap_ids[] array to locate right bitmap for button enum { B_NORMAL = 0 }; enum { B_HIGHLIGHT = 1 }; enum { B_PRESSED = 2 }; enum { B_DISABLED = 3 }; enum { B_REPEAT_TIME = 100 }; // ms void (*m_just_highlighted_function)(void); // call-back that gets called when button gets highlighted void (*m_disabled_function)(void); // callback that gets called when disabled button gets pressed (sound, popup, etc) void frame_reset(); virtual void process(int focus = 0); virtual void destroy(); int custom_cursor_bmap; // bmap handle of special cursor used on mouseovers int previous_cursor_bmap; // store old cursor void maybe_show_custom_cursor(); // call this in process() void restore_previous_cursor(); // called in frame_reset() public: virtual void draw(); void set_hotkey_if_focus(int key); int pressed(); // has it been selected (ie clicked on) int double_clicked(); // button was double clicked on int just_pressed(); // button has just been selected int just_highlighted(); // button has just had mouse go over it int button_down(); // is the button depressed? int button_hilighted(); // is the mouse over this button? void set_button_hilighted(); // force button to be highlighted void press_button(); // force button to get pressed void create(UI_WINDOW *wnd, char *_text, int _x, int _y, int _w, int _h, int do_repeat=0, int ignore_focus = 0); void set_highlight_action( void (*user_function)(void) ); void set_disabled_action( void (*user_function)(void) ); void draw_forced(int frame_num); void reset_status(); void reset_timestamps(); void skip_first_highlight_callback(); void repeatable(int yes); void set_custom_cursor_bmap(int bmap_id) { custom_cursor_bmap = bmap_id; }; }; class UI_KEYTRAP : public UI_GADGET { int pressed_down; virtual void draw(); virtual void process(int focus = 0); public: int pressed(); void create(UI_WINDOW *wnd, int hotkey, void (*user_function)(void) ); }; class UI_USERBOX : public UI_GADGET { int b1_held_down; int b1_clicked; int b1_double_clicked; int b1_dragging; int b1_drag_x1, b1_drag_y1; int b1_drag_x2, b1_drag_y2; int b1_done_dragging; int keypress; int mouse_onme; int mouse_x, mouse_y; int bitmap_number; }; class UI_INPUTBOX : public UI_GADGET { char *text; char *passwd_text; int length; int position; int oldposition; int pressed_down; int changed_flag; int flags; int pixel_limit; // base max characters on how wide the string is (-1 to ignore) in pixels int locked; // int should_reset; int ignore_escape; color *text_color; char *valid_chars; char *invalid_chars; // cursor drawing int cursor_first_frame; int cursor_nframes; int cursor_fps; int cursor_current_frame; int cursor_elapsed_time; int validate_input(int chr); void init_cursor(); virtual void draw(); virtual void process(int focus = 0); virtual void destroy(); public: // int first_time; void create(UI_WINDOW *wnd, int _x, int _y, int _w, int _textlen, char *text, int _flags = 0, int pixel_lim = -1, color *clr = NULL); void set_valid_chars(char *vchars); void set_invalid_chars(char *ichars); int changed(); int pressed(); void get_text(char *out); void set_text(char *in); }; // Icon flags #define ICON_NOT_HIGHLIGHTED (1<<0) // icon is not highlighted (ie mouse is not over) #define ICON_JUST_HIGHLIGHTED (1<<1) // icon has just been highlighted, true for 1 frame class UI_ICON : public UI_GADGET { char *text; // Used to index into bmap_ids[] array to locate right bitmap for button enum { ICON_NORMAL = 0 }; enum { ICON_HIGHLIGHT = 1 }; enum { ICON_SELECTED = 2 }; enum { ICON_DISABLED = 3 }; virtual void draw(); virtual void process(int focus = 0); virtual void destroy(); public: void create(UI_WINDOW *wnd, char *_text, int _x, int _y, int _w, int _h); }; class UI_CHECKBOX : public UI_GADGET { char *text; int position; int pressed_down; int flag; virtual void draw(); virtual void process(int focus = 0); virtual void destroy(); // Used to index into bmap_ids[] array to locate right bitmap for checkbox enum { CBOX_UP_CLEAR = 0 }; enum { CBOX_DOWN_CLEAR = 1 }; enum { CBOX_UP_MARKED = 2 }; enum { CBOX_DOWN_MARKED = 3 }; enum { CBOX_DISABLED_CLEAR = 4 }; enum { CBOX_DISABLED_MARKED = 5 }; public: int changed(); int checked(); void create(UI_WINDOW *wnd, char *_text, int _x, int _y, int _state ); void set_state(int _state); }; class UI_RADIO : public UI_GADGET { char *text; int position; int pressed_down; int flag; int group; virtual void draw(); virtual void process(int focus = 0); virtual void destroy(); // Used to index into bmap_ids[] array to locate right bitmap for radio button enum { RADIO_UP_CLEAR = 0 }; enum { RADIO_DOWN_CLEAR = 1 }; enum { RADIO_UP_MARKED = 2 }; enum { RADIO_DOWN_MARKED = 3 }; enum { RADIO_DISABLED_CLEAR = 4 }; enum { RADIO_DISABLED_MARKED = 5 }; public: int changed(); int checked(); void create(UI_WINDOW *wnd, char *_text, int _x, int _y, int _state, int _group ); }; class UI_SCROLLBAR : public UI_GADGET { friend class UI_LISTBOX; friend class UI_BUTTON; int horz; int start; int stop; int position; int window_size; int bar_length; int bar_position; int bar_size; UI_BUTTON up_button; UI_BUTTON down_button; int last_scrolled; int drag_x, drag_y; int drag_starting; int dragging; int moved; virtual void draw(); virtual void process(int focus = 0); // Used to index into bmap_ids[] array to locate right bitmap for scrollbar enum { SB_NORMAL = 0 }; enum { SB_DISABLED = 1 }; public: void create(UI_WINDOW *wnd, int _x, int _y, int _h,int _start, int _stop, int _position, int _window_size ); int getpos(); int changed(); void hide(); void unhide(); int get_hidden(); void link_hotspot(int up_button_num, int down_button_num); int set_bmaps(char *up_button_fname, char *down_button_fname, char *line_fname); }; class UI_SLIDER2 : public UI_GADGET { friend class UI_BUTTON; private: int numberItems; // total range int numberPositions; // total positions (height - bitmapbuttonheight) int currentItem; // current item we are on int currentPosition; // current position int last_scrolled; int mouse_locked; int slider_mode; // UI_BUTTON sliderBackground;// invisible button to detect clicks int bitmapSliderControl; // this is the bitmap of the slider button itself void (*upCallback)(); void (*downCallback)(); void (*captureCallback)(); // this is called when the mouse is released UI_BUTTON *upButton, *downButton; int slider_w, slider_h, slider_half_h; // this is the width and height and half height of the bitmap used for the slider virtual void draw(); virtual void process(int focus = 0); // Used to index into bmap_ids[] array to locate right bitmap for slider enum { S2_NORMAL = 0 }; enum { S2_HIGHLIGHT = 1 }; enum { S2_PRESSED = 2 }; enum { S2_DISABLED = 3 }; // Used for slider mode enum { S2M_ON_ME = 0 }; enum { S2M_MOVING = 1 }; enum { S2M_DEFAULT = 2 }; public: // create the slider void create(UI_WINDOW *wnd, int _x, int _y, int _w, int _h, int _numberItems, char *_bitmapSliderControl, void (*_upCallback)(), void (*_downCallback)(), void (*_captureCallback)()); // range management int get_numberItems(); // return number of itmes int get_currentPosition(); // return current position int get_currentItem(); // return current item void set_numberItems(int _numberItems, int reset = 1); // change range. maybe reset back to position 0 void set_currentItem(int _currentItem); // force slider to new position manually void force_currentItem(int _currentItem); // force slider to new position manually, _not_ calling any callbacks // force down void forceDown(); // force up void forceUp(); // general ui commands void hide(); void unhide(); int get_hidden(); }; // to be phased out eventually in FS2 class UI_DOT_SLIDER : public UI_GADGET { friend class UI_BUTTON; UI_BUTTON button; UI_BUTTON up_button; UI_BUTTON down_button; int first_frame, total_frames; int has_end_buttons; int num_pos; public: int pos; // 0 thru 10 void create(UI_WINDOW *wnd, int _x, int _y, char *bm, int id, int end_buttons = 1, int num_pos = 10); virtual void draw(); virtual void process(int focus = 0); virtual void destroy(); }; class UI_DOT_SLIDER_NEW : public UI_GADGET { friend class UI_BUTTON; UI_BUTTON button; UI_BUTTON up_button; UI_BUTTON down_button; int has_end_buttons; int num_pos; int dot_width; public: int pos; // 0 thru 10 void create(UI_WINDOW *wnd, int _x, int _y, int num_pos, char *bm_slider, int slider_mask, char *bm_left = NULL, int left_mask = -1, int left_x = -1, int left_y = -1, char *bm_right = NULL, int right_mask = -1, int right_x = -1, int right_y = -1, int dot_width = 19); virtual void draw(); virtual void process(int focus = 0); }; class UI_LISTBOX : public UI_GADGET { private: char **list; char *check_list; int max_items; int num_items; int num_items_displayed; int first_item; int old_first_item; int current_item; int selected_item; int toggled_item; int old_current_item; int last_scrolled; int dragging; int textheight; int has_scrollbar; char key_buffer[MAX_KEY_BUFFER]; int key_buffer_count; int last_typed; UI_SCROLLBAR scrollbar; // kazan int draw_frame; virtual void draw(); virtual void process(int focus = 0); // Used to index into bmap_ids[] array to locate right bitmap for listbox enum { LBOX_NORMAL = 0 }; enum { LBOX_DISABLED = 1 }; public: void create(UI_WINDOW *wnd, int _x, int _y, int _w, int _h, int _numitem, char **_list, char *_check_list = NULL, int _max_items = -1); int selected(); // selected: Returns >= 0 if an item was selected int current(); // current: Returns which item listbox bar is currently on. This could be -1, if none selected! int toggled(); // toggled: Returns which item was toggled with spacebr or mouse click of check_list is not NULL void set_current(int _index); // sets the current item in the list box void set_first_item(int _index); char *get_string(int _index); void clear_all_items(); // deletes all the items in the list (makes them empty strings) int add_string(char *str); int sel_changed(); // returns > 0 if the selected item has changed void set_new_list(int _numitems, char **_list); // kazan void set_drawframe(int mode); int CurSize(); int MaxSize(); void RemoveFirstItem(); void ScrollEnd(); int set_bmaps(char *lbox_fname, char *b_up_fname, char *b_down_fname, char *sb_fname); void link_hotspot(int up_button_num, int down_button_num); }; #define WIN_BORDER 1 #define WIN_FILLED 2 #define WIN_SAVE_BG 4 #define WIN_DIALOG (4+2+1) class UI_WINDOW { friend class UI_GADGET; friend class UI_BUTTON; friend class UI_KEYTRAP; friend class UI_CHECKBOX; friend class UI_RADIO; friend class UI_SCROLLBAR; friend class UI_LISTBOX; friend class UI_INPUTBOX; // friend class UI_SLIDER; friend class UI_SLIDER2; friend class UI_DOT_SLIDER; friend class UI_DOT_SLIDER_NEW; friend class UI_ICON; protected: int flags; int x, y; int w, h; int f_id; // font id int last_tooltip_hotspot; uint last_tooltip_time; int tt_group; // which tooltip group this window uses, or -1 if none int ignore_gadgets; UI_GADGET *first_gadget; UI_GADGET *selected_gadget; UI_GADGET *mouse_captured_gadget; int mask_bmap_id; // bitmap id of the mask bitmap to define hotspots int foreground_bmap_id; // bitmap id of the foreground bitmap to display bitmap *mask_bmap_ptr; // pointer to bitmap of the mask ushort *mask_data; // points to raw mask bitmap data int mask_w, mask_h; // width and height of the mask UI_XSTR *xstrs[MAX_UI_XSTRS]; // strings for drawing in code instead of in artwork int keypress; // filled in each frame void capture_mouse(UI_GADGET *gadget = NULL); void release_bitmaps(); // called internally when window destroys gadgets void check_focus_switch_keys(); void do_dump_check(); void draw_xstrs(); // draw xstrs void draw_one_xstr(UI_XSTR *xstr, int frame); public: UI_WINDOW(); // constructor ~UI_WINDOW(); // destructor void set_mask_bmap(char *fname); void set_mask_bmap(int bmap, char *name); void set_foreground_bmap(char *fname); void create( int x, int y, int w, int h, int flags ); int process( int key_in = -1,int process_mouse = 1); void draw(); void draw_tooltip(); void draw_XSTR_forced(UI_GADGET *owner, int frame); int get_current_hotspot(); void destroy(); ushort *get_mask_data(int *w, int *h) { *w = mask_w; *h = mask_h; return mask_data; } void render_tooltip(char *str); void set_ignore_gadgets(int state); void add_XSTR(char *string, int xstr_id, int x, int y, UI_GADGET *assoc, int color_type, int font_id = -1); void add_XSTR(UI_XSTR *xstr); char *(*tooltip_handler)(char *text); int last_keypress; // filled in each frame int ttx, tty; int use_hack_to_get_around_stupid_problem_flag; }; // 2 extremely useful structs typedef struct ui_button_info { char *filename; int x, y, xt, yt; int hotspot; UI_BUTTON button; // because we have a class inside this struct, we need the constructor below.. ui_button_info(char *name, int x1, int y1, int xt1, int yt1, int h) : filename(name), x(x1), y(y1), xt(xt1), yt(yt1), hotspot(h) {} } ui_button_info; /* typedef struct { char *mask; int start; int end; } tooltip_group; typedef struct { int hotspot; char *text; } tooltip; #define MAX_TOOLTIP_GROUPS 50 #define MAX_TOOLTIPS 500 extern int Num_tooltip_groups; extern tooltip_group Tooltip_groups[MAX_TOOLTIP_GROUPS]; extern tooltip Tooltips[MAX_TOOLTIPS]; */ int ui_getfilelist( int MaxNum, char **list, char *filespec ); void ui_sort_filenames( int n, char **list ); /* class UI_SLIDER : public UI_GADGET { friend class UI_BUTTON; int horz; int position; int window_size; int fake_length; int fake_position; int fake_size; UI_BUTTON left_button; UI_BUTTON right_button; int last_scrolled; int drag_x, drag_y; int drag_starting; int dragging; int moved; int marker_x, marker_y, marker_w, marker_h; int n_positions, pixel_range, increment; float start, stop, current; int mouse_locked; virtual void draw(); virtual void process(int focus = 0); // Used to index into bmap_ids[] array to locate right bitmap for slider enum { SLIDER_BAR_NORMAL = 0 }; enum { SLIDER_BAR_DISABLED = 1 }; enum { SLIDER_MARKER_NORMAL = 2 }; enum { SLIDER_MARKER_DISABLED = 3 }; public: void create(UI_WINDOW *wnd, int _x, int _y, int _w, int _h, float _start, float _stop, float _pos, int n_positions); int getpos(); float getcurrent(); int changed(); void hide(); void unhide(); int get_hidden(); void link_hotspot(int up_button_num, int down_button_num); int set_bmaps(char *left_button_fname, char *right_button_fname, char *bar_fname, char *marker_fname); }; */ #endif
[ [ [ 1, 1077 ] ] ]
c1e3189ddf420ec92318ca8d7d2c18ae5f64d840
28a5dacf5e1a5a2d0d3fdf89bdc12a88dd897f86
/ConfigDlg.cpp
9907d6454c53e16264f651b897854fa4e09c51f0
[]
no_license
yogengg6/fp_attendance
3f4cababbe33d03e519341a6312015e5cb365a63
574338e53717ff2fbc62c57f14fa749a3a84a53a
refs/heads/master
2020-04-07T20:02:06.843808
2011-07-20T13:09:12
2011-07-20T13:09:12
158,672,408
0
0
null
null
null
null
GB18030
C++
false
false
1,403
cpp
// Dbconfig.cpp : 实现文件 // #include "stdafx.h" #include "FP_Attendance.h" #include "ConfigDlg.h" #include "ultility.h" // CConfigDlg 对话框 IMPLEMENT_DYNAMIC(CConfigDlg, CDialog) CConfigDlg::CConfigDlg(Config& cfg, CWnd* pParent /*=NULL*/) : CDialog(CConfigDlg::IDD, pParent), m_cfg(cfg) { } CConfigDlg::~CConfigDlg() { } void CConfigDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BOOL CConfigDlg::OnInitDialog() { CDialog::OnInitDialog(); SetDlgItemText(IDC_DBHOST, stringToCString(m_cfg.m_dbhost)); SetDlgItemText(IDC_DBPORT, stringToCString(m_cfg.m_dbport)); SetDlgItemText(IDC_DBUSER, stringToCString(m_cfg.m_dbuser)); SetDlgItemText(IDC_DBPASSWD, stringToCString(m_cfg.m_dbpasswd)); return TRUE; } BEGIN_MESSAGE_MAP(CConfigDlg, CDialog) ON_BN_CLICKED(IDOK, &CConfigDlg::OnBnClickedOk) END_MESSAGE_MAP() // CConfigDlg 消息处理程序 void CConfigDlg::OnBnClickedOk() { CString dbHost, dbPort, dbUser, dbPasswd; GetDlgItemText(IDC_DBHOST, dbHost); GetDlgItemText(IDC_DBPORT, dbPort); GetDlgItemText(IDC_DBUSER, dbUser); GetDlgItemText(IDC_DBPASSWD, dbPasswd); m_cfg.m_dbhost = CStringToString(dbHost); m_cfg.m_dbport = CStringToString(dbPort); m_cfg.m_dbuser = CStringToString(dbUser); m_cfg.m_dbpasswd = CStringToString(dbPasswd); m_cfg.save(); OnOK(); }
[ "yusuke2000@e4a03d97-ca6b-4887-8e5f-4c51e936fd37" ]
[ [ [ 1, 64 ] ] ]
09b4886a9c3c9805a1173eda8e2c99daa2ef4181
acf1b4792425a2ff0565451a044f00029ccf794d
/src/token_datatype.h
5107553df348f9630cca9543b4de945387e70e47
[]
no_license
davgit/ahk2exe-1
d36330e101dbf0f631ebcbb925635ab0631c3619
93e6af3188cff3444dc5be6ad37dd032dd3665d1
refs/heads/master
2016-09-10T22:43:59.400053
2010-07-08T07:34:46
2010-07-08T07:34:46
22,427,624
1
0
null
null
null
null
UTF-8
C++
false
false
2,378
h
#ifndef __TOKEN_H #define __TOKEN_H /////////////////////////////////////////////////////////////////////////////// // // AutoIt // // Copyright (C)1999-2003: // - Jonathan Bennett <[email protected]> // - See "AUTHORS.txt" for contributors. // // 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. // /////////////////////////////////////////////////////////////////////////////// // // token_datatype.h // // The class for a token datatype (requires variant_datatype). // Functions are called via operator overloading! // /////////////////////////////////////////////////////////////////////////////// // Includes #include "variant_datatype.h" // Token types #define TOK_KEYWORD 0 // If, else... #define TOK_FUNCTION 1 // chr, user, send, winwait... #define TOK_VARIANT 2 // 10.0, 10, string ("string") #define TOK_ASSIGNMENT 3 // = #define TOK_EQUAL TOK_ASSIGNMENT // = #define TOK_GREATER 4 // > #define TOK_LESS 5 // < #define TOK_NOTEQUAL 6 // <> #define TOK_GREATEREQUAL 7 // >= #define TOK_LESSEQUAL 8 // <= #define TOK_LEFTPAREN 9 // ( #define TOK_RIGHTPAREN 10 // ) #define TOK_PLUS 11 // + #define TOK_MINUS 12 // - #define TOK_DIV 13 // / #define TOK_MULT 14 // * #define TOK_VARIABLE 15 // var ($var) #define TOK_END 16 // End of tokens #define TOK_USERFUNCTION 17 // User defined function #define TOK_COMMA 18 // , #define TOK_CONCAT 19 // & #define TOK_LEFTSUBSCRIPT 20 // [ #define TOK_RIGHTSUBSCRIPT 21 // ] #define TOK_MACRO 22 // predefined var (@var) #define TOK_EQUALCASE 23 // == class Token { public: // Functions Token(); // Constructor Token(const Token &vOp2); // Copy constructor ~Token(); // Destructor Token& operator=(const Token &vOp2); // Overloaded = for tokens // Variables int m_nType; // Token type Variant m_Variant; // Variant int m_nCol; // Column number this token came from }; /////////////////////////////////////////////////////////////////////////////// #endif
[ [ [ 1, 77 ] ] ]
248e0b61745f62957a79960c5307898af916f8d5
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Physics/Collide/Shape/Convex/Box/hkpBoxShape.h
ceb8670298ced41c8d3adf92d0d4f5669273913c
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
4,606
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_COLLIDE2_BOX_SHAPE_H #define HK_COLLIDE2_BOX_SHAPE_H #include <Physics/Collide/Shape/Convex/hkpConvexShape.h> extern const hkClass hkpBoxShapeClass; /// A simple box shape centered around the origin. class hkpBoxShape : public hkpConvexShape { public: HK_DECLARE_REFLECTION(); HK_DECLARE_GET_SIZE_FOR_SPU(hkpBoxShape); /// Creates a box with the given half extents ( An (X by Y by Z) box has the half-extents (X/2, Y/2, Z/2) ). hkpBoxShape( const hkVector4& halfExtents, hkReal radius = hkConvexShapeDefaultRadius ); /// Gets the half extents ( An (X by Y by Z) box has the half-extent (X/2, Y/2, Z/2) ). inline const hkVector4& getHalfExtents() const; /// Sets the half extents. Note that changing the half extents will not wake up sleeping objects. void setHalfExtents(const hkVector4& halfExtents); // // hkpConvexShape implementation // // hkpConvexShape::getSupportingVertex() interface implementation. HKP_SHAPE_VIRTUAL void getSupportingVertexImpl( HKP_SHAPE_VIRTUAL_THIS hkVector4Parameter direction, hkpCdVertex& supportingVertexOut ) HKP_SHAPE_VIRTUAL_CONST; // hkpConvexShape interface implementation. HKP_SHAPE_VIRTUAL void convertVertexIdsToVerticesImpl( HKP_SHAPE_VIRTUAL_THIS const hkpVertexId* ids, int numIds, hkpCdVertex* verticesOut) HKP_SHAPE_VIRTUAL_CONST; // hkpConvexShape interface implementation. HKP_SHAPE_VIRTUAL void getCentreImpl( HKP_SHAPE_VIRTUAL_THIS hkVector4& centreOut ) HKP_SHAPE_VIRTUAL_CONST; // // hkpSphereRepShape implementation // // hkpSphereRepShape interface implementation. HKP_SHAPE_VIRTUAL int getNumCollisionSpheresImpl( HKP_SHAPE_VIRTUAL_THIS2 ) HKP_SHAPE_VIRTUAL_CONST; // hkpSphereRepShape interface implementation. HKP_SHAPE_VIRTUAL const hkSphere* getCollisionSpheresImpl( HKP_SHAPE_VIRTUAL_THIS hkSphere* sphereBuffer ) HKP_SHAPE_VIRTUAL_CONST; // // hkpShape implementation // // hkpShape interface implementation. HKP_SHAPE_VIRTUAL void getAabbImpl( HKP_SHAPE_VIRTUAL_THIS const hkTransform& localToWorld, hkReal tolerance, hkAabb& out ) HKP_SHAPE_VIRTUAL_CONST; // hkpShape interface implementation. HKP_SHAPE_VIRTUAL hkBool castRayImpl( HKP_SHAPE_VIRTUAL_THIS const hkpShapeRayCastInput& input, hkpShapeRayCastOutput& results) HKP_SHAPE_VIRTUAL_CONST; // hkpConvexShape interface implementation. virtual void getFirstVertex(hkVector4& v) const; /// Returns a struct of function pointers needed by the SPU static void HK_CALL registerSimulationFunctions( ShapeFuncs& sf ); /// Returns a struct of function pointers needed by the SPU static void HK_CALL HK_INIT_FUNCTION( registerCollideQueryFunctions )( ShapeFuncs& sf ); /// Returns a struct of function pointers needed by the SPU static void HK_CALL registerRayCastFunctions( ShapeFuncs& sf ); /// Returns a struct of function pointers needed by the SPU static void HK_CALL registerGetAabbFunction( ShapeFuncs& sf ); virtual void calcContentStatistics( hkStatisticsCollector* collector, const hkClass* cls) const; protected: hkVector4 m_halfExtents; public: ~hkpBoxShape(); hkpBoxShape( hkFinishLoadedObjectFlag flag ) : hkpConvexShape(flag) { m_type = HK_SHAPE_BOX; } }; #include <Physics/Collide/Shape/Convex/Box/hkpBoxShape.inl> #endif // HK_COLLIDE2_BOX_SHAPE_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. * */
[ [ [ 1, 120 ] ] ]
6e9bf783176556b7c60e3c02444e7ac37152c4d2
335783c9e5837a1b626073d1288b492f9f6b057f
/source/fbxcmd/daolib/Model/MESH/DECL.h
80b6284e8e6d57edf900e49608755af0fae62964
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
code-google-com/fbx4eclipse
110766ee9760029d5017536847e9f3dc09e6ebd2
cc494db4261d7d636f8c4d0313db3953b781e295
refs/heads/master
2016-09-08T01:55:57.195874
2009-12-03T20:35:48
2009-12-03T20:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,843
h
/********************************************************************** *< FILE: DECL.h DESCRIPTION: MESH File Format HISTORY: *> Copyright (c) 2009, All Rights Reserved. **********************************************************************/ #pragma once #include "MESH/MESHCommon.h" #include "GFF/GFFField.h" #include "GFF/GFFList.h" #include "GFF/GFFStruct.h" #include "../DataHeader.h" namespace DAO { using namespace GFF; namespace MESH { /////////////////////////////////////////////////////////////////// enum DECLTYPE : unsigned long { /// 1 float DECLTYPE_FLOAT1 = 0, /// 2 floats DECLTYPE_FLOAT2 = 1, /// 3 floats DECLTYPE_FLOAT3 = 2, /// 4 floats DECLTYPE_FLOAT4 = 3, /// 4-byte color DECLTYPE_COLOR = 4, /// 4 unsigned bytes DECLTYPE_UBYTE4 = 5, /// 2 shorts DECLTYPE_SHORT2 = 6, /// 4 shorts DECLTYPE_SHORT4 = 7, /// 4 normalized bytes DECLTYPE_UBYTE4N = 8, /// 2 normalized shorts DECLTYPE_SHORT2N = 9, /// 4 normalized shorts DECLTYPE_SHORT4N = 10, /// 2 normalized unsigned shorts DECLTYPE_USHORT2N = 11, /// 4 normalized unsigned shorts DECLTYPE_USHORT4N = 12, /// 3d unsigned 10/10/10 format DECLTYPE_UDEC3 = 13, /// 3d unsigned 10/10/10 normalized DECLTYPE_DEC3N = 14, /// 2 16-bit floats DECLTYPE_FLOAT16_2 = 15, /// 4 16-bit unsigned floats DECLTYPE_FLOAT16_4 = 16, DECLTYPE_UNUSED = 0xffffffff }; enum DECLUSAGE { /// Position DECLUSAGE_POSITION = 0, /// Blend weights DECLUSAGE_BLENDWEIGHT = 1, /// Blend indices DECLUSAGE_BLENDINDICES = 2, /// Normal DECLUSAGE_NORMAL = 3, /// Point Size DECLUSAGE_PSIZE = 4, /// Texture coordinates DECLUSAGE_TEXCOORD = 5, /// Tangent vector DECLUSAGE_TANGENT = 6, /// binormal vector DECLUSAGE_BINORMAL = 7, /// tessellation factor DECLUSAGE_TESSFACTOR = 8, /// PositionT DECLUSAGE_POSITIONT = 9, /// color channel DECLUSAGE_COLOR = 10, /// fog value DECLUSAGE_FOG = 11, /// depth DECLUSAGE_DEPTH = 12, /// sample DECLUSAGE_SAMPLE = 13, // error/other/unset DECLUSAGE_UNUSED = 0xffffffff }; class DECL { protected: GFFStructRef impl; static ShortString type; public: DECL(GFFStructRef owner); static const ShortString& Type() { return type; } const ShortString& get_type() const { return type; } long get_Stream() const; void set_Stream(long value); long get_Offset() const; void set_Offset(long value); DECLTYPE get_dataType() const; void set_dataType(DECLTYPE value); DECLUSAGE get_usage() const; void set_usage(DECLUSAGE value); unsigned long get_usageIndex() const; void set_usageIndex(unsigned long value); unsigned long get_Method() const; void set_Method(unsigned long value); }; typedef ValuePtr<DECL> DECLPtr; typedef ValueRef<DECL> DECLRef; class DECLValue { DECLTYPE type; LPVOID data; public: DECLValue(); DECLValue(DECLTYPE type, LPVOID data); DECLValue(const DECLValue& rhs); DECLTYPE get_type() const; bool isEmpty() const; float asFloat() const; Vector2f asVector2f() const; Vector3f asVector3f() const; Vector4f asVector4f() const; ARGB4 asColor() const; UByte4 asUByte4() const; Short2 asShort2() const; Short4 asShort4() const; UShort2 asUShort2() const; UShort4 asUShort4() const; Signed_10_10_10 asS101010() const; Unsigned_10_10_10 asU101010() const; Float16_2 asFloat16_2() const; Float16_4 asFloat16_4() const; }; } //namespace MESH } //namespace DAO template<> void ::Dump(IDAODumpStream& out, LPCTSTR name, DAO::MESH::DECLTYPE const & val); Text EnumToText(DAO::MESH::DECLTYPE const & val); template<> void ::Dump(IDAODumpStream& out, LPCTSTR name, DAO::MESH::DECLUSAGE const & val); Text EnumToText(DAO::MESH::DECLUSAGE const & val);
[ "tazpn314@ccf8930c-dfc1-11de-9043-17b7bd24f792" ]
[ [ [ 1, 171 ] ] ]
6d70c14e4a205735e0957e590e11791ea0e854a5
b26957d6f3a64b19cda1d76b265d93047c114891
/ImageProcessor.cpp
b51f857ae66c51cd34b1cf2b64ae708e49036a4f
[]
no_license
SachinTS/khoa-luan-tot-nghiep
58e7efbd51d5f807f08b62a641672b4fc62f7990
7200721aded827731232c49aeade804febfba086
refs/heads/master
2016-09-06T13:46:12.228528
2010-08-07T06:47:45
2010-08-07T06:47:45
33,529,631
0
0
null
null
null
null
UTF-8
C++
false
false
1,110
cpp
#include "ImageProcessor.h" ImageProcessor::ImageProcessor(void) { } ImageProcessor::~ImageProcessor(void) { } IplImage* ImageProcessor::getSubImageAndResize(IplImage* img,CvRect rect,int new_width,int new_height){ if((rect.x >= 0) && (rect.y >= 0) && (rect.x + rect.width <= img->width) && (rect.y + rect.height <= img->height)) { IplImage* subimg = cvCreateImage(cvSize(rect.width,rect.height),img->depth,img->nChannels); int nchannels = img->nChannels; for(int i = 0; i < rect.height; i++) { uchar* ptr1Tmp = (uchar*)img->imageData + (i+rect.y)*img->widthStep; uchar* ptr2Tmp = (uchar*)subimg->imageData + i*subimg->widthStep; for(int j = 0; j < rect.width; j++){ uchar* ptr1 = ptr1Tmp + (j + rect.x)*nchannels; uchar* ptr2 = ptr2Tmp + j*nchannels; for(int t = 0; t < nchannels; t++){ ptr2[t] = ptr1[t]; } } } IplImage* imageScale = cvCreateImage(cvSize(new_width,new_height),img->depth, nchannels); cvResize(subimg,imageScale); cvReleaseImage(&subimg); return imageScale; }else return NULL; }
[ "tuonghuy09@b0713345-de22-efb3-841d-461946120171" ]
[ [ [ 1, 43 ] ] ]
85aacf85abb54878619c8e92b6da5f22cfeada76
9921e3c9d530e5368becdc89ab81ec3d1459607b
/expressionoperators.h
96cc49ceee63c97560e8fb64bf312a18534a516c
[]
no_license
kimgr/etassert
c81b471d513d1cfd77257f3cf75b692d985b29e4
ca8801b00346d7d61bb42c62b0761106d129ab96
refs/heads/master
2021-01-19T00:12:46.634545
2010-01-14T21:39:51
2010-01-14T21:39:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
712
h
#ifndef INCLUDED_EXPRESSIONOPERATORS_H #define INCLUDED_EXPRESSIONOPERATORS_H #include "notexpression.h" #include "andexpression.h" #include "orexpression.h" template<typename T> struct ExpressionOperators { NotExpression<T> operator!() const { return NotExpression<T>(static_cast<const T&>(*this)); } template< typename Right > AndExpression<T, Right> operator&&(const Right& right) const { return AndExpression<T, Right>(static_cast<const T&>(*this), right); } template< typename Right > OrExpression<T, Right> operator||(const Right& right) const { return OrExpression<T, Right>(static_cast<const T&>(*this), right); } }; #endif INCLUDED_EXPRESSIONOPERATORS_H
[ [ [ 1, 29 ] ] ]
cd6761aedc4ea65363cebdb5505ef262e27a4b73
a4756c3232fd88a74df199acc84ab70ec48d7875
/FileManagerServer/common/parameter.h
8e716589a5ad8bae76000cc1ccf4698f7c6a7d14
[]
no_license
raygray/filemanagermlf
a7a0cdd14cd558657116b6ae641bcb743084ba37
0648183e9c88d6e883861f1f1dcbe67550e5c11f
refs/heads/master
2021-01-10T05:03:12.702335
2010-07-14T13:31:02
2010-07-14T13:31:02
49,008,746
0
0
null
null
null
null
UTF-8
C++
false
false
364
h
#ifndef PARAMETER_H #define PARAMETER_H #include <QString> #include <QStringList> #include <QMap> class Parameter { public: Parameter(); Parameter(QMap<QString, QString> paraMap); ~Parameter(); public: QString getValueOf(const QString key) const; private: QMap<QString, QString> m_paraMap; }; #endif // PARAMETER_H
[ "malongfei88@0a542be3-54de-31ef-7baa-42960c810bab" ]
[ [ [ 1, 23 ] ] ]
91256359a3c5cdcb38196fe47572a8317d4744c5
f6529b63d418f7d0563d33e817c4c3f6ec6c618d
/source/cheats/gct.h
c30b78b4a474068c4cc2de0a8c77be62d1569e92
[]
no_license
Captnoord/Wodeflow
b087659303bc4e6d7360714357167701a2f1e8da
5c8d6cf837aee74dc4265e3ea971a335ba41a47c
refs/heads/master
2020-12-24T14:45:43.854896
2011-07-25T14:15:53
2011-07-25T14:15:53
2,096,630
1
3
null
null
null
null
UTF-8
C++
false
false
2,590
h
/* * gct.h * Class to handle Ocarina TXT Cheatfiles * */ #ifndef _GCT_H #define _GCT_H #include <sstream> #define MAXCHEATS 100 using namespace std; //!Handles Ocarina TXT Cheatfiles class GCTCheats { private: string sGameID; string sGameTitle; string sCheatName[MAXCHEATS]; string sCheats[MAXCHEATS]; string sCheatComment[MAXCHEATS]; unsigned int iCntCheats; public: //!Array which shows which cheat is selected bool sCheatSelected[MAXCHEATS]; //!Constructor GCTCheats(void); //!Destructor ~GCTCheats(void); //!Open txt file with cheats //!\param filename name of TXT file //!\return error code int openTxtfile(const char * filename); //!Creates GCT file for one cheat //!\param nr selected Cheat Numbers //!\param filename name of GCT file //!\return error code int createGCT(unsigned int nr,const char * filename); //!Creates GCT file from a buffer //!\param chtbuffer buffer that holds the cheat data //!\param filename name of GCT file //!\return error code int createGCT(const char * chtbuffer,const char * filename); //!Creates GCT file //!\param nr[] array of selected Cheat Numbers //!\param cnt size of array //!\param filename name of GCT file //!\return error code int createGCT(int nr[],int cnt,const char * filename); //!Creates GCT file //!\param filename name of GCT file //!\return error code int createGCT(const char * filename); //!Creates directly gct in memory //!\param filename name of TXT file //!\return GCT buffer string createGCTbuff(int nr[],int cnt); //!Creates TXT file //!\param filename name of GCT file //!\return error code int createTXT(const char * filename); //!Gets Count cheats //!\return Count cheats unsigned int getCnt(); //!Gets Game Name //!\return Game Name string getGameName(void); //!Gets GameID //!\return GameID string getGameID(void); //!Gets cheat data //!\return cheat data string getCheat(unsigned int nr); //!Gets Cheat Name //!\return Cheat Name string getCheatName(unsigned int nr); //!Gets Cheat Comment //!\return Cheat Comment string getCheatComment(unsigned int nr); //!Check if string is a code //!\return true/false bool IsCode(const std::string& s); //!Check if string is a code //!\return 0=ok, 1="X", 2=no code int IsCodeEx(const std::string& s); }; #endif /* _GCT_H */
[ "[email protected]@a6d911d2-2a6f-2b2f-592f-0469abc2858f" ]
[ [ [ 1, 91 ] ] ]
6e575ab7b66a8581707b5063400b5f0d9d2687aa
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Stellar_/code/Render/coregraphics/shadervariableinstance.cc
d15485ddcbe46a29109a14c75274e0ac6475ee51
[]
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
528
cc
//------------------------------------------------------------------------------ // shadervariableinstance.cc // (C) 2007 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "coregraphics/shadervariableinstance.h" #if __WIN32__ namespace CoreGraphics { ImplementClass(CoreGraphics::ShaderVariableInstance, 'SDVI', Base::ShaderVariableInstanceBase); } #else #error "ShaderVariableInstance class not implemented on this platform!" #endif
[ "ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38" ]
[ [ [ 1, 15 ] ] ]
c9296ec85b5687af6a5727ab08dd7518fc905924
b2b5c3694476d1631322a340c6ad9e5a9ec43688
/Baluchon/IEventHandler.h
0e28b7d2c4dcf2a111c68556021e0dda444281d4
[]
no_license
jpmn/rough-albatross
3c456ea23158e749b029b2112b2f82a7a5d1fb2b
eb2951062f6c954814f064a28ad7c7a4e7cc35b0
refs/heads/master
2016-09-05T12:18:01.227974
2010-12-19T08:03:25
2010-12-19T08:03:25
32,195,707
1
0
null
null
null
null
UTF-8
C++
false
false
859
h
/** * \file IEventHandler.h * \brief Interface offrant les signatures de fonction d'un gestionnaire d'&eacute;v&egrave;nements. * \author Mathieu Plourde * \author Jean-Philippe Morin * \version 1.0 * * Interface qui offre les signatures de base pour un gestionnaire d'&eacute;v&egrave;nements de l'application. * */ #pragma once #include "IEvent.h" namespace baluchon { namespace core { namespace events { class IEventHandler { public: /** * \fn virtual ~IEventHandler() * \brief Destructeur virtuel de la classe. */ virtual ~IEventHandler(void) {}; /** * \fn virtual void handle(IEvent* e) * \brief Fonction de gestion d'un &eacute;v&egrave;nement. * \param e L'&eacute;v&egrave;nement &agrave; g&eacute;rer. */ virtual void handle(IEvent* e) = 0; }; }}};
[ "[email protected]@bd4f47a5-da4e-a94a-6a47-2669d62bc1a5" ]
[ [ [ 1, 36 ] ] ]
0251ee0955e3791ca64bb43177ae33f0195bd0ea
99527557aee4f1db979a7627e77bd7d644098411
/utils/sdlutils/sdlbitmap.h
e47dd20a14dff99273cb0678f82928fc3b1e9fa3
[]
no_license
GunioRobot/2deffects
7aeb02400090bb7118d23f1fc435ffbdd4417c59
39d8e335102d6a51cab0d47a3a2dc7686d7a7c67
refs/heads/master
2021-01-18T14:10:32.049756
2008-09-15T15:56:50
2008-09-15T15:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
713
h
#ifndef _SDLBITMAP_H_ #define _SDLBITMAP_H_ // #include "utils/bitmap.h" // struct SDL_Surface; namespace syd { class SdlBitmap : public Bitmap { SDL_Surface* sdlSurface_p; static SDL_Surface* mainSurface_p; public: SDL_Surface* getSdlSurface() const; public: virtual unsigned width() const; virtual unsigned height() const; public: virtual Bitmap& lock(); virtual Bitmap& unlock(); // virtual color_t* getPtr(); public: virtual Bitmap* clone(unsigned w, unsigned h, unsigned tagsize) const; public: SdlBitmap(SDL_Surface* s); virtual ~SdlBitmap(); public: virtual void invariant() const; // not implemented!!! }; } //syd #endif //_SDLBITMAP_H_
[ [ [ 1, 42 ] ] ]
e432f0afe1b47028647a67ae8400cec943fe6440
8a8873b129313b24341e8fa88a49052e09c3fa51
/src/CoCo.cpp
7e35761eb93c394896fbf8b024081560a9cec78e
[]
no_license
flaithbheartaigh/wapbrowser
ba09f7aa981d65df810dba2156a3f153df071dcf
b0d93ce8517916d23104be608548e93740bace4e
refs/heads/master
2021-01-10T11:29:49.555342
2010-03-08T09:36:03
2010-03-08T09:36:03
50,261,329
1
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
/* ============================================================================ Name : CoCo.cpp Author : 浮生若茶 Version : Copyright : Your copyright notice Description : Application entry point ============================================================================ */ // INCLUDE FILES #ifdef __SERIES60_3X__ #include <eikstart.h> #endif #include "CoCoApplication.h" #include "PreDefine.h" #include "UtilityTools.h" #ifdef __SERIES60_3X__ LOCAL_C CApaApplication* NewApplication() { return new CCoCoApplication; } GLDEF_C TInt E32Main() { return EikStart::RunApplication( NewApplication ); } #else EXPORT_C CApaApplication* NewApplication() { return new CCoCoApplication; } GLDEF_C TInt E32Dll( TDllReason ) { return KErrNone; } #endif
[ "sungrass.xp@37a08ede-ebbd-11dd-bd7b-b12b6590754f" ]
[ [ [ 1, 38 ] ] ]
7d9e5dbc410c79d48b2574ca267377a831f63c51
aefc3d630a28e054a438d13ab16d32f2d39ccb1e
/XTypeEx.h
e3b9a694e55bd4a8027d96d5057ec878ae345a6a
[]
no_license
imcooder/publicwince
e64305d86496b550116c312d2e9a67e7fb33c6f8
58a337768161e1a10664b4d5edc2aadfb2ab1328
refs/heads/master
2021-05-28T10:40:35.786601
2010-06-27T06:25:09
2010-06-27T06:25:09
32,301,144
1
0
null
null
null
null
UTF-8
C++
false
false
1,807
h
#ifndef HWX_XTYPEEX_H #define HWX_XTYPEEX_H #include "Ext_Type.h" #define SelectFont(hDC, hFont) \ ((HFONT) ::SelectObject((hDC), (HGDIOBJ) (HFONT) (hFont))) #ifndef HANDLE_MSG #define HANDLE_MSG(m_hWnd, message, fn) \ case (message): \ return HANDLE_##message((m_hWnd), (wParam), (lParam), (fn)) #endif #ifndef HANDLE_WM_COMMAND #define HANDLE_WM_COMMAND(m_hWnd, wParam, lParam, fn) \ ( (fn) ((m_hWnd), (int) (LOWORD(wParam)), (HWND)(lParam), (UINT) HIWORD(wParam)), 0L) #endif #ifdef _XSTRING_ //include <string> #ifndef _TSTRING_DEFINED #define _TSTRING_DEFINED #if defined(UNICODE) || defined(_UNICODE) typedef std::wstring TSTRING; #else typedef std::string TSTRING; #endif #endif #endif #ifdef _SSTREAM_ //include <sstream> #ifndef _TSTRINGSTREAM_DEFINED #define _TSTRINGSTREAM_DEFINED #if defined(UNICODE) || defined(_UNICODE) typedef std::wstringstream TSTRINGSTREAM; #else typedef std::stringstream TSTRINGSTREAM; #endif #endif #endif #ifdef _IOSTREAM_ //include <iostream> #ifndef _TCOUT_DEFINED #define _TCOUT_DEFINED #if defined(UNICODE) || defined(_UNICODE) #define TCOUT std::wcout #else #define TCOUT std::cin #endif #endif #ifndef _TCIN_DEFINED #define _TCIN_DEFINED #if defined(UNICODE) || defined(_UNICODE) #define TCIN std::wcin #else #define TCIN std::cin #endif #endif #ifndef _TCLOG_DEFINED #define _TCLOG_DEFINED #if defined(UNICODE) || defined(_UNICODE) #define TCLOG std::wclog #else #define TCLOG std::clog #endif #endif #ifndef _TCERR_DEFINED #define _TCERR_DEFINED #if defined(UNICODE) || defined(_UNICODE) #define TCERR std::wcerr #else #define TCERR std::cerr #endif #endif #endif #endif//HWXUE_EXT_TYPE_H_INC
[ "[email protected]@a9ac5a9c-960a-11de-b8e1-0bcae535652c" ]
[ [ [ 1, 86 ] ] ]
d772f8c42c75e38d8e8da571d379a450ee6a3673
bef7d0477a5cac485b4b3921a718394d5c2cf700
/dingus/dingus/kernel/ProxyEffect.cpp
1d0426d2a17e9a3fb3e97479124590166be5a57c
[ "MIT" ]
permissive
TomLeeLive/aras-p-dingus
ed91127790a604e0813cd4704acba742d3485400
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
refs/heads/master
2023-04-19T20:45:14.410448
2011-10-04T10:51:13
2011-10-04T10:51:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,622
cpp
// -------------------------------------------------------------------------- // Dingus project - a collection of subsystems for game/graphics applications // -------------------------------------------------------------------------- #include "stdafx.h" #include "ProxyEffect.h" #include "D3DDevice.h" #include "../console/Console.h" #include "../utils/Errors.h" using namespace dingus; CD3DXEffect::CD3DXEffect( ID3DXEffect* object ) : CBaseProxyClass(object) { if( object ) init(); } void CD3DXEffect::setObject( ID3DXEffect* object ) { setPtr(object); if( object ) init(); } void CD3DXEffect::init() { CD3DDevice& dx = CD3DDevice::getInstance(); mSoftwareVertexProcessed = false; bool devNonSW = dx.getCaps().getVertexProcessing() != CD3DDeviceCaps::VP_SW; if( devNonSW ) dx.getDevice().SetSoftwareVertexProcessing( FALSE ); bool okhwvp = tryInit(); if( !okhwvp ) { mSoftwareVertexProcessed = true; if( devNonSW ) dx.getDevice().SetSoftwareVertexProcessing( TRUE ); bool okswvp = tryInit(); if( !okswvp ) { // no valid technique found, throw exception std::string msg = "no valid techniques found in effect"; CConsole::CON_ERROR.write( msg ); THROW_ERROR( msg ); } if( devNonSW ) dx.getDevice().SetSoftwareVertexProcessing( FALSE ); } } bool CD3DXEffect::isValidTechnique( D3DXHANDLE tech ) { ID3DXEffect* fx = getObject(); assert( fx ); // validate the technique if( FAILED( fx->ValidateTechnique( tech ) ) ) return false; CD3DDevice& dx = CD3DDevice::getInstance(); D3DXHANDLE annot; // needs shadow map support? annot = fx->GetAnnotationByName( tech, "shadowMap" ); if( annot != NULL ) { BOOL val = FALSE; fx->GetBool( annot, &val ); if( val && !dx.getCaps().hasShadowMaps() ) return false; } // needs floating point RT support? annot = fx->GetAnnotationByName( tech, "floatTexture" ); if( annot != NULL ) { BOOL val = FALSE; fx->GetBool( annot, &val ); if( val && !dx.getCaps().hasFloatTextures() ) return false; } // all ok! return true; } bool CD3DXEffect::tryInit() { HRESULT hres; ID3DXEffect* fx = getObject(); assert( fx ); // // find a valid technique D3DXHANDLE tech = fx->GetTechnique( 0 ); while( tech && !isValidTechnique( tech ) ) { hres = fx->FindNextValidTechnique( tech, &tech ); } if( tech != NULL ) fx->SetTechnique( tech ); else return false; assert( tech != NULL ); // // back to front? D3DXHANDLE annot = fx->GetAnnotationByName( tech, "backToFront" ); BOOL backToFront = FALSE; if( annot != NULL ) fx->GetBool( annot, &backToFront ); mBackToFrontSorted = backToFront ? true : false; // sort value mSortValue = 0; mSortValue += mBackToFrontSorted ? 0x10 : 0x00; mSortValue += mSoftwareVertexProcessed ? 0 : 1; // // has restoring pass? D3DXTECHNIQUE_DESC techdsc; fx->GetTechniqueDesc( tech, &techdsc ); D3DXPASS_DESC passdsc; fx->GetPassDesc( fx->GetPass(tech,techdsc.Passes-1), &passdsc ); mHasRestoringPass = !stricmp( passdsc.Name, DINGUS_FX_RESTORE_PASS ); mPassCount = mHasRestoringPass ? techdsc.Passes-1 : techdsc.Passes; return true; } // -------------------------------------------------------------------------- #define FX_BEGIN_PARAMS (D3DXFX_DONOTSAVESTATE | D3DXFX_DONOTSAVESHADERSTATE | D3DXFX_DONOTSAVESAMPLERSTATE) #define FX_USE_RESTORING_PASS // if using this, uncomment DISABLE_FILTERING in D3DDevice.cpp and EffectStateManager.cpp! //#define FX_BEGIN_PARAMS (0) int CD3DXEffect::beginFx() { UINT p; DWORD flags = mHasRestoringPass ? (FX_BEGIN_PARAMS) : 0; HRESULT hr = getObject()->Begin( &p, flags ); assert( SUCCEEDED(hr) ); assert( mHasRestoringPass && (int)p==mPassCount+1 || !mHasRestoringPass && (int)p==mPassCount ); return mPassCount; } void CD3DXEffect::endFx() { #ifdef FX_USE_RESTORING_PASS if( mHasRestoringPass ) { beginPass( mPassCount ); endPass(); } #endif HRESULT hr = getObject()->End(); assert( SUCCEEDED(hr) ); } void CD3DXEffect::beginPass( int p ) { #ifdef DINGUS_HAVE_D3DX_SUMMER_2004 HRESULT hr = getObject()->BeginPass( p ); #else HRESULT hr = getObject()->Pass( p ); #endif assert( SUCCEEDED(hr) ); } void CD3DXEffect::endPass() { #ifdef DINGUS_HAVE_D3DX_SUMMER_2004 HRESULT hr = getObject()->EndPass(); assert( SUCCEEDED(hr) ); #endif } void CD3DXEffect::commitParams() { #ifdef DINGUS_HAVE_D3DX_SUMMER_2004 HRESULT hr = getObject()->CommitChanges(); assert( SUCCEEDED(hr) ); #endif }
[ [ [ 1, 189 ] ] ]
dd80ad31d97425f5a155af848eca955677efa307
fac8de123987842827a68da1b580f1361926ab67
/inc/physics/Physics/Dynamics/World/BroadPhaseBorder/hkpBroadPhaseBorder.h
c2b569e1d4e72e09f49ca8f6e665dcfbd5b88c6c
[]
no_license
blockspacer/transporter-game
23496e1651b3c19f6727712a5652f8e49c45c076
083ae2ee48fcab2c7d8a68670a71be4d09954428
refs/heads/master
2021-05-31T04:06:07.101459
2009-02-19T20:59:59
2009-02-19T20:59:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,952
h
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent.This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2008 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_UTILITIES2_BROAD_PHASE_BORDER_H #define HK_UTILITIES2_BROAD_PHASE_BORDER_H #include <Common/Base/hkBase.h> #include <Physics/Dynamics/World/hkpWorldCinfo.h> #include <Physics/Dynamics/Phantom/hkpPhantomOverlapListener.h> #include <Physics/Dynamics/World/Listener/hkpWorldDeletionListener.h> class hkpWorld; class hkpEntity; /// This class monitors objects leaving the broadphase. class hkpBroadPhaseBorder : public hkReferencedObject, protected hkpWorldDeletionListener, protected hkpPhantomOverlapListener { public: HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_UTILITIES); /// Creates an instance and attaches it to the world. It also adds a second reference to it that gets removed when the world gets deleted /// The positions of the border phantoms are derived from the broadphase extents of the hkpWorld hkpBroadPhaseBorder( hkpWorld* world, hkpWorldCinfo::BroadPhaseBorderBehaviour type = hkpWorldCinfo::BROADPHASE_BORDER_ASSERT ); virtual ~hkpBroadPhaseBorder(); /// This function is called when an object goes beyond the scope of the broadphase. /// By default, it removes the entity from the world, you may implement your own version. virtual void maxPositionExceededCallback( hkpEntity* body ); /// Deactivate this class virtual void deactivate(); virtual void collidableAddedCallback( const hkpCollidableAddedEvent& event ); /// Callback implementation virtual void collidableRemovedCallback( const hkpCollidableRemovedEvent& event ); public: virtual void worldDeletedCallback( hkpWorld* world ); hkpWorld* m_world; class hkpPhantom* m_phantoms[6]; hkpWorldCinfo::BroadPhaseBorderBehaviour m_type; }; #endif // HK_UTILITIES2_BROAD_PHASE_BORDER_H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20080529) * * Confidential Information of Havok. (C) Copyright 1999-2008 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at * www.havok.com/tryhavok * */
[ "uraymeiviar@bb790a93-564d-0410-8b31-212e73dc95e4" ]
[ [ [ 1, 73 ] ] ]
6741fc648c83516f2f5c36af4aa36b441e0b6f4b
7f6f9788d020e97f729af85df4f6741260274bee
/src/gui/Interface.cpp
18bbc112e7ceda435b2a38ed159bc7bf1285a276
[]
no_license
cnsuhao/nyanco
0fb88ed1cf2aa9390fa62f6723e8424ba9a42ed4
ba199267a33d4c6d2e473ed4b777765057aaf844
refs/heads/master
2021-05-31T05:37:51.892873
2008-05-27T05:23:19
2008-05-27T05:23:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,745
cpp
/*! @file Interface.cpp @author dasyprocta */ #include "gui_base.h" #include "gui/Interface.h" #include "afx/GraphicsDevice.h" #include "afx/InputDevice.h" #include "WindowManager.hpp" namespace nyanco { void GuiInterface::Implement() { GuiInterface::RegistFactory(gui::Interface::Create); } namespace gui { void Interface::onInitialize() { impl::WindowManager& manager = impl::WindowManager::GetImplement(); GraphicsDevice& graphics = GraphicsDevice::GetInterface(); manager.initialize(graphics.getD3dDevice()); } void Interface::onFinalize() { impl::WindowManager& manager = impl::WindowManager::GetImplement(); manager.finalize(); } void Interface::onUpdate() { impl::WindowManager& manager = impl::WindowManager::GetImplement(); manager.update(); } void Interface::onDraw() { impl::WindowManager& manager = impl::WindowManager::GetImplement(); manager.draw(); } void Interface::setClientRect(sint32 left, sint32 top, sint32 right, sint32 bottom) { impl::WindowManager& manager = impl::WindowManager::GetImplement(); manager.setClientRect(Rect<sint32>(left, top, right, bottom)); } void Interface::getClientRect(sint32& left, sint32& top, sint32& right, sint32& bottom) { impl::WindowManager& manager = impl::WindowManager::GetImplement(); Rect<sint32> const& rect = manager.getViewRect(); left = rect.left; top = rect.top; right = rect.right; bottom = rect.bottom; } } } // namespace nyanco::gui
[ "dasyprocta@27943c09-b335-0410-ab52-7f3c671fdcc1" ]
[ [ [ 1, 63 ] ] ]
14374df74fbae1145a9dfea6df44cc0ded3490fb
619941b532c6d2987c0f4e92b73549c6c945c7e5
/Source/DirectInput8Plugin/Input/DirectInput8InputDevice.cpp
d4f78b556291bda7e434daf67fc18fd8c89fddb6
[]
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
11,226
cpp
//  // // # # ### # # -= Nuclex Library =-  // // ## # # # ## ## DirectInput8InputDevice.cpp - DirectInput8 input device  // // ### # # ###  // // # ### # ### Default implementation of an input device which uses the  // // # ## # # ## ## operating system's mouse support routines  // // # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt  // //  // #include "DirectInput8Plugin/Input/DirectInput8InputDevice.h" #include "Nuclex/Input/InputReceiver.h" #include "Nuclex/Input/InputServer.h" #include "Nuclex/Kernel.h" #include "Nuclex/Application.h" //#include "MemoryTracker/DisableMemoryTracker.h" #include "Loki/SmallObj.h" //#include "MemoryTracker/MemoryTracker.h" #ifdef NUCLEX_WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <iostream> using namespace std; using namespace Nuclex; using namespace Nuclex::Input; namespace { //  // //  DirectInput8TriggerEnumerator  // //  // class DirectInput8TriggerEnumerator : public InputDevice::TriggerEnumerator { public: DirectInput8TriggerEnumerator(const IDirectInputDevice8Ptr &spDevice) : m_CurrentTrigger(0) { DInputCheck( "DirectInput8TriggerEnumerator::DirectInput8TriggerEnumerator()", "IDirectInputDevice8::EnumObjects()", spDevice->EnumObjects(DIEnumDeviceObjectsCallback, this, DIDFT_ALL) ); } /// Destructor virtual ~DirectInput8TriggerEnumerator() {} // // DirectInput8TriggerEnumerator // public: void addTrigger(const InputDevice::Trigger &Trigger) { m_Triggers.push_back(Trigger); } // // TriggerEnumerator implementation // public: /// Cycle through triggers const InputDevice::Trigger *cycle() { if(m_CurrentTrigger < m_Triggers.size()) return &m_Triggers[m_CurrentTrigger++]; else return NULL; } private: static BOOL CALLBACK DIEnumDeviceObjectsCallback( LPCDIDEVICEOBJECTINSTANCE lpddoi, LPVOID pvRef ) { DirectInput8TriggerEnumerator &TheEnumerator = *static_cast<DirectInput8TriggerEnumerator *>(pvRef); InputDevice::Trigger Trigger; Trigger.sName = lpddoi->tszName; switch(DIDFT_GETINSTANCE(lpddoi->dwType)) { case DIDFT_RELAXIS: { Trigger.eKind = InputDevice::Trigger::K_AXIS; break; } case DIDFT_ABSAXIS: { Trigger.eKind = InputDevice::Trigger::K_SLIDER; break; } case DIDFT_PSHBUTTON: case DIDFT_TGLBUTTON: { Trigger.eKind = InputDevice::Trigger::K_BUTTON; break; } default: Trigger.eKind = InputDevice::Trigger::K_UNKNOWN; } TheEnumerator.addTrigger(Trigger); return DIENUM_CONTINUE; } std::vector<InputDevice::Trigger> m_Triggers; size_t m_CurrentTrigger; }; } // namespace //  // //  Nuclex::Input::DirectInput8InputDevice::DirectInput8TriggerStates  // //  // /* class DirectInput8InputDevice::DirectInput8TriggerStates : public InputDevice::TriggerStates, public Loki::SmallObject<DEFAULT_THREADING, 36 * MaxSnapshotHistory, 36> { public: /// Constructor DirectInput8TriggerStates(const TimeSpan &SnapshotTime) : m_SnapshotTime() {} /// Destructor virtual ~DirectInput8TriggerStates() {} /// Get time it which snapshot was taken void setSnapshotTime(const TimeSpan &Time) { m_SnapshotTime = Time; } // // TriggerStates implementation // public: shared_ptr<TriggerStates> clone() const { return shared_ptr<TriggerStates>(new DirectInput8TriggerStates(*this)); } /// Get time it which snapshot was taken const TimeSpan &getSnapshotTime() const { return m_SnapshotTime; } /// Get state of an input trigger real getTriggerState(const string &sTrigger) { return 0; } private: TimeSpan m_SnapshotTime; }; */ // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::DirectInput8InputDevice() Constructor # // // ############################################################################################# // /** Initializes an instance of DirectInput8InputDevice */ DirectInput8InputDevice::DirectInput8InputDevice(GUID InstanceGUID) : m_sName("DirectInput8 device") { DInputCheck( "Nuclex::Input::DirectInput8InputDevice::DirectInput8InputDevice()", "IDirectInput8::CreateDevice()", getDirectInput8()->CreateDevice(InstanceGUID, &m_spDirectInputDevice, NULL) ); DIDEVICEINSTANCE DeviceInstance = { sizeof(DeviceInstance) }; DInputCheck( "Nuclex::Input::DirectInput8InputDevice::DirectInput8InputDevice()", "IDirectInputDevice8::GetDeviceInfo()", m_spDirectInputDevice->GetDeviceInfo(&DeviceInstance) ); // D m_sName = string(DeviceInstance.tszProductName) + " through DirectInput 8"; m_eDeviceType = InputDeviceTypeFromDInputDevType(DeviceInstance.dwDevType); } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::~DirectInput8InputDevice() Destructor # // // ############################################################################################# // /** Releases an instance of DirectInput8InputDevice */ DirectInput8InputDevice::~DirectInput8InputDevice() {} // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::enumTriggers() # // // ############################################################################################# // /** Returns a new enumerator over all triggers of the input device. A trigger is an abstract representation of an axis, a key or any other kind of button on an input device. @return A new enumerator over all triggers */ shared_ptr<InputDevice::TriggerEnumerator> DirectInput8InputDevice::enumTriggers() const { return shared_ptr<InputDevice::TriggerEnumerator>( new DirectInput8TriggerEnumerator(m_spDirectInputDevice) ); } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::getTriggerState() # // // ############################################################################################# // /* shared_ptr<InputDevice::TriggerStates> DirectInput8InputDevice::snapTriggerStates() const { throw NotSupportedException( "Nuclex::Input::DirectInput8InputDevice::getTriggerState()", "Not implemented yet" ); } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::setSnapshotInterval() # // // ############################################################################################# // void DirectInput8InputDevice::setSnapshotInterval(const TimeSpan &Interval, size_t MaxHistory) { m_Interval = Interval; } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::withdrawSnapshots() # // // ############################################################################################# // std::list<shared_ptr<InputDevice::TriggerStates> > DirectInput8InputDevice::withdrawSnapshots(const TimeSpan &EndTime) { std::list<shared_ptr<InputDevice::TriggerStates> > Snapshots; while(m_TriggerStateHistory.size() > 1) { if(m_TriggerStateHistory.front()->getSnapshotTime() > EndTime) break; Snapshots.push_back(m_TriggerStateHistory.front()); m_TriggerStateHistory.pop_front(); } return Snapshots; } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::getCurrentStates() # // // ############################################################################################# // DirectInput8InputDevice::DirectInput8TriggerStates &DirectInput8InputDevice::getCurrentStates() { if(m_TriggerStateHistory.empty()) { TimeSpan Now = TimeSpan::getRunningTime(); m_TriggerStateHistory.push_back(shared_ptr<DirectInput8TriggerStates>( new DirectInput8TriggerStates(Now - (Now % m_Interval)) )); } else if(m_TriggerStateHistory.front()->getSnapshotTime() < TimeSpan::getRunningTime() - m_Interval) { TimeSpan Now = TimeSpan::getRunningTime(); m_TriggerStateHistory.push_back(shared_ptr<DirectInput8TriggerStates>( new DirectInput8TriggerStates(*m_TriggerStateHistory.front().get()) )); m_TriggerStateHistory.front()->setSnapshotTime(Now - (Now % m_Interval)); } return *m_TriggerStateHistory.front().get(); } // ############################################################################################# // // # Nuclex::Input::DirectInput8InputDevice::updateTriggerstates() # // // ############################################################################################# // void DirectInput8InputDevice::updateTriggerStates() { DInputCheck( "Nuclex::Input::DirectInput8InputDevice::updateTriggerStates()", "IDirectInput8InputDevice::Poll()", m_spDirectInputDevice->Poll() ); } */ /// Access the device in exclusive mode ? void DirectInput8InputDevice::setExclusive(bool bExclusive) { } /// Add control void DirectInput8InputDevice::addControl(const string &sName, const string &sTrigger) { } /// Remove control void DirectInput8InputDevice::removeControl(const string &sName, const string &sTrigger) { } /// Remove all controls void DirectInput8InputDevice::clearControls() { } /// Get control state real DirectInput8InputDevice::getControl(const string &sName) { return 0; }
[ [ [ 1, 285 ] ] ]
4977bf980bcd2ceeb120fab2cad1873d1a163254
9a33169387ec29286d82e6e0d5eb2a388734c969
/3DBipedRobot/NodeMgr.h
a9bd6f12458c4b4ef210f01abdc7d56ef93c67d5
[]
no_license
cecilerap/3dbipedrobot
a62773a6db583d66c80f9b8ab78d932b163c8dd9
83c8f972e09ca8f16c89fc9064c55212d197d06a
refs/heads/master
2021-01-10T13:28:09.532652
2009-04-24T03:03:13
2009-04-24T03:03:13
53,042,363
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
715
h
// NodeMgr.h : Çì´õ ÆÄÀÏ // #pragma once #include <vector> using namespace std; #include "Node.h" #include "Mesh.h" #include "ZMP.h" class CNodeMgr { public: CNodeMgr(LPDIRECT3DDEVICE9 pD3DDevice); ~CNodeMgr(void); void Animate(); void Draw(); void SetWeight(); void SetAngle(COMPONENT id, float angle); CNode* GetNodes(COMPONENT id) { return m_nodes[id]; } D3DXVECTOR3 GetCenterWeight() { return m_vCtWeight; } D3DXVECTOR3 GetOldCenterWeight() { return m_vOldCtWeight; } protected: vector<CNode*> m_nodes; LPDIRECT3DDEVICE9 m_pD3DDevice; D3DXMATRIXA16 m_matTM; D3DXVECTOR3 m_vOldCtWeight, m_vCtWeight; public: CZMP* m_pLeftZMP, * m_pRightZMP; };
[ "t2wish@463fb1f2-0299-11de-9d1d-173cc1d06e3c" ]
[ [ [ 1, 37 ] ] ]
93461bfbbdf68983858ddc3107b974716f604f0e
880e5a47c23523c8e5ba1602144ea1c48c8c8f9a
/enginesrc/math/math.hpp
1abcc9f6bc0f29244e9668b79757c82a054b7266
[]
no_license
kfazi/Engine
050cb76826d5bb55595ecdce39df8ffb2d5547f8
0cedfb3e1a9a80fd49679142be33e17186322290
refs/heads/master
2020-05-20T10:02:29.050190
2010-02-11T17:45:42
2010-02-11T17:45:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,476
hpp
#ifndef ENGINE_MATH_HPP #define ENGINE_MATH_HPP #include "vector3.hpp" #include "quaternion.hpp" namespace engine { class DLLEXPORTIMPORT CMath { public: /** * Returns minimum of its two arguments. * This function is here only because of Microsoft's fuckups. * @param[in] x First value. * @param[in] y Second value. * @return Minimum value. */ template<class CType> inline static const CType &Min(const CType &x, const CType &y) { return (x < y) ? x : y; } /** * Returns maximum of its two arguments. * This function is here only because of Microsoft's fuckups. * @param[in] x First value. * @param[in] y Second value. * @return Maximum value. */ template<class CType> inline static const CType &Max(const CType &x, const CType &y) { return (x < y) ? y : x; } /** * Converts degrees to radians. * @param[in] fDegrees Value in degrees. * @return Value in radians. */ inline static double DegToRad(const double fDegrees) { return fDegrees * 0.017453292519943295769236907684888; /* fDegrees * pi / 180 */ } /** * Converts radians to degrees. * @param[in] fRadians Value in radians. * @return Value in degrees. */ inline static double RadToDeg(const double fRadians) { return fRadians * 57.295779513082320876798154814105; /* fRadians * 180 / pi */ } inline static double DotProduct(const CVector3 &cVector1, const CVector3 &cVector2) { return cVector1.X * cVector2.X + cVector1.Y * cVector2.Y + cVector1.Z * cVector2.Z; } inline static double DotProduct(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2) { return DotProduct(cQuaternion1.GetVector(), cQuaternion2.GetVector()) + cQuaternion1.W * cQuaternion1.W; } inline static CVector3 CrossProduct(const CVector3 &cVector1, const CVector3 &cVector2) { return CVector3(cVector1.Y * cVector2.Z - cVector1.Z * cVector2.Y, cVector1.Z * cVector2.X - cVector1.X * cVector2.Z, cVector1.X * cVector2.Y - cVector1.Y * cVector2.X); } inline static CVector3 Rotate(const CVector3 &cVector, const CQuaternion &cQuaternion) { CQuaternion cVectorQuaternion(0, cVector); CQuaternion cConjugate(cQuaternion); cConjugate.Conjugate(); return (cQuaternion * cVectorQuaternion * cConjugate).GetVector(); } //! linear quaternion interpolation static CQuaternion Lerp(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2, const double fT) { return (cQuaternion1 * (1.0 - fT) + cQuaternion2 * fT).GetNormalized(); } //! spherical linear interpolation static CQuaternion Slerp(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2, const double fT) { CQuaternion cQuaternion3; double fDot = DotProduct(cQuaternion1, cQuaternion2); /* dot = cos(theta) if (dot < 0), q1 and q2 are more than 90 degrees apart, so we can invert one to reduce spinning */ if (fDot < 0) { fDot = -fDot; cQuaternion3 = -cQuaternion2; } else cQuaternion3 = cQuaternion2; if (fDot < 0.95) { double fAngle = acos(fDot); return (cQuaternion1 * sin(fAngle * (1.0 - fT)) + cQuaternion3 * sin(fAngle * fT)) / sin(fAngle); } else // if the angle is small, use linear interpolation return Lerp(cQuaternion1, cQuaternion3, fT); } //! This version of slerp, used by squad, does not check for theta > 90. static CQuaternion SlerpNoInvert(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2, const double fT) { double fDot = DotProduct(cQuaternion1, cQuaternion2); if (fDot > -0.95 && fDot < 0.95) { double fAngle = acos(fDot); return (cQuaternion1 * sin(fAngle * (1.0 - fT)) + cQuaternion2 * sin(fAngle * fT)) / sin(fAngle); } else // if the angle is small, use linear interpolation return Lerp(cQuaternion1, cQuaternion2, fT); } //! spherical cubic interpolation static CQuaternion Squad(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2, const CQuaternion &cQuaternionA, const CQuaternion &cQuaternionB, const double fT) { CQuaternion cQuaternionC = SlerpNoInvert(cQuaternion1, cQuaternion2, fT); CQuaternion cQuaternionD = SlerpNoInvert(cQuaternionA, cQuaternionB, fT); return SlerpNoInvert(cQuaternionC, cQuaternionD, 2.0 * fT * (1.0 - fT)); } //! Shoemake-Bezier interpolation using De Castlejau algorithm static CQuaternion Bezier(const CQuaternion &cQuaternion1, const CQuaternion &cQuaternion2, const CQuaternion &cQuaternionA, const CQuaternion &cQuaternionB, const double fT) { // level 1 CQuaternion cQuaternion11 = SlerpNoInvert(cQuaternion1, cQuaternionA, fT); CQuaternion cQuaternion12 = SlerpNoInvert(cQuaternionA, cQuaternionB, fT); CQuaternion cQuaternion13 = SlerpNoInvert(cQuaternionB, cQuaternion2, fT); // level 2 and 3 return SlerpNoInvert(SlerpNoInvert(cQuaternion11, cQuaternion12, fT), SlerpNoInvert(cQuaternion12,cQuaternion13, fT), fT); } #if 0 //! Given 3 quaternions, qn-1,qn and qn+1, calculate a control point to be used in spline interpolation static quaternion spline(const quaternion &qnm1,const quaternion &qn,const quaternion &qnp1) { quaternion qni(qn.s, -qn.v); return qn * (( (qni*qnm1).log()+(qni*qnp1).log() )/-4).exp(); } #endif }; } #endif /* ENGINE_MATH_HPP */ /* EOF */
[ [ [ 1, 159 ] ] ]
fa40fccfdc4b48768eefe8f75a12c3284dc3101d
1c4a1cd805be8bc6f32b0a616de751ad75509e8d
/jacknero/src/pku_src/2954/3584799_AC_0MS_396K.cc
5671ed18ad9321759a6b2a8989b8bd1fec53892b
[]
no_license
jacknero/mycode
30313261d7e059832613f26fa453abf7fcde88a0
44783a744bb5a78cee403d50eb6b4a384daccf57
refs/heads/master
2016-09-06T18:47:12.947474
2010-05-02T10:16:30
2010-05-02T10:16:30
180,950
1
0
null
null
null
null
UTF-8
C++
false
false
1,048
cc
#include <iostream> using namespace std; #define out(x) (cout << #x << ": " << x << endl) typedef long long int64; const int maxint = 0x7FFFFFFF; const int64 maxint64 = 0x7FFFFFFFFFFFFFFFLL; template <class T> void show(T a, int n) { for (int i = 0; i < n; ++i) cout << a[i] << ' '; cout << endl; } template <class T> void show(T a, int r, int l) { for (int i = 0; i < r; ++i) show(a[i], l); cout << endl; } int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } int main() { int ax, ay, bx, by, cx, cy; while (scanf("%d%d%d%d%d%d", &ax, &ay, &bx, &by, &cx, &cy), !(ax == 0 && ay == 0 && bx == 0 && by == 0 && cx == 0 && cy == 0)) { int tax = bx - cx, tay = by - cy; int tbx = cx - ax, tby = cy - ay; int tcx = ax - bx, tcy = ay - by; int b = gcd(abs(tcx), abs(tcy)) + gcd(abs(tax), abs(tay)) + gcd(abs(tbx), abs(tby)); int a = abs(tax * tby - tay * tbx); printf("%d\n", (a + 2 - b) / 2); } return 0; }
[ [ [ 1, 32 ] ] ]
8142751319425604ec6df54f70ade48a7b08ad16
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testmisc/spawnchild/src/testexitec.cpp
bbe68ea36c27ed15a6c2be2b71613816d6aae83d
[]
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
844
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // INCLUDE FILES #include <e32def.h> #include <e32std.h> #include <stdio.h> #include <e32base.h> #include <unistd.h> #include <stdlib.h> void exitecTest() { exit(3); } TInt E32Main() { __UHEAP_MARK; CTrapCleanup* cleanup = CTrapCleanup::New(); TRAPD(error, exitecTest()); //Destroy cleanup stack delete cleanup; __UHEAP_MARKEND; return error; }
[ "none@none" ]
[ [ [ 1, 42 ] ] ]
7c69bb2b3a731bb6907f8983f6b27819de4bd8b5
1c80a726376d6134744d82eec3129456b0ab0cbf
/Project/C++/POJ/3682/3682.cpp
ef0cb3e0694687c8dbd8d8f1c7b77786c69769dc
[]
no_license
dabaopku/project_pku
338a8971586b6c4cdc52bf82cdd301d398ad909f
b97f3f15cdc3f85a9407e6bf35587116b5129334
refs/heads/master
2021-01-19T11:35:53.500533
2010-09-01T03:42:40
2010-09-01T03:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
#include "stdio.h" #include "iostream" #include "string.h" #include "math.h" #include "string" #include "vector" #include "set" #include "map" #include "queue" #include "list" using namespace std; int main() { int n[10]; int odd[10],even[10]; bool flag; while(true){ flag=false; for(int i=0;i<10;i++){ if(!(cin>>n[i])) { flag=true; break; } } if(flag) break; for(int i=0;i<10;i++){ even[i]=-10; odd[i]=200; if(n[i]%2) even[i]=n[i]; else odd[i]=n[i]; } sort(odd,odd+10); sort(even,even+10); for(int i=9;i>=0;i--) { if(even[i]>=0) cout<<even[i]; else break; if(i==0) break; else cout<<" "; } for(int i=0;i<10;i++) { if(odd[i]<=100) cout<<odd[i]; else { cout<<'\n'; break; } if(i==9) cout<<"\n"; else cout<<" "; } } }
[ "[email protected]@592586dc-1302-11df-8689-7786f20063ad" ]
[ [ [ 1, 54 ] ] ]
b90f1d94dfc7554aa915672f6a2c6283586beb38
58ef4939342d5253f6fcb372c56513055d589eb8
/LemonMicro/source/LPRecorder/src/FileRecordAdapter.cpp
bbda357cae2872321f65a465a3da8e21ea19304a
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
GB18030
C++
false
false
3,204
cpp
/* ============================================================================ Name : FileRecordAdapter.cpp Author : Version : 1.0 Copyright : Your copyright notice Description : CFileRecordAdapter implementation ============================================================================ */ #include "FileRecordAdapter.h" #include "MacroUtil.h" #include <aknnotewrappers.h> CFileRecordAdapter::CFileRecordAdapter() { // No implementation required } CFileRecordAdapter::~CFileRecordAdapter() { SAFE_DELETE(iMdaAudioRecorderUtility); DEBUG(SAFE_DELETE(iFileLogger);) } CFileRecordAdapter* CFileRecordAdapter::NewLC() { CFileRecordAdapter* self = new (ELeave)CFileRecordAdapter(); CleanupStack::PushL(self); self->ConstructL(); return self; } CFileRecordAdapter* CFileRecordAdapter::NewL() { CFileRecordAdapter* self=CFileRecordAdapter::NewLC(); CleanupStack::Pop(); // self; return self; } void CFileRecordAdapter::ConstructL() { DEBUG(iFileLogger = CFileLogger::NewL(_L("c:\\CFileRecordAdapter.txt"));) iMdaAudioRecorderUtility = CMdaAudioRecorderUtility::NewL(*this, 0, 80, EMdaPriorityPreferenceQuality); TestSupportedFormat(); } void CFileRecordAdapter::MoscoStateChangeEvent(CBase* /*Object*/, TInt aPreviousState, TInt CurrentState, TInt aErrorCode) { if (aErrorCode != KErrNone) { //If user wants record, but errors occurs, warning note is shown if (iStatus == ERecorderAdapterRecording) { _LIT(text, "Recording failed!"); CAknWarningNote* note = new (ELeave) CAknWarningNote(); note -> ExecuteLD(text); } iStatus = ERecorderAdapterStop; } //When recorder is ready and state is ERecording, recording may start else if (iStatus == ERecorderAdapterRecording && CurrentState == 1 && aPreviousState == 0) { // Set maximum gain for recording iMdaAudioRecorderUtility->SetGain(iMdaAudioRecorderUtility->MaxGain()); iMdaAudioRecorderUtility->SetPosition(TTimeIntervalMicroSeconds(0)); iMdaAudioRecorderUtility->RecordL(); } //If playing stops to end of the file, status changes to EStop else if (iStatus == ERecorderAdapterPlaying && CurrentState == 1) { iStatus = ERecorderAdapterStop; } } //输入设置 void CFileRecordAdapter::SetFileName(const TDesC& aFileName) { iFileName.Copy(aFileName); } //开始录制 void CFileRecordAdapter::StartRecordL() { iStatus = ERecorderAdapterRecording; iMdaAudioRecorderUtility->OpenFileL(iFileName); } void CFileRecordAdapter::TestSupportedFormat() { _LIT(KTotal,"Supported:%d"); _LIT(KFormat,"Format:%d"); _LIT(KErr,"TestSupportedFormat err:%d"); RArray<TFourCC> array; TRAPD(err,iMdaAudioRecorderUtility->GetSupportedDestinationDataTypesL(array)); if (err != KErrNone) { TBuf<30> info; info.Format(KErr,err); DEBUGLOG(iFileLogger,info); return; } TBuf<30> total; total.Format(KTotal,array.Count()); DEBUGLOG(iFileLogger,total); for(int i=0; i<array.Count(); i++) { TBuf<30> format; format.Format(KFormat,array[i]); DEBUGLOG(iFileLogger,format); } }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 121 ] ] ]
35b9d868c85ce779cd8dd69591179eaa6313b0fd
22d9640edca14b31280fae414f188739a82733e4
/Code/VTK/include/vtk-5.2/vtkDataObject.h
8d2fb335457d723df8b7a791bfc2bdd5636438ef
[]
no_license
tack1/Casam
ad0a98febdb566c411adfe6983fcf63442b5eed5
3914de9d34c830d4a23a785768579bea80342f41
refs/heads/master
2020-04-06T03:45:40.734355
2009-06-10T14:54:07
2009-06-10T14:54:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,112
h
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkDataObject.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkDataObject - general representation of visualization data // .SECTION Description // vtkDataObject is an general representation of visualization data. It serves // to encapsulate instance variables and methods for visualization network // execution, as well as representing data consisting of a field (i.e., just // an unstructured pile of data). This is to be compared with a vtkDataSet, // which is data with geometric and/or topological structure. // // vtkDataObjects are used to represent arbitrary repositories of data via the // vtkFieldData instance variable. These data must be eventually mapped into a // concrete subclass of vtkDataSet before they can actually be displayed. // // .SECTION See Also // vtkDataSet vtkFieldData vtkDataObjectSource vtkDataObjectFilter // vtkDataObjectMapper vtkDataObjectToDataSet // vtkFieldDataToAttributeDataFilter #ifndef __vtkDataObject_h #define __vtkDataObject_h #include "vtkObject.h" class vtkAlgorithmOutput; class vtkExecutive; class vtkFieldData; class vtkInformation; class vtkProcessObject; class vtkSource; class vtkStreamingDemandDrivenPipelineToDataObjectFriendship; class vtkExtentTranslator; class vtkInformationDataObjectKey; class vtkInformationDoubleKey; class vtkInformationDoubleVectorKey; class vtkInformationIntegerKey; class vtkInformationIntegerPointerKey; class vtkInformationIntegerVectorKey; class vtkInformationStringKey; class vtkInformationVector; class vtkStreamingDemandDrivenPipeline; class vtkInformationInformationVectorKey; #define VTK_PIECES_EXTENT 0 #define VTK_3D_EXTENT 1 #define VTK_TIME_EXTENT 2 class VTK_FILTERING_EXPORT vtkDataObject : public vtkObject { public: static vtkDataObject *New(); vtkTypeRevisionMacro(vtkDataObject,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set/Get the source object creating this data object. vtkGetObjectMacro(Source,vtkSource); void SetSource(vtkSource *s); // Description: // Set/Get the information object associated with this data object. vtkGetObjectMacro(Information, vtkInformation); virtual void SetInformation(vtkInformation*); // Description: // Get/Set the pipeline information object that owns this data // object. vtkGetObjectMacro(PipelineInformation, vtkInformation); virtual void SetPipelineInformation(vtkInformation*); // Description: // Get the port currently producing this object. virtual vtkAlgorithmOutput* GetProducerPort(); // Description: // Data objects are composite objects and need to check each part for MTime. // The information object also needs to be considered. unsigned long int GetMTime(); // Description: // Restore data object to initial state, virtual void Initialize(); // Description: // Release data back to system to conserve memory resource. Used during // visualization network execution. Releasing this data does not make // down-stream data invalid, so it does not modify the MTime of this // data object. void ReleaseData(); // Description: // Return flag indicating whether data should be released after use // by a filter. int ShouldIReleaseData(); // Description: // Get the flag indicating the data has been released. vtkGetMacro(DataReleased,int); // Description: // Turn on/off flag to control whether this object's data is released // after being used by a filter. void SetReleaseDataFlag(int); int GetReleaseDataFlag(); vtkBooleanMacro(ReleaseDataFlag,int); // Description: // Turn on/off flag to control whether every object releases its data // after being used by a filter. static void SetGlobalReleaseDataFlag(int val); void GlobalReleaseDataFlagOn() {this->SetGlobalReleaseDataFlag(1);}; void GlobalReleaseDataFlagOff() {this->SetGlobalReleaseDataFlag(0);}; static int GetGlobalReleaseDataFlag(); // Description: // Assign or retrieve field data to this data object. virtual void SetFieldData(vtkFieldData*); vtkGetObjectMacro(FieldData,vtkFieldData); // Handle the source/data loop. virtual void Register(vtkObjectBase* o); virtual void UnRegister(vtkObjectBase* o); // Description: // Provides opportunity for the data object to insure internal // consistency before access. Also causes owning source/filter // (if any) to update itself. The Update() method is composed of // UpdateInformation(), PropagateUpdateExtent(), // TriggerAsynchronousUpdate(), and UpdateData(). virtual void Update(); // Description: // WARNING: INTERNAL METHOD - NOT FOR GENERAL USE. // THIS METHOD IS PART OF THE PIPELINE UPDATE FUNCTIONALITY. // Update all the "easy to update" information about the object such // as the extent which will be used to control the update. // This propagates all the way up then back down the pipeline. // As a by-product the PipelineMTime is updated. virtual void UpdateInformation(); // Description: // WARNING: INTERNAL METHOD - NOT FOR GENERAL USE. // THIS METHOD IS PART OF THE PIPELINE UPDATE FUNCTIONALITY. // The update extent for this object is propagated up the pipeline. // This propagation may early terminate based on the PipelineMTime. virtual void PropagateUpdateExtent(); // Description: // WARNING: INTERNAL METHOD - NOT FOR GENERAL USE. // THIS METHOD IS PART OF THE PIPELINE UPDATE FUNCTIONALITY. // Propagate back up the pipeline for ports and trigger the update on the // other side of the port to allow for asynchronous parallel processing in // the pipeline. // This propagation may early terminate based on the PipelineMTime. virtual void TriggerAsynchronousUpdate(); // Description: // WARNING: INTERNAL METHOD - NOT FOR GENERAL USE. // THIS METHOD IS PART OF THE PIPELINE UPDATE FUNCTIONALITY. // Propagate the update back up the pipeline, and perform the actual // work of updating on the way down. When the propagate arrives at a // port, block and wait for the asynchronous update to finish on the // other side. // This propagation may early terminate based on the PipelineMTime. virtual void UpdateData(); // Description: // Get the estimated size of this data object itself. Should be called // after UpdateInformation() and PropagateUpdateExtent() have both been // called. Should be overridden in a subclass - otherwise the default // is to assume that this data object requires no memory. // The size is returned in kilobytes. virtual unsigned long GetEstimatedMemorySize(); // Description: // A generic way of specifying an update extent. Subclasses // must decide what a piece is. When the NumberOfPieces is zero, then // no data is requested, and the source will not execute. virtual void SetUpdateExtent(int piece,int numPieces, int ghostLevel); void SetUpdateExtent(int piece, int numPieces) {this->SetUpdateExtent(piece, numPieces, 0);} // Description: // Set the update extent for data objects that use 3D extents. Using this // method on data objects that set extents as pieces (such as vtkPolyData or // vtkUnstructuredGrid) has no real effect. // Don't use the set macro to set the update extent // since we don't want this object to be modified just due to // a change in update extent. When the volume of the extent is zero (0, -1,..), // then no data is requested, and the source will not execute. virtual void SetUpdateExtent(int x0, int x1, int y0, int y1, int z0, int z1); virtual void SetUpdateExtent(int extent[6]); virtual int* GetUpdateExtent(); virtual void GetUpdateExtent(int& x0, int& x1, int& y0, int& y1, int& z0, int& z1); virtual void GetUpdateExtent(int extent[6]); // Description: // Return class name of data type. This is one of VTK_STRUCTURED_GRID, // VTK_STRUCTURED_POINTS, VTK_UNSTRUCTURED_GRID, VTK_POLY_DATA, or // VTK_RECTILINEAR_GRID (see vtkSetGet.h for definitions). // THIS METHOD IS THREAD SAFE virtual int GetDataObjectType() {return VTK_DATA_OBJECT;} // Description: // Used by Threaded ports to determine if they should initiate an // asynchronous update (still in development). unsigned long GetUpdateTime(); // Description: // If the whole input extent is required to generate the requested output // extent, this method can be called to set the input update extent to the // whole input extent. This method assumes that the whole extent is known // (that UpdateInformation has been called) void SetUpdateExtentToWholeExtent(); // Description: // Get the cumulative modified time of everything upstream. Does // not include the MTime of this object. unsigned long GetPipelineMTime(); // Description: // Return the actual size of the data in kilobytes. This number // is valid only after the pipeline has updated. The memory size // returned is guaranteed to be greater than or equal to the // memory required to represent the data (e.g., extra space in // arrays, etc. are not included in the return value). virtual unsigned long GetActualMemorySize(); // Description: // Copy the generic information (WholeExtent ...) void CopyInformation( vtkDataObject *data ); // Description: // By default, there is no type specific information virtual void CopyTypeSpecificInformation( vtkDataObject *data ) {this->CopyInformation( data );}; // Description: // Set / Get the update piece and the update number of pieces. Similar // to update extent in 3D. void SetUpdatePiece(int piece); void SetUpdateNumberOfPieces(int num); virtual int GetUpdatePiece(); virtual int GetUpdateNumberOfPieces(); // Description: // Set / Get the update ghost level and the update number of ghost levels. // Similar to update extent in 3D. void SetUpdateGhostLevel(int level); virtual int GetUpdateGhostLevel(); // Description: // This request flag indicates whether the requester can handle // more data than requested. Right now it is used in vtkImageData. // Image filters can return more data than requested. The the // consumer cannot handle this (i.e. DataSetToDataSetFitler) // the image will crop itself. This functionality used to be in // ImageToStructuredPoints. virtual void SetRequestExactExtent(int flag); virtual int GetRequestExactExtent(); vtkBooleanMacro(RequestExactExtent, int); // Description: // Set/Get the whole extent of this data object. // The whole extent is meta data for structured data sets. // It gets set by the source during the update information call. virtual void SetWholeExtent(int x0, int x1, int y0, int y1, int z0, int z1); virtual void SetWholeExtent(int extent[6]); virtual int* GetWholeExtent(); virtual void GetWholeExtent(int& x0, int& x1, int& y0, int& y1, int& z0, int& z1); virtual void GetWholeExtent(int extent[6]); // Description: // Set/Get the whole bounding box of this data object. // The whole whole bounding box is meta data for data sets // It gets set by the source during the update information call. virtual void SetWholeBoundingBox(double x0, double x1, double y0, double y1, double z0, double z1); virtual void SetWholeBoundingBox(double bb[6]); virtual double* GetWholeBoundingBox(); virtual void GetWholeBoundingBox(double& x0, double& x1, double& y0, double& y1, double& z0, double& z1); virtual void GetWholeBoundingBox(double extent[6]); // Description: // Set/Get the maximum number of pieces that can be requested. // The maximum number of pieces is meta data for unstructured data sets. // It gets set by the source during the update information call. // A value of -1 indicates that there is no maximum. A value of virtual void SetMaximumNumberOfPieces(int); virtual int GetMaximumNumberOfPieces(); // Description: // Copy information about this data object to the output // information from its own Information for the given // request. If the second argument is not NULL then it is the // pipeline information object for the input to this data object's // producer. If forceCopy is true, information is copied even // if it exists in the output. virtual void CopyInformationToPipeline(vtkInformation* request, vtkInformation* input, vtkInformation* output, int forceCopy); // Description: // Calls CopyInformationToPipeline(request, input, this->PipelineInformation, 0). // Subclasses should not override this method (not virtual) void CopyInformationToPipeline(vtkInformation* request, vtkInformation* input) { this->CopyInformationToPipeline(request, input, this->PipelineInformation, 0); } // Description: // Copy information about this data object from the // PipelineInformation to its own Information for the given request. virtual void CopyInformationFromPipeline(vtkInformation* request); // Description: // Return the information object within the input information object's // field data corresponding to the specified association // (FIELD_ASSOCIATION_POINTS or FIELD_ASSOCIATION_CELLS) and attribute // (SCALARS, VECTORS, NORMALS, TCOORDS, or TENSORS) static vtkInformation *GetActiveFieldInformation(vtkInformation *info, int fieldAssociation, int attributeType); // Description: // Return the information object within the input information object's // field data corresponding to the specified association // (FIELD_ASSOCIATION_POINTS or FIELD_ASSOCIATION_CELLS) and name. static vtkInformation *GetNamedFieldInformation(vtkInformation *info, int fieldAssociation, const char *name); // Description: // Remove the info associated with an array static void RemoveNamedFieldInformation(vtkInformation *info, int fieldAssociation, const char *name); // Description: // Set the named array to be the active field for the specified type // (SCALARS, VECTORS, NORMALS, TCOORDS, or TENSORS) and association // (FIELD_ASSOCIATION_POINTS or FIELD_ASSOCIATION_CELLS). Returns the // active field information object and creates on entry if one not found. static vtkInformation *SetActiveAttribute(vtkInformation *info, int fieldAssociation, const char *attributeName, int attributeType); // Description: // Set the name, array type, number of components, and number of tuples // within the passed information object for the active attribute of type // attributeType (in specified association, FIELD_ASSOCIATION_POINTS or // FIELD_ASSOCIATION_CELLS). If there is not an active attribute of the // specified type, an entry in the information object is created. If // arrayType, numComponents, or numTuples equal to -1, or name=NULL the // value is not changed. static void SetActiveAttributeInfo(vtkInformation *info, int fieldAssociation, int attributeType, const char *name, int arrayType, int numComponents, int numTuples); // Description: // Convenience version of previous method for use (primarily) by the Imaging // filters. If arrayType or numComponents == -1, the value is not changed. static void SetPointDataActiveScalarInfo(vtkInformation *info, int arrayType, int numComponents); // Description: // This method is called by the source when it executes to generate data. // It is sort of the opposite of ReleaseData. // It sets the DataReleased flag to 0, and sets a new UpdateTime. void DataHasBeenGenerated(); // Description: // make the output data ready for new data to be inserted. For most // objects we just call Initialize. But for vtkImageData we leave the old // data in case the memory can be reused. virtual void PrepareForNewData() {this->Initialize();}; // Description: // Shallow and Deep copy. These copy the data, but not any of the // pipeline connections. virtual void ShallowCopy(vtkDataObject *src); virtual void DeepCopy(vtkDataObject *src); // Description: // An object that will translate pieces into structured extents. void SetExtentTranslator(vtkExtentTranslator* translator); vtkExtentTranslator* GetExtentTranslator(); // Description: // The ExtentType will be left as VTK_PIECES_EXTENT for data objects // such as vtkPolyData and vtkUnstructuredGrid. The ExtentType will be // changed to VTK_3D_EXTENT for data objects with 3D structure such as // vtkImageData (and its subclass vtkStructuredPoints), vtkRectilinearGrid, // and vtkStructuredGrid. The default is the have an extent in pieces, // with only one piece (no streaming possible). virtual int GetExtentType() { return VTK_PIECES_EXTENT; }; // Description: // This method crops the data object (if necesary) so that the extent // matches the update extent. virtual void Crop(); //BTX // Description: // Possible values for the FIELD_ASSOCIATION information entry. enum FieldAssociations { FIELD_ASSOCIATION_POINTS, FIELD_ASSOCIATION_CELLS, FIELD_ASSOCIATION_NONE, FIELD_ASSOCIATION_POINTS_THEN_CELLS, FIELD_ASSOCIATION_VERTICES, FIELD_ASSOCIATION_EDGES, NUMBER_OF_ASSOCIATIONS }; //ETX //BTX // Description: // Possible values for the FIELD_OPERATION information entry. enum FieldOperations { FIELD_OPERATION_PRESERVED, FIELD_OPERATION_REINTERPOLATED, FIELD_OPERATION_MODIFIED, FIELD_OPERATION_REMOVED }; //ETX // Description: // Given an integer association type, this static method returns a string type // for the attribute (i.e. type = 0: returns "Points"). static const char* GetAssociationTypeAsString(int associationType); static vtkInformationStringKey* DATA_TYPE_NAME(); static vtkInformationDataObjectKey* DATA_OBJECT(); static vtkInformationIntegerKey* DATA_EXTENT_TYPE(); static vtkInformationIntegerPointerKey* DATA_EXTENT(); static vtkInformationIntegerKey* DATA_PIECE_NUMBER(); static vtkInformationIntegerKey* DATA_NUMBER_OF_PIECES(); static vtkInformationIntegerKey* DATA_NUMBER_OF_GHOST_LEVELS(); static vtkInformationDoubleVectorKey* DATA_TIME_STEPS(); static vtkInformationInformationVectorKey* POINT_DATA_VECTOR(); static vtkInformationInformationVectorKey* CELL_DATA_VECTOR(); static vtkInformationInformationVectorKey* VERTEX_DATA_VECTOR(); static vtkInformationInformationVectorKey* EDGE_DATA_VECTOR(); static vtkInformationIntegerKey* FIELD_ARRAY_TYPE(); static vtkInformationIntegerKey* FIELD_ASSOCIATION(); static vtkInformationIntegerKey* FIELD_ATTRIBUTE_TYPE(); static vtkInformationIntegerKey* FIELD_ACTIVE_ATTRIBUTE(); static vtkInformationIntegerKey* FIELD_NUMBER_OF_COMPONENTS(); static vtkInformationIntegerKey* FIELD_NUMBER_OF_TUPLES(); static vtkInformationIntegerKey* FIELD_OPERATION(); static vtkInformationDoubleVectorKey* FIELD_RANGE(); static vtkInformationStringKey* FIELD_NAME(); static vtkInformationDoubleVectorKey* ORIGIN(); static vtkInformationDoubleVectorKey* SPACING(); static vtkInformationIntegerKey* DATA_GEOMETRY_UNMODIFIED(); //BTX // Description: // Retrieve an instance of this class from an information object. static vtkDataObject* GetData(vtkInformation* info); static vtkDataObject* GetData(vtkInformationVector* v, int i=0); //ETX protected: vtkDataObject(); ~vtkDataObject(); // General field data associated with data object vtkFieldData *FieldData; // Who generated this data as output? vtkSource *Source; // Keep track of data release during network execution int DataReleased; // When was this data last generated? vtkTimeStamp UpdateTime; // Get the executive that manages this data object. vtkExecutive* GetExecutive(); // Get the port number producing this data object. int GetPortNumber(); virtual void ReportReferences(vtkGarbageCollector*); // Arbitrary extra information associated with this data object. vtkInformation* Information; // Reference the pipeline information object that owns this data // object. vtkInformation* PipelineInformation; //BTX // Check whether this data object is owned by a vtkStreamingDemandDrivenPipeline. vtkStreamingDemandDrivenPipeline* TrySDDP(const char* method); typedef vtkStreamingDemandDrivenPipeline SDDP; //ETX //BTX friend class vtkStreamingDemandDrivenPipelineToDataObjectFriendship; //ETX static const char AssociationNames[NUMBER_OF_ASSOCIATIONS][55]; private: // Helper method for the ShallowCopy and DeepCopy methods. void InternalDataObjectCopy(vtkDataObject *src); private: vtkDataObject(const vtkDataObject&); // Not implemented. void operator=(const vtkDataObject&); // Not implemented. }; #endif
[ "nnsmit@9b22acdf-97ab-464f-81e2-08fcc4a6931f" ]
[ [ [ 1, 536 ] ] ]
fd4926fa85a7fb73dbf7c52a9d57fa2b1990c68d
dde32744a06bb6697823975956a757bd6c666e87
/bwapi/SCProjects/BTHAIModule/Source/CommandCenterAgent.h
dc44936b13764cf5ff9f369c4140051eb563cfd9
[]
no_license
zarac/tgspu-bthai
30070aa8f72585354ab9724298b17eb6df4810af
1c7e06ca02e8b606e7164e74d010df66162c532f
refs/heads/master
2021-01-10T21:29:19.519754
2011-11-16T16:21:51
2011-11-16T16:21:51
2,533,389
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
#ifndef __COMMANDCENTERAGENT_H__ #define __COMMANDCENTERAGENT_H__ #include <BWAPI.h> #include "StructureAgent.h" using namespace BWAPI; using namespace std; /** The CommandCenterAgent handles Terran Command Center buildings. * * Implemented abilities: * - Trains and keeps the number of SCVs (workers) up. Is implemented in levels * where the preferred number of SCVs are higher at higher levels, i.e. later in * the game. * * Author: Johan Hagelback ([email protected]) */ class CommandCenterAgent : public StructureAgent { private: int idealNoWorkers; int level; int hasAddon; UnitType toBuild; bool hasSentWorkers; public: CommandCenterAgent(Unit* mUnit); /** Called each update to issue orders. */ void computeActions(); /** Returns the unique type name for structure agents. */ string getTypeName(); /** Used when building an addon. */ void assignToBuild(UnitType type); }; #endif
[ "rymdpung@.(none)" ]
[ [ [ 1, 41 ] ] ]
b8f0a9f3faf7d5bcc885bd06fd1ef32c14839f40
a84c570acf51a4ddb0ae10c20325370513a4eff4
/Client/src/util/mp3.h
399d3e15b6801127c7e5c16f5faeaf87a9371b48
[]
no_license
tustin2121/Petri-Wars
5b2db2cbeee978faea3fa0d10dc5eec31d87c596
a71cbcb5b997e7de03f75825ee79e36b4ff1ea1d
refs/heads/master
2020-12-25T08:29:24.108805
2011-05-20T00:58:10
2011-05-20T00:58:10
1,763,910
0
0
null
null
null
null
UTF-8
C++
false
false
1,909
h
/*=============================================== -= [url=http://www.poke646.com].:: Poke646 ::.&nbsp;&nbsp;&nbsp;A Half-Life Singleplayer Modification[/url] =- The same old trouble in a brand new environment MP3 player headerfile TheTinySteini ===============================================*/ #include "PetriWars/sound/fmod.h" #include "PetriWars/sound/fmod_errors.h" #ifdef _WIN32 #include "windows.h" #endif class Sound{ private: //system, sound, channel, result FMOD_SYSTEM *system; FMOD_SOUND *sound[5]; //Array of sound files FMOD_CHANNEL *channel; //multiple sounds overlapping FMOD_RESULT result; //comes up with error - put into error check int playing_; public: Sound(); //Constructor loads the sounds ready to be used in the program ~Sound(); //Destructor is important for releasing memory back into the system int get_playing() {return playing_;} //Return playing void play_sound(int a, bool b); //select the sound, and if paused is true/false void is_playing(); //Check if a sound is playing void update(); //Update the sound }; //class CMP3 //{ //private: // //signed char (_stdcall * SCL) (FSOUND_STREAM *stream); // signed char (_stdcall * SOP) (int outputtype); // signed char (_stdcall * SBS) (int len_ms); // signed char (_stdcall * SDRV) (int driver); // signed char (_stdcall * INIT) (int mixrate, int maxsoftwarechannels, unsigned int flags); // //FSOUND_STREAM* (_stdcall * SOF) (const char *filename, unsigned int mode, int memlength); // //int (_stdcall * SPLAY) (int channel, FSOUND_STREAM *stream); // void (_stdcall * CLOSE) ( void ); // // //FSOUND_STREAM *m_Stream; // int m_iIsPlaying; // HINSTANCE m_hFMod; // //public: // int Initialize(); // int Shutdown(); // int PlayMP3( const char *pszSong ); // int StopMP3(); //}; // //extern CMP3 gMP3;
[ [ [ 1, 56 ] ] ]
dfcc1e27ac17288787e2ae39be5165d5efba31f2
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/WayFinder/symbian-r6/RouteContainer.cpp
d61f3e1542157843de893199c938c3e642dcc95f
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
24,661
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // INCLUDE FILES #include <eiklabel.h> // for labels #include <eikedwin.h> // for edwin text boxes #include <eikmfne.h> #include <barsread.h> // for resource reader #include <gulcolor.h> // for color #include <aknutils.h> // for fonts #include <txtfmlyr.h> #include <aknlayoutfont.h> #include "RsgInclude.h" #include "wficons.mbg" #include "RouteContainer.h" #include "WayFinderConstants.h" #include "InfoCompass.h" #include "memlog.h" #include "RouteView.h" #include "WFTextUtil.h" #include "DistancePrintingPolicy.h" #include "WFLayoutUtils.h" #include "WayFinderAppUi.h" #include "RectTools.h" #include <e32std.h> #if defined NAV2_CLIENT_SERIES60_V2 # include <aknsdrawutils.h> #endif #define SHORT_INFO_LABEL_WIDTH 65 #define MARGIN 5 #define SHORT_INFO_LABEL_LENGTH_IN_CHARS 8 #define SCREEN_WIDTH 176 #define DESTINATION_INFO_LABEL_POS TPoint(MARGIN, 20) #define DISTANCE_INFO_LABEL_POS TPoint(MARGIN, 54) #define ETG_INFO_LABEL_POS TPoint(MARGIN, 89) #define ETA_INFO_LABEL_POS TPoint(MARGIN, 124) #define SPEED_INFO_LABEL_POS TPoint(SCREEN_WIDTH-(MARGIN*2+SHORT_INFO_LABEL_WIDTH+2), 54) #define DESTINATION_LABEL_POS TPoint(MARGIN, 4) #define DISTANCE_LABEL_POS TPoint(MARGIN, 38) #define ETG_LABEL_POS TPoint(MARGIN, 72) #define ETA_LABEL_POS TPoint(MARGIN, 107) #define SPEED_LABEL_POS TPoint(SCREEN_WIDTH-(MARGIN*2+SHORT_INFO_LABEL_WIDTH+2), 38) #define COMPASS_CTRL_POS TPoint(SCREEN_WIDTH-(MARGIN+SHORT_INFO_LABEL_WIDTH+2+2), 81) #define COMPASS_SIZE TSize( 60, 60 ) #if defined NAV2_CLIENT_SERIES60_V3 # define COMPASS_IMAGE EMbmWficonsCompass # define COMPASS_IMAGE_M EMbmWficonsCompass_mask # define COMPASS_IMAGE_NIGHT EMbmWficonsCompass_red; # define COMPASS_IMAGE_NIGHT_M EMbmWficonsCompass_red_mask; #else # define COMPASS_IMAGE EMbmWficonsCompass60 # define COMPASS_IMAGE_M EMbmWficonsCompass60_mask # define COMPASS_IMAGE_NIGHT EMbmWficonsCompass60_red; # define COMPASS_IMAGE_NIGHT_M EMbmWficonsCompass60_mask; #endif using namespace isab; _LIT( K1Number, " %i" ); _LIT( K2Numbers, " %i" ); _LIT( K3Numbers, "%i" ); _LIT( KDistanceM, "%i m" ); _LIT( KDistanceK, "%i.%i km" ); _LIT( KDistanceKK, "%i km" ); _LIT( KSpeed1, " %i" ); // Enumarations enum TControls { ESpeedLabel, ESpeedInfoLabel, EDestinationLabel, EDestinationInfoLabel, EDistanceLabel, EDistanceInfoLabel, EETGLabel, EETGInfoLabel, EETALabel, EETAInfoLabel, ECompassControl, ENumberControls }; // ================= MEMBER FUNCTIONS ======================= class CRouteContainer* CRouteContainer::NewL(CRouteView* aParent, const TRect& aRect, const TDesC& aMbmName, isab::Log* aLog, class CWayFinderAppUi* aAppUi) { class CRouteContainer* self = new (ELeave) CRouteContainer(aLog); CleanupStack::PushL(self); self->SetMopParent(aParent); self->ConstructL(aParent, aRect, aMbmName, aAppUi); CleanupStack::Pop(self); return self; } // --------------------------------------------------------- // CRouteContainer::ConstructL(const TRect& aRect) // EPOC two phased constructor // --------------------------------------------------------- // void CRouteContainer::ConstructL(CRouteView* aView, const TRect& aRect, const TDesC& aMbmName, class CWayFinderAppUi* aAppUi) { iView = aView; CreateWindowL(); iMbmName = aMbmName.Alloc(); iAppUi = aAppUi; HBufC* tmp = HBufC::NewL(2); tmp->Des().Copy(_L(" ")); HBufC* text; text = iCoeEnv->AllocReadResourceLC( R_DESTINATION_DESTINATION_LABEL ); iDestinationLabel = new (ELeave) CEikLabel; LOGNEW(iDestinationLabel, CEikLabel); SetUpLabel(iDestinationLabel, text, *this); CleanupStack::PopAndDestroy( text ); iDestinationInfoLabel = new (ELeave) CEikLabel; LOGNEW(iDestinationInfoLabel, CEikLabel); SetUpLabel(iDestinationInfoLabel, tmp, *this); text = iCoeEnv->AllocReadResourceLC( R_DESTINATION_DISTANCE_LABEL ); iDistanceLabel = new (ELeave) CEikLabel; LOGNEW(iDistanceLabel, CEikLabel); SetUpLabel(iDistanceLabel, text, *this); CleanupStack::PopAndDestroy(text); iDistanceInfoLabel = new (ELeave) CEikLabel; LOGNEW(iDistanceInfoLabel, CEikLabel); SetUpLabel(iDistanceInfoLabel, tmp, *this); text = iCoeEnv->AllocReadResourceLC( R_WAYFINDER_DESTINATION_ETA_LABEL ); iETALabel = new (ELeave) CEikLabel; LOGNEW(iETALabel, CEikLabel); SetUpLabel(iETALabel, text, *this); CleanupStack::PopAndDestroy(text); text = iCoeEnv->AllocReadResourceLC( R_WAYFINDER_DESTINATION_ETG_LABEL ); iETGLabel = new (ELeave) CEikLabel; LOGNEW(iETGLabel, CEikLabel); SetUpLabel(iETGLabel, text, *this); CleanupStack::PopAndDestroy(text); #undef _SHOW_DURATION_ #ifdef _SHOW_DURATION_ iCoeEnv->CreateResourceReaderLC(reader, R_WAYFINDER_DESTINATION_ETG_DURATION ); iDurationETG = new (ELeave) CEikDurationEditor; LOGNEW(iDurationETG, CEikDurationEditor); iDurationETG->SetContainerWindowL(*this); iDurationETG->ConstructFromResourceL(reader); iDurationETG->SetBorder(TGulBorder::ENone); TTimeIntervalSeconds duration(0); iDurationETG->SetDuration(duration); #else iETGInfoLabel = new (ELeave) CEikLabel; LOGNEW(iETGInfoLabel, CEikLabel); SetUpLabel(iETGInfoLabel, tmp, *this); #endif iETAInfoLabel = new (ELeave) CEikLabel; LOGNEW(iETAEdwin, CEikLabel); SetUpLabel(iETAInfoLabel, tmp, *this); text = iCoeEnv->AllocReadResourceLC( R_INFO_SPEED_LABEL ); iSpeedLabel = new (ELeave) CEikLabel; LOGNEW(iSpeedLabel, CEikLabel); SetUpLabel(iSpeedLabel, text, *this); CleanupStack::PopAndDestroy(text); iSpeedInfoLabel = new (ELeave) CEikLabel; LOGNEW(iSpeedInfoLabel, CEikLabel); SetUpLabel(iSpeedInfoLabel, tmp, *this); if (iView->IsIronVersion()) { iSpeedLabel->MakeVisible(EFalse); iSpeedInfoLabel->MakeVisible(EFalse); } SetNightModeL(iAppUi->IsNightMode()); // iAppUi->GetBackgroundColor(iR, iG, iB); SetRect(aRect); ActivateL(); } // Destructor CRouteContainer::~CRouteContainer() { delete iCompass; delete iETGLabel; delete iETALabel; delete iDistanceLabel; delete iDestinationLabel; delete iSpeedLabel; delete iETGInfoLabel; delete iETAInfoLabel; delete iDurationETG; delete iDistanceInfoLabel; delete iDestinationInfoLabel; delete iSpeedInfoLabel; delete iMbmName; } void CRouteContainer::SetHeading( TInt aHeading ) { iCompass->SetHeading( aHeading ); } void CRouteContainer::SetSpeed( TInt aSpeed ) { TBuf<64> text( _L("-") ); if( aSpeed > -1 ){ if( aSpeed < 10 ) { text.Format( K1Number, aSpeed ); } else if( aSpeed < 100 ) { text.Format( K2Numbers, aSpeed ); } else { text.Format( K3Numbers, aSpeed ); } HBufC* tmp; switch (iView->GetDistanceMode()) { case DistancePrintingPolicy::ModeImperialYards: case DistancePrintingPolicy::ModeImperialFeet: tmp = iCoeEnv->AllocReadResourceLC( R_INFO_MPH_LABEL ); break; case DistancePrintingPolicy::ModeInvalid: case DistancePrintingPolicy::ModeMetric: default: tmp = iCoeEnv->AllocReadResourceLC( R_INFO_KMH_LABEL ); break; } text.Append(*tmp); CleanupStack::PopAndDestroy(tmp); } TRect oldRect = iSpeedInfoLabel->Rect(); iSpeedInfoLabel->SetTextL( text ); PositionOfControlChanged(iSpeedInfoLabel, iSpeedInfoLabel->Position()); Window().Invalidate(Shrink(oldRect, -3)); Window().Invalidate(Shrink(iSpeedInfoLabel->Rect(), -3)); } void CRouteContainer::SetDestination( TDesC &aDestination ) { TBuf<KBuf64Length> destination; destination.Zero(); if (aDestination.Length() > destination.MaxLength()-2) { destination.Copy( aDestination.Ptr(), destination.MaxLength()-2 ); destination.PtrZ(); } else { destination.Copy(aDestination); } TRect oldRect = iDestinationInfoLabel->Rect(); iDestinationInfoLabel->SetTextL( destination ); PositionOfControlChanged(iDestinationInfoLabel, iDestinationInfoLabel->Position()); Window().Invalidate(Shrink(oldRect, -3)); Window().Invalidate(Shrink(iDestinationInfoLabel->Rect(), -3)); } void CRouteContainer::SetDistanceToGoal( TInt32 aDistance ) { TBuf<32> text(_L("")); if( aDistance == MAX_INT32 || aDistance <= 0 ){ //Invalid distance. text.Copy(_L(" ")); } else { DistancePrintingPolicy::DistanceMode mode = DistancePrintingPolicy::DistanceMode(iView->GetDistanceMode()); char* tmp2 = DistancePrintingPolicy::convertDistance(aDistance, mode); if (tmp2) { WFTextUtil::char2TDes(text, tmp2); delete[] tmp2; } else { text.Copy(_L(" ")); } } TRect oldRect = iDistanceInfoLabel->Rect(); iDistanceInfoLabel->SetTextL( text ); PositionOfControlChanged(iDistanceInfoLabel, iDistanceInfoLabel->Position()); Window().Invalidate(Shrink(oldRect, -3)); Window().Invalidate(Shrink(iDistanceInfoLabel->Rect(), -3)); } void CRouteContainer::SetETG( TInt32 aTime ) { #ifdef _SHOW_DURATION_ iDurationETG->SetDuration( aTime ); #else { TBuf<16> text; TBuf<16> appendedText; text.Copy( _L("") ); TInt32 myTime = aTime; if (myTime <= 0) { // Nothing. } else if (myTime < 30) { // Seconds! text.AppendNum( myTime, EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_SEC ); text.Append( appendedText ); } else if (myTime < 3600) { // Minutes, rounded up. myTime += 30; myTime /= 60; text.AppendNum( myTime, EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_MIN ); text.Append( appendedText ); } else if (myTime < 36000) { myTime += 30; myTime /= 60; TInt32 houres = myTime/60; myTime -= houres*60; text.AppendNum( houres, EDecimal ); #ifdef _DECIMAL_MINUTES_ // Hours, with decimal. myTime = (myTime/60)*10; text.Append( _L(".") ); text.AppendNum( myTime, EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_HOURS ); text.Append( appendedText ); #else // Hours, with minutes. iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_HOURS ); text.Append( appendedText ); text.AppendNum( myTime, EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_MIN ); text.Append( appendedText ); #endif } else if (myTime < 172800) { // Hours, no decimals. myTime /= 3600; text.AppendNum( myTime, EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_HOURS ); text.Append( appendedText ); } else if (myTime < 604800) { // Days, with decimal. myTime /= 8640; text.AppendNum( (myTime/10), EDecimal ); text.Append( _L(".") ); text.AppendNum( (myTime%10), EDecimal ); iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_DAYS ); text.Append( appendedText ); } else { iCoeEnv->ReadResource( appendedText, R_TEXT_ROUTEV_ETG_WEEKS ); text.Append( appendedText ); } TRect oldRect = iETGInfoLabel->Rect(); iETGInfoLabel->SetTextL( text ); PositionOfControlChanged(iETGInfoLabel, iETGInfoLabel->Position()); Window().Invalidate(Shrink(oldRect, -3)); Window().Invalidate(Shrink(iETGInfoLabel->Rect(), -3)); } #endif TBuf<30> text; text.Copy( _L("") ); if (aTime <= 0) { // Nothing. } else { TTime now; now.HomeTime(); now += (TTimeIntervalSeconds)aTime; _LIT(KDateString,"%-B%:0%J%:1%T%:3%+B"); now.FormatL(text, KDateString); } TRect oldRect = iETAInfoLabel->Rect(); iETAInfoLabel->SetTextL(text); PositionOfControlChanged(iETAInfoLabel, iETAInfoLabel->Position()); Window().Invalidate(Shrink(oldRect, -3)); Window().Invalidate(Shrink(iETAInfoLabel->Rect(), -3)); } // --------------------------------------------------------- // CRouteContainer::SizeChanged() // Called by framework when the view size is changed // --------------------------------------------------------- // void CRouteContainer::SizeChanged() { // Position out the different components TRect viewRect = Rect(); if (WFLayoutUtils::WideScreen()) { // If wide screen, center the view rect. TRect rect = WFLayoutUtils::GetMainPaneRect(ETrue, 60); viewRect.iBr.iX = rect.iBr.iX; viewRect.iTl.iX = rect.iTl.iX; } if(iCompass){ iCompass->SetRect(LowerRight(viewRect, iCompass->MinimumSize())); } // Number of lines with components that should be drawn to the screen. TInt numParts = 8; // The height of each component TInt partHeight = viewRect.Height() / numParts; // Left margin TInt xMargin = 8 + viewRect.iTl.iX; // The position of a component, starts with the one at the top. TPoint pos(xMargin, viewRect.iTl.iY); // Size of a component TSize size(viewRect.Width(), partHeight); // Position out each component, start with the one at the top. // Increase pos for each line. if( iDestinationLabel ){ PositionOfControlChanged(iDestinationLabel, pos); pos.iY += size.iHeight; } if( iDestinationInfoLabel ){ PositionOfControlChanged(iDestinationInfoLabel, pos); pos.iY += size.iHeight; } if( iSpeedLabel ){ // Speed label should be positioned at the same height as the // DestinationInfoLabel but its x coord will be 55% of the screen // width PositionOfControlChanged(iSpeedLabel, TPoint(TInt(viewRect.Width() * 0.55), pos.iY)); } if( iDistanceLabel ){ PositionOfControlChanged(iDistanceLabel, pos); pos.iY += size.iHeight; } if( iSpeedInfoLabel ){ // Speed info label should be positioned at the same height as the // DestinationLabel but its x coord will be 55% of the screen // width TInt xPos; if(iSpeedLabel) { xPos = iSpeedLabel->Position().iX; } else { xPos = TInt(viewRect.Width() * 0.55); } PositionOfControlChanged(iSpeedInfoLabel, TPoint(xPos, pos.iY)); } if( iDistanceInfoLabel ){ PositionOfControlChanged(iDistanceInfoLabel, pos); pos.iY += size.iHeight; } if (iETGLabel) { PositionOfControlChanged(iETGLabel, pos); pos.iY += size.iHeight; } if (iETGInfoLabel) { PositionOfControlChanged(iETGInfoLabel, pos); pos.iY += size.iHeight; } if (iETALabel) { PositionOfControlChanged(iETALabel, pos); pos.iY += size.iHeight; } if (iETAInfoLabel) { PositionOfControlChanged(iETAInfoLabel, pos); pos.iY += size.iHeight; } } void CRouteContainer::PositionOfControlChanged(CCoeControl *control, TPoint pos) { const CAknLayoutFont* font = AknLayoutUtils::LayoutFontFromId(EAknLogicalFontPrimaryFont); TSize size = control->MinimumSize(); size.iHeight = font->TextPaneHeight(); control->SetExtent(pos, size); } // --------------------------------------------------------- // CRouteContainer::CountComponentControls() const // --------------------------------------------------------- // TInt CRouteContainer::CountComponentControls() const { return ENumberControls; // return nbr of controls inside this container } // --------------------------------------------------------- // CRouteContainer::ComponentControl(TInt aIndex) const // --------------------------------------------------------- // CCoeControl* CRouteContainer::ComponentControl(TInt aIndex) const { switch ( aIndex ) { case ESpeedLabel: return iSpeedLabel; case ESpeedInfoLabel: return iSpeedInfoLabel; case EETALabel: return iETALabel; case EETAInfoLabel: return iETAInfoLabel; case EETGLabel: return iETGLabel; case EETGInfoLabel: #ifdef _SHOW_DURATION_ return iDurationETG; #else return iETGInfoLabel; #endif case ECompassControl: return iCompass; case EDistanceLabel: return iDistanceLabel; case EDistanceInfoLabel: return iDistanceInfoLabel; case EDestinationLabel: return iDestinationLabel; case EDestinationInfoLabel: return iDestinationInfoLabel; default: return NULL; } } // --------------------------------------------------------- // CRouteContainer::Draw(const TRect& aRect) const // --------------------------------------------------------- // void CRouteContainer::Draw(const TRect& aRect) const { CWindowGc& gc = SystemGc(); gc.SetPenStyle(CGraphicsContext::ENullPen); // gc.SetBrushColor( TRgb( KBackgroundRed, KBackgroundGreen, KBackgroundBlue ) ); gc.SetBrushColor( TRgb( iR, iG, iB ) ); gc.SetBrushStyle(CGraphicsContext::ESolidBrush); gc.DrawRect(aRect); gc.SetPenStyle(CGraphicsContext::ESolidPen); gc.SetPenColor(iBubblePenColor); gc.SetBrushColor(iBubbleBgColor); //the labels that will have bubbles. class CCoeControl* bubbles[] = { iDestinationInfoLabel, iDistanceInfoLabel, iETGInfoLabel, iETAInfoLabel, iSpeedInfoLabel }; size_t num = sizeof(bubbles)/sizeof(*bubbles); for(size_t a = 0; a < num; ++a){ TRect rect = bubbles[a]->Rect(); if(rect.Intersects(aRect)){ gc.DrawRoundRect(Shrink(rect, TSize(-3,-1)), TSize(8,8)); } } } // --------------------------------------------------------- // CRouteContainer::HandleControlEventL( // CCoeControl* aControl,TCoeEvent aEventType) // --------------------------------------------------------- // void CRouteContainer::HandleControlEventL( CCoeControl* /*aControl*/, TCoeEvent /*aEventType*/) { // TODO: Add your control event handler code here } void CRouteContainer::SetUpLabel(class CEikLabel* aLabel, HBufC* aText, class CCoeControl& aContainerWindow) { aLabel->SetContainerWindowL(aContainerWindow); #ifdef NAV2_CLIENT_SERIES60_V3 aLabel->SetFont(AknLayoutUtils::FontFromId(EAknLogicalFontPrimaryFont)); #else aLabel->SetFont(LatinBold12()); #endif if (aText) { aLabel->SetTextL(*aText); } } void CRouteContainer::HandleResourceChange(TInt aType) { CCoeControl::HandleResourceChange(aType); if (aType == KEikDynamicLayoutVariantSwitch) { TBool wideScreen = WFLayoutUtils::WideScreen(); iCompass->SetCompassSizeAndPos(TRect(WFLayoutUtils::CalculatePosUsingMainPane(COMPASS_CTRL_POS, wideScreen), WFLayoutUtils::CalculateSizeUsingMainPane(COMPASS_SIZE, wideScreen))); SetRect(WFLayoutUtils::GetMainPaneRect()); } } void CRouteContainer::SetNightModeL(TBool aNightMode) { iAppUi->GetBackgroundColor(iR, iG, iB); TRgb textColor; TRgb northArrowColor; TRgb southArrowColor; TInt compassImage; TInt compassImageMask; if (aNightMode) { textColor = KRgbRed; iBubblePenColor = TRgb(0x30, 0x30, 0x30); iBubbleBgColor = TRgb(0x30, 0x30, 0x30); compassImage = COMPASS_IMAGE_NIGHT; compassImageMask = COMPASS_IMAGE_NIGHT_M; northArrowColor = KRgbGray; southArrowColor = KRgbRed; } else { textColor = KRgbBlack; iBubblePenColor = KRgbDarkGray; iBubbleBgColor = KRgbWhite; compassImage = COMPASS_IMAGE; compassImageMask = COMPASS_IMAGE_M; northArrowColor = TRgb(255,255,255), southArrowColor = TRgb(100,100,255); } iDestinationLabel->OverrideColorL(EColorLabelText, textColor); iDistanceLabel->OverrideColorL(EColorLabelText, textColor); iETALabel->OverrideColorL(EColorLabelText, textColor); iETGLabel->OverrideColorL(EColorLabelText, textColor); iSpeedLabel->OverrideColorL(EColorLabelText, textColor); iDestinationInfoLabel->OverrideColorL(EColorLabelText, textColor); iDistanceInfoLabel->OverrideColorL(EColorLabelText, textColor); iETAInfoLabel->OverrideColorL(EColorLabelText, textColor); iETGInfoLabel->OverrideColorL(EColorLabelText, textColor); iSpeedInfoLabel->OverrideColorL(EColorLabelText, textColor); TBool wideScreen = WFLayoutUtils::WideScreen(); if (!iCompass) { iCompass = CInfoCompass::NewL(*this, TRect(WFLayoutUtils:: CalculatePosUsingMainPane(COMPASS_CTRL_POS, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPane(COMPASS_SIZE, wideScreen)), *iMbmName, compassImage, compassImageMask, EFalse, northArrowColor, southArrowColor); } else { iCompass->SetNewImage(TRect(WFLayoutUtils:: CalculatePosUsingMainPane(COMPASS_CTRL_POS, wideScreen), WFLayoutUtils:: CalculateSizeUsingMainPane(COMPASS_SIZE, wideScreen)), *iMbmName, compassImage, compassImageMask, EFalse, northArrowColor, southArrowColor); } } // End of File
[ [ [ 1, 715 ] ] ]