Jump to content

  • Log In with Google      Sign In   
  • Create Account


Member Since 21 Feb 2008
Offline Last Active Today, 03:12 PM

#5128784 Gathering information on input systems

Posted by NightCreature83 on 04 February 2014 - 12:52 PM




There is no need to have a HWND, the RawInput API on windows allows you to grab the input on the fly. XINPUT doesnt need a hwnd either and is porbably the easiest way to get a controller to work on windows.

#5128546 intrinsics/no intrinsics (in mingw)

Posted by NightCreature83 on 03 February 2014 - 03:31 PM

I think you are misunderstanding what an intrinsic is, it is a specially instruction to the compiler that it should use a particular instruction or group of instructions to transform the code in to asm. For example __m128 as an intrinsic telling the Compiler that if the target you are compiling for supports SSE2 instructions that this should be stored in a SSE2 register instead of normal registers. And yes for intrinsics you need to include headers as well, and they can be compiler specific so look in the help files of your compiler or the online help page.


Sin is a function defined in the C runtime and is used to calculate a value that approaches a sin value, how that is implemented and optimised by the compiler depends on the used version of the C runtime and the compile settings you are compiling with.

#5127578 CreateBuffer returns E_INVALIDARG

Posted by NightCreature83 on 30 January 2014 - 04:00 PM

XMMath is a newer version of the math library based of the Xbox math library, So basically it is meant to supersede D3DX math.

Or that is my understanding of it.

Not only is XNAMath (XM, which is now renamed to DirectXMath already) newer it also supports SSE2 by default where D3DXMath didnt, it did if you turned the compile options in VS for it on. DirectXMath actually in the header detects whether the target it is being compiled for supports SSE2 and if so starts using SSE2 intrinsics and all the proper ways of using these.


As already pointed out the structure must be 16byte-aligned, this is not the cast with your vector3. You should change it to:

struct ConstantBuffer
	D3DXMATRIX matWorld;
	D3DXMATRIX matView;
	D3DXMATRIX matProjection;
	D3DXVECTOR3 vLightDir;
        float padding; // unused
	D3DXVECTOR4 vLightCol;


struct ConstantBuffer
	D3DXMATRIX matWorld;
	D3DXMATRIX matView;
	D3DXMATRIX matProjection;
	D3DXVECTOR4 vLightCol;
	D3DXVECTOR3 vLightDir;
        float padding;

or simply modify the return of sizeof(ConstantBuffer) to be a multiple of 16.

You dont need to add padding just :

__declspec( align ( 16 ) ) float;
#define ALIGN16 __declspec( align(16) )
ALIGN16 float

When using the declspec or macro the compiler will automatically add padding when needed without you having to write this explicitly, it keeps your code slightly cleaner and easier to understand.


As an example

struct MaterialContent
        m_ambient[0] = 0.2f;
        m_ambient[1] = 0.2f;
        m_ambient[2] = 0.2f;
        m_ambient[3] = 1.0f;

        m_diffuse[0] = 0.8f;
        m_diffuse[1] = 0.8f;
        m_diffuse[2] = 0.8f;
        m_diffuse[3] = 1.0f;

        m_specular[0] = 0.0f;
        m_specular[1] = 0.0f;
        m_specular[2] = 0.0f;
        m_specular[3] = 1.0f;

        m_emissive[0] = 0.0f;
        m_emissive[1] = 0.0f;
        m_emissive[2] = 0.0f;
        m_emissive[3] = 1.0f;
        m_shininess = 1000.0f;

    float m_ambient[4];
    float m_diffuse[4];
    float m_specular[4];
    float m_emissive[4];
    ALIGN16 float m_shininess;

#5125756 Branching in switch statement

Posted by NightCreature83 on 22 January 2014 - 06:17 PM

You should be able to embed a switch in the code block of a case label if that is what you mean to do.

        private void Button_Click(object sender, RoutedEventArgs e)
            int condition = 0;
            switch (condition)
                case 0:
                        switch (condition)
                            case 0:
                                Console.Write("Switch in a Switch");

#5125627 using hash_map vs vector....

Posted by NightCreature83 on 22 January 2014 - 06:27 AM

You will not have a 1000 access of the hash_map in one frame, if you have a screen with a 1000s interactable objects on it, start rethinking that screen because you did it wrong. Besides the code to test this stuff has overhead in it that you don't need remeber that clock() also has an overhead when called, its better to do the insertion for say 1 million elements and taking the clock reading outside of your loop.v Also insertion into the hash map has the overhead of having to hash the key, if you are just using numbers you are better of using a normal std::map as mentioned.


Choice of your container here all comes down to how you want to access it. In a previous project we split the render data from update data completely and the update side, the render data was stored as a normal scenegraph in which each scene contained a normal map from a hash_value of a node name to the pointer of an actual object. This allowed for efficient dispatch of message to the render nodes in big scenes, in the neighbourhood of a few ns for full address dispatch through deep trees. Message dispatch worked along the lines of:

1.-Can we find the object in the tree?

   -No: Flag error and stop dispatch

   -Yes: Is this the last element in the address?

       -Yes: Dispatch message to actual node.

       -No: is this a new scene node?

           -No: Start at 1 again in this scenes map with the next token in the node.

          -Yes: Start at 1 but use the map of the scene node you just found to look for the next token.


This was fast used on big scenes, 100s of nodes active at the same time, address was a list of hash tokens to pass in to a normal std::map::find function, minor RTTI checks to see node types.

#5125301 Struct versus class?

Posted by NightCreature83 on 21 January 2014 - 05:02 AM

I would also like to add that the compiler adds the operator= for any struct, by coping 1-1 all its fields, in a class you generally have to define your own class_name operator=(const class_name right); however there are certain conditions on which the C++ compiler may add that operator automatically (implicitly). If I recall correctly there is yet another difference, but I fail to remember it for the time being, my apologies!

Hope I helped a little

No you dont default copy constructor, default construct/destructor and default assignment operator are generated for a class, as soon as you write one of these the compiler will not generate a default one. There really is no difference between a class or a struct beyond the default access modifiers.

#5125281 Struct versus class?

Posted by NightCreature83 on 21 January 2014 - 02:48 AM

As frob mentioned, in C++ a class and a struct are pretty much identical. The choice of which to use is yours to make, seeing as the following two are very much the same:

struct Vec
   float x, y, z;

class Vec
   float x, y, z;

One issue i ran into when i used a mix of structs and classes was when forward declaring them. Sometimes i would simply forget if Vec was a class or a struct. Similar with Color, Rect, Transform, etc. So i settled on using classes only, and if something needs to have all of it's members public, i simply set them as public and not protected/private.


Actually they are not pretty much identical they are identical, the code generated from them is exactly the same, a struct can have all the same things as a class.


#5123830 Classes and use of 'New'

Posted by NightCreature83 on 15 January 2014 - 04:19 AM

Your first example would be just a pointer which you give later some "life".

something like this is need if you want create dynamically a new object. 


For example you have class Car and ask the user how many cars he/she wants

create; how would you do solve that problem? write everytime a new program

or do you want create just dynamically a new Object of type Car with the new operator?

int count;
std::vector<Car*> cars;

//Ask user the amound of cars he/she wants
std::cout<<"Hello Human! How many car Objects do want that i create for you: \n";

for(int i = 0; i < count;i++)
     Car* Example = new Car;

And because you create a class it's not necessary to delete it explicit because classes have a destructor which do this job for you, of course you should set the pointer to NULL in the end. explicit deleting you need if you allocating memoryfor  e.g. an array of size X. An array doesn't have an destructor so you have to do this

job per hand. 


Your information on allocation and deallocation is wong, when you use a new or new[] you will need to use a delete or delete[] to delete the memory that that allocation needed.


Constructors and destructors do other things and only manage the space of the member variables of a class not the allocation of the class itself.


In this example you are leaking memory, the amount is count * sizeof(Car).



Thanks for the reply. I am tryingto get my head around it smile.png


Couldn't you push the non 'new' example on to a vector as well though?


Vector::push_back makes a copy of the argument you pass it, so in the example it actually only copies the value of the pointer not the object it is pointing at, in other words that vector only stores the addresses of where the objects are actually in memory.

#5123646 C++ DirectX Renderer Design

Posted by NightCreature83 on 14 January 2014 - 01:52 PM

Actually you dont push the whole scene through the render pipeline,the renderer should only see the infromation it needs, like vbs, ibs, shaders, constants and render state changes. Most scene graphs get culled heavily and only the objects that are visible will have the data needed to display them sent to the renderer.


My scene doesn't even touch the renderer all I do in the update of my game objects is tell them to add there renderable data to a list, this list is then fed to a renderer to display.


The renderer is the only one that knows how to submit a render command to the GPU, the objects only submit the data needed to create the render command.


Most games don't even have scene graphs in the update code they only contain a link to a model or something like that, the model can contain a scnegraph but doesnt have to, my current game doesnt use scene graphs just models which consist of meshgroups, and it is the mesh group that contains links or data to all relevant data to be able to render the mesh group.

#5123435 Vertex elements besides position don't work

Posted by NightCreature83 on 13 January 2014 - 07:31 PM



It's pretty much just a basic struct.

struct SInputElementDesc

		:m_name(""), m_index(0)

	SInputElementDesc(const std::string& name, E_INPUT_FORMAT format, unsigned int idx=0)
		:m_name(name), m_index(idx), m_format(format)

	std::string m_name;///< The semantic name of the input element

	unsigned int m_index;///< The index of the input element

	E_INPUT_FORMAT m_format;///<The format of this input element
	unsigned int m_offset;///< Offset from the start of the vertex structure. Set by the input layout: read only.

	unsigned int m_size;///< Size of the input element. Set by the input layout: read only.


createInputLayout returns S_OK though, and nSight shows the COLOR semantic in the input layout, just not the vertex shader input. I've also opened up the vertex shader in nSight and it compiled the COLOR semantic out or something. This is how I compile the vertex shader.

IVertexShader* CDX11GraphicsDriver::compileVertexShader(const std::string& shaderSource, const std::string& name)
	ID3DBlob* VSblob;
	ID3DBlob* errorBlob;

	HRESULT hr = D3DCompile(&shaderSource[0], shaderSource.length(), name.c_str(), NULL, NULL, "VS", "vs_5_0", D3DCOMPILE_ENABLE_STRICTNESS, NULL, &VSblob, &errorBlob);
	if ( FAILED(hr) )
		std::string error = std::string((char*)errorBlob->GetBufferPointer());//TODO: print this out

		return NULL;

	ID3D11VertexShader* VS = NULL;

	hr = m_device->CreateVertexShader(m_defaultVSblob->GetBufferPointer(), m_defaultVSblob->GetBufferSize(), NULL, &VS);
	if ( FAILED(hr) )
		return NULL;

	return new CDX11VertexShader(VS);

Pass the debug flags to the shader and device intialisation, then go into the DX control panel and activate the debug runtime for your application. By doing this you should be able to get proper symbols in your shaders. Which allow for more extensive debugging.

//Shader Flags
#if defined( DEBUG ) || defined( _DEBUG )

Device flags

#ifdef _DEBUG

And my shader creation function, I load everything from file and that's what the getShaderBufferFunction does for me.

//! @brief   TODO enter a description
//! @remark
bool VertexShader::createShader(const DeviceManager& deviceManager)
    size_t length = 0;
    char* shaderCodeBuffer = getShaderBuffer(m_fileName, length);
    if (shaderCodeBuffer)
        std::string profileName = "";
        getProfileName(deviceManager, eVertexShader, profileName);
        ID3DBlob* errorBlob;
        HRESULT hr = D3DCompile(shaderCodeBuffer, length, m_fileName.c_str(), 0, D3D_COMPILE_STANDARD_FILE_INCLUDE, m_entryPoint.c_str(), profileName.c_str(), shaderCompilerFlags, 0, &m_vertexShaderBlob, &errorBlob);
        if (FAILED(hr))
            MSG_TRACE_CHANNEL("VertexShader_ERROR", "Failed to compile vertex shader with error code: 0x%x(%s)", hr, D3DDebugHelperFunctions::D3DErrorCodeToString(hr));
            MSG_TRACE_CHANNEL("VertexShader_ERROR", "Failed to compile vertex shader: %s, with errors: \n%s", m_fileName.c_str(), (errorBlob != nullptr ? (char*)errorBlob->GetBufferPointer() : "<errorBlob pointer is nullptr>"));
            delete [] shaderCodeBuffer;
            return false;
        hr = deviceManager.getDevice()->CreateVertexShader(m_vertexShaderBlob->GetBufferPointer(), m_vertexShaderBlob->GetBufferSize(), 0, &m_shader);
        if (FAILED(hr))
            MSG_TRACE_CHANNEL("VERTEXSHADER_ERROR", "Failed to create vertex shader: 0x%x(%s)", hr, D3DDebugHelperFunctions::D3DErrorCodeToString(hr));
            delete [] shaderCodeBuffer;
            return false;

        delete []  shaderCodeBuffer;
        return true;

    return false;

#5123432 Vertex elements besides position don't work

Posted by NightCreature83 on 13 January 2014 - 07:17 PM

I vaguely remerber something with the semantic name and how it needs to be either a static or const allocated string, when it is dynamic and the reference the pointer is pointing at disappears before the layout is properly created, it fails to find the actual name.


I use code defined strings at the moment for these things, but my memory on this is vague as I wrote that code a long time ago now and generally dont need to revisit it.

#5122126 Microsoft DirectX11 Win32 Tutorial 2. Vertex Shader.

Posted by NightCreature83 on 08 January 2014 - 04:11 AM

There is a *big* (ok not that big but still) difference between regular shaders and effects. First of all an Effect(*.fx) represents not only a single shader but a set of techniques and passes( technique is a set of passes and pass is a set of vertex + pixel +...  shaders).


Also when using effects there are some *helpers*, such as it is possible to describe a sampler directly into the Effect file(something that is not possible using ordinary shaders).


So basicly effects are sets of shaders (passes) wraped in techniques. The Effects also provide some 'simplification' and structures that are not usable when compiling ordinary shader.

That's not exactly true the extension doesn't define what the file is to be honest and in this case the .fx file doesn't contain techniques or passes or any pipeline state changes, all it contains is shader code. And thus there is no difference between the extensions, heck I could even defien an effect in a .ps or .vs file, it depends on how you interprete these files that determine wheter the thing is an effect or not.


When actually talking about the difference between an effect and just a shader code file thats when your definition holds, I was simply talking about the files themselves, and I can add all of the shaders to one file and still create separate shaders in code from that one file.


Samplers are part of HLSL not part of the effect parsing, http://msdn.microsoft.com/en-us/library/windows/desktop/bb509644%28v=vs.85%29.aspx, and you can set on up in D3D9 and D3D10 and up in the shader code.


The sample code in this case isn't even using the effect system, very little tutorials use the effect system for D3D11.

#5122115 Writing an Asset Manager

Posted by NightCreature83 on 08 January 2014 - 03:14 AM

Btw, I've noticed that some programmers generally make their method parameters const references (for example GetAsset(const std::string &name)). Is this just good practice to make parameters read-only that aren't meant to yield output?

Yes it specifies to the using programmer that this function will not mess with the parameters you pass into the function, by value semantics mean the same so the const is only needed for pointers and references.


The other benefit is that if you pass a big class through a reference is that it doesn't need to make a stack copy of that object to pass to the function, which makes the application faster. For example I had a bad copy in one of my asset loading functions, whilst what I wanted was an alias(reference), in debug asset loading was super slow untill I removed my copy of a std::vector.

#5122110 Microsoft DirectX11 Win32 Tutorial 2. Vertex Shader.

Posted by NightCreature83 on 08 January 2014 - 03:04 AM

There is no real difference between an .fx file or a .hlsl file its an extenstion, the internals of both files will just be a shader and that is loaded into the D3DBlob* pointer so it can be compiled to the runtime.\


You can actually read and/or write to SV_ vars as outline in the link imoogiBG provided, for example you can use the SV_VertexID to generate a screen alligned quad in the GS without having to provide actual vertex data.

#5121868 Properly planning a game and its structure

Posted by NightCreature83 on 07 January 2014 - 03:51 AM


I have attempted to make 2 little indie games and each of them have failed for one reason, planning. For both of the projects I started off only planning to have a few parts to the game. As I started to code those parts I would realized  that each of these parts needed a lot more code and classes and such than I originally thought. The problem is I would have already coded the majority of the game before I realized this. Thus leaving me with two options, 1) Rewriting the whole game, and throwing out countless hours of time. 2) Giving up sad.png . After thinking about where I went wrong it would always come down to the fact that when I started writing the game I didn't fully understand what I needed and thus didn't design it properly. I figure that this might happen a lot in many games(Realizing that a major change needs to be done) and I imagine that they don't all restart or quit. Which leads me to the conclusion that my planning might not be sufficient but the main structure of my code might be the problem. When I looked over my first game I found that a lot of my code was very specific and could not be easily rewritten without affecting other parts.


The question:

1) How do you go about properly planning a game and allowing major changes to be made without a re-write?

2)To avoid problems with having to rewrite everything should I try and write everything as a module that can be used in a main game loop?


If anyone has any good ways of organizing a game that you could point me to that would be awesome(Currently I am using the Model, View, Screen system)

Start using a source code revision tool as it allows you to code a lot more fearlessly of  losing old work, make sure you checking in often. If something doesn't pan out just revert to the last working version and start afresh, if something pans out to work check it in so you have a backup.