Ejemplo n.º 1
0
//*****************************************************************************
// Using the existing RegMeta and reopen with another chuck of memory. Make sure that all stgdb
// is still kept alive.
//*****************************************************************************
HRESULT RegMeta::ReOpenWithMemory(
    LPCVOID     pData,                  // [in] Location of scope data.
    ULONG       cbData,                 // [in] Size of the data pointed to by pData.
    DWORD       dwReOpenFlags)           // [in] ReOpen flags
{
    HRESULT hr = NOERROR;

    // Only allow the ofCopyMemory and ofTakeOwnership flags 
    if (dwReOpenFlags != 0 && ((dwReOpenFlags & (~(ofCopyMemory|ofTakeOwnership))) > 0))
        return E_INVALIDARG;

    LOCKWRITE();

    
    // put the current m_pStgdb to the free list
    m_pStgdb->m_pNextStgdb = m_pStgdbFreeList;
    m_pStgdbFreeList = m_pStgdb;
    m_pStgdb = new (nothrow) CLiteWeightStgdbRW;
    IfNullGo( m_pStgdb );
    IfFailGo( OpenExistingMD(0 /* szFileName */, const_cast<void*>(pData), cbData, ofReOpen|dwReOpenFlags /* flags */) );

#ifdef FEATURE_METADATA_INTERNAL_APIS
    // We've created a new Stgdb, but may still have an Internal Importer hanging around accessing the old Stgdb.
    // The free list ensures we don't have a dangling pointer, but the 
    // If we have a corresponding InternalInterface, need to clear it because it's now using stale data.
    // Others will need to update their Internal interface to get the new data.
    {
        HRESULT hrIgnore = SetCachedInternalInterface(NULL);
        (void)hrIgnore; //prevent "unused variable" error from GCC
        _ASSERTE(hrIgnore == NOERROR); // clearing the cached interface should always succeed.
    }
#endif //FEATURE_METADATA_INTERNAL_APIS

    // we are done!
ErrExit:
    if (FAILED(hr))
    {
        // recover to the old state
        if (m_pStgdb)
            delete m_pStgdb;
        m_pStgdb = m_pStgdbFreeList;
        m_pStgdbFreeList = m_pStgdbFreeList->m_pNextStgdb;
    }
#ifdef FEATURE_METADATA_RELEASE_MEMORY_ON_REOPEN
    else
    {
        if( !(CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_MD_PreserveDebuggerMetadataMemory)) && IsSafeToDeleteStgdb())
        {
            // now that success is assured, delete the old block of memory
            // This isn't normally a safe operation because we would have given out
            // internal pointers to the memory. However when this feature is enabled
            // we track calls that might have given out internal pointers. If none
            // of the APIs were ever called then we can safely delete.
            CLiteWeightStgdbRW* pStgdb = m_pStgdbFreeList;
            m_pStgdbFreeList = m_pStgdbFreeList->m_pNextStgdb;
            delete pStgdb;
        }

        MarkSafeToDeleteStgdb(); // As of right now, no APIs have given out internal pointers
                                 // to the newly allocated stgdb
    }
#endif

    return hr;
} // RegMeta::ReOpenWithMemory
Ejemplo n.º 2
0
//
// D3DSkyNode9::VOnRestore				- 3rd Edition, Chapter 14, page 500
//
HRESULT D3DSkyNode9::VOnRestore(Scene *pScene)
{

	// Call the base class's restore
	SceneNode::VOnRestore(pScene);

	m_camera = pScene->GetCamera();					// added post press!

	m_numVerts = 20;

	SAFE_RELEASE(m_pVerts);
    if( FAILED( DXUTGetD3D9Device()->CreateVertexBuffer( 
		m_numVerts*sizeof(D3D9Vertex_ColoredTextured),
		D3DUSAGE_WRITEONLY, D3D9Vertex_ColoredTextured::FVF,
        D3DPOOL_MANAGED, &m_pVerts, NULL ) ) )
    {
        return E_FAIL;
    }

    // Fill the vertex buffer. We are setting the tu and tv texture
    // coordinates, which range from 0.0 to 1.0
    D3D9Vertex_ColoredTextured* pVertices;
    if( FAILED( m_pVerts->Lock( 0, 0, (void**)&pVertices, 0 ) ) )
        return E_FAIL;

	// Loop through the grid squares and calc the values
	// of each index. Each grid square has two triangles:
	//
	//		A - B
	//		| / |
	//		C - D

	D3D9Vertex_ColoredTextured skyVerts[4];
	D3DCOLOR skyVertColor = 0xffffffff;
	float dim = 50.0f;

	skyVerts[0].position = Vec3( dim, dim, dim ); skyVerts[0].color=skyVertColor; skyVerts[0].tu=1; skyVerts[0].tv=0; 
	skyVerts[1].position = Vec3(-dim, dim, dim ); skyVerts[1].color=skyVertColor; skyVerts[1].tu=0; skyVerts[1].tv=0; 
	skyVerts[2].position = Vec3( dim,-dim, dim ); skyVerts[2].color=skyVertColor; skyVerts[2].tu=1; skyVerts[2].tv=1; 
	skyVerts[3].position = Vec3(-dim,-dim, dim ); skyVerts[3].color=skyVertColor; skyVerts[3].tu=0; skyVerts[3].tv=1; 

	Vec3 triangle[3];
	triangle[0] = Vec3(0.f,0.f,0.f);
	triangle[1] = Vec3(5.f,0.f,0.f);
	triangle[2] = Vec3(5.f,5.f,0.f);

	Vec3 edge1 = triangle[1]-triangle[0];
	Vec3 edge2 = triangle[2]-triangle[0];

	Vec3 normal;
	normal = edge1.Cross(edge2);
	normal.Normalize();

	Mat4x4 rotY;
	rotY.BuildRotationY(GCC_PI/2.0f);
	Mat4x4 rotX;
	rotX.BuildRotationX(-GCC_PI/2.0f);
	
	m_sides = 5;

	for (DWORD side = 0; side < m_sides; side++)
	{
		for (DWORD v = 0; v < 4; v++)
		{
			Vec4 temp;
			if (side < m_sides-1)
			{
				temp = rotY.Xform(Vec3(skyVerts[v].position));
			}
			else
			{
				skyVerts[0].tu=1; skyVerts[0].tv=1; 
				skyVerts[1].tu=1; skyVerts[1].tv=0; 
				skyVerts[2].tu=0; skyVerts[2].tv=1; 
				skyVerts[3].tu=0; skyVerts[3].tv=0; 

				temp = rotX.Xform(Vec3(skyVerts[v].position));
			}
			skyVerts[v].position = Vec3(temp.x, temp.y, temp.z);
		}
		memcpy(&pVertices[side*4], skyVerts, sizeof(skyVerts));
	}

	m_pVerts->Unlock();
	return S_OK;
}
Ejemplo n.º 3
0
static HRESULT load_region(IDirectMusicInstrumentImpl *This, IStream *stream, instrument_region *region, ULONG length)
{
    HRESULT ret;
    DMUS_PRIVATE_CHUNK chunk;

    TRACE("(%p, %p, %p, %u)\n", This, stream, region, length);

    while (length)
    {
        ret = read_from_stream(stream, &chunk, sizeof(chunk));
        if (FAILED(ret))
            return ret;

        length = subtract_bytes(length, sizeof(chunk));

        switch (chunk.fccID)
        {
            case FOURCC_RGNH:
                TRACE("RGNH chunk (region header): %u bytes\n", chunk.dwSize);

                ret = read_from_stream(stream, &region->header, sizeof(region->header));
                if (FAILED(ret))
                    return ret;

                length = subtract_bytes(length, sizeof(region->header));
                break;

            case FOURCC_WSMP:
                TRACE("WSMP chunk (wave sample): %u bytes\n", chunk.dwSize);

                ret = read_from_stream(stream, &region->wave_sample, sizeof(region->wave_sample));
                if (FAILED(ret))
                    return ret;
                length = subtract_bytes(length, sizeof(region->wave_sample));

                if (!(region->loop_present = (chunk.dwSize != sizeof(region->wave_sample))))
                    break;

                ret = read_from_stream(stream, &region->wave_loop, sizeof(region->wave_loop));
                if (FAILED(ret))
                    return ret;

                length = subtract_bytes(length, sizeof(region->wave_loop));
                break;

            case FOURCC_WLNK:
                TRACE("WLNK chunk (wave link): %u bytes\n", chunk.dwSize);

                ret = read_from_stream(stream, &region->wave_link, sizeof(region->wave_link));
                if (FAILED(ret))
                    return ret;

                length = subtract_bytes(length, sizeof(region->wave_link));
                break;

            default:
                TRACE("Unknown chunk %s (skipping): %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);

                ret = advance_stream(stream, chunk.dwSize);
                if (FAILED(ret))
                    return ret;

                length = subtract_bytes(length, chunk.dwSize);
                break;
        }
    }

    return S_OK;
}
Ejemplo n.º 4
0
bool AVIDump::CreateFile()
{
	m_totalBytes = 0;
	m_frameCount = 0;
	char movie_file_name[255];
	sprintf(movie_file_name, "%sframedump%d.avi", File::GetUserPath(D_DUMPFRAMES_IDX).c_str(), m_fileCount);
	// Create path
	File::CreateFullPath(movie_file_name);

	// Ask to delete file
	if (File::Exists(movie_file_name))
	{
		if (AskYesNoT("Delete the existing file '%s'?", movie_file_name))
			File::Delete(movie_file_name);
	}

	AVIFileInit();
	NOTICE_LOG(VIDEO, "Opening AVI file (%s) for dumping", movie_file_name);
	// TODO: Make this work with AVIFileOpenW without it throwing REGDB_E_CLASSNOTREG
	HRESULT hr = AVIFileOpenA(&m_file, movie_file_name, OF_WRITE | OF_CREATE, NULL);
	if (FAILED(hr))
	{
		if (hr == AVIERR_BADFORMAT) NOTICE_LOG(VIDEO, "The file couldn't be read, indicating a corrupt file or an unrecognized format."); 
		if (hr == AVIERR_MEMORY)  NOTICE_LOG(VIDEO, "The file could not be opened because of insufficient memory."); 
		if (hr == AVIERR_FILEREAD) NOTICE_LOG(VIDEO, "A disk error occurred while reading the file."); 
		if (hr == AVIERR_FILEOPEN) NOTICE_LOG(VIDEO, "A disk error occurred while opening the file.");
		if (hr == REGDB_E_CLASSNOTREG) NOTICE_LOG(VIDEO, "AVI class not registered");
		Stop();
		return false;
	}

	SetBitmapFormat();
	NOTICE_LOG(VIDEO, "Setting video format...");
	if (!SetVideoFormat())
	{
		NOTICE_LOG(VIDEO, "Setting video format failed");
		Stop();
		return false;
	}

	if (!m_fileCount) {
		if (!SetCompressionOptions()) {
			NOTICE_LOG(VIDEO, "SetCompressionOptions failed");
			Stop();
			return false;
		}
	}

	if (FAILED(AVIMakeCompressedStream(&m_streamCompressed, m_stream, &m_options, NULL)))
	{
		NOTICE_LOG(VIDEO, "AVIMakeCompressedStream failed");
		Stop();
		return false;
	}

	if (FAILED(AVIStreamSetFormat(m_streamCompressed, 0, &m_bitmap, m_bitmap.biSize)))
	{
		NOTICE_LOG(VIDEO, "AVIStreamSetFormat failed");
		Stop();
		return false;
	}

	return true;
}
void CDisplayGPSData::SendSMS(BOOL bSendConfirmation, BOOL bUseDefaultSMSC, LPCTSTR lpszSMSC, LPCTSTR lpszRecipient, LPCTSTR lpszMessage)
{
	SMS_HANDLE smshHandle;
	SMS_ADDRESS smsaSource;
	SMS_ADDRESS smsaDestination;
	TEXT_PROVIDER_SPECIFIC_DATA tpsd;
	SMS_MESSAGE_ID smsmidMessageID;

	// try to open an SMS Handle
	if(FAILED(SmsOpen(SMS_MSGTYPE_TEXT, SMS_MODE_SEND, &smshHandle, NULL)))
	{
/*		MessageBox(NULL,
					(LPCTSTR)LoadString(ghInstance, IDS_ERROR_SMSOPEN, 0, 0), 
					(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_ERROR, 0, 0),
					MB_OK | MB_ICONERROR);*/
		return;
	}

	// Create the source address
	if(!bUseDefaultSMSC)
	{
		smsaSource.smsatAddressType = SMSAT_INTERNATIONAL;
		_tcsncpy(smsaSource.ptsAddress, lpszSMSC, SMS_MAX_ADDRESS_LENGTH);
	}

	// Create the destination address
	if( lstrlen(lpszRecipient) < 11 ){
		smsaDestination.smsatAddressType = SMSAT_ABBREVIATED;
	}
	else{
		smsaDestination.smsatAddressType = SMSAT_INTERNATIONAL;
	}
	_tcsncpy(smsaDestination.ptsAddress, lpszRecipient, SMS_MAX_ADDRESS_LENGTH);

	// Set up provider specific data
    memset(&tpsd, 0, sizeof(tpsd));
	tpsd.dwMessageOptions = bSendConfirmation ? PS_MESSAGE_OPTION_STATUSREPORT : PS_MESSAGE_OPTION_NONE;
	tpsd.psMessageClass = PS_MESSAGE_CLASS1;
	tpsd.psReplaceOption = PSRO_NONE;
	tpsd.dwHeaderDataSize = 0;

	// Send the message, indicating success or failure
	if(SUCCEEDED(SmsSendMessage(smshHandle, ((bUseDefaultSMSC) ? NULL : &smsaSource), 
								 &smsaDestination, NULL, (PBYTE) lpszMessage, 
								 _tcslen(lpszMessage) * sizeof(TCHAR), (PBYTE) &tpsd, 
								 sizeof(TEXT_PROVIDER_SPECIFIC_DATA), SMSDE_OPTIMAL, 
								 SMS_OPTION_DELIVERY_NONE, &smsmidMessageID)))
	{
	/*	MessageBox(NULL,
					(LPCTSTR)LoadString(ghInstance, IDS_SMSSENT, 0, 0), 
					(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_SUCCESS, 0, 0),
					MB_OK);*/
	}
	else
	{
	/*	MessageBox(NULL,
					(LPCTSTR)LoadString(ghInstance, IDS_ERROR_SMSSEND, 0, 0), 
					(LPCTSTR)LoadString(ghInstance, IDS_CAPTION_ERROR, 0, 0),
					MB_OK | MB_ICONERROR);
					*/
	}

	// clean up
	VERIFY(SUCCEEDED(SmsClose(smshHandle)));
}
Ejemplo n.º 6
0
bool scRenderSystem::Initialize( HWND hwnd, int width, int height )
{
	mHwnd = hwnd;
	mWindowWidth = width;
	mWindowHeight = height;
    HRESULT hr;
	
	// 创建设备

    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP, D3D_DRIVER_TYPE_SOFTWARE
    };
    unsigned int totalDriverTypes = ARRAYSIZE( driverTypes );

    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0
    };
    unsigned int totalFeatureLevels = ARRAYSIZE( featureLevels );

    DXGI_SWAP_CHAIN_DESC swapChainDesc;
    ZeroMemory( &swapChainDesc, sizeof( swapChainDesc ) );
    swapChainDesc.BufferCount = 1;
    swapChainDesc.BufferDesc.Width = width;
    swapChainDesc.BufferDesc.Height = height;
    swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    swapChainDesc.BufferDesc.RefreshRate.Numerator = 60;
    swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
    swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    swapChainDesc.OutputWindow = hwnd;
    swapChainDesc.Windowed = true;
    swapChainDesc.SampleDesc.Count = 1;
    swapChainDesc.SampleDesc.Quality = 0;
	
    for (unsigned int i = 0; i < totalDriverTypes; ++i)
    {
		// 尝试创建
		hr = D3D11CreateDeviceAndSwapChain(0, driverTypes[i], 0, 0,
                                                featureLevels, totalFeatureLevels,
                                                D3D11_SDK_VERSION, &swapChainDesc, &mSwapChain,
                                                &mDevice, &mFeatureLevel, &mContext);
        if(SUCCEEDED(hr))
        {
            mDriverType = driverTypes[i];
            break;
        }
    }
    if(FAILED(hr))
    {
		scErrMsg("Failed to create the Direct3D device!");
        return false;
    }


	// 创建backbuffer

    ID3D11Texture2D* backBufferTexture;
    hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferTexture);
    if(FAILED(hr))
    {
		scErrMsg("Failed to get the swap chain back buffer!");
        return false;
    }

    hr = mDevice->CreateRenderTargetView(backBufferTexture, 0, &mBackBuffer);
    if(backBufferTexture)
        backBufferTexture->Release();
    if(FAILED(hr))
    {
		scErrMsg("Failed to create back buffer!");
        return false;
    }

	// 创建depthbuffer

	D3D11_TEXTURE2D_DESC depthTexDesc;
	ZeroMemory(&depthTexDesc, sizeof(depthTexDesc));
	depthTexDesc.Width = width;
	depthTexDesc.Height = height;
	depthTexDesc.MipLevels = 1;
	depthTexDesc.ArraySize = 1;
	depthTexDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	depthTexDesc.SampleDesc.Count = 1;
	depthTexDesc.SampleDesc.Quality = 0;
	depthTexDesc.Usage = D3D11_USAGE_DEFAULT;
	depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
	depthTexDesc.CPUAccessFlags = 0;
	depthTexDesc.MiscFlags = 0;

	ID3D11Texture2D* depthTexture;
	hr = mDevice->CreateTexture2D(&depthTexDesc, NULL, &depthTexture);
	if(FAILED(hr))
	{
		scErrMsg("Failed to create the depth texture!");
		return false;
	}

	D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory(&descDSV, sizeof(descDSV));
	descDSV.Format = depthTexDesc.Format;
	descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
	descDSV.Texture2D.MipSlice = 0;

	hr = mDevice->CreateDepthStencilView(depthTexture, &descDSV, &mDepthBuffer);
	if(FAILED(hr))
	{
		scErrMsg("Failed to create the depth stencil target view!");
		return false;
	}

	// 设置render target

	mContext->OMSetRenderTargets(1, &mBackBuffer, mDepthBuffer);

	// 设置viewport

	/*D3D11_VIEWPORT viewport;
	viewport.Width = static_cast<float>(width);
	viewport.Height = static_cast<float>(height);
	viewport.MinDepth = 0.0f;
	viewport.MaxDepth = 1.0f;
	viewport.TopLeftX = 0.0f;
	viewport.TopLeftY = 0.0f;
	mContext->RSSetViewports(1, &viewport);*/

	// 初始化各种manager
	mTextureManager.Initialize(mDevice);
	mTextureManager.LoadArchive("../../res/texture.txt");
	mTextureManager.LoadAll();
	mMeshManager.Initialize(mDevice);
	mMeshManager.LoadArchive("../../res/mesh.txt");
	mMeshManager.LoadAll();
	mVertexShaderManager.Initialize(mDevice);
	mVertexShaderManager.LoadArchive("../../res/vshader.txt");
	//mVertexShaderManager.LoadAll();
	mVertexShaderManager.CreateDefaultShader();
	mPixelShaderManager.Initialize(mDevice);
	mPixelShaderManager.LoadArchive("../../res/vshader.txt");
	//mPixelShaderManager.LoadAll();
	mPixelShaderManager.CreateDefaultShader(); 

	// sampler
	D3D11_SAMPLER_DESC samplerDesc;
	ZeroMemory(&samplerDesc, sizeof(samplerDesc));
	samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
	samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	samplerDesc.MaxLOD = D3D11_FLOAT32_MAX;

	hr = mDevice->CreateSamplerState(&samplerDesc, &mSampler);
	if (FAILED(hr))
	{
		scErrMsg("Faileed to create color map sampler state!");
		return false;
	}

	// 初始化完成
	mInitialized = true;

	return _LoadScene();
}
Ejemplo n.º 7
0
HRESULT 
MDFormat::VerifySignature(
    PSTORAGESIGNATURE pSig,     // The signature to check.
    ULONG             cbData)
{
    HRESULT hr = S_OK;
    
    // If signature didn't match, you shouldn't be here.
    ULONG dwSignature = pSig->GetSignature();
    if (dwSignature == STORAGE_MAGIC_OLD_SIG)
    {
        Debug_ReportError("Invalid MetaData storage signature - old magic signature +MOC.");
        return PostError(CLDB_E_FILE_OLDVER, 1, 0);
    }
    if (dwSignature != STORAGE_MAGIC_SIG)
    {
        Debug_ReportError("Invalid MetaData storage signature - unrecognized magic signature, should be BSJB.");
        return PostError(CLDB_E_FILE_CORRUPT);
    }
    
    // Check for overflow
    ULONG lVersionString = pSig->GetVersionStringLength();
    ULONG sum = sizeof(STORAGESIGNATURE) + lVersionString;
    if ((sum < sizeof(STORAGESIGNATURE)) || (sum < lVersionString))
    {
        Debug_ReportError("Invalid MetaData storage signature - version string too long, integer overflow.");
        return PostError(CLDB_E_FILE_CORRUPT);
    }
    
    // Check for invalid version string size
    if ((sizeof(STORAGESIGNATURE) + lVersionString) > cbData)
    {
        Debug_ReportError("Invalid MetaData storage signature - version string too long.");
        return PostError(CLDB_E_FILE_CORRUPT);
    }
    
    // Check that the version string is null terminated. This string
    // is ANSI, so no double-null checks need to be made.
    {
        BYTE *pStart = &pSig->pVersion[0];
        BYTE *pEnd = pStart + lVersionString + 1; // Account for terminating NULL
        BYTE *pCur;
        
        for (pCur = pStart; pCur < pEnd; pCur++)
        {
            if (*pCur == 0)
                break;
        }
        
        // If we got to the end without hitting a NULL, we have a bad version string
        if (pCur == pEnd)
        {
            Debug_ReportError("Invalid MetaData storage signature - version string has not null-terminator.");
            return PostError(CLDB_E_FILE_CORRUPT);
        }
    }
    
#if !defined(FEATURE_METADATA_STANDALONE_WINRT)
    // Only a specific version of the 0.x format is supported by this code
    // in order to support the NT 5 beta clients which used this format.
    if (pSig->GetMajorVer() == FILE_VER_MAJOR_v0)
    {
        if (pSig->GetMinorVer() < FILE_VER_MINOR_v0)
        {
            Debug_ReportError("Invalid MetaData storage signature - unrecognized version, should be 1.1.");
            hr = CLDB_E_FILE_OLDVER;
        }
    }
    else
#endif  // !defined(FEATURE_METADATA_STANDALONE_WINRT)
    // There is currently no code to migrate an old format of the 1.x.  This
    // would be added only under special circumstances.
    if ((pSig->GetMajorVer() != FILE_VER_MAJOR) || (pSig->GetMinorVer() != FILE_VER_MINOR))
    {
        Debug_ReportError("Invalid MetaData storage signature - unrecognized version, should be 1.1.");
        hr = CLDB_E_FILE_OLDVER;
    }

    if (FAILED(hr))
        hr = PostError(hr, (int)pSig->GetMajorVer(), (int)pSig->GetMinorVer());
    return hr;
} // MDFormat::VerifySignature
Ejemplo n.º 8
0
//-----------------------------------------------------------------------------
// Name: CWaveFile::Open()
// Desc: Opens a wave file for reading
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Open( LPWSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags )
{
    HRESULT hr;

    m_dwFlags = dwFlags;
    m_bIsReadingFromMemory = FALSE;

    if( m_dwFlags == WAVEFILE_READ )
    {
        if( strFileName == NULL )
            return E_INVALIDARG;
        SAFE_DELETE_ARRAY( m_pwfx );

        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ );

        if( NULL == m_hmmio )
        {
            HRSRC   hResInfo;
            HGLOBAL hResData;
            DWORD   dwSize;
            VOID*   pvRes;

            // Loading it as a file failed, so try it as a resource
            if( NULL == ( hResInfo = FindResource( NULL, strFileName, L"WAVE" ) ) )
            {
                if( NULL == ( hResInfo = FindResource( NULL, strFileName, L"WAV" ) ) )
                    return DXTRACE_ERR( L"FindResource", E_FAIL );
            }

            if( NULL == ( hResData = LoadResource( GetModuleHandle(NULL), hResInfo ) ) )
                return DXTRACE_ERR( L"LoadResource", E_FAIL );

            if( 0 == ( dwSize = SizeofResource( GetModuleHandle(NULL), hResInfo ) ) )
                return DXTRACE_ERR( L"SizeofResource", E_FAIL );

            if( NULL == ( pvRes = LockResource( hResData ) ) )
                return DXTRACE_ERR( L"LockResource", E_FAIL );

            m_pResourceBuffer = new CHAR[ dwSize ];
            if( m_pResourceBuffer == NULL )
                return DXTRACE_ERR( L"new", E_OUTOFMEMORY );
            memcpy( m_pResourceBuffer, pvRes, dwSize );

            MMIOINFO mmioInfo;
            ZeroMemory( &mmioInfo, sizeof(mmioInfo) );
            mmioInfo.fccIOProc = FOURCC_MEM;
            mmioInfo.cchBuffer = dwSize;
            mmioInfo.pchBuffer = (CHAR*) m_pResourceBuffer;

            m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ );
        }

        if( FAILED( hr = ReadMMIO() ) )
        {
            // ReadMMIO will fail if its an not a wave file
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR( L"ReadMMIO", hr );
        }

        if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( L"ResetFile", hr );

        // After the reset, the size of the wav file is m_ck.cksize so store it now
        m_dwSize = m_ck.cksize;
    }
    else
    {
        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF  |
                                                  MMIO_READWRITE |
                                                  MMIO_CREATE );
        if( NULL == m_hmmio )
            return DXTRACE_ERR( L"mmioOpen", E_FAIL );

        if( FAILED( hr = WriteMMIO( pwfx ) ) )
        {
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR( L"WriteMMIO", hr );
        }

        if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( L"ResetFile", hr );
    }

    return hr;
}
Ejemplo n.º 9
0
Archivo: dsound.c Proyecto: m64/PEG
static ALCboolean DSoundOpenPlayback(ALCdevice *device, const ALCchar *deviceName)
{
    DSBUFFERDESC DSBDescription;
    DSoundData *pData = NULL;
    WAVEFORMATEXTENSIBLE OutputType;
    DWORD frameSize = 0;
    LPGUID guid = NULL;
    DWORD speakers;
    HRESULT hr;

    if(deviceName)
    {
        int i;
        for(i = 0;DeviceList[i].name;i++)
        {
            if(strcmp(deviceName, DeviceList[i].name) == 0)
            {
                device->szDeviceName = DeviceList[i].name;
                if(i > 0)
                    guid = &DeviceList[i].guid;
                break;
            }
        }
        if(!DeviceList[i].name)
            return ALC_FALSE;
    }
    else
        device->szDeviceName = DeviceList[0].name;

    memset(&OutputType, 0, sizeof(OutputType));

    //Initialise requested device

    pData = calloc(1, sizeof(DSoundData));
    if(!pData)
    {
        SetALCError(ALC_OUT_OF_MEMORY);
        return ALC_FALSE;
    }

    //DirectSound Init code
    hr = DirectSoundCreate(guid, &pData->lpDS, NULL);
    if(SUCCEEDED(hr))
        hr = IDirectSound_SetCooperativeLevel(pData->lpDS, GetForegroundWindow(), DSSCL_PRIORITY);

    if(SUCCEEDED(hr))
        hr = IDirectSound_GetSpeakerConfig(pData->lpDS, &speakers);
    if(SUCCEEDED(hr))
    {
        speakers = DSSPEAKER_CONFIG(speakers);
        if(speakers == DSSPEAKER_MONO)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                device->Format = AL_FORMAT_MONO8;
            else
                device->Format = AL_FORMAT_MONO16;
        }
        else if(speakers == DSSPEAKER_STEREO)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                device->Format = AL_FORMAT_STEREO8;
            else
                device->Format = AL_FORMAT_STEREO16;
        }
        else if(speakers == DSSPEAKER_QUAD)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                device->Format = AL_FORMAT_QUAD8;
            else
                device->Format = AL_FORMAT_QUAD16;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT;
        }
        else if(speakers == DSSPEAKER_5POINT1)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                device->Format = AL_FORMAT_51CHN8;
            else
                device->Format = AL_FORMAT_51CHN16;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_FRONT_CENTER |
                                       SPEAKER_LOW_FREQUENCY |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT;
        }
        else if(speakers == DSSPEAKER_7POINT1)
        {
            if(aluBytesFromFormat(device->Format) == 1)
                device->Format = AL_FORMAT_71CHN8;
            else
                device->Format = AL_FORMAT_71CHN16;
            OutputType.dwChannelMask = SPEAKER_FRONT_LEFT |
                                       SPEAKER_FRONT_RIGHT |
                                       SPEAKER_FRONT_CENTER |
                                       SPEAKER_LOW_FREQUENCY |
                                       SPEAKER_BACK_LEFT |
                                       SPEAKER_BACK_RIGHT |
                                       SPEAKER_SIDE_LEFT |
                                       SPEAKER_SIDE_RIGHT;
        }
        frameSize = aluBytesFromFormat(device->Format) *
                    aluChannelsFromFormat(device->Format);

        OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
        OutputType.Format.nChannels = aluChannelsFromFormat(device->Format);
        OutputType.Format.wBitsPerSample = aluBytesFromFormat(device->Format) * 8;
        OutputType.Format.nBlockAlign = OutputType.Format.nChannels*OutputType.Format.wBitsPerSample/8;
        OutputType.Format.nSamplesPerSec = device->Frequency;
        OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec*OutputType.Format.nBlockAlign;
        OutputType.Format.cbSize = 0;

        device->UpdateSize /= DS_FRAGS;
    }

    if(OutputType.Format.nChannels > 2)
    {
        OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
        OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
        OutputType.Format.cbSize = 22;
        OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
    }
    else
    {
        if(SUCCEEDED(hr))
        {
            memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
            DSBDescription.dwSize=sizeof(DSBUFFERDESC);
            DSBDescription.dwFlags=DSBCAPS_PRIMARYBUFFER;
            hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSpbuffer, NULL);
        }
        if(SUCCEEDED(hr))
            hr = IDirectSoundBuffer_SetFormat(pData->DSpbuffer,&OutputType.Format);
    }

    if(SUCCEEDED(hr))
    {
        memset(&DSBDescription,0,sizeof(DSBUFFERDESC));
        DSBDescription.dwSize=sizeof(DSBUFFERDESC);
        DSBDescription.dwFlags=DSBCAPS_GLOBALFOCUS|DSBCAPS_GETCURRENTPOSITION2;
        DSBDescription.dwBufferBytes=device->UpdateSize * DS_FRAGS * frameSize;
        DSBDescription.lpwfxFormat=&OutputType.Format;
        hr = IDirectSound_CreateSoundBuffer(pData->lpDS, &DSBDescription, &pData->DSsbuffer, NULL);
    }

    if(SUCCEEDED(hr))
        hr = IDirectSoundBuffer_Play(pData->DSsbuffer, 0, 0, DSBPLAY_LOOPING);

    device->ExtraData = pData;
    pData->thread = StartThread(DSoundProc, device);
    if(!pData->thread)
        hr = E_FAIL;

    if(FAILED(hr))
    {
        if (pData->DSsbuffer)
            IDirectSoundBuffer_Release(pData->DSsbuffer);
        if (pData->DSpbuffer)
            IDirectSoundBuffer_Release(pData->DSpbuffer);
        if (pData->lpDS)
            IDirectSound_Release(pData->lpDS);

        free(pData);
        return ALC_FALSE;
    }

    return ALC_TRUE;
}
Ejemplo n.º 10
0
RegMeta::~RegMeta()
{
    BEGIN_CLEANUP_ENTRYPOINT;
    
    _ASSERTE(!m_bCached);

    HRESULT hr = S_OK;

    LOCKWRITENORET();
    
#ifdef FEATURE_METADATA_INTERNAL_APIS
    // This should have worked if we've cached the public interface in the past
    _ASSERTE(SUCCEEDED(hr) || (m_pInternalImport == NULL) || (m_pInternalImport->GetCachedPublicInterface(false) == NULL));
#endif //FEATURE_METADATA_INTERNAL_APIS

    if (SUCCEEDED(hr))
    {
#ifdef FEATURE_METADATA_INTERNAL_APIS
        if (m_pInternalImport != NULL)
        {
            // RegMeta is going away. Make sure we clear up the pointer from MDInternalRW to this RegMeta.
            if (FAILED(m_pInternalImport->SetCachedPublicInterface(NULL)))
            {   // Do nothing on error
            }
            m_pInternalImport = NULL;
            m_fOwnSem = false;
        }
#endif //FEATURE_METADATA_INTERNAL_APIS

        UNLOCKWRITE();
    }

    if (m_pFreeThreadedMarshaler)
    {
        m_pFreeThreadedMarshaler->Release();
        m_pFreeThreadedMarshaler = NULL;
    }

    if (m_pSemReadWrite && m_fOwnSem)
        delete m_pSemReadWrite;

    // If this RegMeta is a wrapper on an external StgDB, release it.
    if (IsOfExternalStgDB(m_OpenFlags))
    {
        _ASSERTE(m_pUnk != NULL);   // Owning IUnknown for external StgDB.
        if (m_pUnk)
            m_pUnk->Release();
        m_pUnk = 0;
    }
    else
    {   // Not a wrapper, so free our StgDB.
        _ASSERTE(m_pUnk == NULL); 
        // It's possible m_pStdbg is NULL in OOM scenarios
        if (m_pStgdb != NULL)
            delete m_pStgdb;
        m_pStgdb = 0;
    }

    // Delete the old copies of Stgdb list. This is the list track all of the 
    //  old snapshuts with ReOpenWithMemory call.
    CLiteWeightStgdbRW  *pCur; 
    while (m_pStgdbFreeList)
    {
        pCur = m_pStgdbFreeList;
        m_pStgdbFreeList = m_pStgdbFreeList->m_pNextStgdb;
        delete pCur;
    }

    if (m_pVEHandler)
        m_pVEHandler->Release();

    // If This RegMeta spun up the runtime (probably to process security 
    //  attributes), shut it down now.
    if (m_fStartedEE) 
    {
        m_pAppDomain->Release();
#ifdef FEATURE_INCLUDE_ALL_INTERFACES
        m_pCorHost->Stop();
        m_pCorHost->Release();
#endif // FEATURE_INCLUDE_ALL_INTERFACES
    }

    if (m_pFilterManager != NULL)
        delete m_pFilterManager;


    if (m_OptionValue.m_RuntimeVersion != NULL)
        delete[] m_OptionValue.m_RuntimeVersion;

    END_CLEANUP_ENTRYPOINT;
    
} // RegMeta::~RegMeta()
bool LoadModuleIntoBuffer(std::wstring plyFileName, std::wstring &error)
{

	// Load our ply file... in a moment...
	CPlyFile5nt_DX11 myPly;
	if ( !myPly.OpenPLYFile( plyFileName, error ) )	//ply\\bun_zipper_res3.ply
	{
		MessageBox(NULL, error.c_str(), L"Error", MB_OK );
		return false;
	}


	//Check if model has been already loaded
	if (g_mapPlyInfo.find(plyFileName) != g_mapPlyInfo.end())
	{
		//Already exist
		error = L"PLY file already loaded.";
		return false;
	}

	g_mapPlyInfo[plyFileName].numberOfElementsToDraw = myPly.GetNumberOfElements();
	g_mapPlyInfo[plyFileName].numberOfVertices = myPly.GetNumberOfVerticies();
	g_mapPlyInfo[plyFileName].maxExtent = myPly.getMaxExtent();

	myPly.normalizeTheModelBaby();

	//Week 9
	// Calculate texture coordinates...if there weren't any.
	myPly.GenTextureCoordsSpherical( CPlyFile5nt_DX11::POSITIVE_X, 
		CPlyFile5nt_DX11::POSITIVE_Y, 
		true, 1.0f, false );

	int totalNumberOfVertices = myPly.GetNumberOfVerticies() * 2;	// Make it a bit bigger.
	SimpleVertex* tempVertexArray = new SimpleVertex[ totalNumberOfVertices ];
	memset( tempVertexArray, 0, totalNumberOfVertices * sizeof( SimpleVertex ) );

	// Create a temporary "local" index array
	int totalNumberOfElements = myPly.GetNumberOfElements() * 2;
	DWORD* tempIndexArray = new DWORD[ totalNumberOfElements * 3 ];
	memset( tempIndexArray, 0, totalNumberOfElements * 3 * sizeof(DWORD) );

	for ( int index = 0; index != myPly.GetNumberOfVerticies(); index++ )
	{
		tempVertexArray[index].Pos.x = myPly.getVertex_at( index ).xyz.x;
		tempVertexArray[index].Pos.y = myPly.getVertex_at( index ).xyz.y;
		tempVertexArray[index].Pos.z = myPly.getVertex_at( index ).xyz.z;
		tempVertexArray[index].Pos.w = 1.0f;	// W is almost alway 1.0f;

		tempVertexArray[index].Normal.x = myPly.getVertex_at( index ).nx;
		tempVertexArray[index].Normal.y = myPly.getVertex_at( index ).ny;
		tempVertexArray[index].Normal.z = myPly.getVertex_at( index ).nz;
		tempVertexArray[index].Normal.w = 1.0f;	// W is almost alway 1.0f;
		// week 9
		tempVertexArray[index].Tex.x = myPly.getVertex_at(index).tex0u;
		tempVertexArray[index].Tex.y = myPly.getVertex_at(index).tex0v;
		std::wostringstream  wss;
		wss << L"x: " << tempVertexArray[index].Tex.x << std::endl;

		//OutputDebugString(wss.str().c_str());
		//wss << L"";
		//wss << L"y: " << tempVertexArray[index].Tex.y << std::endl;
		//OutputDebugString(wss.str().c_str());
		//

	}

	// Now the maddness starts when we copy the index buffer...
	for ( int triNum = 0; triNum != myPly.GetNumberOfElements(); triNum++ )
	{
		int arrayIndex = triNum * 3;		// Because it's triangles (3 side)

		tempIndexArray[arrayIndex + 0] = myPly.getElement_at( triNum ).vertex_index_1;
		tempIndexArray[arrayIndex + 1] = myPly.getElement_at( triNum ).vertex_index_2;
		tempIndexArray[arrayIndex + 2] = myPly.getElement_at( triNum ).vertex_index_3;
	}

	D3D11_BUFFER_DESC bd;
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof( SimpleVertex ) * totalNumberOfVertices;
	bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	InitData.pSysMem = tempVertexArray;

	HRESULT hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &(g_mapPlyInfo[plyFileName].vertexBuffer));
	if( FAILED( hr ) )
	{
		error = L"ERROR: Unable to create vertex buffer.";
		return false;
	}

	// Same thing, but with the index buffer...
	bd.Usage = D3D11_USAGE_DEFAULT;
	bd.ByteWidth = sizeof( DWORD ) * totalNumberOfElements * 3;       
	bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
	InitData.pSysMem = tempIndexArray;
	hr = g_pd3dDevice->CreateBuffer( &bd, &InitData, &(g_mapPlyInfo[plyFileName].indexBuffer));
	if( FAILED( hr ) )
	{
		error = L"ERROR: Unable to create index buffer";
		return false;
	}


	// Delete all of our stuff...
	delete [] tempVertexArray;		// WATCH IT!!
	delete [] tempIndexArray;

	return true;
}
Ejemplo n.º 12
0
//---------------------------------------------------------------------------------------
// 
// Returns the memory region of the mapped file and type of its mapping. The choice of the file mapping type 
// for each scope is CLR implementation specific and user cannot explicitly set it.
// 
// The memory is valid only as long as the underlying MetaData scope is opened (there's a reference to 
// a MetaData interface for this scope).
// 
// Implements public API code:IMetaDataInfo::GetFileMapping.
// 
// Arguments:
//    ppvData - Fills with pointer to the start of the mapped file.
//    pcbData - Fills with the size of the mapped memory region (for flat-mapping it is the size of the 
//              file).
//    pdwMappingType - Fills with type of file mapping (code:CorFileMapping).
//        Current CLR implementation returns always code:fmFlat. The other value(s) are reserved for future 
//        usage. See code:StgIO::MapFileToMem#CreateFileMapping_SEC_IMAGE for more details.
// 
// Return Value:
//    S_OK               - All output data are filled.
//    COR_E_NOTSUPPORTED - CLR cannot (or doesn't want to) provide the memory region.
//        This can happen when:
//          - The MetaData scope was opened with flag code:ofWrite or code:ofCopyMemory.
//            Note: code:ofCopyMemory could be supported in future CLR versions. For example if we change 
//            code:CLiteWeightStgdbRW::OpenForRead to copy whole file (or add a new flag ofCopyWholeFile).
//          - The MetaData scope was opened without flag code:ofReadOnly.
//            Note: We could support this API without code:ofReadOnly flag in future CLR versions. We just 
//            need some test coverage and user scenario for it.
//          - Only MetaData part of the file was opened using code:OpenScopeOnMemory.
//          - The file is not NT PE file (e.g. it is NT OBJ = .obj file produced by managed C++).
//    E_INVALIDARG       - NULL was passed as an argument value.
// 
HRESULT 
RegMeta::GetFileMapping(
    const void ** ppvData, 
    ULONGLONG *   pcbData, 
    DWORD *       pdwMappingType)
{
    HRESULT hr = S_OK;
    
    if ((ppvData == NULL) || (pcbData == NULL) || (pdwMappingType == NULL))
    {
        return E_INVALIDARG;
    }
    
    // Note: Some of the following checks are duplicit (as some combinations are invalid and ensured by CLR 
    // implementation), but it is easier to check them all
    
    // OpenScope flags have to be (ofRead | ofReadOnly) and not ofCopyMemory 
    // (as code:CLiteWeightStgdbRW::OpenForRead will copy only the MetaData part of the file)
    if (((m_OpenFlags & ofReadWriteMask) != ofRead) || 
        ((m_OpenFlags & ofReadOnly) == 0) || 
        ((m_OpenFlags & ofCopyMemory) != 0))
    {
        IfFailGo(COR_E_NOTSUPPORTED);
    }
    // The file has to be NT PE file (not CLDB = managed C++ .obj file) and we have to have its full mapping 
    // (see code:CLiteWeightStgdbRW::OpenForRead)
    if ((m_pStgdb->m_pImage == NULL) || 
        (m_pStgdb->m_dwImageSize == 0) || 
        (m_pStgdb->GetFileType() != FILETYPE_NTPE))
    {
        IfFailGo(COR_E_NOTSUPPORTED);
    }
    if (m_pStgdb->m_pStgIO->GetFlags() != DBPROP_TMODEF_READ)
    {
        IfFailGo(COR_E_NOTSUPPORTED);
    }
    // The file has to be flat-mapped, or copied to memory (file mapping code:MTYPE_IMAGE is not currently 
    // supported - see code:StgIO::MapFileToMem#CreateFileMapping_SEC_IMAGE)
    // Note: Only small files (<=64K) are copied to memory - see code:StgIO::MapFileToMem#CopySmallFiles
    if ((m_pStgdb->m_pStgIO->GetMemoryMappedType() != MTYPE_FLAT) && 
        (m_pStgdb->m_pStgIO->GetMemoryMappedType() != MTYPE_NOMAPPING))
    {
        IfFailGo(COR_E_NOTSUPPORTED);
    }
    // All necessary conditions are satisfied
    
    *ppvData = m_pStgdb->m_pImage;
    *pcbData = m_pStgdb->m_dwImageSize;
    // We checked that the file was flat-mapped above
    *pdwMappingType = fmFlat;
    
ErrExit:
    if (FAILED(hr))
    {
        *ppvData = NULL;
        *pcbData = 0;
        *pdwMappingType = 0;
    }
    
    return hr;
} // RegMeta::GetFileMapping
Ejemplo n.º 13
0
HRESULT 
RegMeta::QueryInterface(
    REFIID  riid, 
    void ** ppUnk)
{
    HRESULT hr = S_OK;
    BEGIN_ENTRYPOINT_NOTHROW;
    int fIsInterfaceRW = false;
    *ppUnk = 0;

    if (riid == IID_IUnknown)
    {
        *ppUnk = (IUnknown *)(IMetaDataImport2 *)this;
    }
    else if (riid == IID_IMDCommon)
    {
        *ppUnk = (IMDCommon *)this;
    }
    else if (riid == IID_IMetaDataImport)
    {
        *ppUnk = (IMetaDataImport2 *)this;
    }
    else if (riid == IID_IMetaDataImport2)
    {
        *ppUnk = (IMetaDataImport2 *)this;
    }
    else if (riid == IID_IMetaDataAssemblyImport)
    {
        *ppUnk = (IMetaDataAssemblyImport *)this;
    }
    else if (riid == IID_IMetaDataTables)
    {
        *ppUnk = static_cast<IMetaDataTables *>(this);
    }
    else if (riid == IID_IMetaDataTables2)
    {
        *ppUnk = static_cast<IMetaDataTables2 *>(this);
    }

#ifndef FEATURE_METADATA_STANDALONE_WINRT
    else if (riid == IID_IMetaDataInfo)
    {
        *ppUnk = static_cast<IMetaDataInfo *>(this);
    }
#endif //!FEATURE_METADATA_STANDALONE_WINRT

#ifdef FEATURE_METADATA_EMIT
    else if (riid == IID_IMetaDataEmit)
    {
        *ppUnk = (IMetaDataEmit2 *)this;
        fIsInterfaceRW = true;
    }
    else if (riid == IID_IMetaDataEmit2)
    {
        *ppUnk = (IMetaDataEmit2 *)this;
        fIsInterfaceRW = true;
    }
    else if (riid == IID_IMetaDataAssemblyEmit)
    {
        *ppUnk = (IMetaDataAssemblyEmit *)this;
        fIsInterfaceRW = true;
    }
#endif //FEATURE_METADATA_EMIT

#if defined(FEATURE_METADATA_IN_VM) && !defined(FEATURE_CORECLR)
    else if (riid == IID_IMetaDataValidate)
    {
        *ppUnk = (IMetaDataValidate *)this;
    }
#endif //defined(FEATURE_METADATA_IN_VM) && !defined(FEATURE_CORECLR)

#ifdef FEATURE_METADATA_EMIT_ALL
    else if (riid == IID_IMetaDataFilter)
    {
        *ppUnk = (IMetaDataFilter *)this;
    }
#endif //FEATURE_METADATA_EMIT_ALL

#ifdef FEATURE_METADATA_INTERNAL_APIS
    else if (riid == IID_IMetaDataHelper)
    {
        *ppUnk = (IMetaDataHelper *)this;
    }
    else if (riid == IID_IMDInternalEmit)
    {
        *ppUnk = static_cast<IMDInternalEmit *>(this);
    }
    else if (riid == IID_IGetIMDInternalImport)
    {
        *ppUnk = static_cast<IGetIMDInternalImport *>(this);
    }
#endif //FEATURE_METADATA_INTERNAL_APIS

#if defined(FEATURE_METADATA_EMIT) && defined(FEATURE_METADATA_INTERNAL_APIS)
    else if (riid == IID_IMetaDataEmitHelper)
    {
        *ppUnk = (IMetaDataEmitHelper *)this;
        fIsInterfaceRW = true;
    }
#endif //FEATURE_METADATA_EMIT && FEATURE_METADATA_INTERNAL_APIS

#ifdef FEATURE_METADATA_IN_VM
#ifdef FEATURE_COMINTEROP
    else if (riid == IID_IMarshal)
    {
        // We will only repond to this interface if scope is opened for ReadOnly
        if (IsOfReadOnly(m_OpenFlags))
        {
            if (m_pFreeThreadedMarshaler == NULL)
            {
                // Guard ourselves against first time QI on IMarshal from two different threads..
                LOCKWRITE();
                if (m_pFreeThreadedMarshaler == NULL)
                {
                    // First time! Create the FreeThreadedMarshaler
                    IfFailGo(CoCreateFreeThreadedMarshaler((IUnknown *)(IMetaDataEmit2 *)this, &m_pFreeThreadedMarshaler));
                }                
            }
            
            _ASSERTE(m_pFreeThreadedMarshaler != NULL);
            
            IfFailGo(m_pFreeThreadedMarshaler->QueryInterface(riid, ppUnk));
            
            // AddRef has happened in the QueryInterface and thus should just return
            goto ErrExit;
        }
        else
        {
            IfFailGo(E_NOINTERFACE);
        }
    }
#endif // FEATURE_COMINTEROP
#ifdef FEATURE_PREJIT
    else if (riid == IID_IMetaDataCorProfileData)
    {
        *ppUnk = (IMetaDataCorProfileData *)this;
    }
    else if (riid == IID_IMDInternalMetadataReorderingOptions)
    {
        *ppUnk = (IMDInternalMetadataReorderingOptions *)this;
    }
#endif //FEATURE_PREJIT
#endif //FEATURE_METADATA_IN_VM
    else
    {
        IfFailGo(E_NOINTERFACE);
    }

    if (fIsInterfaceRW && IsOfReadOnly(m_OpenFlags))
    {
        // They are asking for a read/write interface and this scope was
        // opened as Read-Only

        *ppUnk = NULL;
        IfFailGo(CLDB_E_INCOMPATIBLE);
    }

    if (fIsInterfaceRW)
    {
        LOCKWRITENORET();

        if (SUCCEEDED(hr))
        {
            hr = m_pStgdb->m_MiniMd.ConvertToRW();
        }

        if (FAILED(hr))
        {
            *ppUnk = NULL;
            goto ErrExit;
        }
    }

    AddRef();
ErrExit:
    
    END_ENTRYPOINT_NOTHROW;

    return hr;
} // RegMeta::QueryInterface
Ejemplo n.º 14
0
//*****************************************************************************
// IGetIMDInternalImport methods
//*****************************************************************************
HRESULT RegMeta::GetIMDInternalImport(
        IMDInternalImport ** ppIMDInternalImport   // [OUT] Buffer to receive IMDInternalImport*
    )
{
    HRESULT       hr = S_OK;
    MDInternalRW *pInternalRW = NULL;
    bool          isLockedForWrite = false;
    IUnknown     *pIUnkInternal = NULL;
    IUnknown     *pThis = (IMetaDataImport2*)this;  

    pIUnkInternal = this->GetCachedInternalInterface(TRUE);
    if (pIUnkInternal)
    {
        // there is already a cached Internal interface. GetCachedInternalInterface does add ref the 
        // returned interface 
        IfFailGo(pIUnkInternal->QueryInterface(IID_IMDInternalImport, (void**)ppIMDInternalImport));
        goto ErrExit;
    }

    if (this->IsThreadSafetyOn())
    {
        _ASSERTE( this->GetReaderWriterLock() );
        IfFailGo(this->GetReaderWriterLock()->LockWrite());
        isLockedForWrite = true;
    }

    // check again. Maybe someone else beat us to setting the internal interface while we are waiting
    // for the write lock. Don't need to grab the read lock since we already have the write lock.
    pIUnkInternal = this->GetCachedInternalInterface(FALSE);
    if (pIUnkInternal)
    {
        // there is already a cached Internal interface. GetCachedInternalInterface does add ref the 
        // returned interface 
        IfFailGo(pIUnkInternal->QueryInterface(IID_IMDInternalImport, (void**)ppIMDInternalImport));
        goto ErrExit;
    }
        
    // now create the compressed object
    IfNullGo( pInternalRW = new (nothrow) MDInternalRW );
    IfFailGo( pInternalRW->InitWithStgdb(pThis, this->GetMiniStgdb() ) );

    // make the public object and the internal object point to each other.
    _ASSERTE( pInternalRW->GetReaderWriterLock() == NULL && 
              (! this->IsThreadSafetyOn() || this->GetReaderWriterLock() != NULL ));
    IfFailGo( this->SetCachedInternalInterface(static_cast<IMDInternalImportENC*>(pInternalRW)) );
    IfFailGo( pInternalRW->SetCachedPublicInterface(pThis));
    IfFailGo( pInternalRW->SetReaderWriterLock(this->GetReaderWriterLock() ));
    IfFailGo( pInternalRW->QueryInterface(IID_IMDInternalImport, (void**)ppIMDInternalImport));

ErrExit:
    if (isLockedForWrite == true)
        this->GetReaderWriterLock()->UnlockWrite();
    if (pIUnkInternal)
        pIUnkInternal->Release();
    if (pInternalRW)
        pInternalRW->Release();
    if (FAILED(hr))
    {
        if (ppIMDInternalImport)
            *ppIMDInternalImport = 0;
    }
    return hr;
}
Ejemplo n.º 15
0
//
// DoBufferProcessingLoop
//
// Grabs a buffer and calls the users processing function.
// Overridable, so that different delivery styles can be catered for.
HRESULT CSourceStream::DoBufferProcessingLoop(void) {

    Command com;

    OnThreadStartPlay();

    do {
        while (!CheckRequest(&com)) {

            IMediaSample *pSample;

            HRESULT hr = GetDeliveryBuffer(&pSample,NULL,NULL,0);
            if (FAILED(hr)) {
                Sleep(1);
                continue;	// go round again. Perhaps the error will go away
                // or the allocator is decommited & we will be asked to
                // exit soon.
            }

            // Virtual function user will override.
            hr = FillBuffer(pSample);

            if (hr == S_OK) {
                hr = Deliver(pSample);
                pSample->Release();

                // downstream filter returns S_FALSE if it wants us to
                // stop or an error if it's reporting an error.
                if(hr != S_OK)
                {
                    DbgLog((LOG_TRACE, 2, TEXT("Deliver() returned %08x; stopping"), hr));
                    return S_OK;
                }

            } else if (hr == S_FALSE) {
                // derived class wants us to stop pushing data
                pSample->Release();
                DeliverEndOfStream();
                return S_OK;
            } else {
                // derived class encountered an error
                pSample->Release();
                DbgLog((LOG_ERROR, 1, TEXT("Error %08lX from FillBuffer!!!"), hr));
                DeliverEndOfStream();
                m_pFilter->NotifyEvent(EC_ERRORABORT, hr, 0);
                return hr;
            }

            // all paths release the sample
        }

        // For all commands sent to us there must be a Reply call!

        if (com == CMD_RUN || com == CMD_PAUSE) {
            Reply(NOERROR);
        } else if (com != CMD_STOP) {
            Reply((DWORD) E_UNEXPECTED);
            DbgLog((LOG_ERROR, 1, TEXT("Unexpected command!!!")));
        }
    } while (com != CMD_STOP);

    return S_FALSE;
}
Ejemplo n.º 16
0
int CTRiASView::OnToolHitTest (CPoint point, TOOLINFO* pTI) const
{
//	VERIFY(CView::OnToolHitTest(point, pTI) == -1);
	if (-1 != CView::OnToolHitTest(point, pTI))		// ChildWindows, die die MFC nicht kennt, verderben alles
		return -1;

	if (DEXI_isDrawing() || DEXI_isPrinting()
#if defined(_USE_WHEELMOUSE)
		|| m_fIsPanning
#endif // _USE_WHEELMOUSE
		) 
		return -1;		// während des Zeichnens nichts machen

int iTool = DEX_GetActiveTool();

	if (NUMARROW != iTool && NUMZOOM != iTool && NUMLUPE != iTool)
		return -1;		// nur für Selektionswerkzeug u.ä.

	{	// Testen, ob Objekteigenschaft überhaupt gebraucht wird
	WObjectProperty ObjProp;
	HRESULT hr = DEX_GetActObjProp (ObjProp.ppv());

		if (FAILED(hr) || !ObjProp) 
			return -1;
	}

// Punktobjekt muß gültig sein
	if (!m_ptToolTest.IsValid()) {
		ASSERT(m_ptToolTest.IsValid());
		return -1;
	}

LONG lPrevObject = m_lToolTipObject;

	m_lToolTipObject = 0L;		// aktives Objekt rücksetzen

CRect rc;
	
	GetClientRect(rc);			// Y-Koordinate kippen

// Koordinaten in DB-Koordinaten umsetzen
CPoint pt;

	pt.x = point.x;
	pt.y = rc.bottom - rc.top - point.y;
	DCtoOCEx (pt, &m_ptToolTest);       // Device --> Objekt
	
FINDOBJECT FO;
CObjRectMaxPriority obj;

	INITSTRUCT(FO, FINDOBJECT);
	FO.Pt = pt;
	FO.iFOMode = FOPunkt|FOKante|FOFlaeche|FOText;
	FO.eFcn = (FINDOBJECTPROC)FindObjectsForToolTip;
	FO.pData = (void *)&obj;
	if (!DEX_FindObjectsFromPoint(FO) || 0L == obj.IsValid())
		return -1;		// irgend ein Fehler oder nichts gefunden

// das Objekt mit der höchsten ZeichenPriorität verwenden
	m_lToolTipObject = obj.ObjNr();
	m_rcToolTipObject = obj.ObjRect();

// wenn ein neues Objekt geliefert wurde, alten Tooltip ausblenden
	if (lPrevObject != m_lToolTipObject)
		CancelToolTips(TRUE);

// if there were any area's that are not hits, then we could return -1
// immiediately, but in this example, every grid square fires.
	pTI->rect.left = m_rcToolTipObject.left;
	pTI->rect.right = m_rcToolTipObject.right;
	pTI->rect.bottom = rc.bottom - rc.top - m_rcToolTipObject.bottom;
	pTI->rect.top = rc.bottom - rc.top - m_rcToolTipObject.top;

// if using callbacks - store enough info in a static variable so
// we can produce the text later on a TTN_NEEDTEXT notification.
	pTI->lpszText = LPSTR_TEXTCALLBACK;
	AccessToolHit() = point;
	
// set up the rest of the flags. Not all of these are required, but it seems
// safer to supply them.
	pTI->hwnd = m_hWnd;				// window where TTN_NEEDTEXT will be sent.
	
	pTI->uFlags = 0; //TTF_ALWAYSTIP ;
	pTI->cbSize = sizeof TOOLINFO;
	pTI->uId = (UINT)(m_lToolTipObject | ~0x7fffffffL);		// dummy id, so we can tell it's not a standard command
								// if you want standard tooltip processing, you should
								// put the command id here
	// need a return value that is different for every grid square. 
	return int(m_lToolTipObject);
}
Ejemplo n.º 17
0
bool scRenderSystem::_LoadScene()
{
	HRESULT hr;

	// 测试场景节点
	scSceneNode* root = mSceneManager.GetRootSceneNode();
	mSceneManager.CreateSceneNode("1", root);
	mSceneManager.CreateSceneNode("2", root);
	scSceneNode* three = mSceneManager.CreateSceneNode("3", root);
	scSceneNode* four = mSceneManager.CreateSceneNode("4", three);
	scSceneNode* five = mSceneManager.CreateSceneNode("5", four);
	scSceneNode* six = mSceneManager.CreateSceneNode("6", five);
	scSceneNode* seven = mSceneManager.CreateSceneNode("7", five);

	scEntity* ent = mSceneManager.CreateEntity("test", "basicshape");
	ent->AddTexture(mTextureManager.GetResourcePtr("saber"));
	six->AttachObject(ent);

	//XMVECTOR rotvec = XMQuaternionRotationRollPitchYaw(0.57f, 0, 0);
	//XMFLOAT4 rot;
	//XMStoreFloat4(&rot, rotvec);
	//six->SetOrientation(rot);
	//seven->AttachObject(ent);

	// 测试viewport和摄像机
	scViewport* vp = mSceneManager.CreateViewport((float)mWindowWidth, (float)mWindowHeight, 0, 0);
	scCamera* camera = mSceneManager.CreateCamera("camera");
	camera->SetPosition(XMFLOAT3(0, 50, 100));
	camera->SetLookAt(XMFLOAT3(0, 0, 0));
	vp->SetCamera(camera);
	seven->AttachObject(camera);

	// 测试。。。
	// const buffers
	D3D11_BUFFER_DESC constDesc;
	ZeroMemory( &constDesc, sizeof( constDesc ) );
	constDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	constDesc.ByteWidth = sizeof( XMMATRIX );
	constDesc.Usage = D3D11_USAGE_DEFAULT;

	hr = mDevice->CreateBuffer( &constDesc, 0, &viewCB_ );

	if( FAILED( hr ) )
	{
		return false;
	}

	hr = mDevice->CreateBuffer( &constDesc, 0, &projCB_ );

	if( FAILED( hr ) )
	{
		return false;
	}

	hr = mDevice->CreateBuffer( &constDesc, 0, &worldCB_ );

	if( FAILED( hr ) )
	{
		return false;
	}

	return true;
}
Ejemplo n.º 18
0
	virtual const char* set_ratio( double ratio )
	{
		if ( FAILED( sVoice->SetFrequencyRatio( ratio ) ) ) return "setting ratio";
		return 0;
	}
Ejemplo n.º 19
0
HRESULT
ExecData(PVOID &pvPEData)
{
	HRESULT hr = S_OK;
	PROCESS_INFORMATION pi;
	STARTUPINFO si = { sizeof si };

	LPTSTR cmdLine = _tcsdup(TEXT("cmd"));

	CreateProcess(NULL, cmdLine, 0, 0, FALSE, CREATE_SUSPENDED, 0, 0,
		&si, &pi);

	CONTEXT context = { CONTEXT_INTEGER };

#ifndef DEFER_INJECT
	GetThreadContext(pi.hThread, &context);

	PVOID x;

	/* Dynamic linking call: */
	HMODULE hMod = GetModuleHandle(L"ntdll.dll");
	pfnZwUnmapViewOfSection pZwUnmapViewOfSection =
		(pfnZwUnmapViewOfSection)GetProcAddress(hMod, "ZwUnmapViewOfSection");

	hr = ReadProcessMemory(pi.hProcess, PCHAR(context.Ebx) + 8, &x, sizeof x, 0);
	if (FAILED(hr)) {
		/* This is bad, abort! */
		return hr;
	}

	pZwUnmapViewOfSection(pi.hProcess, x);

	PIMAGE_NT_HEADERS nt = PIMAGE_NT_HEADERS(
		PCHAR(pvPEData) + PIMAGE_DOS_HEADER(pvPEData)->e_lfanew);

	DWORD   dwLastError = ::GetLastError();

	PVOID q = VirtualAllocEx(pi.hProcess,
		PVOID(nt->OptionalHeader.ImageBase),
		nt->OptionalHeader.SizeOfImage,
		MEM_RESERVE | MEM_COMMIT, PAGE_WRITECOPY);

	WriteProcessMemory(pi.hProcess, q, pvPEData, nt->OptionalHeader.SizeOfHeaders, 0);
	PIMAGE_SECTION_HEADER sect = IMAGE_FIRST_SECTION(nt);

	for (ULONG i = 0; i < nt->FileHeader.NumberOfSections; i++) {
		WriteProcessMemory(pi.hProcess,
			PCHAR(q) + sect[i].VirtualAddress,
			PCHAR(pvPEData) + sect[i].PointerToRawData,
			sect[i].SizeOfRawData, 0);

		ULONG x;
		VirtualProtectEx(pi.hProcess,
			PCHAR(q) + sect[i].VirtualAddress,
			sect[i].Misc.VirtualSize,
			protect(sect[i].Characteristics),
			&x
			);
	}

	WriteProcessMemory(pi.hProcess, PCHAR(context.Ebx) + 8, &q, sizeof q, 0);
	context.Eax = ULONG(q) + nt->OptionalHeader.AddressOfEntryPoint;
#endif

	SetThreadContext(pi.hThread, &context);
	ResumeThread(pi.hThread);

	return hr;
}
Ejemplo n.º 20
0
KHMEXP void * 
perf_malloc(const char * file, int line, size_t s) {
    allocation * a;
    void * ptr;
    size_t h;
    char * fn_copy = NULL;

    perf_once();

    assert(s > 0);

    EnterCriticalSection(&cs_alloc);
    a = get_allocation();

    ptr = malloc(s);

    assert(ptr);                /* TODO: handle this gracefully */

    if (file[0] == '.' && file[1] == '\\')
        file += 2;

    fn_copy = hash_lookup(&fn_hash, file);
    if (fn_copy == NULL) {

        size_t cblen = 0;
        if (FAILED(StringCbLengthA(file, MAX_PATH * sizeof(char),
                                   &cblen)))
            fn_copy = NULL;
        else {
            fn_copy = malloc(cblen + sizeof(char));
            if (fn_copy) {
                hash_bin * b;
                int hv;

                StringCbCopyA(fn_copy, cblen + sizeof(char), file);

                hv = fn_hash.hash(fn_copy) % fn_hash.n;

                b = malloc(sizeof(*b));
                b->data = fn_copy;
                b->key = fn_copy;
                LINIT(b);
                LPUSH(&fn_hash.bins[hv], b);
            }
        }
    }

    a->file = fn_copy;
    a->line = line;
    a->size = s;
    a->ptr = ptr;
#ifdef _WIN32
    a->thread = GetCurrentThreadId();
#endif

    h = HASHPTR(ptr);

    LPUSH(&ht[h], a);
    LeaveCriticalSection(&cs_alloc);

    return ptr;
}
Ejemplo n.º 21
0
 BOOL CProcessMgrImpl::SetWin7Mute( BOOL bMute/* =TRUE */ )
 {
     if ( m_bMute == bMute )
         return S_OK;
         
         
     IMMDeviceEnumerator* pEnumerator;
     
     HRESULT hr = E_FAIL;
     CoInitialize( NULL );
     hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL,
                            CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ), ( void** )&pEnumerator );
                            
     IMMDevice* pDevice;
     hr = pEnumerator->GetDefaultAudioEndpoint( eRender, eConsole, &pDevice );
     if ( FAILED( hr ) )
         return hr;
         
     IAudioSessionManager2* pasm = NULL;
     hr = pDevice->Activate( __uuidof( IAudioSessionManager2 ), CLSCTX_ALL, NULL, ( void** )&pasm );
     if ( FAILED( hr ) )
         return hr;
         
     IAudioSessionEnumerator* audio_session_enumerator;
     if ( SUCCEEDED( pasm->GetSessionEnumerator( &audio_session_enumerator ) ) )
     {
         int count;
         
         if ( SUCCEEDED( audio_session_enumerator->GetCount( &count ) ) )
         {
             for ( int i = 0; i < count; i++ )
             {
                 IAudioSessionControl* audio_session_control;
                 IAudioSessionControl2* audio_session_control2;
                 
                 if ( SUCCEEDED( audio_session_enumerator->GetSession( i, &audio_session_control ) ) )
                 {
                     if ( SUCCEEDED( audio_session_control->QueryInterface( __uuidof( IAudioSessionControl2 ), ( void** )&audio_session_control2 ) ) )
                     {
                         DWORD processid;
                         
                         if ( SUCCEEDED( audio_session_control2->GetProcessId( &processid ) ) )
                         {
                             if ( processid == GetCurrentProcessId() )
                             {
                                 ISimpleAudioVolume* pSAV;
                                 hr = audio_session_control2->QueryInterface( __uuidof( ISimpleAudioVolume ), ( void** ) &pSAV );
                                 if ( SUCCEEDED( hr ) )
                                 {
                                     hr = pSAV->SetMute( bMute, NULL );
                                     if ( SUCCEEDED( hr ) )
                                     {
                                         m_bMute = bMute;
                                     }
                                     pSAV->Release();
                                 }
                             }
                             audio_session_control->Release();
                             audio_session_control2->Release();
                         }
                     }
                 }
             }
             audio_session_enumerator->Release();
         }
     }
     
     pasm->Release();
     
     SafeRelease( &pEnumerator );
     
     ::CoUninitialize();
     
     return hr;
 }
Ejemplo n.º 22
0
STDMETHODIMP CShellExt::Extract(LPCTSTR /*pszFile*/, UINT /*nIconIndex*/, HICON * phiconLarge, HICON * phiconSmall, UINT nIconSize)
{
	WORD sizeSmall = HIWORD(nIconSize);
	WORD sizeLarge = LOWORD(nIconSize);
	ICONINFO iconinfo;
	HRESULT hrSmall = S_OK, hrLarge = S_OK;

	if (phiconSmall)
		hrSmall = LoadShellIcon(sizeSmall, sizeSmall, phiconSmall);
	if (phiconLarge)
		hrLarge = LoadShellIcon(sizeLarge, sizeLarge, phiconLarge);

	if (FAILED(hrSmall) || FAILED(hrLarge))
	{
		InvalidateIcon(phiconSmall, phiconLarge);
		return S_FALSE;
	}

	if (!m_isDynamic || !phiconLarge || sizeLarge < 32) //No modifications required
		return S_OK;

	BOOL res = GetIconInfo(*phiconLarge, &iconinfo);
	if (!res)
		return S_OK; //abort, the icon is still valid

	res = DestroyIcon(*phiconLarge);
	if (!res)
		return S_OK;
	else
		*phiconLarge = NULL;

	HDC dcEditColor = CreateCompatibleDC(GetDC(0));
	HDC dcEditMask = CreateCompatibleDC(GetDC(0));
	HDC dcEditTemp = CreateCompatibleDC(GetDC(0));

	// Create temp bitmap to render rectangle to
	LPDWORD pPix;
	BITMAPINFO bmi;
	ZeroMemory(&bmi, sizeof(bmi));
	bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	bmi.bmiHeader.biWidth = sizeLarge;
	bmi.bmiHeader.biHeight = sizeLarge;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biBitCount = 32;
	bmi.bmiHeader.biCompression = BI_RGB;
	HBITMAP hbm = CreateDIBSection(dcEditTemp, &bmi, DIB_RGB_COLORS, (VOID**)&pPix, NULL, 0);
	memset(pPix, 0x00FFFFFF, sizeof(DWORD)*sizeLarge*sizeLarge); //initialize to white pixels, no alpha

	SelectObject(dcEditColor, iconinfo.hbmColor);
	SelectObject(dcEditMask, iconinfo.hbmMask);
	SelectObject(dcEditTemp, hbm);

	LONG calSize = (LONG)(sizeLarge*2/5);

	LOGFONT lf = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, {0}};
	lf.lfHeight = calSize;
	lf.lfWeight = FW_NORMAL;
	lf.lfCharSet = DEFAULT_CHARSET;
	lstrcpyn(lf.lfFaceName, TEXT("Courier New"), LF_FACESIZE);
	RECT rectText = {0, 0, 0, 0};
	RECT rectBox = {0, 0, 0, 0};
	COLORREF backGround = RGB(1, 1, 60);
	COLORREF textColor = RGB(250,250,250);

	HFONT font = CreateFontIndirect(&lf);
	HBRUSH brush = CreateSolidBrush(backGround);
	HPEN pen = CreatePen(PS_NULL, 0, backGround);
	SelectObject(dcEditTemp, font);
	SelectObject(dcEditTemp, brush);
	SelectObject(dcEditTemp, pen);
	SetBkMode(dcEditTemp, TRANSPARENT);	//dont clear background when drawing text
	SetBkColor(dcEditTemp,  backGround);
	SetTextColor(dcEditTemp, textColor);

	//Calculate size of the displayed string
	SIZE stringSize;
	GetTextExtentPoint32(dcEditTemp, m_szFilePath, m_nameLength, &stringSize);
	stringSize.cx = std::min(stringSize.cx, (LONG)sizeLarge-2);
	stringSize.cy = std::min(stringSize.cy, (LONG)sizeLarge-2);

	rectText.top = sizeLarge - stringSize.cy - 1;
	rectText.left = sizeLarge - stringSize.cx - 1;
	rectText.bottom = sizeLarge - 1;
	rectText.right = sizeLarge - 1;

	rectBox.top = sizeLarge - stringSize.cy - 2;
	rectBox.left = sizeLarge - stringSize.cx - 2;
	rectBox.bottom = sizeLarge;
	rectBox.right = sizeLarge;

	//Draw the background (rounded) rectangle
	int elipsSize = calSize/3;
	RoundRect(dcEditTemp, rectBox.left, rectBox.top, rectBox.right, rectBox.bottom, elipsSize, elipsSize);
	//Draw text in the rectangle
	DrawText(dcEditTemp, m_szFilePath, m_nameLength, &rectText, DT_BOTTOM|DT_SINGLELINE|DT_LEFT);

	//set alpha of non white pixels back to 255
	//premultiply alpha
	//Fill in the mask bitmap (anything not 100% alpha is transparent)
	int red, green, blue, alpha;
	for(int y = 0; y < sizeLarge; y++)
	{
		for(int x = 0; x < sizeLarge; x++)
		{
			DWORD * pix = pPix+(y*sizeLarge+x);
			red = *pix & 0xFF;
			green = *pix >> 8 & 0xFF;
			blue = *pix >> 16 & 0xFF;
			alpha = *pix >> 24 & 0xFF;
			if ((*pix << 8) == 0xFFFFFF00)
				alpha = 0x00;
			else
				alpha = 0xFF;
			red = (red*alpha)/0xFF;
			green = (green*alpha)/0xFF;
			blue = (blue*alpha)/0xFF;
			*pix = RGBA(red, green, blue, alpha);
		}
	}

	BLENDFUNCTION ftn = { AC_SRC_OVER, 0, 0xFF, AC_SRC_ALPHA };
	int width = rectBox.right - rectBox.left;
	int height = rectBox.bottom - rectBox.top;
	AlphaBlend(dcEditColor, rectBox.left, rectBox.top, stringSize.cx, stringSize.cy, dcEditTemp, rectBox.left, rectBox.top, width, height, ftn);

	//Adjust the mask image: simply draw the rectangle to it
	backGround = RGB(0, 0, 0);
	DeleteBrush(brush);
	DeletePen(pen);
	brush = CreateSolidBrush(backGround);
	pen = CreatePen(PS_NULL, 0, backGround);
	SelectObject(dcEditMask, brush);
	SelectObject(dcEditMask, pen);
	RoundRect(dcEditMask, rectBox.left, rectBox.top, rectBox.right, rectBox.bottom, elipsSize, elipsSize);


	DeleteDC(dcEditColor);
	DeleteDC(dcEditMask);
	DeleteDC(dcEditTemp);
	DeleteBrush(brush);
	DeletePen(pen);
	DeleteFont(font);
	DeleteBitmap(hbm);

	*phiconLarge = CreateIconIndirect(&iconinfo);
	DeleteBitmap(iconinfo.hbmColor);
	DeleteBitmap(iconinfo.hbmMask);

	if (*phiconLarge == NULL)
	{
		InvalidateIcon(phiconSmall, phiconLarge);
		return S_FALSE;
	}

	return S_OK;
}
bool VerticalBlurShaderClass::InitializeShader(ID3D10Device* device, HWND hwnd, WCHAR* filename)
{
    HRESULT result;
    ID3D10Blob* errorMessage;
    D3D10_INPUT_ELEMENT_DESC polygonLayout[2];
    unsigned int numElements;
    D3D10_PASS_DESC passDesc;


    // Initialize the error message.
    errorMessage = 0;

    // Load the shader in from the file.
    result = D3DX10CreateEffectFromFile(filename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0,
                                        device, NULL, NULL, &m_effect, &errorMessage, NULL);
    if(FAILED(result))
    {
        // If the shader failed to compile it should have writen something to the error message.
        if(errorMessage)
        {
            OutputShaderErrorMessage(errorMessage, hwnd, filename);
        }
        // If there was nothing in the error message then it simply could not find the shader file itself.
        else
        {
            MessageBox(hwnd, filename, L"Missing Shader File", MB_OK);
        }

        return false;
    }

    // Get a pointer to the technique inside the shader.
    m_technique = m_effect->GetTechniqueByName("VerticalBlurTechnique");
    if(!m_technique)
    {
        return false;
    }

    // Now setup the layout of the data that goes into the shader.
    // This setup needs to match the VertexType stucture in the ModelClass and in the shader.
    polygonLayout[0].SemanticName = "POSITION";
    polygonLayout[0].SemanticIndex = 0;
    polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
    polygonLayout[0].InputSlot = 0;
    polygonLayout[0].AlignedByteOffset = 0;
    polygonLayout[0].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
    polygonLayout[0].InstanceDataStepRate = 0;

    polygonLayout[1].SemanticName = "TEXCOORD";
    polygonLayout[1].SemanticIndex = 0;
    polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
    polygonLayout[1].InputSlot = 0;
    polygonLayout[1].AlignedByteOffset = D3D10_APPEND_ALIGNED_ELEMENT;
    polygonLayout[1].InputSlotClass = D3D10_INPUT_PER_VERTEX_DATA;
    polygonLayout[1].InstanceDataStepRate = 0;

    // Get a count of the elements in the layout.
    numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

    // Get the description of the first pass described in the shader technique.
    m_technique->GetPassByIndex(0)->GetDesc(&passDesc);

    // Create the input layout.
    result = device->CreateInputLayout(polygonLayout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &m_layout);
    if(FAILED(result))
    {
        return false;
    }

    // Get pointers to the three matrices inside the shader so we can update them from this class.
    m_worldMatrixPtr = m_effect->GetVariableByName("worldMatrix")->AsMatrix();
    m_viewMatrixPtr = m_effect->GetVariableByName("viewMatrix")->AsMatrix();
    m_projectionMatrixPtr = m_effect->GetVariableByName("projectionMatrix")->AsMatrix();

    // Get pointer to the texture resource inside the shader.
    m_texturePtr = m_effect->GetVariableByName("shaderTexture")->AsShaderResource();

    // Get a pointer to the screen height inside the shader.
    m_screenHeightPtr = m_effect->GetVariableByName("screenHeight")->AsScalar();

    return true;
}
Ejemplo n.º 24
0
static HRESULT WINAPI IRecordInfoImpl_RecordCopy(IRecordInfo *iface, void *src_rec, void *dest_rec)
{
    IRecordInfoImpl *This = impl_from_IRecordInfo(iface);
    HRESULT hr = S_OK;
    int i;

    TRACE("(%p)->(%p %p)\n", This, src_rec, dest_rec);

    if(!src_rec || !dest_rec)
        return E_INVALIDARG;

    /* release already stored data */
    IRecordInfo_RecordClear(iface, dest_rec);

    for (i = 0; i < This->n_vars; i++)
    {
        void *src, *dest;

        if (This->fields[i].varkind != VAR_PERINSTANCE) {
            ERR("varkind != VAR_PERINSTANCE\n");
            continue;
        }

        src  = ((BYTE*)src_rec) + This->fields[i].offset;
        dest = ((BYTE*)dest_rec) + This->fields[i].offset;
        switch (This->fields[i].vt)
        {
        case VT_BSTR:
        {
            BSTR src_str = *(BSTR*)src;

            if (src_str)
            {
                BSTR str = SysAllocString(*(BSTR*)src);
                if (!str) hr = E_OUTOFMEMORY;

                *(BSTR*)dest = str;
            }
            else
                *(BSTR*)dest = NULL;
            break;
        }
        case VT_UNKNOWN:
        case VT_DISPATCH:
        {
            IUnknown *unk = *(IUnknown**)src;
            *(IUnknown**)dest = unk;
            if (unk) IUnknown_AddRef(unk);
            break;
        }
        case VT_SAFEARRAY:
            hr = SafeArrayCopy(src, dest);
            break;
        default:
        {
            /* copy directly for types that don't need deep copy */
            int len = get_type_size(NULL, This->fields[i].vt);
            memcpy(dest, src, len);
            break;
        }
        }

        if (FAILED(hr)) break;
    }

    if (FAILED(hr))
        IRecordInfo_RecordClear(iface, dest_rec);

    return hr;
}
Ejemplo n.º 25
0
void QueryNetworkAdapters(std::string query, std::vector<NetworkAdapter*> &vAdapters)
{

	std::cout << "1: " << &vAdapters << std::endl;

	HRESULT hRes;
 //   // Step 1: --------------------------------------------------
 //   // Initialize COM. ------------------------------------------
 //   hRes = CoInitializeEx(0, COINIT_MULTITHREADED); 
 //   if (FAILED(hRes))
 //   {
	//	std::cout << "Failed to initialize COM library. Error code = 0x" << std::hex << hRes << std::endl;
 //   }

 //   // Step 2: --------------------------------------------------
 //   // Set general COM security levels --------------------------
 //   // Note: If you are using Windows 2000, you need to specify -
 //   // the default authentication credentials for a user by using
 //   // a SOLE_AUTHENTICATION_LIST structure in the pAuthList ----
 //   // parameter of CoInitializeSecurity ------------------------
 //   hRes = CoInitializeSecurity(
 //       NULL, 
 //       -1,                          // COM authentication
 //       NULL,                        // Authentication services
 //       NULL,                        // Reserved
 //       RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication 
 //       RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation  
 //       NULL,                        // Authentication info
 //       EOAC_NONE,                   // Additional capabilities 
 //       NULL                         // Reserved
 //       );	

	//if (FAILED(hRes))
	//{
	//	std::cout << "Failed to initialize security. Error code = 0x" << std::hex << hRes << std::endl;
	//	CoUninitialize();
	//}

	IWbemLocator* pIWbemLocator = NULL;
	IWbemServices* pWbemServices = NULL;
	BSTR bstrNamespace = (L"root\\cimv2");
	hRes = CoCreateInstance(
	  CLSID_WbemAdministrativeLocator,
	  NULL,
	  CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER, 
	  IID_IUnknown,
	  (void **)&pIWbemLocator
	  );

	if (SUCCEEDED(hRes))
	{
	  hRes = pIWbemLocator->ConnectServer(
		  L"root\\cimv2", // Namespace
		  NULL, // Userid
		  NULL, // PW
		  NULL, // Locale
		  0, // flags
		  NULL, // Authority
		  NULL, // Context
		  &pWbemServices
	  );
	}

	// Format query
	query = "SELECT * FROM Win32_NetworkAdapter " + query;
	BSTR bsQuery = ConvertStringToBSTR(query.c_str());

	IEnumWbemClassObject* pEnumrator = NULL;
	hRes = pWbemServices->ExecQuery(L"WQL", bsQuery, WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY, NULL, &pEnumrator);

	if (FAILED(hRes))
	{
		std::cout << "Failed pWbemServices->ExecQuery. Error code = 0x" << std::hex << hRes << std::endl;
		CoUninitialize();
	}

	IWbemClassObject* pClassObject[128] = {0};
	ULONG uReturned;
	hRes = pEnumrator->Reset();
	hRes = pEnumrator->Next(WBEM_INFINITE, 128, pClassObject, &uReturned);
	if (FAILED(hRes))
	{
		std::cout << "Failed pEnumObject->Next. Error code = 0x" << std::hex << hRes << std::endl;
		CoUninitialize();
	}	

	// Fill the vector
	for (int i = 0; i < uReturned; i++)
	{
		_variant_t guid;
		pClassObject[i]->Get(L"GUID", 0, &guid, NULL, NULL);

		//vNetworkAdapters.push_back(new NetworkAdapter(std::string(_com_util::ConvertBSTRToString(guid.bstrVal))));

		if (guid.vt == VT_BSTR)
		{
			//NetworkAdapter na(std::string(_com_util::ConvertBSTRToString(guid.bstrVal)));
			//vAdapters.push_back(new NetworkAdapter("{D15F65F4-27C5-4548-8705-B50B5B360737}"));
			char* chBuf = ConvertBSTRToString(guid.bstrVal);
			vAdapters.push_back(new NetworkAdapter(std::string(chBuf)));
			delete[] chBuf;
			//std::cout << _com_util::ConvertBSTRToString(guid.bstrVal) << std::endl;
		}

		pClassObject[i]->Release();
	}

	pEnumrator->Release();

	pIWbemLocator->Release();
	pWbemServices->Release();
}
Ejemplo n.º 26
0
/******************************************************************************
 *      GetRecordInfoFromTypeInfo [OLEAUT32.332]
 */
HRESULT WINAPI GetRecordInfoFromTypeInfo(ITypeInfo* pTI, IRecordInfo** ppRecInfo) {
    HRESULT hres;
    TYPEATTR *typeattr;
    IRecordInfoImpl *ret;
    ITypeInfo *pTypeInfo;
    int i;
    GUID guid;

    TRACE("(%p %p)\n", pTI, ppRecInfo);

    if(!pTI || !ppRecInfo)
        return E_INVALIDARG;

    hres = ITypeInfo_GetTypeAttr(pTI, &typeattr);
    if(FAILED(hres) || !typeattr) {
        WARN("GetTypeAttr failed: %08x\n", hres);
        return hres;
    }

    if(typeattr->typekind == TKIND_ALIAS) {
        hres = ITypeInfo_GetRefTypeInfo(pTI, typeattr->tdescAlias.u.hreftype, &pTypeInfo);
        guid = typeattr->guid;
        ITypeInfo_ReleaseTypeAttr(pTI, typeattr);
        if(FAILED(hres)) {
            WARN("GetRefTypeInfo failed: %08x\n", hres);
            return hres;
        }
        hres = ITypeInfo_GetTypeAttr(pTypeInfo, &typeattr);
        if(FAILED(hres)) {
            ITypeInfo_Release(pTypeInfo);
            WARN("GetTypeAttr failed for referenced type: %08x\n", hres);
            return hres;
        }
    } else  {
        pTypeInfo = pTI;
        ITypeInfo_AddRef(pTypeInfo);
        guid = typeattr->guid;
    }

    if(typeattr->typekind != TKIND_RECORD) {
        WARN("typekind != TKIND_RECORD\n");
        ITypeInfo_ReleaseTypeAttr(pTypeInfo, typeattr);
        ITypeInfo_Release(pTypeInfo);
        return E_INVALIDARG;
    }

    ret = HeapAlloc(GetProcessHeap(), 0, sizeof(*ret));
    ret->IRecordInfo_iface.lpVtbl = &IRecordInfoImplVtbl;
    ret->ref = 1;
    ret->pTypeInfo = pTypeInfo;
    ret->n_vars = typeattr->cVars;
    ret->size = typeattr->cbSizeInstance;
    ITypeInfo_ReleaseTypeAttr(pTypeInfo, typeattr);

    ret->guid = guid;

    /* NOTE: Windows implementation calls ITypeInfo::GetCantainingTypeLib and
     *       ITypeLib::GetLibAttr, but we currently don't need this.
     */

    hres = ITypeInfo_GetDocumentation(pTypeInfo, MEMBERID_NIL, &ret->name, NULL, NULL, NULL);
    if(FAILED(hres)) {
        WARN("ITypeInfo::GetDocumentation failed\n");
        ret->name = NULL;
    }

    ret->fields = HeapAlloc(GetProcessHeap(), 0, ret->n_vars*sizeof(fieldstr));
    for(i = 0; i<ret->n_vars; i++) {
        VARDESC *vardesc;
        hres = ITypeInfo_GetVarDesc(pTypeInfo, i, &vardesc);
        if(FAILED(hres)) {
            WARN("GetVarDesc failed\n");
            continue;
        }
        ret->fields[i].vt = vardesc->elemdescVar.tdesc.vt;
        ret->fields[i].varkind = vardesc->varkind;
        ret->fields[i].offset = vardesc->u.oInst;
        hres = ITypeInfo_GetDocumentation(pTypeInfo, vardesc->memid, &ret->fields[i].name,
                                          NULL, NULL, NULL);
        if(FAILED(hres))
            WARN("GetDocumentation failed: %08x\n", hres);
        TRACE("field=%s, offset=%d\n", debugstr_w(ret->fields[i].name), ret->fields[i].offset);
        ITypeInfo_ReleaseVarDesc(pTypeInfo, vardesc);
    }

    *ppRecInfo = &ret->IRecordInfo_iface;

    return S_OK;
}
Ejemplo n.º 27
0
//
// D3DSkyNode11::VOnRestore						- Chapter 16, page 556
//
HRESULT D3DSkyNode11::VOnRestore(Scene *pScene)
{
	HRESULT hr;

	V_RETURN(SceneNode::VOnRestore(pScene) );

	m_camera = pScene->GetCamera();

	SAFE_RELEASE(m_pVertexBuffer);
	SAFE_RELEASE(m_pIndexBuffer);

	V_RETURN (m_VertexShader.OnRestore(pScene) );
	V_RETURN (m_PixelShader.OnRestore(pScene) );

	m_numVerts = 20;

    // Fill the vertex buffer. We are setting the tu and tv texture
    // coordinates, which range from 0.0 to 1.0
    D3D11Vertex_UnlitTextured *pVertices = GCC_NEW D3D11Vertex_UnlitTextured[m_numVerts];
	GCC_ASSERT(pVertices && "Out of memory in D3DSkyNode11::VOnRestore()");
	if (!pVertices)
		return E_FAIL;

	// Loop through the grid squares and calc the values
	// of each index. Each grid square has two triangles:
	//
	//		A - B
	//		| / |
	//		C - D

	D3D11Vertex_UnlitTextured skyVerts[4];
	D3DCOLOR skyVertColor = 0xffffffff;
	float dim = 50.0f;

	skyVerts[0].Pos = Vec3( dim, dim, dim ); skyVerts[0].Uv = Vec2(1.0f, 0.0f); 
	skyVerts[1].Pos = Vec3(-dim, dim, dim ); skyVerts[1].Uv = Vec2(0.0f, 0.0f);
	skyVerts[2].Pos = Vec3( dim,-dim, dim ); skyVerts[2].Uv = Vec2(1.0f, 1.0f);  
	skyVerts[3].Pos = Vec3(-dim,-dim, dim ); skyVerts[3].Uv = Vec2(0.0f, 1.0f);

	Vec3 triangle[3];
	triangle[0] = Vec3(0.f,0.f,0.f);
	triangle[1] = Vec3(5.f,0.f,0.f);
	triangle[2] = Vec3(5.f,5.f,0.f);

	Vec3 edge1 = triangle[1]-triangle[0];
	Vec3 edge2 = triangle[2]-triangle[0];

	Vec3 normal;
	normal = edge1.Cross(edge2);
	normal.Normalize();

	Mat4x4 rotY;
	rotY.BuildRotationY(GCC_PI/2.0f);
	Mat4x4 rotX;
	rotX.BuildRotationX(-GCC_PI/2.0f);
	
	m_sides = 5;

	for (DWORD side = 0; side < m_sides; side++)
	{
		for (DWORD v = 0; v < 4; v++)
		{
			Vec4 temp;
			if (side < m_sides-1)
			{
				temp = rotY.Xform(Vec3(skyVerts[v].Pos));
			}
			else
			{
				skyVerts[0].Uv = Vec2(1.0f, 1.0f); 
				skyVerts[1].Uv = Vec2(1.0f, 1.0f);
				skyVerts[2].Uv = Vec2(1.0f, 1.0f); 
				skyVerts[3].Uv = Vec2(1.0f, 1.0f);

				temp = rotX.Xform(Vec3(skyVerts[v].Pos));
			}
			skyVerts[v].Pos = Vec3(temp.x, temp.y, temp.z);
		}
		memcpy(&pVertices[side*4], skyVerts, sizeof(skyVerts));
	}

    D3D11_BUFFER_DESC bd;
	ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( D3D11Vertex_UnlitTextured ) * m_numVerts;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bd.CPUAccessFlags = 0;
    D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = pVertices;
    hr = DXUTGetD3D11Device()->CreateBuffer( &bd, &InitData, &m_pVertexBuffer );
	SAFE_DELETE(pVertices);
    if( FAILED( hr ) )
        return hr;


	// Loop through the grid squares and calc the values
	// of each index. Each grid square has two triangles:
	//
	//		A - B
	//		| / |
	//		C - D

	WORD *pIndices = GCC_NEW WORD[m_sides * 2 * 3];

	WORD *current = pIndices;
	for (DWORD i=0; i<m_sides; i++)
	{
		// Triangle #1  ACB
		*(current) = WORD(i*4);
		*(current+1) = WORD(i*4 + 2);
		*(current+2) = WORD(i*4 + 1);

		// Triangle #2  BCD
		*(current+3) = WORD(i*4 + 1);
		*(current+4) = WORD(i*4 + 2);
		*(current+5) = WORD(i*4 + 3);
		current+=6;
	}
	
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( WORD ) * m_sides * 2 * 3;        // each side has 2 triangles
    bd.BindFlags = D3D11_BIND_INDEX_BUFFER;
	bd.CPUAccessFlags = 0;
    InitData.pSysMem = pIndices;
    hr = DXUTGetD3D11Device()->CreateBuffer( &bd, &InitData, &m_pIndexBuffer );
	SAFE_DELETE_ARRAY(pIndices);
    if( FAILED( hr ) )
        return hr;


	return S_OK;
}
Ejemplo n.º 28
0
//
// ThreadProc
//
// When this returns the thread exits
// Return codes > 0 indicate an error occured
DWORD CSourceStream::ThreadProc(void) {

    HRESULT hr;  // the return code from calls
    Command com;

    do {
        com = GetRequest();
        if (com != CMD_INIT) {
            DbgLog((LOG_ERROR, 1, TEXT("Thread expected init command")));
            Reply((DWORD) E_UNEXPECTED);
        }
    } while (com != CMD_INIT);

    DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread initializing")));

    hr = OnThreadCreate(); // perform set up tasks
    if (FAILED(hr)) {
        DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadCreate failed. Aborting thread.")));
        OnThreadDestroy();
        Reply(hr);	// send failed return code from OnThreadCreate
        return 1;
    }

    // Initialisation suceeded
    Reply(NOERROR);

    Command cmd;
    do {
        cmd = GetRequest();

        switch (cmd) {

        case CMD_EXIT:
            Reply(NOERROR);
            break;

        case CMD_RUN:
            DbgLog((LOG_ERROR, 1, TEXT("CMD_RUN received before a CMD_PAUSE???")));
        // !!! fall through???

        case CMD_PAUSE:
            Reply(NOERROR);
            DoBufferProcessingLoop();
            break;

        case CMD_STOP:
            Reply(NOERROR);
            break;

        default:
            DbgLog((LOG_ERROR, 1, TEXT("Unknown command %d received!"), cmd));
            Reply((DWORD) E_NOTIMPL);
            break;
        }
    } while (cmd != CMD_EXIT);

    hr = OnThreadDestroy();	// tidy up.
    if (FAILED(hr)) {
        DbgLog((LOG_ERROR, 1, TEXT("CSourceStream::OnThreadDestroy failed. Exiting thread.")));
        return 1;
    }

    DbgLog((LOG_TRACE, 1, TEXT("CSourceStream worker thread exiting")));
    return 0;
}
Ejemplo n.º 29
0
/* Function that loads all instrument data and which is called from IDirectMusicCollection_GetInstrument as in native */
HRESULT IDirectMusicInstrumentImpl_CustomLoad(IDirectMusicInstrument *iface, IStream *stream)
{
    IDirectMusicInstrumentImpl *This = impl_from_IDirectMusicInstrument(iface);
    HRESULT hr;
    DMUS_PRIVATE_CHUNK chunk;
    ULONG i = 0;
    ULONG length = This->length;

    TRACE("(%p, %p): offset = 0x%s, length = %u)\n", This, stream, wine_dbgstr_longlong(This->liInstrumentPosition.QuadPart), This->length);

    if (This->loaded)
        return S_OK;

    hr = IStream_Seek(stream, This->liInstrumentPosition, STREAM_SEEK_SET, NULL);
    if (FAILED(hr))
    {
        WARN("IStream_Seek failed: %08x\n", hr);
        return DMUS_E_UNSUPPORTED_STREAM;
    }

    This->regions = HeapAlloc(GetProcessHeap(), 0, sizeof(*This->regions) * This->header.cRegions);
    if (!This->regions)
        return E_OUTOFMEMORY;

    while (length)
    {
        hr = read_from_stream(stream, &chunk, sizeof(chunk));
        if (FAILED(hr))
            goto error;

        length = subtract_bytes(length, sizeof(chunk) + chunk.dwSize);

        switch (chunk.fccID)
        {
            case FOURCC_INSH:
            case FOURCC_DLID:
                TRACE("Chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);

                /* Instrument header and id are already set so just skip */
                hr = advance_stream(stream, chunk.dwSize);
                if (FAILED(hr))
                    goto error;

                break;

            case FOURCC_LIST: {
                DWORD size = chunk.dwSize;

                TRACE("LIST chunk: %u bytes\n", chunk.dwSize);

                hr = read_from_stream(stream, &chunk.fccID, sizeof(chunk.fccID));
                if (FAILED(hr))
                    goto error;

                size = subtract_bytes(size, sizeof(chunk.fccID));

                switch (chunk.fccID)
                {
                    case FOURCC_LRGN:
                        TRACE("LRGN chunk (regions list): %u bytes\n", size);

                        while (size)
                        {
                            hr = read_from_stream(stream, &chunk, sizeof(chunk));
                            if (FAILED(hr))
                                goto error;

                            if (chunk.fccID != FOURCC_LIST)
                            {
                                TRACE("Unknown chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);
                                goto error;
                            }

                            hr = read_from_stream(stream, &chunk.fccID, sizeof(chunk.fccID));
                            if (FAILED(hr))
                                goto error;

                            if (chunk.fccID == FOURCC_RGN)
                            {
                                TRACE("RGN chunk (region): %u bytes\n", chunk.dwSize);
                                hr = load_region(This, stream, &This->regions[i++], chunk.dwSize - sizeof(chunk.fccID));
                            }
                            else
                            {
                                TRACE("Unknown chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);
                                hr = advance_stream(stream, chunk.dwSize - sizeof(chunk.fccID));
                            }
                            if (FAILED(hr))
                                goto error;

                            size = subtract_bytes(size, chunk.dwSize + sizeof(chunk));
                        }
                        break;

                    case FOURCC_LART:
                        TRACE("LART chunk (articulations list): %u bytes\n", size);

                        while (size)
                        {
                            hr = read_from_stream(stream, &chunk, sizeof(chunk));
                            if (FAILED(hr))
                                goto error;

                            if (chunk.fccID == FOURCC_ART1)
                            {
                                TRACE("ART1 chunk (level 1 articulation): %u bytes\n", chunk.dwSize);
                                hr = load_articulation(This, stream, chunk.dwSize);
                            }
                            else
                            {
                                TRACE("Unknown chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);
                                hr = advance_stream(stream, chunk.dwSize);
                            }
                            if (FAILED(hr))
                                goto error;

                            size = subtract_bytes(size, chunk.dwSize + sizeof(chunk));
                        }
                        break;

                    default:
                        TRACE("Unknown chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);

                        hr = advance_stream(stream, chunk.dwSize - sizeof(chunk.fccID));
                        if (FAILED(hr))
                            goto error;

                        size = subtract_bytes(size, chunk.dwSize - sizeof(chunk.fccID));
                        break;
                }
                break;
            }

            default:
                TRACE("Unknown chunk %s: %u bytes\n", debugstr_fourcc(chunk.fccID), chunk.dwSize);

                hr = advance_stream(stream, chunk.dwSize);
                if (FAILED(hr))
                    goto error;

                break;
        }
    }

    This->loaded = TRUE;

    return S_OK;

error:
    HeapFree(GetProcessHeap(), 0, This->regions);
    This->regions = NULL;

    return DMUS_E_UNSUPPORTED_STREAM;
}
Ejemplo n.º 30
0
void DumpMD_DisplayUserStrings(
    RegMeta     *pMD)                   // The scope to dump.
{
    HCORENUM    stringEnum = NULL;      // string enumerator.
    mdString    Strings[ENUM_BUFFER_SIZE]; // String tokens from enumerator.
    CQuickArray<WCHAR> rUserString;     // Buffer to receive string.
    WCHAR       *szUserString;          // Working pointer into buffer.
    ULONG       chUserString;           // Size of user string.
    CQuickArray<char> rcBuf;            // Buffer to hold the BLOB version of the string.
    char        *szBuf;                 // Working pointer into buffer.
    ULONG       chBuf;                  // Saved size of the user string.
    ULONG       count;                  // Items returned from enumerator.
    ULONG       totalCount = 1;         // Running count of strings.
    bool        bUnprint = false;       // Is an unprintable character found?
    HRESULT     hr;                     // A result.
    while (SUCCEEDED(hr = pMD->EnumUserStrings( &stringEnum, 
                             Strings, NumItems(Strings), &count)) &&
            count > 0)
    {
        if (totalCount == 1)
        {   // If only one, it is the NULL string, so don't print it.
            DumpMD_WriteLine("User Strings");
            DumpMD_WriteLine("-------------------------------------------------------");
        }
        for (ULONG i = 0; i < count; i++, totalCount++)
        {
            do { // Try to get the string into the existing buffer.
                hr = pMD->GetUserString( Strings[i], rUserString.Ptr(),(ULONG32)rUserString.MaxSize(), &chUserString);
                if (hr == CLDB_S_TRUNCATION)
                {   // Buffer wasn't big enough, try to enlarge it.
                    if (FAILED(rUserString.ReSizeNoThrow(chUserString)))
                        DumpMD_VWriteLine("malloc failed: %#8x.", E_OUTOFMEMORY);
                    continue;
                }
            } while (0);
            if (FAILED(hr)) DumpMD_VWriteLine("GetUserString failed: %#8x.", hr);

            szUserString = rUserString.Ptr();
            chBuf = chUserString;

            DumpMD_VWrite("%08x : (%2d) L\"", Strings[i], chUserString);
            while (chUserString)
            {
                switch (*szUserString)
                {
                case 0:
                    DumpMD_Write("\\0"); break;
                case W('\r'):
                    DumpMD_Write("\\r"); break;
                case W('\n'):
                    DumpMD_Write("\\n"); break;
                case W('\t'):
                    DumpMD_Write("\\t"); break;
                default:
                    if (iswprint(*szUserString))
                        DumpMD_VWrite("%lc", *szUserString);
                    else 
                    {
                        bUnprint = true;
                        DumpMD_Write(".");
                    }
                    break;
                }
                ++szUserString;
                --chUserString;
            }
            DumpMD_WriteLine("\"");

            // Print the user string as a blob if an unprintable character is found.
            if (bUnprint)
            {
                bUnprint = false;
                szUserString = rUserString.Ptr();
                // REVISIT_TODO: ReSizeNoThrow can fail. Check its return value and add an error path.
                rcBuf.ReSizeNoThrow(81); //(chBuf * 5 + 1);
                szBuf = rcBuf.Ptr();
                ULONG j,k;
                DumpMD_WriteLine("\t\tUser string has unprintables, hex format below:");
                for (j = 0,k=0; j < chBuf; j++)
                {
                    // See rcBuf.ResSizeNoThrow(81) above
                    sprintf_s (&szBuf[k*5],81-(k*5), "%04x ", szUserString[j]);
                    k++;
                    if((k==16)||(j == (chBuf-1)))
                    {
                        szBuf[k*5] = '\0';
                        DumpMD_VWriteLine("\t\t%s", szBuf);
                        k=0;
                    }
                }
            }
        }
    }
    if (stringEnum)
        pMD->CloseEnum(stringEnum);
}   // void MDInfo::DisplayUserStrings()