Slowly eating into my reading list

I have decided to slowly eat into my reading list and get done with books I started and never finished. I will be starting with one that has been there probably for the longest.

WP_20160419_07_51_46_Pro.jpg

Advertisements

Git squash multiple commits into one

If you ever have a scenario where you have to make a lot of changes to a branch but commit regularly so you can go back during this process if something fails BUT when you are done as a whole none of those commits actually matter except the last one (historically it will be off no use to see what was changing between revisions) you can do this in git:

Note: Before you do this all your changes need to have been committed, make sure you have nothing staged.

git reset –soft <sha_of_initial_commit>
git commit -a –amend -m “commit message”

Making Nunit tests execute in order

Have you ever wanted to run a given suite of Nunit tests in order? Normally your tests should be created in such a way that execution order is no concern. I stand by that rule, however there is that one edge case were you need to break that rule. The one scenario I came across was with R.NET whereby in a given process you can only initialize one R Engine and once disposed you cannot reinitialize. One of my test happened to deal with disposing the engine and if this test were to run before any other test(s) they would fail.

You will find below a code snippet of how I managed to get this to run in order using Nunit.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using RSamples;

    public class OrderedTestAttribute : Attribute
    {
        public int Order { get; set; }

        public OrderedTestAttribute(int order)
        {
            this.Order = order;
        }
    }

    public class TestStructure
    {
        public Action Test;
    }

    public class SampleTests
    {
        [TearDown]
        public void CleanUpAfterTest()
        {
            REngineExecutionContext.ClearLog();
        }

        [OrderedTest(0)]
        public void Test1(){}

        [OrderedTest(1)]
        public void Test2(){}

        [OrderedTest(2)]
        public void Test3(){}

        [TestCaseSource(sourceName: "TestSource")]
        public void MainTest(TestStructure test)
        {
            test.Test();
        }

        public static IEnumerable<TestCaseData> TestSource
        {
            get
            {
                var assembly = Assembly.GetExecutingAssembly();
                Dictionary<int, List<MethodInfo>> methods = assembly
                    .GetTypes()
                    .SelectMany(x => x.GetMethods())
                    .Where(y => y.GetCustomAttributes().OfType<OrderedTestAttribute>().Any())
                    .GroupBy(z => z.GetCustomAttribute<OrderedTestAttribute>().Order)
                    .ToDictionary(gdc => gdc.Key, gdc => gdc.ToList());

                foreach (var order in methods.Keys.OrderBy(x => x))
                {
                    foreach (var methodInfo in methods[order])
                    {
                        MethodInfo info = methodInfo;
                        yield return new TestCaseData(
                            new TestStructure
                            {
                                Test = () =>
                                {
                                    object classInstance = Activator.CreateInstance(info.DeclaringType, null);
                                    info.Invoke(classInstance, null);
                                }
                            }).SetName(methodInfo.Name);
                    }
                }
            }
        }
    }

Unreal engine build types

You will note that if you open an Unreal Engine game project in Visual Studio you will be presented with the following build options:

  1. DebugGame
  2. DebugGameEditor
  3. Developement
  4. DevelopementEditor
  5. Shipping

The editor build can be attached to and loaded to the Unreal Editor. There is off course some overhead associated with this.

The non-editor bulds are stand alone builds that you can run out of the editor. To run these builds you would need to cook content for the given platform in the editor through File-> Cook content for [Platform].

The debug game options are the least optimized and allow access to all variables during debug, while the development options are semi optimized and the shipping option is fully optimized.

2016-04-03 14_00_34-SampleProject - Unreal Editor.png

The shipping build is the actual game you distribute for a given platform. This has full optimization on no debugging features.

The unreal editor has a compile option that will create new binaries for a DevelopementEditor build.

Random UE snippets (C++)

On this thread I am going to post a bunch of random Unreal Engine snippets I make use of
Make calls easier by redefining them


#define print(text) if (GEngine) GEngine-&gt;AddOnScreenDebugMessage(-1, 1.5, FColor::White,text)

Convert Fstring to std::string and vice-versa


std::string cppString = &quot;Sample string&quot;;
FString ue4String(cppString.c_str());

FString ue4String2 = &quot;Flowers&quot;;
std::string cppString2(TCHAR_TO_UTF8(*ue4String2));

Convert int/float to FString and vice-versa


FString ue4String = &quot;123.021&quot;;
int32 intValue = FCString::Atoi(*ue4String);
float floatValue = FCString::Atof(*ue4String);

FString ue4String2 = FString::FromInt(intValue);
FString ue4String3 = FString::SanitizeFloat(intValue)

Reading and writing to config files in UE

Configuration files are a nice way to store various game variables in Unreal Engine games. They are particularly good in that you can make changes to parameters in them and not have to compile/build you game again. Your power users could even tweak things by making changes to these parameters.

Unreal comes with a bunch of configuration files that you can find under [Game Location]\Saved\Config\Windows

Below is a screenshot indicating the config files I have by default on creating a new blank project

configuration files

Reading from config files:

You can read any parameter from these files by making use of GConfig as shown below:


 if(!GConfig) return;

 FString value;

 GConfig-&amp;amp;amp;gt;GetString(TEXT("/Script/UnrealEd.LevelEditorPlaySettings"),
 TEXT("MouseControlLabelPosition"),
 value,
 GEditorPerProjectIni);

 UE_LOG(LogTemp, Log, TEXT("%s"),*value);

In this example we intend to read the MouseControlLabelPosition value under the catergory /Script/UnrealEd.LevelEditorPlaySettings from the file EditorPerProjectUserSettings.ini.

We call the GeString method in this case because the target value is a string, you have other options such as GetBool etc. The first argument you pass in is the section name. Take a look at the screenshot below showing what the file contents look like. The second argument is the name of the parameter you want to read. The third argument is the variable you want to store the result into, note we have made this an FString. The fourth argument is a const for the file we want to read in this case for EditorPerProjectUserSettings.ini it is GEditorPerProjectIni.

configuration file sample.png

Writing to config files:

In the example below we will write to the config file Game.ini and create a new section called Sample.Section.


if (!GConfig) return;

FString newSection = "Sample.Section";
GConfig->SetString(
*newSection,
TEXT("PlayerName"),
TEXT("Chloe"),
GGameIni
);
GConfig->Flush(false,GGameIni);

Note that on completion we called GConfig->Flush. This is to ensure that any data held in buffers is flushed to the target config file.

Sending debug messages in UE

One thing that really comes handy during debugging is being able to send messages to yourself say in a log window or the game screen even. You may for instance want to know what data your actor is operating on. This is really easy to do in Unreal Engine.

To send messages to the console:


UE_LOG(LogTemp, Log, TEXT("Sample debug %s."),"message");

LogTemp is the default category for temporary log messages.
Log represents ordinary log messages that will be shown in grey. You have the option from:

  • Log (grey)
  • Warning (yellow)
  • Error (red)

The last two parameters represent the log message format and arguments. Optionally you can you the format as the actual log message.

To send a message to the game screen:


GEngine->AddOnScreenDebugMessage(-1, 15, FColor::Red, "Sample debug message.");

You make use of GEngine to log messages to the screen by calling AddOnScreenDebugMessage. The first parameters is a key (-1 represents messages that can be repeated each shown individually, inverse being key 0). The second parameter is the number of seconds to display the message for. The third parameter is an FColor representing the color you would like to show the message in. The last parameter is the debug message you would like to show.

There is one disadvantage to sending messages to the game screen. These messages are displayed for a limited amount of time and you cannot go back to review these messages at a later stage.