Refactored d3d9 a bit
[reactos.git] / reactos / dll / directx / d3d9 / d3d9_helpers.c
1 /*
2 * COPYRIGHT: See COPYING in the top level directory
3 * PROJECT: ReactOS ReactX
4 * FILE: dll/directx/d3d9/d3d9_helpers.c
5 * PURPOSE: d3d9.dll helper functions
6 * PROGRAMERS: Gregor Brunmar <gregor (dot) brunmar (at) home (dot) se>
7 */
8
9 #include <d3d9.h>
10 #include "d3d9_helpers.h"
11 #include <stdio.h>
12 #include <ddraw.h>
13 #include <debug.h>
14
15 #define MEM_ALIGNMENT 0x20
16
17 static LPCSTR D3D9_DebugRegPath = "Software\\Microsoft\\Direct3D";
18
19 LPDIRECT3D9_INT impl_from_IDirect3D9(LPDIRECT3D9 iface)
20 {
21 return (LPDIRECT3D9_INT)((ULONG_PTR)iface - FIELD_OFFSET(DIRECT3D9_INT, lpVtbl));
22 }
23
24 BOOL ReadRegistryValue(IN DWORD ValueType, IN LPCSTR ValueName, OUT LPBYTE DataBuffer, IN OUT LPDWORD DataBufferSize)
25 {
26 HKEY hKey;
27 DWORD Type;
28 LONG Ret;
29
30 if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, D3D9_DebugRegPath, 0, KEY_QUERY_VALUE, &hKey))
31 return FALSE;
32
33 Ret = RegQueryValueEx(hKey, ValueName, 0, &Type, DataBuffer, DataBufferSize);
34
35 RegCloseKey(hKey);
36
37 if (ERROR_SUCCESS != Ret)
38 return FALSE;
39
40 if (Type != ValueType)
41 return FALSE;
42
43 return TRUE;
44 }
45
46 HRESULT FormatDebugString(IN OUT LPSTR Buffer, IN LONG BufferSize, IN LPCSTR FormatString, ... )
47 {
48 int BytesWritten;
49 va_list vargs;
50
51 if (BufferSize == 0)
52 return DDERR_INVALIDPARAMS;
53
54 va_start(vargs, FormatString);
55 BytesWritten = _vsnprintf(Buffer, BufferSize-1, FormatString, vargs);
56
57 if (BytesWritten < BufferSize)
58 return DDERR_GENERIC;
59
60 Buffer[BufferSize-1] = '\0';
61
62 return 0;
63 }
64
65 HRESULT AlignedAlloc(IN OUT LPVOID *ppObject, IN SIZE_T dwSize)
66 {
67 ULONG AddressOffset;
68 ULONG AlignedMask = MEM_ALIGNMENT - 1;
69 CHAR *AlignedPtr;
70 ULONG_PTR *AlignedOffsetPtr;
71
72 if (ppObject == 0)
73 return DDERR_INVALIDPARAMS;
74
75 if (dwSize == 0)
76 {
77 *ppObject = NULL;
78 return S_OK;
79 }
80
81 dwSize += MEM_ALIGNMENT;
82
83 AlignedPtr = (CHAR *)LocalAlloc(LMEM_ZEROINIT, dwSize);
84
85 if (AlignedPtr == 0)
86 return DDERR_OUTOFMEMORY;
87
88 AddressOffset = MEM_ALIGNMENT - ((ULONG)AlignedPtr & AlignedMask);
89
90 AlignedPtr += AddressOffset;
91
92 AlignedOffsetPtr = (ULONG_PTR *)(AlignedPtr - sizeof(ULONG));
93 *AlignedOffsetPtr = AddressOffset;
94
95 *ppObject = (ULONG_PTR *)AlignedPtr;
96
97 return S_OK;
98 }
99
100 VOID AlignedFree(IN OUT LPVOID pObject)
101 {
102 CHAR *NonAlignedPtr = pObject;
103 ULONG_PTR *AlignedPtr = pObject;
104
105 if (pObject == 0)
106 return;
107
108 NonAlignedPtr -= *(AlignedPtr - 1);
109
110 LocalFree(NonAlignedPtr);
111 }