Search Results

Search found 418 results on 17 pages for 'uint'.

Page 4/17 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • My rhythm game runs choppy even with high frame rate

    - by felipedrl
    I'm coding a rhythm game and the game runs smoothly with uncapped fps. But when I try to cap it around 60 the game updates in little chunks, like hiccups, as if it was skipping frames or at a very low frame rate. The reason I need to cap frame rate is because in some computers I tested, the fps varies a lot (from ~80 - ~250 fps) and those drops are noticeable and degrade response time. Since this is a rhythm game this is very important. This issue is driving me crazy. I've spent a few weeks already on it and still can't figure out the problem. I hope someone more experienced than me could shed some light on it. I'll try to put here all the hints I've tried along with two pseudo codes for game loops I tried, so I apologize if this post gets too lengthy. 1st GameLoop: const uint UPDATE_SKIP = 1000 / 60; uint nextGameTick = SDL_GetTicks(); while(isNotDone) { // only false when a QUIT event is generated! if (processEvents()) { if (SDL_GetTicks() > nextGameTick) { update(UPDATE_SKIP); render(); nextGameTick += UPDATE_SKIP; } } } 2nd Game Loop: const uint UPDATE_SKIP = 1000 / 60; while (isNotDone) { LARGE_INTEGER startTime; QueryPerformanceCounter(&startTime); // process events will return false in case of a QUIT event processed if (processEvents()) { update(frameTime); render(); } LARGE_INTEGER endTime; do { QueryPerformanceCounter(&endTime); frameTime = static_cast<uint>((endTime.QuadPart - startTime.QuadPart) * 1000.0 / frequency.QuadPart); } while (frameTime < UPDATE_SKIP); } [1] At first I thought it was a timer resolution problem. I was using SDL_GetTicks, but even when I switched to QueryPerformanceCounter, supposedly less granular, I saw no difference. [2] Then I thought it could be due to a rounding error in my position computation and since game updates are smaller in high FPS that would be less noticeable. Indeed there is an small error, but from my tests I realized that it is not enough to produce the position jumps I'm getting. Also, another intriguing factor is that if I enable vsync I'll get smooth updates @60fps regardless frame cap code. So why not rely on vsync? Because some computers can force a disable on gfx card config. [3] I started printing the maximum and minimum frame time measured in 1sec span, in the hope that every a few frames one would take a long time but still not enough to drop my fps computation. It turns out that, with frame cap code I always get frame times in the range of [16, 18]ms, and still, the game "does not moves like jagger". [4] My process' priority is set to HIGH (Windows doesn't allow me to set REALTIME for some reason). As far as I know there is only one thread running along with the game (a sound callback, which I really don't have access to it). I'm using AudiereLib. I then disabled Audiere by removing it from the project and still got the issue. Maybe there are some others threads running and one of them is taking too long to come back right in between when I measured frame times, I don't know. Is there a way to know which threads are attached to my process? [5] There are some dynamic data being created during game run. But It is a little bit hard to remove it to test. Maybe I'll have to try harder this one. Well, as I told you I really don't know what to try next. Anything, I mean, anything would be of great help. What bugs me more is why at 60fps & vsync enabled I get an smooth update and at 60fps & no vsync I don't. Is there a way to implement software vsync? I mean, query display sync info? Thanks in advance. I appreciate the ones that got this far and yet again I apologize for the long post. Best Regards from a fellow coder.

    Read the article

  • Triangle Picking Picking Back faces

    - by Tangeleno
    I'm having a bit of trouble with 3D picking, at first I thought my ray was inaccurate but it turns out that the picking is happening on faces facing the camera and faces facing away from the camera which I'm currently culling. Here's my ray creation code, I'm pretty sure the problem isn't here but I've been wrong before. private uint Pick() { Ray cursorRay = CalculateCursorRay(); Vector3? point = Control.Mesh.RayCast(cursorRay); if (point != null) { Tile hitTile = Control.TileMesh.GetTileAtPoint(point); return hitTile == null ? uint.MaxValue : (uint)(hitTile.X + hitTile.Y * Control.Generator.TilesWide); } return uint.MaxValue; } private Ray CalculateCursorRay() { Vector3 nearPoint = Control.Camera.Unproject(new Vector3(Cursor.Position.X, Control.ClientRectangle.Height - Cursor.Position.Y, 0f)); Vector3 farPoint = Control.Camera.Unproject(new Vector3(Cursor.Position.X, Control.ClientRectangle.Height - Cursor.Position.Y, 1f)); Vector3 direction = farPoint - nearPoint; direction.Normalize(); return new Ray(nearPoint, direction); } public Vector3 Camera.Unproject(Vector3 source) { Vector4 result; result.X = (source.X - _control.ClientRectangle.X) * 2 / _control.ClientRectangle.Width - 1; result.Y = (source.Y - _control.ClientRectangle.Y) * 2 / _control.ClientRectangle.Height - 1; result.Z = source.Z - 1; if (_farPlane - 1 == 0) result.Z = 0; else result.Z = result.Z / (_farPlane - 1); result.W = 1f; result = Vector4.Transform(result, Matrix4.Invert(ProjectionMatrix)); result = Vector4.Transform(result, Matrix4.Invert(ViewMatrix)); result = Vector4.Transform(result, Matrix4.Invert(_world)); result = Vector4.Divide(result, result.W); return new Vector3(result.X, result.Y, result.Z); } And my triangle intersection code. Ripped mainly from the XNA picking sample. public float? Intersects(Ray ray) { float? closestHit = Bounds.Intersects(ray); if (closestHit != null && Vertices.Length == 3) { Vector3 e1, e2; Vector3.Subtract(ref Vertices[1].Position, ref Vertices[0].Position, out e1); Vector3.Subtract(ref Vertices[2].Position, ref Vertices[0].Position, out e2); Vector3 directionCrossEdge2; Vector3.Cross(ref ray.Direction, ref e2, out directionCrossEdge2); float determinant; Vector3.Dot(ref e1, ref directionCrossEdge2, out determinant); if (determinant > -float.Epsilon && determinant < float.Epsilon) return null; float inverseDeterminant = 1.0f/determinant; Vector3 distanceVector; Vector3.Subtract(ref ray.Position, ref Vertices[0].Position, out distanceVector); float triangleU; Vector3.Dot(ref distanceVector, ref directionCrossEdge2, out triangleU); triangleU *= inverseDeterminant; if (triangleU < 0 || triangleU > 1) return null; Vector3 distanceCrossEdge1; Vector3.Cross(ref distanceVector, ref e1, out distanceCrossEdge1); float triangleV; Vector3.Dot(ref ray.Direction, ref distanceCrossEdge1, out triangleV); triangleV *= inverseDeterminant; if (triangleV < 0 || triangleU + triangleV > 1) return null; float rayDistance; Vector3.Dot(ref e2, ref distanceCrossEdge1, out rayDistance); rayDistance *= inverseDeterminant; if (rayDistance < 0) return null; return rayDistance; } return closestHit; } I'll admit I don't fully understand all of the math behind the intersection and that is something I'm working on, but my understanding was that if rayDistance was less than 0 the face was facing away from the camera, and shouldn't be counted as a hit. So my question is, is there an issue with my intersection or ray creation code, or is there another check I need to perform to tell if the face is facing away from the camera, and if so any hints on what that check might contain would be appreciated.

    Read the article

  • Drawing Shape in DebugView (Farseer)

    - by keyvan kazemi
    As the title says, I need to draw a shape/polygon in Farseer using debugview. I have this piece of code which converts a Texture to polygon: //load texture that will represent the tray trayTexture = Content.Load<Texture2D>("tray"); //Create an array to hold the data from the texture uint[] data = new uint[trayTexture.Width * trayTexture.Height]; //Transfer the texture data to the array trayTexture.GetData(data); //Find the vertices that makes up the outline of the shape in the texture Vertices verts = PolygonTools.CreatePolygon(data, trayTexture.Width, false); //Since it is a concave polygon, we need to partition it into several smaller convex polygons _list = BayazitDecomposer.ConvexPartition(verts); Vector2 vertScale = new Vector2(ConvertUnits.ToSimUnits(1)); foreach (Vertices verti in _list) { verti.Scale(ref vertScale); } tray = BodyFactory.CreateCompoundPolygon(MyWorld, _list, 10); Now in DebugView I guess I have to use "DrawShape" method which requires: DrawShape(Fixture fixture, Transform xf, Color color) My question is how can I get the variables needed for this method, namely Fixture and Transform?

    Read the article

  • C++ unmanaged inside winform

    - by Gosso
    First: I am using C# and C++ on windows 7. I have created a basic rendering engine in c++ with directx 10. It works good as a stand alone application. But, when I sending the Form.Handle of a WinForm I want to render inside to the engine it crashes during D3D10CreateDeviceAndSwapChain with the following error: HRESULT: 0x887a0001 (2289696769) Name: DXGI_ERROR_INVALID_CALL I get the handle from the winform during loading of the form. unsafe { void *ptr=m_view.Handle.ToPointer(); uint v = (uint)ptr; lhandle = v.ToString(); };

    Read the article

  • Deserializing Metafile

    - by Kildareflare
    I have an application that works with Enhanced Metafiles. I am able to create them, save them to disk as .emf and load them again no problem. I do this by using the gdi32.dll methods and the DLLImport attribute. However, to enable Version Tolerant Serialization I want to save the metafile in an object along with other data. This essentially means that I need to serialize the metafile data as a byte array and then deserialize it again in order to reconstruct the metafile. The problem I have is that the deserialized data would appear to be corrupted in some way, since the method that I use to reconstruct the Metafile raises a "Parameter not valid exception". At the very least the pixel format and resolutions have changed. Code use is below. [DllImport("gdi32.dll")] public static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer); [DllImport("gdi32.dll")] public static extern IntPtr SetEnhMetaFileBits(uint cbBuffer, byte[] lpBuffer); [DllImport("gdi32.dll")] public static extern bool DeleteEnhMetaFile(IntPtr hemf); The application creates a metafile image and passes it to the method below. private byte[] ConvertMetaFileToByteArray(Image image) { byte[] dataArray = null; Metafile mf = (Metafile)image; IntPtr enhMetafileHandle = mf.GetHenhmetafile(); uint bufferSize = GetEnhMetaFileBits(enhMetafileHandle, 0, null); if (enhMetafileHandle != IntPtr.Zero) { dataArray = new byte[bufferSize]; GetEnhMetaFileBits(enhMetafileHandle, bufferSize, dataArray); } DeleteEnhMetaFile(enhMetafileHandle); return dataArray; } At this point the dataArray is inserted into an object and serialized using a BinaryFormatter. The saved file is then deserialized again using a BinaryFormatter and the dataArray retrieved from the object. The dataArray is then used to reconstruct the original Metafile using the following method. public static Image ConvertByteArrayToMetafile(byte[] data) { Metafile mf = null; try { IntPtr hemf = SetEnhMetaFileBits((uint)data.Length, data); mf = new Metafile(hemf, true); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return (Image)mf; } The reconstructed metafile is then saved saved to disk as a .emf (Model) at which point it can be accessed by the Presenter for display. private static void SaveFile(Image image, String filepath) { try { byte[] buffer = ConvertMetafileToByteArray(image); File.WriteAllBytes(filepath, buffer); //will overwrite file if it exists } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } } The problem is that the save to disk fails. If this same method is used to save the original Metafile before it is serialized everything is OK. So something is happening to the data during serialization/deserializtion. Indeed if I check the Metafile properties in the debugger I can see that the ImageFlags, PropertyID, resolution and pixelformats change. Original Format32bppRgb changes to Format32bppArgb Original Resolution 81 changes to 96 I've trawled though google and SO and this has helped me get this far but Im now stuck. Does any one have enough experience with Metafiles / serialization to help..? EDIT: If I serialize/deserialize the byte array directly (without embedding in another object) I get the same problem.

    Read the article

  • My sample app is getting crash while registering to Filechangeinfo notification

    - by Solitaire
    public partial class Form1 : Form { [DllImport("coredll.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("coredll.dll")] static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam); [DllImport("coredll.dll")] public static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex); //public struct tagSHCHANGENOTIFYENTRY //{ // [MarshalAs(UnmanagedType.SysUInt)] // public ulong dwEventMask; // [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4096)] // public string WatchDir; // [MarshalAs(UnmanagedType.Bool)] // public bool fRecursive; //} //tagSHCHANGENOTIFYENTRY test; //[DllImport("aygshell.dll")] //static extern bool SHChangeNotifyRegister(IntPtr hwnd, ref tagSHCHANGENOTIFYENTRY test); const int GWL_WNDPROC = -4; public delegate int WindProc(IntPtr hWnd, int msg, IntPtr Wparam, IntPtr lparam); static private WindProc SampleProc; IntPtr OldDefProc = IntPtr.Zero; public enum SHCNE : uint { SHCNE_RENAMEITEM = 0x00000001, SHCNE_CREATE = 0x00000002, SHCNE_DELETE = 0x00000004, SHCNE_MKDIR = 0x00000008, SHCNE_RMDIR = 0x00000010, SHCNE_MEDIAINSERTED = 0x00000020, SHCNE_MEDIAREMOVED = 0x00000040, SHCNE_DRIVEREMOVED = 0x00000080, SHCNE_DRIVEADD = 0x00000100, SHCNE_NETSHARE = 0x00000200, SHCNE_NETUNSHARE = 0x00000400, SHCNE_ATTRIBUTES = 0x00000800, SHCNE_UPDATEDIR = 0x00001000, SHCNE_UPDATEITEM = 0x00002000, SHCNE_SERVERDISCONNECT = 0x00004000, SHCNE_UPDATEIMAGE = 0x00008000, SHCNE_DRIVEADDGUI = 0x00010000, SHCNE_RENAMEFOLDER = 0x00020000, SHCNE_FREESPACE = 0x00040000, SHCNE_EXTENDED_EVENT = 0x04000000, SHCNE_ASSOCCHANGED = 0x08000000, SHCNE_DISKEVENTS = 0x0002381F, SHCNE_GLOBALEVENTS = 0x0C0581E0, SHCNE_ALLEVENTS = 0x7FFFFFFF, SHCNE_INTERRUPT = 0x80000000, } public enum SHCNF { SHCNF_IDLIST = 0x0000, SHCNF_PATHA = 0x0001, SHCNF_PRINTERA = 0x0002, SHCNF_DWORD = 0x0003, SHCNF_PATHW = 0x0005, SHCNF_PRINTERW = 0x0006, SHCNF_TYPE = 0x00FF, SHCNF_FLUSH = 0x1000, SHCNF_FLUSHNOWAIT = 0x2000 } public const uint WM_SHNOTIFY = 0x0401; private const int WM_FILECHANGEINFO = (0x8000 + 0x101); public struct SHChangeNotifyEntry { public IntPtr pIdl; [MarshalAs(UnmanagedType.Bool)] public Boolean Recursively; } [DllImport("coredll.dll", EntryPoint = "#2", CharSet = CharSet.Auto)] private static extern uint SHChangeNotifyRegister( IntPtr hWnd, SHCNF fSources, SHCNE fEvents, uint wMsg, int cEntries, ref SHChangeNotifyEntry pFsne); [DllImport("Ceshell.dll", CharSet = CharSet.Auto)] private static extern uint SHGetSpecialFolderLocation( IntPtr hWnd, CSIDL nFolder, out IntPtr Pidl); public enum CSIDL { /// <summary> /// Desktop /// </summary> CSIDL_DESKTOP = 0x0000, /// <summary> /// Internet Explorer (icon on desktop) /// </summary> CSIDL_INTERNET = 0x0001, /// <summary> /// Start Menu\Programs /// </summary> CSIDL_PROGRAMS = 0x0002, /// <summary> /// My Computer\Control Panel /// </summary> CSIDL_CONTROLS = 0x0003, /// <summary> /// My Computer\Printers /// </summary> CSIDL_PRINTERS = 0x0004, /// <summary> /// My Documents /// </summary> CSIDL_PERSONAL = 0x0005, /// <summary> /// user name\Favorites /// </summary> CSIDL_FAVORITES = 0x0006, /// <summary> /// Start Menu\Programs\Startup /// </summary> CSIDL_STARTUP = 0x0007, /// <summary> /// user name\Recent /// </summary> CSIDL_RECENT = 0x0008, /// <summary> /// user name\SendTo /// </summary> CSIDL_SENDTO = 0x0009, /// <summary> /// desktop\Recycle Bin /// </summary> CSIDL_BITBUCKET = 0x000a, /// <summary> /// user name\Start Menu /// </summary> CSIDL_STARTMENU = 0x000b, /// <summary> /// logical "My Documents" desktop icon /// </summary> CSIDL_MYDOCUMENTS = 0x000c, /// <summary> /// "My Music" folder /// </summary> CSIDL_MYMUSIC = 0x000d, /// <summary> /// "My Videos" folder /// </summary> CSIDL_MYVIDEO = 0x000e, /// <summary> /// user name\Desktop /// </summary> CSIDL_DESKTOPDIRECTORY = 0x0010, /// <summary> /// My Computer /// </summary> CSIDL_DRIVES = 0x0011, /// <summary> /// Network Neighborhood (My Network Places) /// </summary> CSIDL_NETWORK = 0x0012, /// <summary> /// user name>nethood /// </summary> CSIDL_NETHOOD = 0x0013, /// <summary> /// windows\fonts /// </summary> CSIDL_FONTS = 0x0014, CSIDL_TEMPLATES = 0x0015, /// <summary> /// All Users\Start Menu /// </summary> CSIDL_COMMON_STARTMENU = 0x0016, /// <summary> /// All Users\Start Menu\Programs /// </summary> CSIDL_COMMON_PROGRAMS = 0X0017, /// <summary> /// All Users\Startup /// </summary> CSIDL_COMMON_STARTUP = 0x0018, /// <summary> /// All Users\Desktop /// </summary> CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019, /// <summary> /// user name\Application Data /// </summary> CSIDL_APPDATA = 0x001a, /// <summary> /// user name\PrintHood /// </summary> CSIDL_PRINTHOOD = 0x001b, /// <summary> /// user name\Local Settings\Applicaiton Data (non roaming) /// </summary> CSIDL_LOCAL_APPDATA = 0x001c, /// <summary> /// non localized startup /// </summary> CSIDL_ALTSTARTUP = 0x001d, /// <summary> /// non localized common startup /// </summary> CSIDL_COMMON_ALTSTARTUP = 0x001e, CSIDL_COMMON_FAVORITES = 0x001f, CSIDL_INTERNET_CACHE = 0x0020, CSIDL_COOKIES = 0x0021, CSIDL_HISTORY = 0x0022, /// <summary> /// All Users\Application Data /// </summary> CSIDL_COMMON_APPDATA = 0x0023, /// <summary> /// GetWindowsDirectory() /// </summary> CSIDL_WINDOWS = 0x0024, /// <summary> /// GetSystemDirectory() /// </summary> CSIDL_SYSTEM = 0x0025, /// <summary> /// C:\Program Files /// </summary> CSIDL_PROGRAM_FILES = 0x0026, /// <summary> /// C:\Program Files\My Pictures /// </summary> CSIDL_MYPICTURES = 0x0027, /// <summary> /// USERPROFILE /// </summary> CSIDL_PROFILE = 0x0028, /// <summary> /// x86 system directory on RISC /// </summary> CSIDL_SYSTEMX86 = 0x0029, /// <summary> /// x86 C:\Program Files on RISC /// </summary> CSIDL_PROGRAM_FILESX86 = 0x002a, /// <summary> /// C:\Program Files\Common /// </summary> CSIDL_PROGRAM_FILES_COMMON = 0x002b, /// <summary> /// x86 Program Files\Common on RISC /// </summary> CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c, /// <summary> /// All Users\Templates /// </summary> CSIDL_COMMON_TEMPLATES = 0x002d, /// <summary> /// All Users\Documents /// </summary> CSIDL_COMMON_DOCUMENTS = 0x002e, /// <summary> /// All Users\Start Menu\Programs\Administrative Tools /// </summary> CSIDL_COMMON_ADMINTOOLS = 0x002f, /// <summary> /// user name\Start Menu\Programs\Administrative Tools /// </summary> CSIDL_ADMINTOOLS = 0x0030, /// <summary> /// Network and Dial-up Connections /// </summary> CSIDL_CONNECTIONS = 0x0031, /// <summary> /// All Users\My Music /// </summary> CSIDL_COMMON_MUSIC = 0x0035, /// <summary> /// All Users\My Pictures /// </summary> CSIDL_COMMON_PICTURES = 0x0036, /// <summary> /// All Users\My Video /// </summary> CSIDL_COMMON_VIDEO = 0x0037, /// <summary> /// Resource Direcotry /// </summary> CSIDL_RESOURCES = 0x0038, /// <summary> /// Localized Resource Direcotry /// </summary> CSIDL_RESOURCES_LOCALIZED = 0x0039, /// <summary> /// Links to All Users OEM specific apps /// </summary> CSIDL_COMMON_OEM_LINKS = 0x003a, /// <summary> /// USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning /// </summary> CSIDL_CDBURN_AREA = 0x003b, /// <summary> /// Computers Near Me (computered from Workgroup membership) /// </summary> CSIDL_COMPUTERSNEARME = 0x003d, /// <summary> /// combine with CSIDL_ value to force folder creation in SHGetFolderPath() /// </summary> CSIDL_FLAG_CREATE = 0x8000, /// <summary> /// combine with CSIDL_ value to return an unverified folder path /// </summary> CSIDL_FLAG_DONT_VERIFY = 0x4000, /// <summary> /// combine with CSIDL_ value to insure non-alias versions of the pidl /// </summary> CSIDL_FLAG_NO_ALIAS = 0x1000, /// <summary> /// combine with CSIDL_ value to indicate per-user init (eg. upgrade) /// </summary> CSIDL_FLAG_PER_USER_INIT = 0x0800, /// <summary> /// mask for all possible /// </summary> CSIDL_FLAG_MASK = 0xFF00, } public enum SHGetFolderLocationReturnValues : uint { /// <summary> /// Success /// </summary> S_OK = 0x00000000, /// <summary> /// The CSIDL in nFolder is valid but the folder does not exist /// </summary> S_FALSE = 0x00000001, /// <summary> /// The CSIDL in nFolder is not valid /// </summary> E_INVALIDARG = 0x80070057 } public static IntPtr GetPidlFromFolderID(IntPtr hWnd, CSIDL Id) { IntPtr pIdl = IntPtr.Zero; SHGetFolderLocationReturnValues res = (SHGetFolderLocationReturnValues) SHGetSpecialFolderLocation( hWnd, Id, out pIdl); return (pIdl); } public Form1() { InitializeComponent(); SampleProc = new WindProc (SubclassWndProc); OldDefProc = GetWindowLong(this.Handle, GWL_WNDPROC); SetWindowLong(this.Handle, GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(SampleProc)/*SampleProc.Method.MethodHandle.Value.ToInt32()*/); //tagSHCHANGENOTIFYENTRY changeentry = new tagSHCHANGENOTIFYENTRY(); //changeentry.dwEventMask = (ulong)SHCNE.SHCNE_ALLEVENTS; //changeentry.fRecursive = true; //changeentry.WatchDir = null; //SHChangeNotifyRegister(this.Handle, ref changeentry); SHChangeNotifyEntry changeentry = new SHChangeNotifyEntry(); changeentry.pIdl = GetPidlFromFolderID(this.Handle, CSIDL.CSIDL_DESKTOP); changeentry.Recursively = true; try { uint notifyid = SHChangeNotifyRegister( this.Handle, SHCNF.SHCNF_TYPE | SHCNF.SHCNF_IDLIST, SHCNE.SHCNE_ALLEVENTS, WM_FILECHANGEINFO, 1, ref changeentry); } catch (Exception ee) { } i am failing in SHChangeNotifyRegister please help me.. tell me the reason why i am crashing..same code work fine for desktop.. please help Thanks.

    Read the article

  • Smart way to find the corresponding nullable type?

    - by Marc Wittke
    How could I avoid this dictionary (or create it dynamically)? Dictionary<Type,Type> CorrespondingNullableType = new Dictionary<Type, Type> { {typeof(bool), typeof(bool?)}, {typeof(byte), typeof(byte?)}, {typeof(sbyte), typeof(sbyte?)}, {typeof(char), typeof(char?)}, {typeof(decimal), typeof(decimal?)}, {typeof(double), typeof(double?)}, {typeof(float), typeof(float?)}, {typeof(int), typeof(int?)}, {typeof(uint), typeof(uint?)}, {typeof(long), typeof(long?)}, {typeof(ulong), typeof(ulong?)}, {typeof(short), typeof(short?)}, {typeof(ushort), typeof(ushort?)}, {typeof(Guid), typeof(Guid?)}, };

    Read the article

  • Issues passing values to shader

    - by numerical25
    I am having issues passing values to my shader. My application compiles fine, but my cube object won't shade. Below is majority of my code. Most of my code for communicating with my shader is in createObject method myGame.cpp #include "MyGame.h" #include "OneColorCube.h" /* This code sets a projection and shows a turning cube. What has been added is the project, rotation and a rasterizer to change the rasterization of the cube. The issue that was going on was something with the effect file which was causing the vertices not to be rendered correctly.*/ typedef struct { ID3D10Effect* pEffect; ID3D10EffectTechnique* pTechnique; //vertex information ID3D10Buffer* pVertexBuffer; ID3D10Buffer* pIndicesBuffer; ID3D10InputLayout* pVertexLayout; UINT numVertices; UINT numIndices; }ModelObject; ModelObject modelObject; // World Matrix D3DXMATRIX WorldMatrix; // View Matrix D3DXMATRIX ViewMatrix; // Projection Matrix D3DXMATRIX ProjectionMatrix; ID3D10EffectMatrixVariable* pProjectionMatrixVariable = NULL; ID3D10EffectVectorVariable* pLightVarible = NULL; bool MyGame::InitDirect3D() { if(!DX3dApp::InitDirect3D()) { return false; } D3D10_RASTERIZER_DESC rastDesc; rastDesc.FillMode = D3D10_FILL_WIREFRAME; rastDesc.CullMode = D3D10_CULL_FRONT; rastDesc.FrontCounterClockwise = true; rastDesc.DepthBias = false; rastDesc.DepthBiasClamp = 0; rastDesc.SlopeScaledDepthBias = 0; rastDesc.DepthClipEnable = false; rastDesc.ScissorEnable = false; rastDesc.MultisampleEnable = false; rastDesc.AntialiasedLineEnable = false; ID3D10RasterizerState *g_pRasterizerState; mpD3DDevice->CreateRasterizerState(&rastDesc, &g_pRasterizerState); //mpD3DDevice->RSSetState(g_pRasterizerState); // Set up the World Matrix D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixLookAtLH(&ViewMatrix, new D3DXVECTOR3(0.0f, 10.0f, -20.0f), new D3DXVECTOR3(0.0f, 0.0f, 0.0f), new D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // Set up the projection matrix D3DXMatrixPerspectiveFovLH(&ProjectionMatrix, (float)D3DX_PI * 0.5f, (float)mWidth/(float)mHeight, 0.1f, 100.0f); if(!CreateObject()) { return false; } return true; } //These are actions that take place after the clearing of the buffer and before the present void MyGame::GameDraw() { static float rotationAngleY = 15.0f; static float rotationAngleX = 0.0f; static D3DXMATRIX rotationXMatrix; static D3DXMATRIX rotationYMatrix; // create the rotation matrix using the rotation angle D3DXMatrixRotationY(&rotationYMatrix, rotationAngleY); D3DXMatrixRotationX(&rotationXMatrix, rotationAngleX); //rotationAngleY += (float)D3DX_PI * 0.002f; //rotationAngleX += (float)D3DX_PI * 0.001f; WorldMatrix = rotationYMatrix * rotationXMatrix; // Set the input layout mpD3DDevice->IASetInputLayout(modelObject.pVertexLayout); // Set vertex buffer UINT stride = sizeof(VertexPos); UINT offset = 0; mpD3DDevice->IASetVertexBuffers(0, 1, &modelObject.pVertexBuffer, &stride, &offset); // Set primitive topology mpD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); //ViewMatrix._43 += 0.005f; // Combine and send the final matrix to the shader D3DXMATRIX finalMatrix = (WorldMatrix * ViewMatrix * ProjectionMatrix); pProjectionMatrixVariable->SetMatrix((float*)&finalMatrix); // make sure modelObject is valid // Render a model object D3D10_TECHNIQUE_DESC techniqueDescription; modelObject.pTechnique->GetDesc(&techniqueDescription); // Loop through the technique passes for(UINT p=0; p < techniqueDescription.Passes; ++p) { modelObject.pTechnique->GetPassByIndex(p)->Apply(0); // draw the cube using all 36 vertices and 12 triangles mpD3DDevice->Draw(36,0); } } //Render actually incapsulates Gamedraw, so you can call data before you actually clear the buffer or after you //present data void MyGame::Render() { DX3dApp::Render(); } bool MyGame::CreateObject() { //Create Layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 24, D3D10_INPUT_PER_VERTEX_DATA, 0} }; UINT numElements = (sizeof(layout)/sizeof(layout[0])); modelObject.numVertices = sizeof(vertices)/sizeof(VertexPos); for(int i = 0; i < modelObject.numVertices; i += 3) { D3DXVECTOR3 out; D3DXVECTOR3 v1 = vertices[0 + i].pos; D3DXVECTOR3 v2 = vertices[1 + i].pos; D3DXVECTOR3 v3 = vertices[2 + i].pos; D3DXVECTOR3 u = v2 - v1; D3DXVECTOR3 v = v3 - v1; D3DXVec3Cross(&out, &u, &v); D3DXVec3Normalize(&out, &out); vertices[0 + i].normal = out; vertices[1 + i].normal = out; vertices[2 + i].normal = out; } //Create buffer desc D3D10_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(VertexPos) * modelObject.numVertices; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; //Create the buffer HRESULT hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pVertexBuffer); if(FAILED(hr)) return false; /* //Create indices DWORD indices[] = { 0,1,3, 1,2,3 }; ModelObject.numIndices = sizeof(indices)/sizeof(DWORD); bufferDesc.ByteWidth = sizeof(DWORD) * ModelObject.numIndices; bufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; initData.pSysMem = indices; hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &ModelObject.pIndicesBuffer); if(FAILED(hr)) return false;*/ ///////////////////////////////////////////////////////////////////////////// //Set up fx files LPCWSTR effectFilename = L"effect.fx"; modelObject.pEffect = NULL; hr = D3DX10CreateEffectFromFile(effectFilename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, mpD3DDevice, NULL, NULL, &modelObject.pEffect, NULL, NULL); if(FAILED(hr)) return false; pProjectionMatrixVariable = modelObject.pEffect->GetVariableByName("Projection")->AsMatrix(); pLightVarible = modelObject.pEffect->GetVariableByName("lightSource")->AsVector(); //Dont sweat the technique. Get it! LPCSTR effectTechniqueName = "Render"; D3DXVECTOR3 vLight(10.0f, 10.0f, 10.0f); pLightVarible->SetFloatVector(vLight); modelObject.pTechnique = modelObject.pEffect->GetTechniqueByName(effectTechniqueName); if(modelObject.pTechnique == NULL) return false; //Create Vertex layout D3D10_PASS_DESC passDesc; modelObject.pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); hr = mpD3DDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &modelObject.pVertexLayout); if(FAILED(hr)) return false; return true; } And below is my shader effect.fx matrix Projection; float3 lightSource; float4 lightColor = {0.5, 0.5, 0.5, 0.5}; // PS_INPUT - input variables to the pixel shader // This struct is created and fill in by the // vertex shader struct PS_INPUT { float4 Pos : SV_POSITION; float4 Color : COLOR0; float4 Normal : NORMAL; }; //////////////////////////////////////////////// // Vertex Shader - Main Function /////////////////////////////////////////////// PS_INPUT VS(float4 Pos : POSITION, float4 Color : COLOR, float4 Normal : NORMAL) { PS_INPUT psInput; // Pass through both the position and the color psInput.Pos = mul( Pos, Projection ); psInput.Color = Color; psInput.Normal = Normal; return psInput; } /////////////////////////////////////////////// // Pixel Shader /////////////////////////////////////////////// float4 PS(PS_INPUT psInput) : SV_Target { float4 finalColor = 0; finalColor = saturate(dot(lightSource, psInput.Normal) * lightColor); return finalColor; } // Define the technique technique10 Render { pass P0 { SetVertexShader( CompileShader( vs_4_0, VS() ) ); SetGeometryShader( NULL ); SetPixelShader( CompileShader( ps_4_0, PS() ) ); } }

    Read the article

  • Using Window Handle to disable Mouse clicks using c#

    - by srk
    I need to disable the Mouse Clicks, Mouse movement for a specific windows for a Kiosk application. Is it Feasible in C# ? I have removed the menu bar and title bar of a specific window, will that be a starting point to achieve the above requirement ? How can i achieve this requirement. The code for removing the menu bar and title bar using window handle : #region Constants //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); [DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] static extern bool DrawMenuBar(IntPtr hWnd); [DllImport("user32.dll")] static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //assorted constants needed public static uint MF_BYPOSITION = 0x400; public static uint MF_REMOVE = 0x1000; public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public static int WS_SYSMENU = 0x00080000; //window menu #endregion public static void WindowsReStyle() { Process[] Procs = Process.GetProcesses(); foreach (Process proc in Procs) { if (proc.ProcessName.StartsWith("notepad")) { IntPtr pFoundWindow = proc.MainWindowHandle; int style = GetWindowLong(pFoundWindow, GWL_STYLE); //get menu IntPtr HMENU = GetMenu(proc.MainWindowHandle); //get item count int count = GetMenuItemCount(HMENU); //loop & remove for (int i = 0; i < count; i++) RemoveMenu(HMENU, 0, (MF_BYPOSITION | MF_REMOVE)); //force a redraw DrawMenuBar(proc.MainWindowHandle); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_SYSMENU)); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_CAPTION)); } } }

    Read the article

  • How to change the coordinate origin in Flash's stage with Actionscript?

    - by Petruza
    I think I did this before but can't find the code. Flash as many other graphical frameworks use the top-left corner as the coordinate origin (0,0) because it's how the underlying memory model is by convention. But it would be really simpler for my calculations if the origin was in the center of the stage, because all the game revolves around the center and uses a lot of trigonometry, angles, etc. Is there some built-in method like Stage::setOrigin( uint, uint ); or something like that?

    Read the article

  • Title: Using Window Handle to disable Mouse clicks and Keyboard Inputs using Pinvoke c#

    - by srk
    I need to disable the Mouse Clicks, Mouse movement and Keyboard Inputs for a specific windows for a Kiosk application. Is it Feasible in C# ? I have removed the menu bar and title bar of a specific window, will that be a starting point to achieve the above requirement ? The code for removing the menu bar and title bar using window handle : #region Constants //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); [DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] static extern bool DrawMenuBar(IntPtr hWnd); [DllImport("user32.dll")] static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //assorted constants needed public static uint MF_BYPOSITION = 0x400; public static uint MF_REMOVE = 0x1000; public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public static int WS_SYSMENU = 0x00080000; //window menu #endregion public static void WindowsReStyle() { Process[] Procs = Process.GetProcesses(); foreach (Process proc in Procs) { if (proc.ProcessName.StartsWith("notepad")) { IntPtr pFoundWindow = proc.MainWindowHandle; int style = GetWindowLong(pFoundWindow, GWL_STYLE); //get menu IntPtr HMENU = GetMenu(proc.MainWindowHandle); //get item count int count = GetMenuItemCount(HMENU); //loop & remove for (int i = 0; i < count; i++) RemoveMenu(HMENU, 0, (MF_BYPOSITION | MF_REMOVE)); //force a redraw DrawMenuBar(proc.MainWindowHandle); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_SYSMENU)); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_CAPTION)); } } }

    Read the article

  • Using Window Handle to disable Mouse clicks and Keyboard Inputs using c#

    - by srk
    I need to disable the Mouse Clicks, Mouse movement and Keyboard Inputs for a specific windows for a Kiosk application. Is it Feasible in C# ? I have removed the menu bar and title bar of a specific window, will that be a starting point to achieve the above requirement ? The code for removing the menu bar and title bar using window handle : #region Constants //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); [DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] static extern bool DrawMenuBar(IntPtr hWnd); [DllImport("user32.dll")] static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //assorted constants needed public static uint MF_BYPOSITION = 0x400; public static uint MF_REMOVE = 0x1000; public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public static int WS_SYSMENU = 0x00080000; //window menu #endregion public static void WindowsReStyle() { Process[] Procs = Process.GetProcesses(); foreach (Process proc in Procs) { if (proc.ProcessName.StartsWith("notepad")) { IntPtr pFoundWindow = proc.MainWindowHandle; int style = GetWindowLong(pFoundWindow, GWL_STYLE); //get menu IntPtr HMENU = GetMenu(proc.MainWindowHandle); //get item count int count = GetMenuItemCount(HMENU); //loop & remove for (int i = 0; i < count; i++) RemoveMenu(HMENU, 0, (MF_BYPOSITION | MF_REMOVE)); //force a redraw DrawMenuBar(proc.MainWindowHandle); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_SYSMENU)); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_CAPTION)); } } }

    Read the article

  • Using Window Handle to disable Mouse clicks and Keyboard Inputs using P/Invoke

    - by srk
    I need to disable the Mouse Clicks, Mouse movement and Keyboard Inputs for a specific windows for a Kiosk application. Is it feasible using .NET ? I have removed the menu bar and title bar of a specific window, will that be a starting point to achieve the above requirement ? The code for removing the menu bar and title bar using window handle : #region Constants //Finds a window by class name [DllImport("USER32.DLL")] public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); //Sets a window to be a child window of another window [DllImport("USER32.DLL")] public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //Sets window attributes [DllImport("USER32.DLL")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); //Gets window attributes [DllImport("USER32.DLL")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); [DllImport("user32.dll")] static extern IntPtr GetMenu(IntPtr hWnd); [DllImport("user32.dll")] static extern int GetMenuItemCount(IntPtr hMenu); [DllImport("user32.dll")] static extern bool DrawMenuBar(IntPtr hWnd); [DllImport("user32.dll")] static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags); //assorted constants needed public static uint MF_BYPOSITION = 0x400; public static uint MF_REMOVE = 0x1000; public static int GWL_STYLE = -16; public static int WS_CHILD = 0x40000000; //child window public static int WS_BORDER = 0x00800000; //window with border public static int WS_DLGFRAME = 0x00400000; //window with double border but no title public static int WS_CAPTION = WS_BORDER | WS_DLGFRAME; //window with a title bar public static int WS_SYSMENU = 0x00080000; //window menu #endregion public static void WindowsReStyle() { Process[] Procs = Process.GetProcesses(); foreach (Process proc in Procs) { if (proc.ProcessName.StartsWith("notepad")) { IntPtr pFoundWindow = proc.MainWindowHandle; int style = GetWindowLong(pFoundWindow, GWL_STYLE); //get menu IntPtr HMENU = GetMenu(proc.MainWindowHandle); //get item count int count = GetMenuItemCount(HMENU); //loop & remove for (int i = 0; i < count; i++) RemoveMenu(HMENU, 0, (MF_BYPOSITION | MF_REMOVE)); //force a redraw DrawMenuBar(proc.MainWindowHandle); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_SYSMENU)); SetWindowLong(pFoundWindow, GWL_STYLE, (style & ~WS_CAPTION)); } } }

    Read the article

  • Go - Methods of an interface

    - by nevalu
    Would be correct the next way to implement the methods attached to an interface? (getKey, getData) type reader interface { getKey(ver uint) string getData() string } type location struct { reader fileLocation string err os.Error } func (self *location) getKey(ver uint) string {...} func (self *location) getData() string {...} func NewReader(fileLocation string) *location { _location := new(location) _location.fileLocation = fileLocation return _location }

    Read the article

  • Read hexa data from file

    - by confusedman
    I'm trying to read hexa data(color value ex. 0xffffffff) from txt file... but i don't know how to read it.... i declared the color value like 'uint color' and i want to change the value though txt file. if i use int data i can use 'atoi' function, but what can i use function for uint?

    Read the article

  • Run-Time Check Failure #2 - Stack around the variable 'indices' was corrupted.

    - by numerical25
    well I think I know what the problem is. I am just having a hard time debugging it. I am working with the directx api and I am trying to generate a plane along the x and z axis according to a book I have. The problem is when I am creating my indices. I think I am setting values out of the bounds of the indices array. I am just having a hard time figuring out what I did wrong. I am unfamiliar with the this method of generating a plane. so its a little difficult for me. below is my code. Take emphasis on the indices loop. #include "MyGame.h" //#include "CubeVector.h" /* This code sets a projection and shows a turning cube. What has been added is the project, rotation and a rasterizer to change the rasterization of the cube. The issue that was going on was something with the effect file which was causing the vertices not to be rendered correctly.*/ typedef struct { ID3D10Effect* pEffect; ID3D10EffectTechnique* pTechnique; //vertex information ID3D10Buffer* pVertexBuffer; ID3D10Buffer* pIndicesBuffer; ID3D10InputLayout* pVertexLayout; UINT numVertices; UINT numIndices; }ModelObject; ModelObject modelObject; // World Matrix D3DXMATRIX WorldMatrix; // View Matrix D3DXMATRIX ViewMatrix; // Projection Matrix D3DXMATRIX ProjectionMatrix; ID3D10EffectMatrixVariable* pProjectionMatrixVariable = NULL; //grid information #define NUM_COLS 16 #define NUM_ROWS 16 #define CELL_WIDTH 32 #define CELL_HEIGHT 32 #define NUM_VERTSX (NUM_COLS + 1) #define NUM_VERTSY (NUM_ROWS + 1) bool MyGame::InitDirect3D() { if(!DX3dApp::InitDirect3D()) { return false; } D3D10_RASTERIZER_DESC rastDesc; rastDesc.FillMode = D3D10_FILL_WIREFRAME; rastDesc.CullMode = D3D10_CULL_FRONT; rastDesc.FrontCounterClockwise = true; rastDesc.DepthBias = false; rastDesc.DepthBiasClamp = 0; rastDesc.SlopeScaledDepthBias = 0; rastDesc.DepthClipEnable = false; rastDesc.ScissorEnable = false; rastDesc.MultisampleEnable = false; rastDesc.AntialiasedLineEnable = false; ID3D10RasterizerState *g_pRasterizerState; mpD3DDevice->CreateRasterizerState(&rastDesc, &g_pRasterizerState); mpD3DDevice->RSSetState(g_pRasterizerState); // Set up the World Matrix D3DXMatrixIdentity(&WorldMatrix); D3DXMatrixLookAtLH(&ViewMatrix, new D3DXVECTOR3(0.0f, 10.0f, -20.0f), new D3DXVECTOR3(0.0f, 0.0f, 0.0f), new D3DXVECTOR3(0.0f, 1.0f, 0.0f)); // Set up the projection matrix D3DXMatrixPerspectiveFovLH(&ProjectionMatrix, (float)D3DX_PI * 0.5f, (float)mWidth/(float)mHeight, 0.1f, 100.0f); if(!CreateObject()) { return false; } return true; } //These are actions that take place after the clearing of the buffer and before the present void MyGame::GameDraw() { static float rotationAngle = 0.0f; // create the rotation matrix using the rotation angle D3DXMatrixRotationY(&WorldMatrix, rotationAngle); rotationAngle += (float)D3DX_PI * 0.0f; // Set the input layout mpD3DDevice->IASetInputLayout(modelObject.pVertexLayout); // Set vertex buffer UINT stride = sizeof(VertexPos); UINT offset = 0; mpD3DDevice->IASetVertexBuffers(0, 1, &modelObject.pVertexBuffer, &stride, &offset); mpD3DDevice->IASetIndexBuffer(modelObject.pIndicesBuffer, DXGI_FORMAT_R32_UINT, 0); // Set primitive topology mpD3DDevice->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // Combine and send the final matrix to the shader D3DXMATRIX finalMatrix = (WorldMatrix * ViewMatrix * ProjectionMatrix); pProjectionMatrixVariable->SetMatrix((float*)&finalMatrix); // make sure modelObject is valid // Render a model object D3D10_TECHNIQUE_DESC techniqueDescription; modelObject.pTechnique->GetDesc(&techniqueDescription); // Loop through the technique passes for(UINT p=0; p < techniqueDescription.Passes; ++p) { modelObject.pTechnique->GetPassByIndex(p)->Apply(0); // draw the cube using all 36 vertices and 12 triangles mpD3DDevice->DrawIndexed(modelObject.numIndices,0,0); } } //Render actually incapsulates Gamedraw, so you can call data before you actually clear the buffer or after you //present data void MyGame::Render() { DX3dApp::Render(); } bool MyGame::CreateObject() { VertexPos vertices[NUM_VERTSX * NUM_VERTSY]; for(int z=0; z < NUM_VERTSY; ++z) { for(int x = 0; x < NUM_VERTSX; ++x) { vertices[x + z * NUM_VERTSX].pos.x = (float)x * CELL_WIDTH; vertices[x + z * NUM_VERTSX].pos.z = (float)z * CELL_HEIGHT; vertices[x + z * NUM_VERTSX].pos.y = 0.0f; vertices[x + z * NUM_VERTSX].color = D3DXVECTOR4(1.0, 0.0f, 0.0f, 0.0f); } } DWORD indices[NUM_VERTSX * NUM_VERTSY]; int curIndex = 0; for(int z=0; z < NUM_ROWS; ++z) { for(int x = 0; x < NUM_COLS; ++x) { int curVertex = x + (z * NUM_VERTSX); indices[curIndex] = curVertex; indices[curIndex + 1] = curVertex + NUM_VERTSX; indices[curIndex + 2] = curVertex + 1; indices[curIndex + 3] = curVertex + 1; indices[curIndex + 4] = curVertex + NUM_VERTSX; indices[curIndex + 5] = curVertex + NUM_VERTSX + 1; curIndex += 6; } } //Create Layout D3D10_INPUT_ELEMENT_DESC layout[] = { {"POSITION",0,DXGI_FORMAT_R32G32B32_FLOAT, 0 , 0, D3D10_INPUT_PER_VERTEX_DATA, 0}, {"COLOR",0,DXGI_FORMAT_R32G32B32A32_FLOAT, 0 , 12, D3D10_INPUT_PER_VERTEX_DATA, 0} }; UINT numElements = (sizeof(layout)/sizeof(layout[0])); modelObject.numVertices = sizeof(vertices)/sizeof(VertexPos); //Create buffer desc D3D10_BUFFER_DESC bufferDesc; bufferDesc.Usage = D3D10_USAGE_DEFAULT; bufferDesc.ByteWidth = sizeof(VertexPos) * modelObject.numVertices; bufferDesc.BindFlags = D3D10_BIND_VERTEX_BUFFER; bufferDesc.CPUAccessFlags = 0; bufferDesc.MiscFlags = 0; D3D10_SUBRESOURCE_DATA initData; initData.pSysMem = vertices; //Create the buffer HRESULT hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pVertexBuffer); if(FAILED(hr)) return false; modelObject.numIndices = sizeof(indices)/sizeof(DWORD); bufferDesc.ByteWidth = sizeof(DWORD) * modelObject.numIndices; bufferDesc.BindFlags = D3D10_BIND_INDEX_BUFFER; initData.pSysMem = indices; hr = mpD3DDevice->CreateBuffer(&bufferDesc, &initData, &modelObject.pIndicesBuffer); if(FAILED(hr)) return false; ///////////////////////////////////////////////////////////////////////////// //Set up fx files LPCWSTR effectFilename = L"effect.fx"; modelObject.pEffect = NULL; hr = D3DX10CreateEffectFromFile(effectFilename, NULL, NULL, "fx_4_0", D3D10_SHADER_ENABLE_STRICTNESS, 0, mpD3DDevice, NULL, NULL, &modelObject.pEffect, NULL, NULL); if(FAILED(hr)) return false; pProjectionMatrixVariable = modelObject.pEffect->GetVariableByName("Projection")->AsMatrix(); //Dont sweat the technique. Get it! LPCSTR effectTechniqueName = "Render"; modelObject.pTechnique = modelObject.pEffect->GetTechniqueByName(effectTechniqueName); if(modelObject.pTechnique == NULL) return false; //Create Vertex layout D3D10_PASS_DESC passDesc; modelObject.pTechnique->GetPassByIndex(0)->GetDesc(&passDesc); hr = mpD3DDevice->CreateInputLayout(layout, numElements, passDesc.pIAInputSignature, passDesc.IAInputSignatureSize, &modelObject.pVertexLayout); if(FAILED(hr)) return false; return true; }

    Read the article

  • Calling managed code from unmanaged win32 assembly dll - crash

    - by JustGreg
    I'm developing a serial port dll in win32 assembly (MASM32). It has its own thread checking multiple events and at a specified buffer treshold it'd notify the managed main application by calling a callback function. It just a call with no arguments/return value. At startup the main application stores the callback function's address by calling a function in the dll: pCallBackFunction dd 0 SetCallBackPointer proc pcb:DWORD mov eax, pcb mov pCallBackFunction, eax call DWORD ptr pCallBackFunction ; verify it immediately ret SetCallBackPointer endp The upper function immediately calls back the managed application callback routine for verification purposes. It is working fine. However, when I place the call instruction to other functions in the dll it crashes the application. It doesn't matter if the call is in a simple function or in the threadproc of the dll. For example: OpenPort proc pn:byte,br:dword, inputbuffersize: dword, outputbuffersize:dword, tresholdsize: dword LOCAL dcb: DCB LOCAL SerialTimeOuts: COMMTIMEOUTS call DWORD ptr pCallBackFunction xor eax, eax mov al, pn mov [com_port+3],al etc. etc. will crash at call DWORD ptr pCallBackFunction always. Since I call SetCallBackPointer first to store a valid address in pCallBackFunction, it should have a valid address. My managed app is written in C# and the relevant part is: public partial class Form1 : Form { public delegate void CallBackDelegate(); public static CallBackDelegate mydelegate; [DllImport("serialport.dll")] private static extern void SetCallBackPointer(CallBackDelegate Delegate); [DllImport("serialport.dll")] public static extern int OpenPort(byte com, uint br, uint inbufsize, uint outbufsize, uint treshsize); public Form1() { InitializeComponent(); mydelegate =new CallBackDelegate(CallbackFunction); SetCallBackPointer(mydelegate); unsafe { int sysstat; int hResult; hResult = OpenPort(Convert.ToByte('5'), 9600, 306, 4, 4); } } public static void CallbackFunction() { MessageBox.Show( "CallBack Function Called by Windows DLL"); } The VS debugger reported that the dll had tried to read/write from/to a protected memory address. But when calling SetCallBackPointer there is no such problem. What am I doing wrong here? Any tips would be great!

    Read the article

  • Pass a pointer to a proc as an argument

    - by user146780
    I want to pass a pointer to a procedure in c++. I tried passing this LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc but it didn't work. How is this done? Thanks HWND OGLFRAME::create(HWND parent, LRESULT(*)(HWND, UINT, WPARAM, LPARAM) prc) { if(framehWnd != NULL) { return framehWnd; ZeroMemory(&rwc,sizeof(rwc)); } } By "it didn't work" I mean it's a syntax error.

    Read the article

  • Win32 WndProc Name: why can't I change its name ?

    - by asksuperuser
    I have compiled a simple win32 app successfully with bc++ (2 lines excerpt only): LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM); wincl.lpfnWndProc = WindowProcedure; Why can't I rename WindowProcedure and compile this: LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); wincl.lpfnWndProc = WndProc; as error message gives: Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland Error: Unresolved external 'stdcall WndProc(HWND *, unsigned int, unsigned int, long)' referenced from C:\PROGRAMMING\SALLY\WIN32TUTORIAL\MAIN.OBJ

    Read the article

  • UV Atlas Generation and Seam Removal

    - by P. Avery
    I'm generating light maps for scene mesh objects using DirectX's UV Atlas Tool( D3DXUVAtlasCreate() ). I've succeeded in generating an atlas, however, when I try to render the mesh object using the atlas the seams are visible on the mesh. Below are images of a lightmap generated for a cube. Here is the code I use to generate a uv atlas for a cube: struct sVertexPosNormTex { D3DXVECTOR3 vPos, vNorm; D3DXVECTOR2 vUV; sVertexPosNormTex(){} sVertexPosNormTex( D3DXVECTOR3 v, D3DXVECTOR3 n, D3DXVECTOR2 uv ) { vPos = v; vNorm = n; vUV = uv; } ~sVertexPosNormTex() { } }; // create a light map texture to fill programatically hr = D3DXCreateTexture( pd3dDevice, 128, 128, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &pLightmap ); if( FAILED( hr ) ) { DebugStringDX( "Main", "Failed to D3DXCreateTexture( lightmap )", __LINE__, hr ); return hr; } // get the zero level surface from the texture IDirect3DSurface9 *pS = NULL; pLightmap->GetSurfaceLevel( 0, &pS ); // clear surface pd3dDevice->ColorFill( pS, NULL, D3DCOLOR_XRGB( 0, 0, 0 ) ); // load a sample mesh DWORD dwcMaterials = 0; LPD3DXBUFFER pMaterialBuffer = NULL; V_RETURN( D3DXLoadMeshFromX( L"cube3.x", D3DXMESH_MANAGED, pd3dDevice, &pAdjacency, &pMaterialBuffer, NULL, &dwcMaterials, &g_pMesh ) ); // generate adjacency DWORD *pdwAdjacency = new DWORD[ 3 * g_pMesh->GetNumFaces() ]; g_pMesh->GenerateAdjacency( 1e-6f, pdwAdjacency ); // create light map coordinates LPD3DXMESH pMesh = NULL; LPD3DXBUFFER pFacePartitioning = NULL, pVertexRemapArray = NULL; FLOAT resultStretch = 0; UINT numCharts = 0; hr = D3DXUVAtlasCreate( g_pMesh, 0, 0, 128, 128, 3.5f, 0, pdwAdjacency, NULL, NULL, NULL, NULL, NULL, 0, &pMesh, &pFacePartitioning, &pVertexRemapArray, &resultStretch, &numCharts ); if( SUCCEEDED( hr ) ) { // release and set mesh SAFE_RELEASE( g_pMesh ); g_pMesh = pMesh; // write mesh to file hr = D3DXSaveMeshToX( L"cube4.x", g_pMesh, 0, ( const D3DXMATERIAL* )pMaterialBuffer->GetBufferPointer(), NULL, dwcMaterials, D3DXF_FILEFORMAT_TEXT ); if( FAILED( hr ) ) { DebugStringDX( "Main", "Failed to D3DXSaveMeshToX() at OnD3D9CreateDevice()", __LINE__, hr ); } // fill the the light map hr = BuildLightmap( pS, g_pMesh ); if( FAILED( hr ) ) { DebugStringDX( "Main", "Failed to BuildLightmap()", __LINE__, hr ); } } else { DebugStringDX( "Main", "Failed to D3DXUVAtlasCreate() at OnD3D9CreateDevice()", __LINE__, hr ); } SAFE_RELEASE( pS ); SAFE_DELETE_ARRAY( pdwAdjacency ); SAFE_RELEASE( pFacePartitioning ); SAFE_RELEASE( pVertexRemapArray ); SAFE_RELEASE( pMaterialBuffer ); Here is code to fill lightmap texture: HRESULT BuildLightmap( IDirect3DSurface9 *pS, LPD3DXMESH pMesh ) { HRESULT hr = S_OK; // validate lightmap texture surface and mesh if( !pS || !pMesh ) return E_POINTER; // lock the mesh vertex buffer sVertexPosNormTex *pV = NULL; pMesh->LockVertexBuffer( D3DLOCK_READONLY, ( void** )&pV ); // lock the mesh index buffer WORD *pI = NULL; pMesh->LockIndexBuffer( D3DLOCK_READONLY, ( void** )&pI ); // get the lightmap texture surface description D3DSURFACE_DESC desc; pS->GetDesc( &desc ); // lock the surface rect to fill with color data D3DLOCKED_RECT rct; hr = pS->LockRect( &rct, NULL, 0 ); if( FAILED( hr ) ) { DebugStringDX( "main.cpp:", "Failed to IDirect3DTexture9::LockRect()", __LINE__, hr ); return hr; } // iterate the pixels of the lightmap texture // check each pixel to see if it lies between the uv coordinates of a cube face BYTE *pBuffer = ( BYTE* )rct.pBits; for( UINT y = 0; y < desc.Height; ++y ) { BYTE* pBufferRow = ( BYTE* )pBuffer; for( UINT x = 0; x < desc.Width * 4; x+=4 ) { // determine the pixel's uv coordinate D3DXVECTOR2 p( ( ( float )x / 4.0f ) / ( float )desc.Width + 0.5f / 128.0f, y / ( float )desc.Height + 0.5f / 128.0f ); // for each face of the mesh // check to see if the pixel lies within the face's uv coordinates for( UINT i = 0; i < 3 * pMesh->GetNumFaces(); i +=3 ) { sVertexPosNormTex v[ 3 ]; v[ 0 ] = pV[ pI[ i + 0 ] ]; v[ 1 ] = pV[ pI[ i + 1 ] ]; v[ 2 ] = pV[ pI[ i + 2 ] ]; if( TexcoordIsWithinBounds( v[ 0 ].vUV, v[ 1 ].vUV, v[ 2 ].vUV, p ) ) { // the pixel lies b/t the uv coordinates of a cube face // light contribution functions aren't needed yet //D3DXVECTOR3 vPos = TexcoordToPos( v[ 0 ].vPos, v[ 1 ].vPos, v[ 2 ].vPos, v[ 0 ].vUV, v[ 1 ].vUV, v[ 2 ].vUV, p ); //D3DXVECTOR3 vNormal = v[ 0 ].vNorm; // set the color of this pixel red( for demo ) BYTE ba[] = { 0, 0, 255, 255, }; //ComputeContribution( vPos, vNormal, g_sLight, ba ); // copy the byte array into the light map texture memcpy( ( void* )&pBufferRow[ x ], ( void* )ba, 4 * sizeof( BYTE ) ); } } } // go to next line of the texture pBuffer += rct.Pitch; } // unlock the surface rect pS->UnlockRect(); // unlock mesh vertex and index buffers pMesh->UnlockIndexBuffer(); pMesh->UnlockVertexBuffer(); // write the surface to file hr = D3DXSaveSurfaceToFile( L"LightMap.jpg", D3DXIFF_JPG, pS, NULL, NULL ); if( FAILED( hr ) ) DebugStringDX( "Main.cpp", "Failed to D3DXSaveSurfaceToFile()", __LINE__, hr ); return hr; } bool TexcoordIsWithinBounds( const D3DXVECTOR2 &t0, const D3DXVECTOR2 &t1, const D3DXVECTOR2 &t2, const D3DXVECTOR2 &p ) { // compute vectors D3DXVECTOR2 v0 = t1 - t0, v1 = t2 - t0, v2 = p - t0; float f00 = D3DXVec2Dot( &v0, &v0 ); float f01 = D3DXVec2Dot( &v0, &v1 ); float f02 = D3DXVec2Dot( &v0, &v2 ); float f11 = D3DXVec2Dot( &v1, &v1 ); float f12 = D3DXVec2Dot( &v1, &v2 ); // Compute barycentric coordinates float invDenom = 1 / ( f00 * f11 - f01 * f01 ); float fU = ( f11 * f02 - f01 * f12 ) * invDenom; float fV = ( f00 * f12 - f01 * f02 ) * invDenom; // Check if point is in triangle if( ( fU >= 0 ) && ( fV >= 0 ) && ( fU + fV < 1 ) ) return true; return false; } Screenshot Lightmap I believe the problem comes from the difference between the lightmap uv coordinates and the pixel center coordinates...for example, here are the lightmap uv coordinates( generated by D3DXUVAtlasCreate() ) for a specific face( tri ) within the mesh, keep in mind that I'm using the mesh uv coordinates to write the pixels for the texture: v[ 0 ].uv = D3DXVECTOR2( 0.003581, 0.295631 ); v[ 1 ].uv = D3DXVECTOR2( 0.003581, 0.003581 ); v[ 2 ].uv = D3DXVECTOR2( 0.295631, 0.003581 ); the lightmap texture size is 128 x 128 pixels. The upper-left pixel center coordinates are: float halfPixel = 0.5 / 128 = 0.00390625; D3DXVECTOR2 pixelCenter = D3DXVECTOR2( halfPixel, halfPixel ); will the mapping and sampling of the lightmap texture will require that an offset be taken into account or that the uv coordinates are snapped to the pixel centers..? ...Any ideas on the best way to approach this situation would be appreciated...What are the common practices?

    Read the article

  • OpenGL loading functions error [on hold]

    - by Ghilliedrone
    I'm new to OpenGL, and I bought a book on it for beginners. I finished writing the sample code for making a context/window. I get an error on this line at the part PFNWGLCREATECONTEXTATTRIBSARBPROC, saying "Error: expected a ')'": typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*); Replacing it or adding a ")" makes it error, but the error disappears when I use the OpenGL headers included in the books CD, which are OpenGL 3.0. I would like a way to make this work with the newest gl.h/wglext.h and without libraries. Here's the rest of the class if it's needed: #include <ctime> #include <windows.h> #include <iostream> #include <gl\GL.h> #include <gl\wglext.h> #include "Example.h" #include "GLWindow.h" typedef HGLRC(APIENTRYP PFNWGLCREATECONTEXTATTRIBSARBPROC)(HDC, HGLRC, const int*); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; bool GLWindow::create(int width, int height, int bpp, bool fullscreen) { DWORD dwExStyle; //Window Extended Style DWORD dwStyle; //Window Style m_isFullscreen = fullscreen;//Store the fullscreen flag m_windowRect.left = 0L; m_windowRect.right = (long)width; m_windowRect.top = 0L; m_windowRect.bottom = (long)height;//Set bottom to height // fill out the window class structure m_windowClass.cbSize = sizeof(WNDCLASSEX); m_windowClass.style = CS_HREDRAW | CS_VREDRAW; m_windowClass.lpfnWndProc = GLWindow::StaticWndProc; //We set our static method as the event handler m_windowClass.cbClsExtra = 0; m_windowClass.cbWndExtra = 0; m_windowClass.hInstance = m_hinstance; m_windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon m_windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow m_windowClass.hbrBackground = NULL; // don't need background m_windowClass.lpszMenuName = NULL; // no menu m_windowClass.lpszClassName = (LPCWSTR)"GLClass"; m_windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon if (!RegisterClassEx(&m_windowClass)) { MessageBox(NULL, (LPCWSTR)"Failed to register window class", NULL, MB_OK); return false; } if (m_isFullscreen)//If we are fullscreen, we need to change the display { DEVMODE dmScreenSettings; //Device mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; //Screen width dmScreenSettings.dmPelsHeight = height; //Screen height dmScreenSettings.dmBitsPerPel = bpp; //Bits per pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { MessageBox(NULL, (LPCWSTR)"Display mode failed", NULL, MB_OK); m_isFullscreen = false; } } if (m_isFullscreen) //Is it fullscreen? { dwExStyle = WS_EX_APPWINDOW; //Window Extended Style dwStyle = WS_POPUP; //Windows Style ShowCursor(false); //Hide mouse pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; //Window Exteneded Style dwStyle = WS_OVERLAPPEDWINDOW; //Windows Style } AdjustWindowRectEx(&m_windowRect, dwStyle, false, dwExStyle); //Adjust window to true requested size //Class registered, so now create window m_hwnd = CreateWindowEx(NULL, //Extended Style (LPCWSTR)"GLClass", //Class name (LPCWSTR)"Chapter 2", //App name dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, //x, y coordinates m_windowRect.right - m_windowRect.left, m_windowRect.bottom - m_windowRect.top, //Width and height NULL, //Handle to parent NULL, //Handle to menu m_hinstance, //Application instance this); //Pass a pointer to the GLWindow here //Check if window creation failed, hwnd would equal NULL if (!m_hwnd) { return 0; } m_hdc = GetDC(m_hwnd); ShowWindow(m_hwnd, SW_SHOW); UpdateWindow(m_hwnd); m_lastTime = GetTickCount() / 1000.0f; return true; } LRESULT CALLBACK GLWindow::StaticWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { GLWindow* window = nullptr; //If this is the create message if (uMsg == WM_CREATE) { //Get the pointer we stored during create window = (GLWindow*)((LPCREATESTRUCT)lParam)->lpCreateParams; //Associate the window pointer with the hwnd for the other events to access SetWindowLongPtr(hWnd, GWL_USERDATA, (LONG_PTR)window); } else { //If this is not a creation event, then we should have stored a pointer to the window window = (GLWindow*)GetWindowLongPtr(hWnd, GWL_USERDATA); if (!window) { //Do the default event handling return DefWindowProc(hWnd, uMsg, wParam, lParam); } } //Call our window's member WndProc(allows us to access member variables) return window->WndProc(hWnd, uMsg, wParam, lParam); } LRESULT GLWindow::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: { m_hdc = GetDC(hWnd); setupPixelFormat(); //Set the version that we want, in this case 3.0 int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, 0}; //Create temporary context so we can get a pointer to the function HGLRC tmpContext = wglCreateContext(m_hdc); //Make the context current wglMakeCurrent(m_hdc, tmpContext); //Get the function pointer wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); //If this is NULL then OpenGl 3.0 is not supported if (!wglCreateContextAttribsARB) { MessageBox(NULL, (LPCWSTR)"OpenGL 3.0 is not supported", (LPCWSTR)"An error occured", MB_ICONERROR | MB_OK); DestroyWindow(hWnd); return 0; } //Create an OpenGL 3.0 context using the new function m_hglrc = wglCreateContextAttribsARB(m_hdc, 0, attribs); //Delete the temporary context wglDeleteContext(tmpContext); //Make the GL3 context current wglMakeCurrent(m_hdc, m_hglrc); m_isRunning = true; } break; case WM_DESTROY: //Window destroy case WM_CLOSE: //Windows is closing wglMakeCurrent(m_hdc, NULL); wglDeleteContext(m_hglrc); m_isRunning = false; //Stop the main loop PostQuitMessage(0); break; case WM_SIZE: { int height = HIWORD(lParam); //Get height and width int width = LOWORD(lParam); getAttachedExample()->onResize(width, height); //Call the example's resize method } break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) //If the escape key was pressed { DestroyWindow(m_hwnd); } break; default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } void GLWindow::processEvents() { MSG msg; //While there are messages in the queue, store them in msg while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { //Process the messages TranslateMessage(&msg); DispatchMessage(&msg); } } Here is the header: #pragma once #include <ctime> #include <windows.h> class Example;//Declare our example class class GLWindow { public: GLWindow(HINSTANCE hInstance); //default constructor bool create(int width, int height, int bpp, bool fullscreen); void destroy(); void processEvents(); void attachExample(Example* example); bool isRunning(); //Is the window running? void swapBuffers() { SwapBuffers(m_hdc); } static LRESULT CALLBACK StaticWndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam); float getElapsedSeconds(); private: Example* m_example; //A link to the example program bool m_isRunning; //Is the window still running? bool m_isFullscreen; HWND m_hwnd; //Window handle HGLRC m_hglrc; //Rendering context HDC m_hdc; //Device context RECT m_windowRect; //Window bounds HINSTANCE m_hinstance; //Application instance WNDCLASSEX m_windowClass; void setupPixelFormat(void); Example* getAttachedExample() { return m_example; } float m_lastTime; };

    Read the article

  • i have a win32 windows application and want to capture full screen and remove the border of window d

    - by moon
    win32 windows application and want to capture full screen and remove the border of window displayed any one tell me how can i do so if this window capture the mouse keyboard controls then it will be ideal? // MonitorScreen.cpp : Defines the entry point for the application. // include "stdafx.h" include "MonitorScreen.h" define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_MONITORSCREEN, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MONITORSCREEN)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; int s =sizeof(WNDCLASSEX); wcex.cbSize =sizeof(WNDCLASSEX); wcex.style = DESKTOP_HOOKCONTROL ;//CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = NULL;//hInstance; wcex.hIcon = NULL;//LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MONITORSCREEN)); wcex.hCursor = NULL;//LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(9); wcex.lpszMenuName = NULL;//MAKEINTRESOURCE(IDC_MONITORSCREEN); wcex.lpszClassName = szWindowClass; wcex.hIconSm = NULL;//LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }

    Read the article

  • Tessellation Texture Coordinates

    - by Stuart Martin
    Firstly some info - I'm using DirectX 11 , C++ and I'm a fairly good programmer but new to tessellation and not a master graphics programmer. I'm currently implementing a tessellation system for a terrain model, but i have reached a snag. My current system produces a terrain model from a height map complete with multiple texture coordinates, normals, binormals and tangents for rendering. Now when i was using a simple vertex and pixel shader combination everything worked perfectly but since moving to include a hull and domain shader I'm slightly confused and getting strange results. My terrain is a high detail model but the textured results are very large patches of solid colour. My current setup passes the model data into the vertex shader then through the hull into the domain and then finally into the pixel shader for use in rendering. My only thought is that in my hull shader i pass the information into the domain shader per patch and this is producing the large areas of solid colour because each patch has identical information. Lighting and normal data are also slightly off but not as visibly as texturing. Below is a copy of my hull shader that does not work correctly because i think the way that i am passing the data through is incorrect. If anyone can help me out but suggesting an alternative way to get the required data into the pixel shader? or by showing me the correct way to handle the data in the hull shader id be very thankful! cbuffer TessellationBuffer { float tessellationAmount; float3 padding; }; struct HullInputType { float3 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; float3 binormal : BINORMAL; float2 tex2 : TEXCOORD1; }; struct ConstantOutputType { float edges[3] : SV_TessFactor; float inside : SV_InsideTessFactor; }; struct HullOutputType { float3 position : POSITION; float2 tex : TEXCOORD0; float3 normal : NORMAL; float3 tangent : TANGENT; float3 binormal : BINORMAL; float2 tex2 : TEXCOORD1; float4 depthPosition : TEXCOORD2; }; ConstantOutputType ColorPatchConstantFunction(InputPatch<HullInputType, 3> inputPatch, uint patchId : SV_PrimitiveID) { ConstantOutputType output; output.edges[0] = tessellationAmount; output.edges[1] = tessellationAmount; output.edges[2] = tessellationAmount; output.inside = tessellationAmount; return output; } [domain("tri")] [partitioning("integer")] [outputtopology("triangle_cw")] [outputcontrolpoints(3)] [patchconstantfunc("ColorPatchConstantFunction")] HullOutputType ColorHullShader(InputPatch<HullInputType, 3> patch, uint pointId : SV_OutputControlPointID, uint patchId : SV_PrimitiveID) { HullOutputType output; output.position = patch[pointId].position; output.tex = patch[pointId].tex; output.tex2 = patch[pointId].tex2; output.normal = patch[pointId].normal; output.tangent = patch[pointId].tangent; output.binormal = patch[pointId].binormal; return output; } Edited to include the domain shader:- [domain("tri")] PixelInputType ColorDomainShader(ConstantOutputType input, float3 uvwCoord : SV_DomainLocation, const OutputPatch<HullOutputType, 3> patch) { float3 vertexPosition; PixelInputType output; // Determine the position of the new vertex. vertexPosition = uvwCoord.x * patch[0].position + uvwCoord.y * patch[1].position + uvwCoord.z * patch[2].position; output.position = mul(float4(vertexPosition, 1.0f), worldMatrix); output.position = mul(output.position, viewMatrix); output.position = mul(output.position, projectionMatrix); output.depthPosition = output.position; output.tex = patch[0].tex; output.tex2 = patch[0].tex2; output.normal = patch[0].normal; output.tangent = patch[0].tangent; output.binormal = patch[0].binormal; return output; }

    Read the article

  • HRESULT of 0x806D0005 from Microsoft's Dia2Lib

    - by Aeolien
    I'm trying to read a PDB file into a C# application. When I call loadDataFromPdb or loadAndValidateDataFromPdb with a file that I know exists, I get an HRESULT of 0x806D0005. Unfortunately, I have no idea what that means. I have the list of possible results [here](http://msdn.microsoft.com/en-us/library/2008hf0e(v=VS.80).aspx) but I'm afraid I can't conclusively determine the problem. Does anybody know what I'm doing wrong? Or at least a method of checking what that corresponds to? Exception: System.Runtime.InteropServices.COMException (0x806D0005): Exception from HRESULT: 0x806D0005 at Dia2Lib.DiaSourceClass.loadDataFromPdb(String pdbPath) Code Sample: public static void LoadSymbolsForModule(uint baseAddress, uint size, uint timeStamp, DM_PDB_SIGNATURE signature) { IDiaDataSource m_source = new DiaSourceClass(); //m_source.loadAndValidateDataFromPdb(signature.path, ref signature.guid, 0, signature.age); m_source.loadDataFromPdb(signature.path); IDiaSession m_session; m_source.openSession(out m_session); m_session.loadAddress = baseAddress; modules.Add(new Module(baseAddress, size, m_session)); } Thanks in advance, guys. This problem has been killing me all day.

    Read the article

  • WTL Child window event handling

    - by Rushi
    I am developing window application in that I am having 2 child windows on left and right side. I want to handle input events for both windows separately. How to achieve it? My code: class EditorWindow : public DxWindow { public: CSplitterWindow m_vSplit; CPaneContainer m_lPane; CPaneContainer m_rPane; PropertyDialog m_propertyWnd; DECLARE_WND_CLASS(_T("Specific_Class_Name")) BEGIN_MSG_MAP(EditorWindow) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) MESSAGE_HANDLER(WM_LBUTTONDOWN, KeyHandler) MESSAGE_HANDLER(WM_KEYUP, KeyHandler) MESSAGE_HANDLER(WM_LBUTTONDOWN, KeyHandler) END_MSG_MAP() LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&) { CRect rcVert; GetClientRect(&rcVert); m_vSplit.Create(m_hWnd, rcVert, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); m_vSplit.SetSplitterPos(rcVert.Width()/1.4f); // from left m_lPane.Create(m_vSplit.m_hWnd); m_vSplit.SetSplitterPane(0, m_lPane); //m_lPane.SetTitle(L"Left Pane"); m_rPane.Create(m_vSplit.m_hWnd); m_vSplit.SetSplitterPane(1, m_rPane); m_rPane.SetTitle(L"Properties"); m_propertyWnd.Create(m_rPane.m_hWnd); //m_vSplit.SetSplitterPane(SPLIT_PANE_LEFT, md.m_hWnd); return 0; } LRESULT OnDestroy( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled ) { PostQuitMessage(0); bHandled = FALSE; return 0; } LRESULT KeyHandler( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled ) { return 0; } };

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >