Unreal Engine 3 game crashes with Steam Input - c++

I'm not much of a C++ programmer, and I'm looking for help with implementing Steam Input into my Unreal Engine 3 game (yes, that's 3 and not 4). I'm under NDAs to both Epic (for Unreal 3) and Valve (for Steamworks), so I don't think I'm able to copy any of their code, but I'm going to do my best here to describe what's going on. And if you know of a better place I can ask these questions, please let me know. And if you think I'm violating an NDA, please let me know that too so I can delete the offending portions.
I have a UE3 game that works with mouse and keyboard. Steam Input, which is part of the Steamworks SDK, provides a way to get input from any controller. Basically, your controller, your actions (such as "shoot" or "walk forward"), and action sets (control schemes that can change based on game state, such as "in menu," "walking," or "driving") all get assigned unique UINT64 handles. I'm at the stage where I'm using the provided functions to assign handles, and it's crashing my game.
I have a class that contains these variables...
// typedef uint64 InputActionSetHandle_t;
InputActionSetHandle_t IsometricSetHandle;
InputActionSetHandle_t WorldMapSetHandle;
InputActionSetHandle_t SquadMenuSetHandle;
InputActionSetHandle_t BattleSetupSetHandle;
InputActionSetHandle_t InBattleSetHandle;
InputActionSetHandle_t MenuSetHandle;
I create an object and then I try to set up its variables by calling this function.
void URPGTacSteamInput::SetActionSetHandles()
{
IsometricSetHandle = SteamInput()->GetActionSetHandle( "Isometric" );
WorldMapSetHandle = SteamInput()->GetActionSetHandle( "WorldMap" );
SquadMenuSetHandle = SteamInput()->GetActionSetHandle( "SquadMenu" );
BattleSetupSetHandle = SteamInput()->GetActionSetHandle( "BattleSetup" );
InBattleSetHandle = SteamInput()->GetActionSetHandle( "InBattle" );
MenuSetHandle = SteamInput()->GetActionSetHandle( "Menu" );
}
The function completes, but the game crashes later, with the error "Unhandled exception ... Access violation reading location ..." Call stack location is FArchiveRealtimeGC::PerformReachabilityAnalysis(), which I understand is part of Unreal 3's garbage collection system.
I'm not sure how to tackle this problem, and I've just been trying stuff. I logged the handles that get assigned, and I tried setting those handles manually:
void URPGTacSteamInput::SetActionSetHandles()
{
IsometricSetHandle = 1;
WorldMapSetHandle = 2;
SquadMenuSetHandle = 3;
BattleSetupSetHandle = 4;
InBattleSetHandle = 5;
MenuSetHandle = 6;
}
But the game still crashes after running that function. So I tried removing more from it.
void URPGTacSteamInput::SetActionSetHandles()
{
}
And I can run that function, and the game moves along just fine, except that I don't have any Steam Input action sets I can switch to.
So what might I be able to check to find out why my game is crashing? What else would I need to find out in order to track this down? Is there somewhere else I might have better luck asking about this issue?
Thanks for any guidance you can give me on this.

I found the problem. I was declaring all of my InputActionSetHandle_t variables in the cpptext area of my UnrealScript classes. I'm not supposed to do that. I declared all of those variables as UnrealScript qwords instead, and they work just fine for holding the C++ uint64 handles that get sent back by the Steam API. And no more crashes.

Related

OpenGL multithreading

Ok I am trying to switch my Game Engine to multithreading. I have done the research on how to make it work to use OpenGL in multithreaded application. I have no problem with rendering or switching contexts. Let my piece of code explain the problem :) :
for (it = (*mIt).Renderables.begin(); it != (*mIt).Renderables.end(); it++)
{
//Set State Modeling matrix
CORE_RENDERER->state.ModelMatrix = (*it).matrix;
CORE_RENDERER->state.ActiveSubmesh = (*it).submesh;
//Internal Model Uniforms
THREAD_POOL->service.post([&]
{
for (unsigned int i = 0; i < CORE_RENDERER->state.ActiveShaderProgram->InternalModelUniforms.size(); i++)
{
CORE_RENDERER->state.ActiveShaderProgram->InternalModelUniforms[i]->Set( CORE_RENDERER->state.ModelMatrix);
}
CORE_RENDERER->state.ActiveSubmesh->_Render();
});
//Sleep(10);
}
I'll quickly explain what are the elements in the code to make my problem more clear. Renderables is a simple std::vector of elements with _Render() function which works perfectly. CORE_RENDERER->state is a struct holding information about current render state such as current material properties as well as current submesh ModelMatrix. So Matrix and Submesh are stored to state struct (I KNOW THIS IS SLOW, I'll probably change that in time :) ) The next piece of code is sent to THREAD_POOL->service which is actually boost::asio::io_service and has only one thread so it acts like a queue of rendering commands. The idea is that the main thread provides information about what to render and do frustum culling and other tests while an auxilary thread does actual rendering. This works fine, except there is a slight problem:
The code that is sent to thread pool starts to execute, but before all InternalModelUniforms are set and submesh is rendered the next iteration of Renderables is executed and both ModelMatrix and ActiveSubmesh are changed. The program doesn't crash but both informations change and some meshes are rendered some matrices are right others not which results in flickering image. Objects apear on frame and the next frame they are gone. The problem is only fixed if I enable that Sleep(10) function which makes sure that the code is executed before next iteration which obviously kills the idea of gaining preformance. What is the best possible solution for this? How can I send commands to the queue each with unique built in data? Maybe I need to implement my own queue for commands and a single thread without io_service?
I will continue my research as I know there is a way. The idea is right cause I get preformance boost as not a single if/else statement is processed by the rendering thread :) Any help or tips will really help!
Thanks!
Update:
After struggling for few nights I have created a very primitive model of communication between main thread and an Aux Thread. I created a class that represents a base command to be executed by aux thread:
class _ThreadCommand
{
public:
_ThreadCommand() {}
~_ThreadCommand() {}
virtual void _Execute() = 0;
virtual _ThreadCommand* Clone() = 0;
};
These commands that are childs of this class have _Execute() function to do whatever operation needs to be done. The main thread upon rendering fills a boost::ptr_vector of these commands While aux thread keeps on checking if there are any commands to process. When commands are found it copies entire vector to it's own vector inside _AuxThread and clears the original one. Commands are then executed by calling _Execute functions on each:
void _AuxThread()
{
//List of Thread commands
boost::ptr_vector<_ThreadCommand> _cmd;
//Infinitive loop
while(CORE_ENGINE->isRunning())
{
boost::lock_guard<boost::mutex> _lock(_auxMutex);
if (CORE_ENGINE->_ThreadCommands.size() > 0)
{
boost::lock_guard<boost::mutex> _auxLock(_cmdMutex);
for (unsigned int i = 0; i < CORE_ENGINE->_ThreadCommands.size(); i++)
{
_cmd.push_back(CORE_ENGINE->_ThreadCommands[i].Clone());
}
//Clear commands
CORE_ENGINE->_ThreadCommands.clear();
//Execute Commands
for (unsigned int i = 0; i < _cmd.size(); i++)
{
//Execute
_cmd[i]._Execute();
}
//Empty _cmd
_cmd.clear();
}
}
//Notify main thread that we have finished
CORE_ENGINE->_ShutdownCondition->notify_one();
}
I know that this is a really bad way to do it. Preformance is quite slower which I'm quite sure is because of all the copying and mutex locks. But at least the renderer works. You can get the idea of what I want to achieve but as I said I am very new to multithreading. What is the best solution for this scenario? Should I return back to ThreadPool system with asio::io_service? How can I feed commands to AuxThread with all values that must be sent to renderer to preform tasks in correct way?
First, a warning. Your "slight problem" is not slight at all. It is race condition, which is undefined behavior in C++, which, in turn, implies that anything could happen, including:
Everything renders fine
Image flickers
Nothing renders at all
It crashes on the last Saturday of every month. Or working fine on your computer and crashing on everyone's else.
Seriously, do not ever rely on UB, especially when writing library/framework/game engine.
Now about your question.
Lets leave aside any practical benefits of your approach and fix it first.
Actually, OpenGL implementation uses something very similar under the hood. Commands are executed asynchronously by the driver thread. I recommend you to read about their implementation to get some ideas on how to improve your design.
What you need to do, is to somehow "capture" the state at the time you post a rendering command. Simplest possible thing - copy the CORE_RENDERER->state into closure and use this copy to do the rendering. If state is large enough, it can be costly, though.
Alternative solution (and OpenGL goes that way) is to make every change in the state a command also, so
CORE_RENDERER->state.ModelMatrix = (*it).matrix;
CORE_RENDERER->state.ActiveSubmesh = (*it).submesh;
translates into
Matrix matrix = (*it).matrix;
Submesh submesh = (*it).submesh;
THREAD_POOL->service.post([&,matrix,submesh]{
CORE_RENDERER->state.ModelMatrix = matrix;
CORE_RENDERER->state.ActiveSubmesh = submesh;
});
Notice, however, that now you can't simply read CORE_RENDERER->state.ModelMatrix from your main thread, as it is changing in a different thread. You must first ensure that command queue is empty.

UE4.9 C++ Puzzle Block Addressing

In UE4 I am working on a Puzzle Block game in my Graphics 2 class. Our professor and our class is learning about UE4 together. Our class as a whole is a little confused about one thing in the C++ code and my professor said he would try to figure the answer out himself, but I figured I would jump start our next class with information that I find here.
Okay so in the BlockGrid.cpp file this section of code is used to create the blocks.
void AMyProject2BlockGrid::BeginPlay()
{
Super::BeginPlay();
// Number of blocks
const int32 NumBlocks = Size * Size;
// Loop to spawn each block
for(int32 BlockIndex=0; BlockIndex<NumBlocks; BlockIndex++)
{
const float XOffset = (BlockIndex/Size) * BlockSpacing; // Divide by dimension
const float YOffset = (BlockIndex%Size) * BlockSpacing; // Modulo gives remainder
// Make postion vector, offset from Grid location
const FVector BlockLocation = FVector(XOffset, YOffset, 0.f) + GetActorLocation();
// Spawn a block
AMyProject2Block* NewBlock = GetWorld()->SpawnActor<AMyProject2Block>(BlockLocation, FRotator(0,0,0));
// Tell the block about its owner
if(NewBlock != NULL)
{
NewBlock->OwningGrid = this;
}
}
}
The confusion starts with the following line in this function:
AMyProject2Block* NewBlock = GetWorld()->SpawnActor<AMyProject2Block>(BlockLocation, FRotator(0,0,0));
Each time it looks like it is rewriting NewBlock for each new block in the puzzle. Our problem is for the game we are creating, which is a Lights Out game, is if NewBlock is being continually being rewritten, then how is it keeping track of the addresses for the information to the blocks that are being displayed on the screen? This could be fixed by simply creating an array to store the information, but if the information is still being kept somewhere this would be inefficient. So how can we access the information for the blocks if NewBlock is being overwritten with each loop without making an array to inefficiently store the data?
THANKS!!!! :)
#Mathew's comment has the right idea, when you use SpawnActor, Unreal does a whole bunch of behind the scenes stuff but essentially creates your actor inside the world and manages its lifetime. (For example, to remove your actor from the level, you would need to use:
MyActor->Destroy();
Rather than the C++ method:
delete PtrToActor;
This handles removing it from the scene, updating collision volumes etc. before actually deleting the actor.
To your code, you are of course overwriting the pointer to your block, so the block itself is left untouched. You can use the TActorIterator<T> iterable to loop through all actors of a type which would save you having to store an array yourself. You would do something like this:
for (TActorIterator<AMyProject2Block> ActorItr(GetWorld()); ActorItr; ++ActorItr )
{
AMyProject2Block* PtrToActor = *ActorItr;
}
Where here the PtrToActor will point to each instance in turn as the loop advances.
However, it isn't really inefficient (and in many cases, is efficient) to store your own separate array of pointers. It is only a small memory cost (since it is just pointers) and might be faster as you don't have to filter the actors to find the one you want. In either case, it is a much of a muchness so you should choose whichever one feels more logical.
In your example, I'd keep them in 2D data structure so you can access them via their position rather than just getting an un-ordered list of them from the engine.

C++ parallel loops

I'm making a console game called alien spaceships as a homework. It should look something like this http://img74.imageshack.us/img74/8362/alieninvadersfdcl192720mu1.jpg .
So far so good I ain't allowed to use classes nor objects => only functions and arrays.
I have one while loop that checks the buttons I press on the keyboard and according to the button applies some functions.
The problem comes when I try to shoot a missle because it's done with a "for" loop and when I shoot I can't move. Can someone give me an idea how the model is supposed to look like and how can I make something like this work. I don't think it's needed to post my code, but if you want I'll post it.
I assume that you're not willing to play with multiple threads. It is not mandatory for a simple game like this and would add a bit of complexity.
So generic loop for monothreaded game is:
state new_state = createInitialState();
do
{
input = readInput(); // non blocking !
new_state = modifyState(input, new_state);
updateScreen(new_state);
}
while (!exitCondition(input));
None of these functions should loop for long.
In your case, the missile position should be updated in modifyState taking into account the time since the last modifyState.
I assume you use a matrix to store all the data, and periodically you print the content of the matrix (that's how you create a console game).
So, your code should look something like this:
render()
{
update_position(x,y);
if(missile_fired)
update_missile_position();
}
main()
{
for(;;)
{
read_input(&x,&y);
render();
draw_image();
}
}

MFC WebBrowser Control: How many (normal) lines of code does it take to simulate Ctrl+N?

Update: Answer: Two normal lines of code required. Thanks Noseratio!
I banged my head on the keyboard for more hours than I would have cared to trying to simulate IEs Ctrl+N behavior in my hosted Browser control app. Unfortunately, due to complications which I've abstracted out of my code examples below, I can't just let IE do Ctlr+N itself. So I have to do it manually.
Keep in mind that I am running a hosted browser. So typically, opening links in new windows will actuall open it within a new "tab" within my application (it's not really a tab, but another window... but appearance-wise it's a tab). However, Ctrl+N is different -- here, it is expected a fully-fledged IE window will launch when pressed.
I think my problem is that of framing the questions -- admittedly I am new to WebBrowser control and I find it to be a lot of yucky. Regardless, I've scoured the Internet for the past day and couldn't come up with an elegant solution.
Basically, the ideal solution would be to call a "NewWindow" function within WebBrowser control or its affiliate libraries; however, all I was able to find where the *On*NewWindow methods, which were event handlers, not event signallers. Which I understand that most of the time, the user will be creating the events... but what about programmatic simulation?
I tried looking into an SENDMESSAGE approach where I could use the IDs that the OnNewWindow events use... that ended up in nothing than crashes. Perhaps I could go back to get it work, but I'd like confirmation is that approach is even worth my time.
The next approach, which should have been the most elegeant, but sadly didn't pan out, was like the following:
Navigate2(GetLocationURL().GetBuffer(), BrowserNavConstants::navOpenInNewWindow);
It would have worked marvelously if it weren't for the fact that the new window would open in the background, blinking in the taskbar. needing clicking to bring it to the front.
I tried to get around the limitation in a myriad of ways, including getting the dispatcher of the current context, then calling OnNewWindow2 with that IDispatch object. Then I would invoke QueryInterface on the dispatch object for an IWebBrowser control. The webBrowser control (presumably under the control of the new window) could then navigate to the page of the original context. However... this too was a pretty messy solution and in the end would cause crashes.
Finally, I resorted to manually invoking JavaScript to get the desired behavior. Really?? Was there really no more elegant a solution to my problem than the below mess of code?
if ((pMsg->wParam == 'N') && (GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_SHIFT) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000))
{
LPDISPATCH pDisp = CHtmlView::GetHtmlDocument();
IHTMLDocument2 *pDoc;
if (SUCCEEDED(pDisp->QueryInterface(IID_IHTMLDocument2, (void **)&pDoc)))
{
IHTMLWindow2* pWnd;
pDoc->get_parentWindow(&pWnd);
BSTR bStrLang = ::SysAllocString(L"JavaScript");
CString sCode(L"window.open(\"");
sCode.Append(GetLocationURL().GetBuffer());
sCode.Append(L"\");");
BSTR bStrCode = sCode.AllocSysString();
COleVariant retVal;
pWnd->execScript(bStrCode, bStrLang, retVal);
::SysFreeString(bStrLang);
::SysFreeString(bStrCode);
pDoc->Release();
}
pDisp->Release();
I find it hard to believe that I must resort to such hackery as this to get something as simple as opening a new window when the user presses Ctrl+N.
Please stackoverflow, please point out the clearly obvious thing I overlooked.
Ctrl-N in IE starts a new window on the same session. In your case, window.open or webBrowser.Navigate2 will create a window on a new session, because it will be run by iexplore.exe process which is separate from your app. The session is shared per-process, this is how the underlying UrlMon library works. So you'll loose all cookies and authentication cache for the new window. On the other hand, when you create a new window which hosts WebBrowser control within your own app process, you'll keep the session.
If such behavior is OK for your needs, try first your initial Navigate2 approach, precededing it with AllowSetForegroundWindow(ASFW_ANY) call. If the new window still doesn't receive the focus correctly, you can try creating an instance of InternetExplorer.Application out-of-proc COM object, and use the same IWebBrowser2 interface to automate it. Below is a simple C# app which works OK for me, the new window is correctly brought to the foreground, no focus issues. It should not be a problem to do the same with MFC.
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace IeApp
{
public partial class MainForm : Form
{
// get the underlying WebBrowser ActiveX object;
// this code depends on SHDocVw.dll COM interop assembly,
// generate SHDocVw.dll: "tlbimp.exe ieframe.dll",
// and add as a reference to the project
public MainForm()
{
InitializeComponent();
}
private void NewWindow_Click(object sender, EventArgs e)
{
AllowSetForegroundWindow(ASFW_ANY);
// could do: var ie = new SHDocVw.InternetExplorer()
var ie = (SHDocVw.InternetExplorer)Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
ie.Visible = true;
ie.Navigate("http://www.example.com");
}
const int ASFW_ANY = -1;
[DllImport("user32.dll")]
static extern bool AllowSetForegroundWindow(int dwProcessId);
}
}

How to do a lot simpler version of UT kismet (C++ and Lua)

I know this is a non trivial question, but I have spent last week thinking about how to do this, and I can't fidn a good way.
Mainly I have a 2D level editor. I can put entities in the world, add tiles, collisions, etc... What I want is to be able to script easy things visually. For example if I have a lever and a door, I want to select the level select its "onactivate" event and link it to the "close" action of the door.
The editor loads a xml with the possible entities, and what actions each publishes, in the case of the lever (activate/deactivate) and the door (open/close).
Now the difficult part. I need to translate this into running code. I have thought about some solutions but all seems awkard to me. For eample, for the lever/door event I could autogenerate code in a lua function with name Lever1_onactivate_Door1_open() that will register a LuaListener in the Lever1 instance listener cue foro the onactivate event (in C++), and let it be called later, when the onEnter for the trigger is triggered.
Could anyone explain how ussually this kind of things are done? One of my probs is that I want to integrate this into my event system as I exposed, to have an orthogonal arquitecture.
Thanks in advance,
Maleira.
In games like Doom, this is approximately done as follows: when pressing the Use key [func: P_UseLines], the nearest wall that it would apply to is searched for [func: P_UseTraverse] and, provided you are in range and have the right angle of turn, calls an action (called "special") associated with the line in [func: P_ActivateLine], which essentially maps it to a preexisting function in the end.
In other words, a simple lookup in a function pointer array:
/* Premise */
struct line_t {
...
int special;
...
};
struct line_t *line = activation_line;
/* Function call from p_spec.cpp */
LineSpecials[line->special](line, ...);
LineSpecials would be an array of function pointers:
int LS_Door_Open(struct line_t *, ...)
{
...
}
typedef int (*lnSpecFunc)(struct line_t *, ...);
lnSpecFunc LineSpecials[256] = {
...
/* 13 */ LS_Door_Open,
...
};