int CDVDOverlayCodecText::Decode(DemuxPacket *pPacket) { if(m_pOverlay) SAFE_RELEASE(m_pOverlay); if(!pPacket) return OC_ERROR; uint8_t *data = pPacket->pData; int size = pPacket->iSize; m_pOverlay = new CDVDOverlayText(); CDVDOverlayCodec::GetAbsoluteTimes(m_pOverlay->iPTSStartTime, m_pOverlay->iPTSStopTime, pPacket, m_pOverlay->replace); char *start, *end, *p; start = (char*)data; end = (char*)data + size; p = (char*)data; if (m_bIsSSA) { // currently just skip the prefixed ssa fields (8 fields) int nFieldCount = 8; while (nFieldCount > 0 && start < end) { if (*start == ',') nFieldCount--; start++; p++; } } CDVDSubtitleTagSami TagConv; bool Taginit = TagConv.Init(); while(p<end) { if(*p == '{') { if(p>start) { if(Taginit) TagConv.ConvertLine(m_pOverlay, start, p-start); else m_pOverlay->AddElement(new CDVDOverlayText::CElementText(start, p-start)); } start = p+1; while(*p != '}' && p<end) p++; char* override = (char*)malloc(p-start + 1); memcpy(override, start, p-start); override[p-start] = '\0'; CLog::Log(LOGINFO, "%s - Skipped formatting tag %s", __FUNCTION__, override); free(override); start = p+1; } p++; }
void GdsResTexture::vClear() { SAFE_RELEASE( m_pTexture ); }
m_pD3DRenderTargetSurface->GetDesc(&desc); m_uiSurfaceSizeX = desc.Width; m_uiSurfaceSizeY = desc.Height; m_iMemoryKBUsed = CRenderItemManager::CalcD3DResourceMemoryKBUsage(m_pD3DRenderTargetSurface); } //////////////////////////////////////////////////////////////// // // CWebBrowserItem::ReleaseUnderlyingData // // // //////////////////////////////////////////////////////////////// void CWebBrowserItem::ReleaseUnderlyingData() { SAFE_RELEASE(m_pD3DRenderTargetSurface) SAFE_RELEASE(m_pD3DTexture) } void CWebBrowserItem::Resize(const CVector2D& size) { // Update size m_uiSizeX = static_cast<uint>(size.fX); m_uiSizeY = static_cast<uint>(size.fY); // Recreate texture ReleaseUnderlyingData(); CreateUnderlyingData(); }
//-------------------------------------------------------------------------------------- HRESULT CLoaderXFile::Load( WCHAR* szFileName, FRAME_TRANSFORM_TYPE requestedBHT ) { HRESULT hr = E_FAIL; ID3DXBuffer *pMat = NULL; ID3DXMesh *pRawMesh = NULL; ID3DXMesh *pMesh = NULL; DWORD cMat; IDirect3DDevice9* pDev9 = NULL; DWORD* pAdjBuffer = NULL; // Create a d3d9 object IDirect3D9* pD3D9 = Direct3DCreate9( D3D_SDK_VERSION ); if( pD3D9 == NULL ) return E_FAIL; D3DPRESENT_PARAMETERS pp; pp.BackBufferWidth = 320; pp.BackBufferHeight = 240; pp.BackBufferFormat = D3DFMT_X8R8G8B8; pp.BackBufferCount = 1; pp.MultiSampleType = D3DMULTISAMPLE_NONE; pp.MultiSampleQuality = 0; pp.SwapEffect = D3DSWAPEFFECT_DISCARD; pp.hDeviceWindow = GetShellWindow(); pp.Windowed = true; pp.Flags = 0; pp.FullScreen_RefreshRateInHz = 0; pp.PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; pp.EnableAutoDepthStencil = false; hr = pD3D9->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_NULLREF, NULL, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &pp, &pDev9 ); if(FAILED(hr)) goto Error; if( szFileName ) { hr = D3DXLoadMeshFromX( szFileName, 0, pDev9, NULL, &pMat, NULL, &cMat, &pRawMesh ); if(FAILED(hr)) goto Error; } D3DVERTEXELEMENT9 declTanBi[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 }, { 0, 24, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 }, { 0, 32, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TANGENT, 0 }, { 0, 44, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_BINORMAL, 0 }, D3DDECL_END() }; D3DVERTEXELEMENT9* pdecl = declTanBi; // Make a clone with the desired vertex format. if( SUCCEEDED( pRawMesh->CloneMesh( D3DXMESH_32BIT | D3DXMESH_DYNAMIC, pdecl, pDev9, &m_pMesh ) ) ) { // Optimize pAdjBuffer = new DWORD[ 3*m_pMesh->GetNumFaces() ]; if( !pAdjBuffer ) { hr = E_OUTOFMEMORY; goto Error; } m_pMesh->GenerateAdjacency( 0.001f, pAdjBuffer ); m_pMesh->OptimizeInplace( D3DXMESHOPT_ATTRSORT, pAdjBuffer, NULL, NULL, NULL ); // Attributes m_pMesh->GetAttributeTable( NULL, &m_dwNumAttr ); if( m_dwNumAttr > 0 ) { m_pAttr = new D3DXATTRIBUTERANGE[m_dwNumAttr]; m_pMesh->GetAttributeTable( m_pAttr, &m_dwNumAttr ); } // Materials m_dwNumMaterials = cMat; if( m_dwNumMaterials > 0 ) { D3DXMATERIAL* pMaterialBuffer = (D3DXMATERIAL*)pMat->GetBufferPointer(); m_pMats = new D3DXMATERIAL[ m_dwNumMaterials ]; if( !m_pMats ) { hr = E_OUTOFMEMORY; goto Error; } for( DWORD m=0; m<m_dwNumMaterials; m++ ) { CopyMemory( &m_pMats[m], &pMaterialBuffer[m], sizeof(D3DXMATERIAL) ); } } // Create the intermediate mesh hr = CreateIntermediateMesh( declTanBi, 6 ); if(FAILED(hr)) goto Error; } hr = S_OK; Error: SAFE_RELEASE( pMat ); SAFE_RELEASE( pRawMesh ); SAFE_RELEASE( pMesh ); SAFE_RELEASE( pDev9 ); SAFE_RELEASE( pD3D9 ); SAFE_DELETE_ARRAY( pAdjBuffer ); return hr; }
// Format negotiation HRESULT CWASAPIRenderFilter::NegotiateFormat(const WAVEFORMATEXTENSIBLE* pwfx, int nApplyChangesDepth, ChannelOrder* pChOrder) { if (!pwfx) return VFW_E_TYPE_NOT_ACCEPTED; if (FormatsEqual(pwfx, m_pInputFormat)) { *pChOrder = m_chOrder; return S_OK; } bool bApplyChanges = nApplyChangesDepth != 0; bool bitDepthForced = (m_pSettings->GetForceBitDepth() != 0 && m_pSettings->GetForceBitDepth() != pwfx->Format.wBitsPerSample); bool sampleRateForced = (m_pSettings->GetForceSamplingRate() != 0 && m_pSettings->GetForceSamplingRate() != pwfx->Format.nSamplesPerSec); if ((bitDepthForced || sampleRateForced) && pwfx->SubFormat == KSDATAFORMAT_SUBTYPE_IEC61937_DOLBY_DIGITAL || pwfx->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT && bitDepthForced) return VFW_E_TYPE_NOT_ACCEPTED; if (((bitDepthForced && m_pSettings->GetForceBitDepth() != pwfx->Format.wBitsPerSample) || (sampleRateForced && m_pSettings->GetForceSamplingRate() != pwfx->Format.nSamplesPerSec))) return VFW_E_TYPE_NOT_ACCEPTED; CAutoLock lock(&m_csResources); HRESULT hr = CreateAudioClient(); if (FAILED(hr)) { Log("CWASAPIRenderFilter::NegotiateFormat Error, audio client not initialized: (0x%08x)", hr); return VFW_E_CANNOT_CONNECT; } WAVEFORMATEXTENSIBLE* pwfxAccepted = NULL; WAVEFORMATEXTENSIBLE outFormat = *pwfx; hr = IsFormatSupported(pwfx, &pwfxAccepted); // Try different speaker setup if (FAILED(hr)) { DWORD dwSpeakers = pwfx->dwChannelMask; if (dwSpeakers == KSAUDIO_SPEAKER_5POINT1) dwSpeakers = KSAUDIO_SPEAKER_5POINT1_SURROUND; else if (dwSpeakers == KSAUDIO_SPEAKER_5POINT1_SURROUND) dwSpeakers = KSAUDIO_SPEAKER_5POINT1; else if (dwSpeakers == KSAUDIO_SPEAKER_7POINT1) dwSpeakers = KSAUDIO_SPEAKER_7POINT1_SURROUND; else if (dwSpeakers == KSAUDIO_SPEAKER_7POINT1_SURROUND) dwSpeakers = KSAUDIO_SPEAKER_7POINT1; if (dwSpeakers != pwfx->dwChannelMask) { outFormat.dwChannelMask = dwSpeakers; hr = IsFormatSupported(&outFormat, &pwfxAccepted); } } if (FAILED(hr)) { SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; } if (bApplyChanges) { LogWaveFormat(&outFormat, "REN - applying "); // Stop and discard audio client StopAudioClient(); SAFE_RELEASE(m_pRenderClient); SAFE_RELEASE(m_pAudioClock); SAFE_RELEASE(m_pAudioClient); // We must use incoming format so the WAVEFORMATEXTENSIBLE to WAVEFORMATEXT difference // that some audio drivers require is not causing an infinite loop of format changes SetInputFormat(pwfx); SetOutputFormat(&outFormat); // Reinitialize audio client hr = CreateAudioClient(true); } else LogWaveFormat(pwfx, "Input format "); m_chOrder = *pChOrder = DS_ORDER; SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; }
bool SceneService::onInit() { _scene.reset(gameplay::Scene::create()); _scene->setAmbientColor(0.1f, 0.1f, 0.1f); _camera.reset(gameplay::Camera::createPerspective(30.0f, gameplay::Game::getInstance()->getAspectRatio(), 5.0f, 30.0f)); _scene->setActiveCamera(_camera.get()); _light.reset(gameplay::Light::createDirectional(0.9f, 0.9f, 0.9f)); gameplay::Node * cameraNode = _scene->addNode("Camera"); cameraNode->setCamera(_camera.get()); gameplay::Node * lightNode = _scene->addNode("Light"); lightNode->setLight(_light); lightNode->setRotation(gameplay::Vector3(1.0f, 0.0f, 0.0f), -MATH_PIOVER4); ServiceManager::getInstance()->signals.inputTouchEvent.connect(10, sigc::mem_fun(this, &SceneService::onTouchEvent)); ServiceManager::getInstance()->signals.inputMouseEvent.connect(10, sigc::mem_fun(this, &SceneService::onMouseEvent)); ServiceManager::getInstance()->signals.inputGesturePinchEvent.connect(10, sigc::mem_fun(this, &SceneService::onGesturePinchEvent)); getSettings()->sidebarWidthChangedSignal.connect(sigc::mem_fun(this, &SceneService::onSidebarWidthChanged)); _renderService = _manager->findService<RenderService>(); gameplay::Game::getInstance()->registerGesture(gameplay::Gesture::GESTURE_PINCH); PrimitivesPool::getInstance()->generatePrimitives(); _moleculeModel.reset(MoleculeModel::create(getSettings()->getMolecule())); insertNode(_moleculeModel->getRootNode()); _moleculeModel->modelChangedSignal.connect(sigc::mem_fun(this, &SceneService::moleculeChanged)); updateCamera(); _lastTime = static_cast< float >(gameplay::Game::getInstance()->getGameTime() * 0.001f); float vpwidth = static_cast<float>(gameplay::Game::getInstance()->getWidth()); float vpheight = static_cast<float>(gameplay::Game::getInstance()->getHeight()); float sidebarWidth = getSettings()->getSidebarWidth(); _camera->setAspectRatio((vpwidth - sidebarWidth) / vpheight); gameplay::Vector3 axisX[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitX() }; gameplay::Vector3 axisY[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitY() }; gameplay::Vector3 axisZ[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitZ() }; gameplay::Mesh * axisXMesh = gameplay::Mesh::createLines(axisX, 2); gameplay::Mesh * axisYMesh = gameplay::Mesh::createLines(axisY, 2); gameplay::Mesh * axisZMesh = gameplay::Mesh::createLines(axisZ, 2); _axisXModel.reset(gameplay::Model::create(axisXMesh)); _axisYModel.reset(gameplay::Model::create(axisYMesh)); _axisZModel.reset(gameplay::Model::create(axisZMesh)); _axisXModel->setMaterial("materials/models/line.material"); _axisYModel->setMaterial("materials/models/line.material"); _axisZModel->setMaterial("materials/models/line.material"); _axisXModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(1.0f, 0.0f, 0.0f, 1.0f)); _axisYModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(0.0f, 1.0f, 0.0f, 1.0f)); _axisZModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(0.0f, 0.0f, 1.0f, 1.0f)); SAFE_RELEASE(axisXMesh); SAFE_RELEASE(axisYMesh); SAFE_RELEASE(axisZMesh); gameplay::Node * axisXNode = _scene->addNode("AxisX"); gameplay::Node * axisYNode = _scene->addNode("AxisY"); gameplay::Node * axisZNode = _scene->addNode("AxisZ"); axisXNode->setDrawable(_axisXModel.get()); axisYNode->setDrawable(_axisYModel.get()); axisZNode->setDrawable(_axisZModel.get()); return true; }
//-----------------------------------【Object_Init( )函数】-------------------------------------- // 描述:渲染资源初始化函数,在此函数中进行要被渲染的物体的资源的初始化 //-------------------------------------------------------------------------------------------------- HRESULT Objects_Init(HWND hwnd) { //创建字体 if(FAILED(D3DXCreateFont(g_pd3dDevice, 36, 0, 0, 1000, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, _T("Calibri"), &g_pTextFPS))) return E_FAIL; if (FAILED(D3DXCreateFont(g_pd3dDevice, 20, 0, 1000, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, _T("华文中宋"), &g_pTextAdaperName))) return E_FAIL; if (FAILED(D3DXCreateFont(g_pd3dDevice, 23, 0, 1000, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, _T("微软雅黑"), &g_pTextHelper))) return E_FAIL; if (FAILED(D3DXCreateFont(g_pd3dDevice, 26, 0, 1000, 0, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, 0, _T("黑体"), &g_pTextInfo))) return E_FAIL; LPD3DXBUFFER pAdjBuffer = NULL; LPD3DXBUFFER pMtrlBuffer = NULL; if (FAILED(D3DXLoadMeshFromX(L"Warden.X", D3DXMESH_MANAGED, g_pd3dDevice, &pAdjBuffer, &pMtrlBuffer, NULL, &g_dwNumMtrls, &g_pMesh))) //if (FAILED(D3DXLoadMeshFromX(L"WYJ.X", D3DXMESH_MANAGED, g_pd3dDevice, &pAdjBuffer, &pMtrlBuffer, NULL, &g_dwNumMtrls, &g_pMesh))) return E_FAIL; D3DXMATERIAL *pMtrls = (D3DXMATERIAL *)pMtrlBuffer->GetBufferPointer(); g_pMaterials = new D3DMATERIAL9[g_dwNumMtrls]; g_pTextures = new LPDIRECT3DTEXTURE9[g_dwNumMtrls]; for (DWORD i = 0; i < g_dwNumMtrls; i++) { g_pMaterials[i] = pMtrls[i].MatD3D; g_pMaterials[i].Ambient = g_pMaterials[i].Diffuse; g_pTextures[i] = NULL; D3DXCreateTextureFromFileA(g_pd3dDevice, pMtrls[i].pTextureFilename, &g_pTextures[i]); } SAFE_RELEASE(pAdjBuffer); SAFE_RELEASE(pMtrlBuffer); g_pd3dDevice->CreateVertexBuffer(4 * sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_MANAGED, &g_pVertexBuffer, 0); CUSTOMVERTEX *pVertices = NULL; g_pVertexBuffer->Lock(0, 0, (void **)&pVertices, 0); pVertices[0] = CUSTOMVERTEX(-500.0f, 0.0f, -500.0f, 0.0f, 1.0f, 0.0f, 0.0f, 50.0f); pVertices[1] = CUSTOMVERTEX(-500.0f, 0.0f, 500.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); pVertices[2] = CUSTOMVERTEX(500.0f, 0.0f, -500.0f, 0.0f, 1.0f, 0.0f, 50.0f, 50.0f); pVertices[3] = CUSTOMVERTEX(500.0f, 0.0f, 500.0f, 0.0f, 1.0f, 0.0f, 50.0f, 0.0f); g_pVertexBuffer->Unlock(); D3DXCreateTextureFromFile(g_pd3dDevice, L"grass.jpg", &g_pTexture); D3DXCreateCylinder(g_pd3dDevice, 10.0f, 10.0f, 500.0f, 60, 60, &g_cylinder, 0); g_MaterialCylinder.Ambient = D3DXCOLOR(0.9f, 0.0f, 0.8f, 1.0f); g_MaterialCylinder.Diffuse = D3DXCOLOR(0.9f, 0.0f, 0.8f, 1.0f); g_MaterialCylinder.Specular = D3DXCOLOR(0.9f, 0.2f, 0.9f, 0.9f); g_MaterialCylinder.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.9f, 1.0f); D3DLIGHT9 light; ZeroMemory(&light, sizeof(light)); light.Type = D3DLIGHT_DIRECTIONAL; light.Ambient = D3DXCOLOR(0.7f, 0.7f, 0.7f, 1.0f); light.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); light.Specular = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f); light.Direction = D3DXVECTOR3(1.0f, 0.0f, 0.0f); g_pd3dDevice->SetLight(0, &light); g_pd3dDevice->LightEnable(0, true); g_pd3dDevice->SetRenderState(D3DRS_NORMALIZENORMALS, true); g_pd3dDevice->SetRenderState(D3DRS_SPECULARENABLE, true); g_pCamera = new CameraClass(g_pd3dDevice); g_pCamera->SetCameraPosition(&D3DXVECTOR3(0.0f, 200.0f, -300.0f)); g_pCamera->SetTargetPosition(&D3DXVECTOR3(0.0f, 300.0f, 0.0f)); g_pCamera->SetViewMatrix(); g_pCamera->SetProjMatrix(); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); //g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); return S_OK; }
//============================================================================= // Release all //============================================================================= void Graphics::releaseAll() { SAFE_RELEASE(sprite); SAFE_RELEASE(device3d); SAFE_RELEASE(direct3d); }
VOID Cleanup() { SAFE_RELEASE(g_pSphereMesh) ; SAFE_RELEASE(g_pd3dDevice) ; SAFE_RELEASE(g_pD3D) ; }
Heightmap::~Heightmap() { SAFE_RELEASE(vertextBuffer); SAFE_RELEASE(indexBuffer); }
HRESULT Create_Internal(IUnknown *pAdapter, D3D_FEATURE_LEVEL MinimumFeatureLevel, REFIID riid, void **ppDevice) { // if we're already inside a wrapped create i.e. this function, then DON'T do anything // special. Just grab the trampolined function and call it. if(m_InsideCreate) { PFN_D3D12_CREATE_DEVICE createFunc = NULL; // shouldn't ever get in here if we're in the case without hooks but let's be safe. if(m_HasHooks) { createFunc = CreateDevice(); } else { HMODULE d3d12 = GetModuleHandleA("d3d12.dll"); if(d3d12) { createFunc = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(d3d12, "D3D12CreateDevice"); } else { RDCERR("Something went seriously wrong, d3d12.dll couldn't be loaded!"); return E_UNEXPECTED; } } return createFunc(pAdapter, MinimumFeatureLevel, riid, ppDevice); } m_InsideCreate = true; if(riid != __uuidof(ID3D12Device)) { RDCERR("Unsupported UUID %s for D3D12CreateDevice", ToStr::Get(riid).c_str()); return E_NOINTERFACE; } RDCDEBUG("Call to Create_Internal Feature Level %x", MinimumFeatureLevel, ToStr::Get(riid).c_str()); bool reading = RenderDoc::Inst().IsReplayApp(); if(reading) { RDCDEBUG("In replay app"); } const bool EnableDebugLayer = #if 1 // toggle on/off if you want debug layer during replay RenderDoc::Inst().IsReplayApp() || #endif (m_EnabledHooks && !reading && RenderDoc::Inst().GetCaptureOptions().APIValidation); if(EnableDebugLayer) { PFN_D3D12_GET_DEBUG_INTERFACE getfn = GetDebugInterface(); if(getfn == NULL) getfn = (PFN_D3D12_GET_DEBUG_INTERFACE)GetProcAddress(GetModuleHandleA("d3d12.dll"), "D3D12GetDebugInterface"); if(getfn) { ID3D12Debug *debug = NULL; HRESULT hr = getfn(__uuidof(ID3D12Debug), (void **)&debug); if(SUCCEEDED(hr) && debug) { debug->EnableDebugLayer(); RDCDEBUG("Enabling debug layer"); // enable this to get GPU-based validation, where available, whenever we enable API validation #if 0 ID3D12Debug1 *debug1 = NULL; hr = debug->QueryInterface(__uuidof(ID3D12Debug1), (void **)&debug1); if(SUCCEEDED(hr) && debug1) { RDCDEBUG("Enabling GPU-based validation"); debug1->SetEnableGPUBasedValidation(true); SAFE_RELEASE(debug1); } else { RDCDEBUG("GPU-based validation not available"); } #endif } else { RDCERR("Couldn't enable debug layer: %x", hr); } SAFE_RELEASE(debug); } else { RDCERR("Couldn't find D3D12GetDebugInterface!"); } } RDCDEBUG("Calling real createdevice..."); PFN_D3D12_CREATE_DEVICE createFunc = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(GetModuleHandleA("d3d12.dll"), "D3D12CreateDevice"); if(createFunc == NULL) createFunc = CreateDevice(); // shouldn't ever get here, we should either have it from procaddress or the trampoline, but // let's be safe. if(createFunc == NULL) { RDCERR("Something went seriously wrong with the hooks!"); m_InsideCreate = false; return E_UNEXPECTED; } HRESULT ret = createFunc(pAdapter, MinimumFeatureLevel, riid, ppDevice); RDCDEBUG("Called real createdevice... 0x%08x", ret); if(SUCCEEDED(ret) && m_EnabledHooks && ppDevice) { RDCDEBUG("succeeded and hooking."); if(!WrappedID3D12Device::IsAlloc(*ppDevice)) { D3D12InitParams params; params.MinimumFeatureLevel = MinimumFeatureLevel; ID3D12Device *dev = (ID3D12Device *)*ppDevice; WrappedID3D12Device *wrap = new WrappedID3D12Device(dev, ¶ms); RDCDEBUG("created wrapped device."); *ppDevice = (ID3D12Device *)wrap; } } else if(SUCCEEDED(ret)) { RDCLOG("Created wrapped D3D12 device."); } else { RDCDEBUG("failed. 0x%08x", ret); } m_InsideCreate = false; return ret; }
//------------------------------------------------------------------------------------- bool Dbmgr::initDB() { ScriptDefModule* pModule = EntityDef::findScriptModule(DBUtil::accountScriptName()); if(pModule == NULL) { ERROR_MSG(fmt::format("Dbmgr::initDB(): not found account script[{}]!\n", DBUtil::accountScriptName())); return false; } ENGINE_COMPONENT_INFO& dbcfg = g_kbeSrvConfig.getDBMgr(); if (dbcfg.dbInterfaceInfos.size() == 0) { ERROR_MSG(fmt::format("DBUtil::initialize: not found dbInterface! (kbengine_defs.xml->dbmgr->databaseInterfaces)\n")); return false; } if (!DBUtil::initialize()) { ERROR_MSG("Dbmgr::initDB(): can't initialize dbInterface!\n"); return false; } bool hasDefaultInterface = false; std::vector<DBInterfaceInfo>::iterator dbinfo_iter = dbcfg.dbInterfaceInfos.begin(); for (; dbinfo_iter != dbcfg.dbInterfaceInfos.end(); ++dbinfo_iter) { Buffered_DBTasks buffered_DBTasks; bufferedDBTasksMaps_.insert(std::make_pair((*dbinfo_iter).name, buffered_DBTasks)); BUFFERED_DBTASKS_MAP::iterator buffered_DBTasks_iter = bufferedDBTasksMaps_.find((*dbinfo_iter).name); buffered_DBTasks_iter->second.dbInterfaceName((*dbinfo_iter).name); } for (dbinfo_iter = dbcfg.dbInterfaceInfos.begin(); dbinfo_iter != dbcfg.dbInterfaceInfos.end(); ++dbinfo_iter) { DBInterface* pDBInterface = DBUtil::createInterface((*dbinfo_iter).name); if(pDBInterface == NULL) { ERROR_MSG("Dbmgr::initDB(): can't create dbInterface!\n"); return false; } bool ret = DBUtil::initInterface(pDBInterface); pDBInterface->detach(); SAFE_RELEASE(pDBInterface); if(!ret) return false; if (std::string("default") == (*dbinfo_iter).name) hasDefaultInterface = true; } if (!hasDefaultInterface) { ERROR_MSG("Dbmgr::initDB(): \"default\" dbInterface was not found! (kbengine_defs.xml->dbmgr->databaseInterfaces)\n"); return false; } return true; }
//------------------------------------------------------------------------------------- void Loginapp::onReqCreateMailAccountResult(Network::Channel* pChannel, MemoryStream& s) { SERVER_ERROR_CODE failedcode; std::string accountName; std::string password; std::string retdatas = ""; s >> failedcode >> accountName >> password; s.readBlob(retdatas); DEBUG_MSG(fmt::format("Loginapp::onReqCreateMailAccountResult: accountName={}, failedcode={}.\n", accountName.c_str(), failedcode)); if(failedcode == SERVER_SUCCESS) { Components::COMPONENTS& loginapps = Components::getSingleton().getComponents(LOGINAPP_TYPE); std::string http_host = "localhost"; if(startGroupOrder_ == 1) { if(strlen((const char*)&g_kbeSrvConfig.getLoginApp().externalAddress) > 0) http_host = g_kbeSrvConfig.getBaseApp().externalAddress; else http_host = inet_ntoa((struct in_addr&)Loginapp::getSingleton().networkInterface().extaddr().ip); } else { Components::COMPONENTS::iterator iter = loginapps.begin(); for(; iter != loginapps.end(); ++iter) { if((*iter).groupOrderid == 1) { if(strlen((const char*)&(*iter).externalAddressEx) > 0) http_host = (*iter).externalAddressEx; else http_host = inet_ntoa((struct in_addr&)(*iter).pExtAddr->ip); } } } threadPool_.addTask(new SendActivateEMailTask(accountName, retdatas, http_host, g_kbeSrvConfig.getLoginApp().http_cbport)); } PendingLoginMgr::PLInfos* ptinfos = pendingCreateMgr_.remove(accountName); if(ptinfos == NULL) return; Network::Channel* pClientChannel = this->networkInterface().findChannel(ptinfos->addr); if(pClientChannel == NULL) return; pClientChannel->extra(""); retdatas = ""; Network::Bundle* pBundle = Network::Bundle::ObjPool().createObject(); (*pBundle).newMessage(ClientInterface::onCreateAccountResult); (*pBundle) << failedcode; (*pBundle).appendBlob(retdatas); pClientChannel->send(pBundle); SAFE_RELEASE(ptinfos); }
PhysicsCollisionShape::Definition PhysicsCollisionShape::Definition::create(Node* node, Properties* properties) { GP_ASSERT(node); // Check if the properties is valid and has a valid namespace. if (!properties || !(strcmp(properties->getNamespace(), "collisionObject") == 0)) { GP_ERROR("Failed to load physics collision shape from properties object: must be non-null object and have namespace equal to 'collisionObject'."); return Definition(); } // Set values to their defaults. PhysicsCollisionShape::Type type = PhysicsCollisionShape::SHAPE_BOX; kmVec3 extents = vec3Zero; kmVec3 center = vec3Zero; bool extentsSpecified = false; bool centerSpecified = false; float radius = -1.0f; float width = -1.0f; float height = -1.0f; bool centerIsAbsolute = false; const char* imagePath = NULL; float maxHeight = 0; float minHeight = 0; bool shapeSpecified = false; // Load the defined properties. properties->rewind(); const char* name; while ((name = properties->getNextProperty())) { if (strcmp(name, "shape") == 0) { std::string shapeStr = properties->getString(); if (shapeStr == "BOX") type = SHAPE_BOX; else if (shapeStr == "SPHERE") type = SHAPE_SPHERE; else if (shapeStr == "MESH") type = SHAPE_MESH; else if (shapeStr == "HEIGHTFIELD") type = SHAPE_HEIGHTFIELD; else if (shapeStr == "CAPSULE") type = SHAPE_CAPSULE; else { GP_ERROR("Could not create physics collision shape; unsupported value for collision shape type: '%s'.", shapeStr.c_str()); return Definition(); } shapeSpecified = true; } else if (strcmp(name, "image") == 0) { imagePath = properties->getString(); } else if (strcmp(name, "maxHeight") == 0) { maxHeight = properties->getFloat(); } else if (strcmp(name, "minHeight") == 0) { minHeight = properties->getFloat(); } else if (strcmp(name, "radius") == 0) { radius = properties->getFloat(); } else if (strcmp(name, "width") == 0) { width = properties->getFloat(); } else if (strcmp(name, "height") == 0) { height = properties->getFloat(); } else if (strcmp(name, "extents") == 0) { properties->getVector3("extents", &extents); extentsSpecified = true; } else if (strcmp(name, "center") == 0) { properties->getVector3("center", ¢er); centerSpecified = true; } else if (strcmp(name, "centerAbsolute") == 0) { centerIsAbsolute = properties->getBool(); } else { // Ignore this case (these are the properties for the rigid body, character, or ghost object that this collision shape is for). } } if (!shapeSpecified) { GP_ERROR("Missing 'shape' specifier for collision shape definition."); return Definition(); } // Create the collision shape. Definition shape; switch (type) { case SHAPE_BOX: if (extentsSpecified) { if (centerSpecified) { shape = box(extents, center, centerIsAbsolute); } else { shape = box(extents); } } else { shape = box(); } break; case SHAPE_SPHERE: if (radius != -1.0f) { if (centerSpecified) { shape = sphere(radius, center, centerIsAbsolute); } else { shape = sphere(radius); } } else { shape = sphere(); } break; case SHAPE_CAPSULE: if (radius != -1.0f && height != -1.0f) { if (centerSpecified) { shape = capsule(radius, height, center, centerIsAbsolute); } else { shape = capsule(radius, height); } } else { shape = capsule(); } break; case SHAPE_MESH: { // Mesh is required on node. Mesh* nodeMesh = node->getDrawable() ? dynamic_cast<Model*>(node->getDrawable())->getMesh() : NULL; if (nodeMesh == NULL) { GP_ERROR("Cannot create mesh collision object for node without model/mesh."); } else { // Check that the node's mesh's primitive type is supported. switch (nodeMesh->getPrimitiveType()) { case Mesh::TRIANGLES: shape = mesh(nodeMesh); break; case Mesh::LINES: case Mesh::LINE_STRIP: case Mesh::POINTS: case Mesh::TRIANGLE_STRIP: GP_ERROR("Mesh collision objects are currently only supported on meshes with primitive type equal to TRIANGLES."); break; } } } break; case SHAPE_HEIGHTFIELD: { if (imagePath == NULL) { // Node requires a valid terrain if (dynamic_cast<Terrain*>(node->getDrawable()) == NULL) { GP_ERROR("Heightfield collision objects can only be specified on nodes that have a valid terrain, or that specify an image path."); } else { shape = PhysicsCollisionShape::heightfield(); } } else { std::string ext = FileSystem::getExtension(imagePath); HeightField* heightfield = NULL; if (ext == ".PNG") heightfield = HeightField::createFromImage(imagePath, minHeight, maxHeight); else if (ext == ".RAW" || ext == ".R16") heightfield = HeightField::createFromRAW(imagePath, (unsigned int)width, (unsigned int)height, minHeight, maxHeight); if (heightfield) { shape = PhysicsCollisionShape::heightfield(heightfield); SAFE_RELEASE(heightfield); } } } break; default: GP_ERROR("Unsupported physics collision shape type (%d).", type); break; } return shape; }
//------------------------------------------------------------------------------------- bool ForwardComponent_MessageBuffer::process() { if(pMap_.size() <= 0) { start_ = false; return false; } MSGMAP::iterator iter = pMap_.begin(); for(; iter != pMap_.end(); ) { Components::ComponentInfos* cinfos = Components::getSingleton().findComponent(iter->first); if(cinfos == NULL || cinfos->pChannel == NULL) return true; // 如果是mgr类组件需要判断是否已经初始化完成 if(g_componentType == CELLAPPMGR_TYPE || g_componentType == BASEAPPMGR_TYPE) { if(cinfos->state != COMPONENT_STATE_RUN) return true; } if(iter->second.size() == 0) { pMap_.erase(iter++); } else { int icount = 5; std::vector<ForwardItem*>::iterator itervec = iter->second.begin(); for(; itervec != iter->second.end(); ) { if (!(*itervec)->isOK()) return true; cinfos->pChannel->send((*itervec)->pBundle); (*itervec)->pBundle = NULL; if((*itervec)->pHandler != NULL) { (*itervec)->pHandler->process(); SAFE_RELEASE((*itervec)->pHandler); } SAFE_RELEASE((*itervec)); itervec = iter->second.erase(itervec); if(--icount <= 0) return true; } DEBUG_MSG(fmt::format("ForwardComponent_MessageBuffer::process(): size:{}.\n", iter->second.size())); iter->second.clear(); ++iter; } } return true; }
void Axis::Release() { SAFE_RELEASE(m_pVB); SAFE_DELETE(m_pVtxs); }
/////////////////////////////////////////////////////////////// //// Retrieve video and audio stream numbers from profile //// HRESULT CSVPWMVReader::GetStreamNumbers(IWMProfile* pProfile) { HRESULT hr = S_OK; IWMStreamConfig* pStream = NULL; DWORD dwStreams = 0; GUID pguidStreamType; if ( NULL == pProfile ) { return( E_INVALIDARG ); } hr = pProfile->GetStreamCount( &dwStreams ); if ( FAILED( hr ) ) { _tprintf( _T( "GetStreamCount on IWMProfile failed (hr=0x%08x).\n" ), hr ); return( hr ); } m_wAudioStreamNum = 0; m_wVideoStreamNum = 0; for ( DWORD i = 0; i < dwStreams; i++ ) { hr = pProfile->GetStream( i, &pStream ); if ( FAILED( hr ) ) { _tprintf( _T( "Could not get Stream %d of %d from IWMProfile (hr=0x%08x).\n" ), i, dwStreams, hr ); break; } WORD wStreamNumber = 0 ; // // Get the stream number of the current stream // hr = pStream->GetStreamNumber( &wStreamNumber ); if ( FAILED( hr ) ) { _tprintf( _T( "Could not get stream number from IWMStreamConfig %d of %d (hr=0x%08x).\n" ), i, dwStreams, hr ); break; } hr = pStream->GetStreamType( &pguidStreamType ); if ( FAILED( hr ) ) { _tprintf( _T("Could not get stream type of stream %d of %d from IWMStreamConfig (hr=0x%08x).\n" ), i, dwStreams, hr ) ; break ; } if( WMMEDIATYPE_Audio == pguidStreamType ) { m_wAudioStreamNum = wStreamNumber; } else if( WMMEDIATYPE_Video == pguidStreamType ) { m_wVideoStreamNum = wStreamNumber; } SAFE_RELEASE( pStream ); } return( hr ); }
BOOL LLDXHardware::getInfo(BOOL vram_only) { LLTimer hw_timer; BOOL ok = FALSE; HRESULT hr; CoInitialize(NULL); IDxDiagProvider *dx_diag_providerp = NULL; IDxDiagContainer *dx_diag_rootp = NULL; IDxDiagContainer *devices_containerp = NULL; // IDxDiagContainer *system_device_containerp= NULL; IDxDiagContainer *device_containerp = NULL; IDxDiagContainer *file_containerp = NULL; IDxDiagContainer *driver_containerp = NULL; // CoCreate a IDxDiagProvider* LL_DEBUGS("AppInit") << "CoCreateInstance IID_IDxDiagProvider" << LL_ENDL; hr = CoCreateInstance(CLSID_DxDiagProvider, NULL, CLSCTX_INPROC_SERVER, IID_IDxDiagProvider, (LPVOID*) &dx_diag_providerp); if (FAILED(hr)) { LL_WARNS("AppInit") << "No DXDiag provider found! DirectX 9 not installed!" << LL_ENDL; gWriteDebug("No DXDiag provider found! DirectX 9 not installed!\n"); goto LCleanup; } if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed { // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are // digital signed as logo'd by WHQL which may connect via internet to update // WHQL certificates. DXDIAG_INIT_PARAMS dx_diag_init_params; ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS)); dx_diag_init_params.dwSize = sizeof(DXDIAG_INIT_PARAMS); dx_diag_init_params.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; dx_diag_init_params.bAllowWHQLChecks = TRUE; dx_diag_init_params.pReserved = NULL; LL_DEBUGS("AppInit") << "dx_diag_providerp->Initialize" << LL_ENDL; hr = dx_diag_providerp->Initialize(&dx_diag_init_params); if(FAILED(hr)) { goto LCleanup; } LL_DEBUGS("AppInit") << "dx_diag_providerp->GetRootContainer" << LL_ENDL; hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp ); if(FAILED(hr) || !dx_diag_rootp) { goto LCleanup; } HRESULT hr; // Get display driver information LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer" << LL_ENDL; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp); if(FAILED(hr) || !devices_containerp) { goto LCleanup; } // Get device 0 LL_DEBUGS("AppInit") << "devices_containerp->GetChildContainer" << LL_ENDL; hr = devices_containerp->GetChildContainer(L"0", &device_containerp); if(FAILED(hr) || !device_containerp) { goto LCleanup; } // Get the English VRAM string { std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish"); // We don't need the device any more SAFE_RELEASE(device_containerp); // Dump the string as an int into the structure char *stopstring; mVRAM = strtol(ram_str.c_str(), &stopstring, 10); LL_INFOS("AppInit") << "VRAM Detected: " << mVRAM << " DX9 string: " << ram_str << LL_ENDL; } if (vram_only) { ok = TRUE; goto LCleanup; } /* for now, we ONLY do vram_only the rest of this is commented out, to ensure no-one is tempted to use it // Now let's get device and driver information // Get the IDxDiagContainer object called "DxDiag_SystemDevices". // This call may take some time while dxdiag gathers the info. DWORD num_devices = 0; WCHAR wszContainer[256]; LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer DxDiag_SystemDevices" << LL_ENDL; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_SystemDevices", &system_device_containerp); if (FAILED(hr)) { goto LCleanup; } hr = system_device_containerp->GetNumberOfChildContainers(&num_devices); if (FAILED(hr)) { goto LCleanup; } LL_DEBUGS("AppInit") << "DX9 iterating over devices" << LL_ENDL; S32 device_num = 0; for (device_num = 0; device_num < (S32)num_devices; device_num++) { hr = system_device_containerp->EnumChildContainerNames(device_num, wszContainer, 256); if (FAILED(hr)) { goto LCleanup; } hr = system_device_containerp->GetChildContainer(wszContainer, &device_containerp); if (FAILED(hr) || device_containerp == NULL) { goto LCleanup; } std::string device_name = get_string(device_containerp, L"szDescription"); std::string device_id = get_string(device_containerp, L"szDeviceID"); LLDXDevice *dxdevicep = new LLDXDevice; dxdevicep->mName = device_name; dxdevicep->mPCIString = device_id; mDevices[dxdevicep->mPCIString] = dxdevicep; // Split the PCI string based on vendor, device, subsys, rev. std::string str(device_id); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("&\\", "", boost::keep_empty_tokens); tokenizer tokens(str, sep); tokenizer::iterator iter = tokens.begin(); S32 count = 0; BOOL valid = TRUE; for (;(iter != tokens.end()) && (count < 3);++iter) { switch (count) { case 0: if (strcmp(iter->c_str(), "PCI")) { valid = FALSE; } break; case 1: dxdevicep->mVendorID = iter->c_str(); break; case 2: dxdevicep->mDeviceID = iter->c_str(); break; default: // Ignore it break; } count++; } // Now, iterate through the related drivers hr = device_containerp->GetChildContainer(L"Drivers", &driver_containerp); if (FAILED(hr) || !driver_containerp) { goto LCleanup; } DWORD num_files = 0; hr = driver_containerp->GetNumberOfChildContainers(&num_files); if (FAILED(hr)) { goto LCleanup; } S32 file_num = 0; for (file_num = 0; file_num < (S32)num_files; file_num++ ) { hr = driver_containerp->EnumChildContainerNames(file_num, wszContainer, 256); if (FAILED(hr)) { goto LCleanup; } hr = driver_containerp->GetChildContainer(wszContainer, &file_containerp); if (FAILED(hr) || file_containerp == NULL) { goto LCleanup; } std::string driver_path = get_string(file_containerp, L"szPath"); std::string driver_name = get_string(file_containerp, L"szName"); std::string driver_version = get_string(file_containerp, L"szVersion"); std::string driver_date = get_string(file_containerp, L"szDatestampEnglish"); LLDXDriverFile *dxdriverfilep = new LLDXDriverFile; dxdriverfilep->mName = driver_name; dxdriverfilep->mFilepath= driver_path; dxdriverfilep->mVersionString = driver_version; dxdriverfilep->mVersion.set(driver_version); dxdriverfilep->mDateString = driver_date; dxdevicep->mDriverFiles[driver_name] = dxdriverfilep; SAFE_RELEASE(file_containerp); } SAFE_RELEASE(device_containerp); } */ } // dumpDevices(); ok = TRUE; LCleanup: if (!ok) { LL_WARNS("AppInit") << "DX9 probe failed" << LL_ENDL; gWriteDebug("DX9 probe failed\n"); } SAFE_RELEASE(file_containerp); SAFE_RELEASE(driver_containerp); SAFE_RELEASE(device_containerp); SAFE_RELEASE(devices_containerp); SAFE_RELEASE(dx_diag_rootp); SAFE_RELEASE(dx_diag_providerp); CoUninitialize(); return ok; }
//-----------------------------------【Direct3D_Init( )函数】-------------------------------------- // 描述:Direct3D初始化函数,进行Direct3D的初始化 //------------------------------------------------------------------------------------------------ HRESULT Direct3D_Init(HWND hwnd) { //-------------------------------------------------------------------------------------- // 【Direct3D初始化四步曲之一,创接口】:创建Direct3D接口对象, 以便用该Direct3D对象创建Direct3D设备对象 //-------------------------------------------------------------------------------------- LPDIRECT3D9 pD3D = NULL; //Direct3D接口对象的创建 if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) ) //初始化Direct3D接口对象,并进行DirectX版本协商 return E_FAIL; //-------------------------------------------------------------------------------------- // 【Direct3D初始化四步曲之二,取信息】:获取硬件设备信息 //-------------------------------------------------------------------------------------- D3DCAPS9 caps; int vp = 0; if( FAILED( pD3D->GetDeviceCaps( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, &caps ) ) ) { return E_FAIL; } if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; //支持硬件顶点运算,我们就采用硬件顶点运算,妥妥的 else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; //不支持硬件顶点运算,无奈只好采用软件顶点运算 //-------------------------------------------------------------------------------------- // 【Direct3D初始化四步曲之三,填内容】:填充D3DPRESENT_PARAMETERS结构体 //-------------------------------------------------------------------------------------- D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(d3dpp)); d3dpp.BackBufferWidth = WINDOW_WIDTH; d3dpp.BackBufferHeight = WINDOW_HEIGHT; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hwnd; d3dpp.Windowed = true; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = 0; //d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; //-------------------------------------------------------------------------------------- // 【Direct3D初始化四步曲之四,创设备】:创建Direct3D设备接口 //-------------------------------------------------------------------------------------- if(FAILED(pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, vp, &d3dpp, &g_pd3dDevice))) return E_FAIL; wchar_t TempName[60] = L"当前型号:"; D3DADAPTER_IDENTIFIER9 Adapter; pD3D->GetAdapterIdentifier(0, 0, &Adapter); int len = MultiByteToWideChar(CP_ACP, 0, Adapter.Description, -1, NULL, 0); MultiByteToWideChar(CP_ACP, 0, Adapter.Description, -1, g_strAdapterName, len); wcscat_s(TempName, g_strAdapterName); wcscpy_s(g_strAdapterName, TempName); SAFE_RELEASE(pD3D); //LPDIRECT3D9接口对象的使命完成,我们将其释放掉 if(!(S_OK==Objects_Init(hwnd))) return E_FAIL; //调用一次Objects_Init,进行渲染资源的初始化 return S_OK; }
LLSD LLDXHardware::getDisplayInfo() { LLTimer hw_timer; HRESULT hr; LLSD ret; CoInitialize(NULL); IDxDiagProvider *dx_diag_providerp = NULL; IDxDiagContainer *dx_diag_rootp = NULL; IDxDiagContainer *devices_containerp = NULL; IDxDiagContainer *device_containerp = NULL; IDxDiagContainer *file_containerp = NULL; IDxDiagContainer *driver_containerp = NULL; // CoCreate a IDxDiagProvider* llinfos << "CoCreateInstance IID_IDxDiagProvider" << llendl; hr = CoCreateInstance(CLSID_DxDiagProvider, NULL, CLSCTX_INPROC_SERVER, IID_IDxDiagProvider, (LPVOID*) &dx_diag_providerp); if (FAILED(hr)) { llwarns << "No DXDiag provider found! DirectX 9 not installed!" << llendl; gWriteDebug("No DXDiag provider found! DirectX 9 not installed!\n"); goto LCleanup; } if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed { // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are // digital signed as logo'd by WHQL which may connect via internet to update // WHQL certificates. DXDIAG_INIT_PARAMS dx_diag_init_params; ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS)); dx_diag_init_params.dwSize = sizeof(DXDIAG_INIT_PARAMS); dx_diag_init_params.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; dx_diag_init_params.bAllowWHQLChecks = TRUE; dx_diag_init_params.pReserved = NULL; llinfos << "dx_diag_providerp->Initialize" << llendl; hr = dx_diag_providerp->Initialize(&dx_diag_init_params); if(FAILED(hr)) { goto LCleanup; } llinfos << "dx_diag_providerp->GetRootContainer" << llendl; hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp ); if(FAILED(hr) || !dx_diag_rootp) { goto LCleanup; } HRESULT hr; // Get display driver information llinfos << "dx_diag_rootp->GetChildContainer" << llendl; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp); if(FAILED(hr) || !devices_containerp) { goto LCleanup; } // Get device 0 llinfos << "devices_containerp->GetChildContainer" << llendl; hr = devices_containerp->GetChildContainer(L"0", &device_containerp); if(FAILED(hr) || !device_containerp) { goto LCleanup; } // Get the English VRAM string std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish"); // Dump the string as an int into the structure char *stopstring; ret["VRAM"] = strtol(ram_str.c_str(), &stopstring, 10); std::string device_name = get_string(device_containerp, L"szDescription"); ret["DeviceName"] = device_name; std::string device_driver= get_string(device_containerp, L"szDriverVersion"); ret["DriverVersion"] = device_driver; // ATI has a slightly different version string if(device_name.length() >= 4 && device_name.substr(0,4) == "ATI ") { // get the key HKEY hKey; const DWORD RV_SIZE = 100; WCHAR release_version[RV_SIZE]; // Hard coded registry entry. Using this since it's simpler for now. // And using EnumDisplayDevices to get a registry key also requires // a hard coded Query value. if(ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\ATI Technologies\\CBT"), &hKey)) { // get the value DWORD dwType = REG_SZ; DWORD dwSize = sizeof(WCHAR) * RV_SIZE; if(ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("ReleaseVersion"), NULL, &dwType, (LPBYTE)release_version, &dwSize)) { // print the value // windows doesn't guarantee to be null terminated release_version[RV_SIZE - 1] = NULL; ret["DriverVersion"] = utf16str_to_utf8str(release_version); } RegCloseKey(hKey); } } } LCleanup: SAFE_RELEASE(file_containerp); SAFE_RELEASE(driver_containerp); SAFE_RELEASE(device_containerp); SAFE_RELEASE(devices_containerp); SAFE_RELEASE(dx_diag_rootp); SAFE_RELEASE(dx_diag_providerp); CoUninitialize(); return ret; }
//-------------------------------------------------------------------------------------- CLoaderXFile::~CLoaderXFile() { SAFE_DELETE_ARRAY( m_pMats ); SAFE_DELETE_ARRAY( m_pAttr ); SAFE_RELEASE( m_pMesh ); }
static int __sys_job_do_record(sys_wkr_ctx_t* wkr_ctx, IPS_EPID src_id, int pc_id, size_t ips_sec_sz, dfv_slot_def_t* slot_def, dfv_slice_def_t* slice_def) { int ret = -1; #ifdef ARCH_ppc64 struct ips_pcctx* pcctx = NULL; struct dfv_file* file_ctx = NULL; int wkr_id = wkr_ctx->wkr_id; spk_stats_t* stats = &wkr_ctx->stats; void* chunk_buf = NULL; size_t chunk_size = slice_def->size * slice_def->num; int dfv_cpu_base = 12+4*wkr_ctx->wkr_id; zlog_notice(sys_zc, "wkr#%d> prepare for recording: ips={0x%x:%d}, dfv={repo={%d:%d}, " "slice={%d, 0x%lx}, cpu_base=%d}", wkr_id, src_id, pc_id, dfv_repo_get_id(slot_def->repo), slot_def->slot_id, slice_def->num, slice_def->size, dfv_cpu_base); // reset stats spk_stats_reset(stats); // open dfv slot file_ctx = dfv_file_open(slot_def->repo, slot_def->slot_id, SPK_DIR_WRITE, slice_def, dfv_cpu_base); if (!file_ctx) { zlog_fatal(sys_zc, "wkr#%d> failed to open dfv file", wkr_id); ret = SPKERR_BADRES; goto out; } // write to dfv if (!(sys_env.dbg_flag & SYSDBG_REC_NOTSAVE2DISK)) { size_t warmup_sz = 128*1024*1024; size_t xferred = 0; void * txbuf = NULL; txbuf = memalign(SYS_INTERLACE_SIZE, DFV_CHUNK_SIZE); assert(txbuf); memset(txbuf, 0xfe, DFV_CHUNK_SIZE); while(xferred < warmup_sz) { ssize_t xfer = dfv_file_write(file_ctx, txbuf, DFV_CHUNK_SIZE); if (xfer != DFV_CHUNK_SIZE) { zlog_fatal(sys_zc, "wkr#%d> failed to write to dfv: xfer=%ld, expect=%u", wkr_id, xfer, DFV_CHUNK_SIZE); ret = SPKERR_EACCESS; SAFE_RELEASE(txbuf); goto out; } xferred += xfer; } dfv_file_seek(file_ctx, 0); SAFE_RELEASE(txbuf); } zlog_notice(sys_zc, "wkr#%d> dfv warmup done", wkr_id); // open ips srio pcctx = ips_chan_open(src_id, pc_id); if (!pcctx) { zlog_fatal(sys_zc, "wkr#%d> failed to open ips channel", wkr_id); ret = SPKERR_EACCESS; goto out; } ret = ips_chan_start(pcctx, SPK_DIR_READ); if (ret != SPK_SUCCESS) { zlog_fatal(sys_zc, "wkr#%d> failed to start ips channel", wkr_id); goto out; } zlog_info(sys_zc, "wkr#%d> ips channel started for reading", wkr_id); // start recording uint64_t now = spk_get_tick_count(); uint64_t tm_upstats = now; uint64_t tm_log = now; uint64_t tm_heartbeat = now; ret = SPK_SUCCESS; size_t xfer; zlog_notice(sys_zc, "wkr#%d> ---------- start recording ----------", wkr_id); while(!wkr_ctx->reset_req) { // read from ips for one chunk // FIXME: our link partner must have enough data // before being stopped ssize_t read_size = ips_chan_read(pcctx, &chunk_buf, chunk_size, chunk_size); if (read_size > 0) { // got a chunk from ips assert(read_size == chunk_size); // preserve first buf for snapshot use pthread_mutex_lock(&wkr_ctx->buf_snap_lock); memcpy(wkr_ctx->buf_snap, chunk_buf, SYS_SNAP_BUF_SZ); pthread_mutex_unlock(&wkr_ctx->buf_snap_lock); // write to dfv if (sys_env.dbg_flag & SYSDBG_REC_NOTSAVE2DISK) { xfer = chunk_size; } else { xfer = dfv_file_write(file_ctx, chunk_buf, read_size); } // notify ips to free buffer first ips_chan_free_buf(pcctx, read_size); if (xfer != read_size) { zlog_fatal(sys_zc, "wkr#%d> failed to write to dfv: xfer=%ld, expect=%lu", wkr_id, xfer, read_size); ret = SPKERR_EACCESS; break; } } else if (read_size == 0) { // no data if (sys_ctx.auto_rec) { if (spk_get_tick_count() - tm_heartbeat > SYS_AUTOSTOP_TIMEOUT*1000) { // timeout zlog_warn(sys_zc, "wkr#%d> no data received since last %d secs, stop.", wkr_id, SYS_AUTOSTOP_TIMEOUT); break; } } } else { // failed to got a chunk from ips zlog_fatal(sys_zc, "wkr#%d> failed to read from ips: read_size=%ld", wkr_id, read_size); ret = read_size; break; } tm_heartbeat = now = spk_get_tick_count(); // update local stats spk_stats_inc_xfer(stats, read_size, (read_size / ips_sec_sz)); if (now > tm_upstats) { if (!(sys_env.features & SYSFEA_USE_LOCALSTATS)) { // update channel stats sys_job_update_stats(pcctx, wkr_id); } tm_upstats = now + 1000; } if (now > tm_log) { zlog_notice(sys_zc, " wkr#%d> time=%lu pkts=%lu bytes=%lu ovfl=%lu spd=%.3f MBPS", wkr_id, spk_stats_get_time_elapsed(stats)/1000, spk_stats_get_xfer_pkts(stats), spk_stats_get_xfer_bytes(stats), spk_stats_get_overflow_bytes(stats), BYTE2MB(spk_stats_get_bps_overall(stats))); tm_log = now + 10*1000; } } // // stop recording // // 1. send stop to link partner int stop_ret = ips_chan_stop(pcctx); if (stop_ret != SPK_SUCCESS) { zlog_fatal(sys_zc, "wkr#%d> failed to close ips channel: ret=%d", wkr_id, stop_ret); ret = stop_ret; goto out; } // 2. drain remained data if (ret == SPK_SUCCESS) { // wait for link partner to do padding sleep(1); ssize_t tail_size; do { tail_size = ips_chan_read(pcctx, &chunk_buf, 0, chunk_size); if (tail_size <= 0) { // done break; } zlog_notice(sys_zc, "wkr#%d> got remained data: size=%zd", wkr_id, tail_size); // data must been padded to 64k alignment by link partner assert(!(tail_size & (0x10000-1))); // save remained data to dfv slot if (sys_env.dbg_flag & SYSDBG_REC_NOTSAVE2DISK) { xfer = tail_size; } else { xfer = dfv_file_write(file_ctx, chunk_buf, tail_size); } ips_chan_free_buf(pcctx, tail_size); if (xfer != tail_size) { zlog_fatal(sys_zc, "wkr#%d> failed to write to dfv: xfer=%ld, expect=%lu", wkr_id, xfer, tail_size); ret = SPKERR_EACCESS; goto out; } } while(1); } // 3. update chstat for last time if (!(sys_env.features & SYSFEA_USE_LOCALSTATS)) { sys_job_update_stats(pcctx, wkr_id); } out: zlog_notice(sys_zc, "wkr#%d> ---------- stop recording ---------- ret=%d,", wkr_id, ret); if (stats) { zlog_notice(sys_zc, "wkr#%d> elapsed=%lu, pkts=%lu, bytes=%lu, ovfl=%lu", wkr_id, spk_stats_get_time_elapsed(stats)/1000, stats->xfer.pkts, stats->xfer.bytes, stats->overflow.bytes); } // close dfv slot if (file_ctx) { dfv_file_close(file_ctx); file_ctx = NULL; } // close ips srio if (pcctx) { ips_chan_close(pcctx); pcctx = NULL; } #endif return(ret); }
HRESULT CWASAPIRenderFilter::InitAudioClient() { Log("WASAPIRenderFilter::InitAudioClient"); HRESULT hr = S_OK; REFERENCE_TIME rtPeriod = m_pSettings->GetPeriod(); // TODO create defines for special period values if (rtPeriod == 0 || rtPeriod == 1) { REFERENCE_TIME defaultPeriod(0); REFERENCE_TIME minimumPeriod(0); hr = m_pAudioClient->GetDevicePeriod(&defaultPeriod, &minimumPeriod); if (SUCCEEDED(hr)) { if (rtPeriod == 0) rtPeriod = defaultPeriod; else rtPeriod = minimumPeriod; Log("WASAPIRenderFilter::InitAudioClient using device period from driver %I64u ms", rtPeriod / 10000); } else { Log("WASAPIRenderFilter::InitAudioClient failed to get device period from driver (0x%08x) - using 50 ms", hr); rtPeriod = 500000; //50 ms is the best according to James @Slysoft } } WAVEFORMATEXTENSIBLE* pwfxAccepted = NULL; hr = IsFormatSupported(m_pOutputFormat, &pwfxAccepted); if (FAILED(hr)) { SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; } //Leave the buffer size alone. Reseting it based on media type causes issues on AMD systems, doesn't seem to impact +/- Intel, haven't tested NVIDIA //GetBufferSize((WAVEFORMATEX*)pwfxAccepted, &rtPeriod); if (SUCCEEDED(hr)) hr = m_pAudioClient->Initialize(m_pSettings->GetWASAPIMode(), m_dwStreamFlags,rtPeriod, rtPeriod, (WAVEFORMATEX*)pwfxAccepted, NULL); if (FAILED(hr) && hr != AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { Log("WASAPIRenderFilter::InitAudioClient Initialize failed (0x%08x)", hr); SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; } if (hr == S_OK) { SAFE_RELEASE(m_pAudioClock); hr = m_pAudioClient->GetService(__uuidof(IAudioClock), (void**)&m_pAudioClock); if (SUCCEEDED(hr)) m_pAudioClock->GetFrequency(&m_nHWfreq); else Log("WASAPIRenderFilter::IAudioClock not found!"); } if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) { // if the buffer size was not aligned, need to do the alignment dance Log("WASAPIRenderFilter::InitAudioClient Buffer size not aligned. Realigning"); // get the buffer size, which will be aligned hr = m_pAudioClient->GetBufferSize(&m_nFramesInBuffer); // throw away this IAudioClient SAFE_RELEASE(m_pAudioClient); // calculate the new aligned periodicity rtPeriod = // hns = (REFERENCE_TIME)( 10000.0 * // (hns / ms) * 1000 * // (ms / s) * m_nFramesInBuffer / // frames / m_pInputFormat->Format.nSamplesPerSec // (frames / s) + 0.5 // rounding ); if (SUCCEEDED(hr)) hr = CreateAudioClient(); Log("WASAPIRenderFilter::InitAudioClient Trying again with periodicity of %I64u hundred-nanoseconds, or %u frames", rtPeriod, m_nFramesInBuffer); if (SUCCEEDED (hr)) hr = m_pAudioClient->Initialize(m_pSettings->GetWASAPIMode(), m_dwStreamFlags, rtPeriod, rtPeriod, (WAVEFORMATEX*)pwfxAccepted, NULL); if (FAILED(hr)) { Log("WASAPIRenderFilter::InitAudioClient Failed to reinitialize the audio client"); SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; } else { SAFE_RELEASE(m_pAudioClock); hr = m_pAudioClient->GetService(__uuidof(IAudioClock), (void**)&m_pAudioClock); if (FAILED(hr)) Log("WASAPIRenderFilter::IAudioClock not found!"); else m_pAudioClock->GetFrequency(&m_nHWfreq); } } // if (AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED == hr) //m_pSettings->SetPeriod(rtPeriod); m_rtLatency = rtPeriod; // get the buffer size, which is aligned if (SUCCEEDED(hr)) hr = m_pAudioClient->GetBufferSize(&m_nFramesInBuffer); // calculate the new period if (SUCCEEDED (hr)) hr = m_pAudioClient->GetService(__uuidof(IAudioRenderClient), (void**)(&m_pRenderClient)); if (FAILED(hr)) Log("WASAPIRenderFilter::InitAudioClient service initialization failed (0x%08x)", hr); else Log("WASAPIRenderer::InitAudioClient service initialization success"); if (m_pSettings->GetUseWASAPIEventMode()) { hr = m_pAudioClient->SetEventHandle(m_hDataEvent); if (FAILED(hr)) { Log("WASAPIRenderFilter::InitAudioClient SetEventHandle failed (0x%08x)", hr); SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; } } REFERENCE_TIME latency(0); m_pAudioClient->GetStreamLatency(&latency); Log("WASAPIRenderFilter::InitAudioClient device reported latency %I64u ms - buffer based latency %I64u ms", latency / 10000, Latency() / 10000); // Dynamic format change requires restart for the audio client if (m_state != StateStopped) StartAudioClient(); m_bDeviceInitialized = true; SAFE_DELETE_WAVEFORMATEX(pwfxAccepted); return hr; }
static int sys_func_dl_prepare(int slot_id, uint64_t blk_start, uint64_t blk_num, uint32_t req_frag) { int ret; sys_ctx_t* ctx = &sys_ctx; int repo_num = ctx->vault->repo_num; size_t cache_sz = SYS_CACHE_SIZE; int i, j; int interlace_sz = SYS_INTERLACE_SIZE; sys_cache_t* file_cache = ctx->file_cache; assert(file_cache); assert(file_cache->data); // get slot_sz ssize_t slot_sz; if (file_cache->slot_id == slot_id ) { slot_sz = file_cache->slot_sz; } else { slot_sz = dfv_vault_get_slotsize(ctx->vault, slot_id); if (slot_sz < 0) { zlog_error(sys_zc, "bad file size: slot_id=%d", slot_id); return(SPKERR_BADRES); } } // request region uint64_t req_start = blk_start * SYS_CACHE_SIZE; uint64_t req_end = (blk_num>0)?(req_start + blk_num * SYS_CACHE_SIZE):slot_sz; // frag region uint64_t frag_start = req_start + (uint64_t)req_frag * CMI_MAX_FRAGSIZE; uint64_t frag_end = frag_start + CMI_MAX_FRAGSIZE; // check if region is valid if (frag_start > slot_sz) { zlog_error(sys_zc, "illegal frag_start: slot_id=%d, slot_sz=%zu, " "frag_start=%lu, req_frag=%u", slot_id, slot_sz, frag_start, req_frag); return(SPKERR_PARAM); } if (frag_end > slot_sz) { zlog_warn(sys_zc, "truncate frag: slot_id=%d, slot_sz=%zu, " "frag=%lu+%lu", slot_id, slot_sz, frag_start, frag_end); frag_end = slot_sz; } // check cache hit int cache_hit = 0; do { if (file_cache->slot_id != slot_id) { // slot not match break; } if (frag_start < file_cache->offset || frag_end > file_cache->offset + file_cache->len) { break; } cache_hit = 1; } while(0); if (cache_hit) { return(SPK_SUCCESS); } // do caching cache_sz = MIN(SYS_CACHE_SIZE, slot_sz - frag_start); size_t cache_sz_repo = cache_sz / repo_num; zlog_notice(sys_zc, "cache file: slot_id=%d, slot_sz=%zu, req_frag=%u, " "req=%lu+%lu, frag=%lu+%lu, cache_sz=%zu, blk=%lu+%lu", slot_id, slot_sz, req_frag, req_start, req_end-req_start, frag_start, frag_end-frag_start, cache_sz, blk_start, blk_num); struct dfv_file* file_ctx = NULL; void* file_buffer = memalign(SYS_INTERLACE_SIZE, cache_sz_repo); for (i=0; i<repo_num; i++) { struct dfv_repo * repo = ctx->vault->repo_tbl[i]; assert(repo); file_ctx = dfv_file_open(repo, slot_id, SPK_DIR_READ, NULL, 12+4*i); if (!file_ctx) { ret = SPKERR_BADRES; goto out; } ret = dfv_file_seek(file_ctx, frag_start / repo_num); if (ret) { goto out; } ssize_t read_sz = dfv_file_read(file_ctx, file_buffer, cache_sz_repo); if (read_sz != cache_sz_repo) { ret = SPKERR_BADRES; goto out; } dfv_file_close(file_ctx); file_ctx = NULL; // do interlace while copy data for (j=0; j<cache_sz_repo/interlace_sz; j++) { memcpy(file_cache->data+(j*repo_num+i)*interlace_sz, file_buffer+j*interlace_sz, interlace_sz); } } // cache done file_cache->slot_id = slot_id; file_cache->offset = frag_start; file_cache->len = cache_sz; file_cache->slot_sz = slot_sz; zlog_notice(sys_zc, "cache done: slot_id=%d, slot_sz=%lu, cache=%lu+%lu", slot_id, slot_sz, file_cache->offset, file_cache->len); ret = SPK_SUCCESS; out: if (file_ctx) { dfv_file_close(file_ctx); file_ctx = NULL; } SAFE_RELEASE(file_buffer); return(ret); }
CWASAPIRenderFilter::CWASAPIRenderFilter(AudioRendererSettings* pSettings, CSyncClock* pClock, Logger* pLogger) : CQueuedAudioSink(pSettings, pLogger), m_pClock(pClock), m_hLibAVRT(NULL), m_pMMDevice(NULL), m_pAudioClient(NULL), m_pRenderClient(NULL), m_nFramesInBuffer(0), m_hTask(NULL), m_nBufferSize(0), m_hDataEvent(NULL), m_pAudioClock(NULL), m_nHWfreq(0), m_dwStreamFlags(AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_NOPERSIST), m_state(StateStopped), m_bIsAudioClientStarted(false), m_bDeviceInitialized(false), m_rtNextSampleTime(0), m_rtHwStart(0), m_nSampleOffset(0), m_nDataLeftInSample(0), m_llPosError(0), m_ullPrevQpc(0), m_ullPrevPos(0), m_hNeedMoreSamples(NULL), m_rtLatency(0), m_dOutputBufferSize(m_pSettings->GetOutputBuffer() * 10000), m_pLogger(pLogger) { OSVERSIONINFO osvi; ZeroMemory(&osvi, sizeof(OSVERSIONINFO)); osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osvi); bool bWASAPIAvailable = osvi.dwMajorVersion > 5; if (!bWASAPIAvailable) Log("Disabling WASAPI - OS version earlier than Vista detected"); // Load Vista specifics DLLs m_hLibAVRT = LoadLibrary (_T("AVRT.dll")); if (m_hLibAVRT && bWASAPIAvailable) { pfAvSetMmThreadCharacteristicsW = (PTR_AvSetMmThreadCharacteristicsW) GetProcAddress (m_hLibAVRT, "AvSetMmThreadCharacteristicsW"); pfAvRevertMmThreadCharacteristics = (PTR_AvRevertMmThreadCharacteristics) GetProcAddress (m_hLibAVRT, "AvRevertMmThreadCharacteristics"); } else pSettings->SetUseWASAPI(false); // WASAPI not available below Vista if (pSettings->GetUseWASAPI()) { IMMDeviceCollection* devices = NULL; pSettings->GetAvailableAudioDevices(&devices, NULL, true); SAFE_RELEASE(devices); // currently only log available devices } // We are the end point in the pipeline so we cannot ever have passtru m_bNextFormatPassthru = false; m_nOutBufferCount = WASAPI_OUT_BUFFER_COUNT; ResetClockData(); }
HRESULT MeshManager::LoadAnimeFromX(LPD3DXANIMATIONCONTROLLER &pAnimControllerTmp,DxAnimeMesh *mesh, const string& fName,const string& path) { //読み込み用アニメーションコントローラ // LPD3DXANIMATIONCONTROLLER pAnimControllerTmp = NULL; /*アニメーションコントローラ関連*/ //アニメーションコントローラの設定 if(pAnimControllerTmp!=NULL) { //トラック数をアニメーションセット数に増やす unsigned TracksNum = pAnimControllerTmp->GetMaxNumTracks(); unsigned AnimSetsNum = pAnimControllerTmp->GetMaxNumAnimationSets(); // if(TracksNum < AnimSetsNum) { TracksNum = AnimSetsNum; } //読み込んだアニメーションコントローラから新たに設定された複製を生成 if(FAILED(pAnimControllerTmp->CloneAnimationController( pAnimControllerTmp->GetMaxNumAnimationOutputs(), pAnimControllerTmp->GetMaxNumAnimationSets(), TracksNum, pAnimControllerTmp->GetMaxNumEvents(), &mesh->pAnimController))) { } //読み込み用アニメーションコントローラの開放 // SAFE_RELEASE(pAnimControllerTmp); //トラックに全てのアニメーションセットを読み込む for(unsigned i = 1; i < AnimSetsNum; i++ ) { //読み込み用オブジェクトの宣言 LPD3DXANIMATIONSET pAnimSet = NULL; //アニメーションコントローラからアニメーションセットを読み込む if(FAILED(mesh->pAnimController->GetAnimationSet(i, &pAnimSet))) { } //指定トラックにアニメーションセットを設定 if(FAILED(mesh->pAnimController->SetTrackAnimationSet(i, pAnimSet))) { } //トラックに設定済みのアニメーションセットを開放 SAFE_RELEASE(pAnimSet); } } else { mesh->pAnimController = NULL; } //フレームの全階層をチェックしてボーンの関連付けを行う if(FAILED((this->SetupBoneFromFrame(mesh->pFrameRoot, mesh->pFrameRoot)))) { return E_FAIL; } return S_OK; }
CameraNode::~CameraNode() { if (mCamera) { SAFE_RELEASE(mCamera); } }
//------------------------------------------------------------------------------------- bool ForwardAnywhere_MessageBuffer::process() { if(pBundles_.size() <= 0) { start_ = false; return false; } Components::COMPONENTS& cts = Components::getSingleton().getComponents(forwardComponentType_); size_t idx = 0; if(cts.size() > 0) { bool hasEnabled = (g_componentType != CELLAPPMGR_TYPE && g_componentType != BASEAPPMGR_TYPE); Components::COMPONENTS::iterator ctiter = cts.begin(); for(; ctiter != cts.end(); ++ctiter) { // 必须所有的组件频道都被设置,如果不是则等待。 if((*ctiter).pChannel == NULL) return true; if((*ctiter).state == COMPONENT_STATE_RUN) hasEnabled = true; } // 必须有可用的进程 if(!hasEnabled) return true; // 最多每个tick处理5个 int icount = 5; std::vector<ForwardItem*>::iterator iter = pBundles_.begin(); for (; iter != pBundles_.end(); ++iter) { if ((*iter)->isOK()) break; } // 必须所有的ForwardItem都处于ok状态 // 何时不处于ok状态?例如:cellappmgr中的ForwardItem需要等待cellapp初始化完毕之后才ok if (iter == pBundles_.end()) return true; for(; iter != pBundles_.end(); ) { Network::Channel* pChannel = NULL; if(g_componentType != CELLAPPMGR_TYPE && g_componentType != BASEAPPMGR_TYPE) { pChannel = cts[idx++].pChannel; if(idx >= cts.size()) idx = 0; } else { while(pChannel == NULL) { if(cts[idx].state != COMPONENT_STATE_RUN) { if(++idx >= cts.size()) idx = 0; continue; } pChannel = cts[idx++].pChannel; if(idx >= cts.size()) idx = 0; } } pChannel->send((*iter)->pBundle); (*iter)->pBundle = NULL; if((*iter)->pHandler != NULL) { (*iter)->pHandler->process(); SAFE_RELEASE((*iter)->pHandler); } SAFE_RELEASE((*iter)); iter = pBundles_.erase(iter); if(--icount <= 0) return true; } DEBUG_MSG(fmt::format("ForwardAnywhere_MessageBuffer::process(): size:{}.\n", pBundles_.size())); start_ = false; return false; } return true; }
bool CAESinkDirectSound::Initialize(AEAudioFormat &format, std::string &device) { if (m_initialized) return false; LPGUID deviceGUID = NULL; RPC_CSTR wszUuid = NULL; HRESULT hr = E_FAIL; std::list<DSDevice> DSDeviceList; std::string deviceFriendlyName; DirectSoundEnumerate(DSEnumCallback, &DSDeviceList); for (std::list<DSDevice>::iterator itt = DSDeviceList.begin(); itt != DSDeviceList.end(); itt++) { if ((*itt).lpGuid) { hr = (UuidToString((*itt).lpGuid, &wszUuid)); std::string sztmp = (char*)wszUuid; std::string szGUID = "{" + std::string(sztmp.begin(), sztmp.end()) + "}"; if (strcasecmp(szGUID.c_str(), device.c_str()) == 0) { deviceGUID = (*itt).lpGuid; deviceFriendlyName = (*itt).name.c_str(); break; } } if (hr == RPC_S_OK) RpcStringFree(&wszUuid); } hr = DirectSoundCreate(deviceGUID, &m_pDSound, NULL); if (FAILED(hr)) { CLog::Log(LOGERROR, __FUNCTION__": Failed to create the DirectSound device."); CLog::Log(LOGERROR, __FUNCTION__": DSErr: %s", dserr2str(hr)); return false; } HWND tmp_hWnd; /* Dodge the null handle on first init by using desktop handle */ if (g_hWnd == NULL) tmp_hWnd = GetDesktopWindow(); else tmp_hWnd = g_hWnd; CLog::Log(LOGDEBUG, __FUNCTION__": Using Window handle: %d", tmp_hWnd); hr = m_pDSound->SetCooperativeLevel(tmp_hWnd, DSSCL_PRIORITY); if (FAILED(hr)) { CLog::Log(LOGERROR, __FUNCTION__": Failed to create the DirectSound device cooperative level."); CLog::Log(LOGERROR, __FUNCTION__": DSErr: %s", dserr2str(hr)); m_pDSound->Release(); return false; } WAVEFORMATEXTENSIBLE wfxex = {0}; //fill waveformatex ZeroMemory(&wfxex, sizeof(WAVEFORMATEXTENSIBLE)); wfxex.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX); wfxex.Format.nChannels = format.m_channelLayout.Count(); wfxex.Format.nSamplesPerSec = format.m_sampleRate; if (AE_IS_RAW(format.m_dataFormat)) { wfxex.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; wfxex.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF; wfxex.SubFormat = _KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF; wfxex.Format.wBitsPerSample = 16; wfxex.Format.nChannels = 2; } else { wfxex.dwChannelMask = SpeakerMaskFromAEChannels(format.m_channelLayout); wfxex.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE; wfxex.SubFormat = _KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; wfxex.Format.wBitsPerSample = 32; } wfxex.Samples.wValidBitsPerSample = wfxex.Format.wBitsPerSample; wfxex.Format.nBlockAlign = wfxex.Format.nChannels * (wfxex.Format.wBitsPerSample >> 3); wfxex.Format.nAvgBytesPerSec = wfxex.Format.nSamplesPerSec * wfxex.Format.nBlockAlign; m_AvgBytesPerSec = wfxex.Format.nAvgBytesPerSec; unsigned int uiFrameCount = (int)(format.m_sampleRate * 0.01); //default to 10ms chunks m_dwFrameSize = wfxex.Format.nBlockAlign; m_dwChunkSize = m_dwFrameSize * uiFrameCount; m_dwBufferLen = m_dwChunkSize * 12; //120ms total buffer // fill in the secondary sound buffer descriptor DSBUFFERDESC dsbdesc; memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); dsbdesc.dwSize = sizeof(DSBUFFERDESC); dsbdesc.dwFlags = DSBCAPS_GETCURRENTPOSITION2 /** Better position accuracy */ | DSBCAPS_GLOBALFOCUS; /** Allows background playing */ if (!g_sysinfo.IsVistaOrHigher()) dsbdesc.dwFlags |= DSBCAPS_LOCHARDWARE; /** Needed for 5.1 on emu101k, fails by design on Vista */ dsbdesc.dwBufferBytes = m_dwBufferLen; dsbdesc.lpwfxFormat = (WAVEFORMATEX *)&wfxex; // now create the stream buffer HRESULT res = IDirectSound_CreateSoundBuffer(m_pDSound, &dsbdesc, &m_pBuffer, NULL); if (res != DS_OK) { if (dsbdesc.dwFlags & DSBCAPS_LOCHARDWARE) { SAFE_RELEASE(m_pBuffer); CLog::Log(LOGDEBUG, __FUNCTION__": Couldn't create secondary buffer (%s). Trying without LOCHARDWARE.", dserr2str(res)); // Try without DSBCAPS_LOCHARDWARE dsbdesc.dwFlags &= ~DSBCAPS_LOCHARDWARE; res = IDirectSound_CreateSoundBuffer(m_pDSound, &dsbdesc, &m_pBuffer, NULL); } if (res != DS_OK) { SAFE_RELEASE(m_pBuffer); CLog::Log(LOGERROR, __FUNCTION__": cannot create secondary buffer (%s)", dserr2str(res)); return false; } } CLog::Log(LOGDEBUG, __FUNCTION__": secondary buffer created"); m_pBuffer->Stop(); AEChannelsFromSpeakerMask(wfxex.dwChannelMask); format.m_channelLayout = m_channelLayout; format.m_frames = uiFrameCount; format.m_frameSamples = format.m_frames * format.m_channelLayout.Count(); format.m_frameSize = (AE_IS_RAW(format.m_dataFormat) ? wfxex.Format.wBitsPerSample >> 3 : sizeof(float)) * format.m_channelLayout.Count(); format.m_dataFormat = AE_IS_RAW(format.m_dataFormat) ? AE_FMT_S16NE : AE_FMT_FLOAT; m_format = format; m_device = device; m_BufferOffset = 0; m_CacheLen = 0; m_LastCacheCheck = XbmcThreads::SystemClockMillis(); m_initialized = true; m_isDirtyDS = false; CLog::Log(LOGDEBUG, __FUNCTION__": Initializing DirectSound with the following parameters:"); CLog::Log(LOGDEBUG, " Audio Device : %s", ((std::string)deviceFriendlyName).c_str()); CLog::Log(LOGDEBUG, " Sample Rate : %d", wfxex.Format.nSamplesPerSec); CLog::Log(LOGDEBUG, " Sample Format : %s", CAEUtil::DataFormatToStr(format.m_dataFormat)); CLog::Log(LOGDEBUG, " Bits Per Sample : %d", wfxex.Format.wBitsPerSample); CLog::Log(LOGDEBUG, " Valid Bits/Samp : %d", wfxex.Samples.wValidBitsPerSample); CLog::Log(LOGDEBUG, " Channel Count : %d", wfxex.Format.nChannels); CLog::Log(LOGDEBUG, " Block Align : %d", wfxex.Format.nBlockAlign); CLog::Log(LOGDEBUG, " Avg. Bytes Sec : %d", wfxex.Format.nAvgBytesPerSec); CLog::Log(LOGDEBUG, " Samples/Block : %d", wfxex.Samples.wSamplesPerBlock); CLog::Log(LOGDEBUG, " Format cBSize : %d", wfxex.Format.cbSize); CLog::Log(LOGDEBUG, " Channel Layout : %s", ((std::string)format.m_channelLayout).c_str()); CLog::Log(LOGDEBUG, " Channel Mask : %d", wfxex.dwChannelMask); CLog::Log(LOGDEBUG, " Frames : %d", format.m_frames); CLog::Log(LOGDEBUG, " Frame Samples : %d", format.m_frameSamples); CLog::Log(LOGDEBUG, " Frame Size : %d", format.m_frameSize); return true; }
void CDVDOverlayCodecText::Dispose() { if(m_pOverlay) SAFE_RELEASE(m_pOverlay); }