<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>3zanders.co.uk</title>
  <icon>https://www.gravatar.com/avatar/597c906ec36c18b968cd390032b2ce88</icon>
  <subtitle>Alex Parker&#39;s Website</subtitle>
  <link href="/atom.xml" rel="self"/>
  
  <link href="http://3zanders.co.uk/"/>
  <updated>2018-02-24T22:23:01.223Z</updated>
  <id>http://3zanders.co.uk/</id>
  
  <author>
    <name>Alex Parker</name>
    <email>3zanders@gmail.com</email>
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>The SLAB Memory Allocator</title>
    <link href="http://3zanders.co.uk/2018/02/24/the-slab-allocator/"/>
    <id>http://3zanders.co.uk/2018/02/24/the-slab-allocator/</id>
    <published>2018-02-24T00:00:00.000Z</published>
    <updated>2018-02-24T22:23:01.223Z</updated>
    
    <content type="html"><![CDATA[<p>One of the primary things an operating system does is allocate memory. In this tutorial we’re going to write our very own memory allocator for the rest of the kernel to use to allocate memory. This will allow us to more safely use and allocate strings and implement more complicated data structures which will come in useful later!</p><p><img src="/2018/02/24/the-slab-allocator/computer-memory-chips.jpg" alt="Allocate this thing!"></p><p>In this tutorial I’m going to focus on the <a href="https://en.wikipedia.org/wiki/Slab_allocation" target="_blank" rel="external">SLAB Memory Allocator</a> used in the Linux operating system which eliminates memory fragmentation caused by allocations and deallocations. In an operating system this is usually built on top of the <a href="https://en.wikipedia.org/wiki/Virtual_memory" target="_blank" rel="external">Virtual Memory</a> system which maps 4KB blocks of memory. This means the goal of the allocator is to chop those 4KB blocks up into more manageable pieces.</p><p>The virtual memory system provides an API where you can map a 4K block of memory to a specific memory address. In my kernel it looks like this:</p><pre><code>void map_page(u32 virtualAddr);</code></pre><p>If you fail to call <code>map_page</code> and attempt to read/write from a memory location that isn’t mapped then you get a page fault. I plan to talk in more detail about the virtual memory system in a future tutorial.</p><h2 id="Allocator-API"><a href="#Allocator-API" class="headerlink" title="Allocator API"></a>Allocator API</h2><p>First off let’s define the interface to our memory allocator. We don’t want to confuse it with <code>malloc</code> so I’ve gone with <code>kalloc</code>. I also like to avoid sprinkling <code>unsigned</code> everywhere so let’s add some typedefs.</p><pre><code>typedef unsigned int u32;typedef unsigned short u16;void kalloc_init(u32 memStart, u32 memSize);void* kalloc(u32 size);void kfree(void* ptr);</code></pre><p><code>kalloc_init</code> allocates a range of memory and sets everything up. We would call this from our kernel setup routine after we’ve initialised the virtual memory system.</p><h2 id="Slab-Algorithm"><a href="#Slab-Algorithm" class="headerlink" title="Slab Algorithm"></a>Slab Algorithm</h2><p>The core idea of the SLAB allocator is that you split each 4K block (from now on a <code>Slab</code>) into an array of blocks of the same size. For example a 4K slab can hold exactly 4 x 1024 byte objects and 32 x 128 byte objects. To avoid wasting space the object size must be a power of 2.</p><p>When you request a block of memory of a specific size the allocator finds a slab with objects that are the next power of 2 of that size and hands you a free block from it. If there are no free blocks left then a new slab is mapped from virtual memory.</p><p>Free memory inside a slab is tracked via a linked list where the pointer to the next free element is stored inside the free memory location itself! This constrains us to a minimum allocation size of 32 bits so we can store the pointer.</p><h2 id="Allocation-within-a-Slab"><a href="#Allocation-within-a-Slab" class="headerlink" title="Allocation within a Slab"></a>Allocation within a Slab</h2><p><img src="/2018/02/24/the-slab-allocator/slab_steps.png" alt="Allocation within a Slab"></p><p>This diagram shows what’s going on for a single Slab as you allocate and free memory. In this example you start with a single 4KB Slab containing 4 x 1KB objects which has been allocated at location 10000 in memory. An unaligned low memory location like this is a bad idea in the real world but this makes it easier to understand ;)</p><p>Initially the free list is pointing at the first block, which is pointing to the second block and so on until we hit the null pointer at the end.</p><p>The first <code>kalloc</code> allocates 1KB of memory and writes <code>0xF00D</code> to it which updates the free list pointer to point at the second block of memory. The second writes <code>0xBEEF</code> and points the free list at the third block.</p><p>When the memory is freed we simply write the free list location into the freed memory location and update the free list to point at our freed block.</p><p>Let’s go ahead and write some code for this!</p><pre><code>struct SlabEntry{    SlabEntry* next;};struct Slab{    Slab* m_nextSlab;    SlabEntry* m_freeList;    u32 m_slabStart;    u16 m_size;    void Init(u32 slabStart, u16 size);    bool Alloc(u32 size, u32&amp; newLoc);    bool Free(u32 location);};</code></pre><p>First we need to initialise the memory for a single slab by setting up the free list to point to each block of free memory. Initially this will be every block of memory in the slab, like this:</p><pre><code>void Slab::Init(u32 slabStart, u16 size){    m_nextSlab = nullptr;    m_slabStart = slabStart;    m_size = size;    map_page(slabStart);    memset((void*)slabStart, 0, 0x1000);    u32 numEntries = (0x1000 / size) - 1;    m_freelist = (SlabEntry*)slabStart;    SlabEntry* current = m_freelist;    for (u32 i = 1; i&lt;numEntries; i++)    {        current-&gt;next = (SlabEntry*)(slabStart + (i * size));        current = current-&gt;next;    }}</code></pre><p>This function takes a virtual memory location which we will ask to be managed by this slab and the size of each object we’ll be allocating. We ask the virtual memory paging system to map this page for us and make it writeable.</p><p>Next the alloc function pops a free object off the free list!</p><pre><code>bool Slab::Alloc(u32 size, u32&amp; newLoc){    if (m_size != size || m_freelist == nullptr)        return false;    newLoc = (u32)m_freelist;    m_freelist = m_freelist-&gt;next;    return true;}</code></pre><p>The free function adds an object back on the free list, after checking that the memory location being freed is within the slab:</p><pre><code>bool Slab::Free(u32 location){    if (location &lt; m_slabStart || location &gt;= m_slabStart + 0x1000)        return false;    SlabEntry* newEntry = (SlabEntry*)location;    newEntry-&gt;next = m_freelist;    m_freelist = newEntry;    return true;}</code></pre><p>There is a whole bunch of extra checks you can do here which I’ve left out to make the code simpler.</p><h2 id="Allocating-Slab-Metadata"><a href="#Allocating-Slab-Metadata" class="headerlink" title="Allocating Slab Metadata"></a>Allocating Slab Metadata</h2><p>So at this point we have a way of allocating memory for a single 4KB block of memory for a single allocation size. How do we build on this? </p><p>We want to support multiple slabs of memory! The simplest option is to have a linked list of them, like this:</p><pre><code>Slab* g_slabList;</code></pre><p>This brings up another problem. Where do we store the members inside each <code>Slab</code> struct? The answer is to store the Slab structs inside a special list of Slabs set aside just for this purpose - a ‘metadata’ slab.</p><pre><code>Slab* g_slabMetaData;</code></pre><p>Here is helper function <code>alloc_slab_meta</code> that will set one of these up. The trick here is to use the first object in the slab to store the fields of the metadata slab itself. It’s <a href="https://xkcd.com/1416/" target="_blank" rel="external">turtles all the way down</a>!</p><pre><code>static Slab* alloc_slab_meta(u32 slabStart){    Slab slabMetadata;    slabMetadata.Init(slabStart, sizeof(Slab), true);    u32 slabLoc;    bool didAlloc = slabMetadata.Alloc(sizeof(Slab), slabLoc);    assert(didAlloc &amp;&amp; slabStart == slabLoc);    Slab* newSlabMeta = (Slab*)slabLoc;    *newSlabMeta = slabMetadata;    return newSlabMeta;}</code></pre><h2 id="Putting-it-all-together"><a href="#Putting-it-all-together" class="headerlink" title="Putting it all together"></a>Putting it all together</h2><p>We need to know where our heap needs to start from in virtual memory:</p><pre><code>u32 g_memStart;</code></pre><p>We’re ready to write our <code>kalloc</code> function! First we loop through the existing slab lists to see if we can allocate memory from those:</p><pre><code>void* kalloc(u32 size){    u32 newLoc;    Slab* slab = g_slabList;    for (; slab; slab = slab-&gt;m_nextSlab) {        if (slab-&gt;Alloc(size, newLoc)) {            return (void*)newLoc;        }    }</code></pre><p>If that fails then we need to allocate a new slab, and hand over the first block of memory from there. The memory for slabs is held by the <code>g_slabMetaData</code> which we can now allocate from:</p><pre><code>u32 slabLoc;bool didAlloc = g_slabMetaData-&gt;Alloc(sizeof(Slab), slabLoc);</code></pre><p>If the metadata is full then we need to allocate a new metadata slab! Since this allocator never throws away allocated slabs we don’t need to keep a reference to previous metadata slabs.</p><pre><code>if (!didAlloc) {    g_slabMetaData = alloc_slab_meta(g_memStart);    g_memStart += 0x1000;    g_slabMetaData-&gt;Alloc(sizeof(Slab), slabLoc);}</code></pre><p>Now we have somewhere to put the metadata we can allocate a new slab and add it to the slab list!</p><pre><code>Slab* newSlab = (Slab*)slabLoc;newSlab-&gt;Init(g_memStart, size, false);g_memStart += 0x1000;newSlab-&gt;m_nextSlab = g_slabList;g_slabList = newSlab;</code></pre><p>Now we can allocate the block of memory inside the slab.</p><pre><code>    newSlab-&gt;Alloc(size, newLoc);    return (void*)newLoc;}</code></pre><p>I have intentionally kept the code here simple meaning there is a lot of room here for optimisation. For example you could maintain multiple slab linked lists allowing you to skip over slabs that are full or find a slab with the correct allocation size more quickly.</p><p>I’ve also missed out some asserts and other safety checks. I’ve included those in the full version below.</p><h2 id="Freeing-memory"><a href="#Freeing-memory" class="headerlink" title="Freeing memory"></a>Freeing memory</h2><p>To keep things simple we’re only going to free memory inside each slab - once a slab has been allocated it is alive forever! A more fancy version would throw away everything that’s been allocated.</p><p>The free function simply asks each slab if it wants to free the block. Again you could be much cleverer and have multiple lists so you can find the slab much more quickly.</p><pre><code>void kfree(void* ptr){    if (!ptr)         return;    u32 loc = (u32)ptr;    for (Slab* slab = g_slabList; slab; slab = slab-&gt;m_nextSlab)        if (slab-&gt;Free(loc))            return;}</code></pre><h2 id="Final-bits"><a href="#Final-bits" class="headerlink" title="Final bits"></a>Final bits</h2><p>That’s the core stuff! All we need now is an init function and a main function to test this thing. The init function allocates the first metadata block and sets up the globals.</p><pre><code>void kalloc_init(u32 memStart, u32 memSize){    g_memStart = memStart;    g_slabList = nullptr;    g_slabMetaData = alloc_slab_meta(g_memStart);    g_memStart += 0x1000;}</code></pre><p>You don’t need your very own operating system to test this! We can point this code at a block of memory, like this:</p><pre><code>char g_memory[1024*1024];// 1 MB!int main(int argc, char** argv){    kalloc_init(&amp;g_memory[0], sizeof(g_memory));}</code></pre><p>You can <a href="/2018/02/24/the-slab-allocator/kalloc.cpp">download the whole file here</a> and then compile and run it like this:</p><pre><code>gcc kalloc.cpp --std=c++11 -m32 -o kalloc &amp;&amp; ./kalloc</code></pre><p>This also includes a couple of simple test routines. Note there are almost certainly bugs - please don’t use this in code you care about ;)</p><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>So that’s how the slab allocator works which concludes this tutorial!</p><p>In a future tutorial series I’m going to talk about setting up <a href="http://wiki.osdev.org/Paging" target="_blank" rel="external">virtual memory</a> and <a href="http://wiki.osdev.org/Interrupts" target="_blank" rel="external">interrupts</a>. You might also be interested in the previous tutorial series I wrote on <a href="/2017/10/13/writing-a-bootloader/">how to write a bootloader!</a>.</p>]]></content>
    
    <summary type="html">
    
      How to write your very own SLAB memory allocator!
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="OSdev" scheme="http://3zanders.co.uk/tags/OSdev/"/>
    
  </entry>
  
  <entry>
    <title>Writing a Bootloader Part 3</title>
    <link href="http://3zanders.co.uk/2017/10/18/writing-a-bootloader3/"/>
    <id>http://3zanders.co.uk/2017/10/18/writing-a-bootloader3/</id>
    <published>2017-10-17T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.195Z</updated>
    
    <content type="html"><![CDATA[<p>In our <a href="/2017/10/16/writing-a-bootloader2/">previous article</a> we got our CPU into 32-bit protected mode and printed the screen using the directly mapped VGA memory. This time we’re going to compile and load a C++ function into memory and call it!</p><h2 id="Going-beyond-512-bytes"><a href="#Going-beyond-512-bytes" class="headerlink" title="Going beyond 512 bytes"></a>Going beyond 512 bytes</h2><p>The BIOS only loads the first 512 bytes of the bootsector. If we want to write programs larger than 512 bytes (maybe you don’t want to and like a challenge?) we’re going to have to load more off the disk. To do this we’re going to use the <code>int 0x13</code> <a href="https://en.wikipedia.org/wiki/INT_13H" target="_blank" rel="external">interrupts</a> which provide disk services.</p><p>The <code>ah=0x2 int 0x13</code> command reads sectors from a drive to a target location, like this:</p><pre><code>mov ah, 0x2    ;read sectorsmov al, 1      ;sectors to readmov ch, 0      ;cylinder idxmov dh, 0      ;head idxmov cl, 2      ;sector idxmov dl, [disk] ;disk idxmov bx, copy_target;target pointerint 0x13</code></pre><p>The disk number is implicitly placed into <code>dl</code> by the BIOS on startup. Earlier on we stashed it into memory with <code>mov [disk], dl</code>.</p><p>So we can now load 512 bytes from the second sector into memory! Let’s make use of that and move the hello world printing code from <a href="/2017/10/13/writing-a-bootloader/boot2.asm">last time</a> beyond the first 512 bytes of disk. Like this:</p><pre><code>times 510 - ($-$$) db 0dw 0xaa55copy_target:bits 32    hello: db &quot;Hello more than 512 bytes world!!&quot;,0boot2:    mov esi,hello    mov ebx,0xb8000.loop:    lodsb    or al,al    jz halt    or eax,0x0F00    mov word [ebx], ax    add ebx,2    jmp .loophalt:    cli    hlttimes 1024 - ($-$$) db 0</code></pre><p>The last line pads our bootloader to 1024 bytes so we’re not copying uninitialised bytes from disk. It’s probably easiest to download <a href="/2017/10/13/writing-a-bootloader/boot3.asm">boot3.asm</a> directly. You can compile and run it with <code>nasm -f bin boot3.asm -o boot.bin &amp;&amp; qemu-system-x86_64 -fda boot.bin</code> getting this result:</p><p><img src="/2017/10/13/writing-a-bootloader/boot3.png" alt="Hello more than 512 bytes world"></p><h2 id="Getting-to-C"><a href="#Getting-to-C" class="headerlink" title="Getting to C++"></a>Getting to C++</h2><p>Next we’re going to load a C++ function that prints Hello world into memory and then call it from the bootloader. Here is the C++ function we want to compile:</p><pre><code>extern &quot;C&quot; void kmain(){    const short color = 0x0F00;    const char* hello = &quot;Hello cpp world!&quot;;    short* vga = (short*)0xb8000;    for (int i = 0; i&lt;16;++i)        vga[i+80] = color | hello[i];}</code></pre><p>I’ve intentionally kept the function as simple as possible - it does almost the same thing as the assembly code. The <code>extern &quot;C&quot;</code> prevents C++ from <a href="https://en.wikipedia.org/wiki/Name_mangling#C.2B.2B" target="_blank" rel="external">name mangling</a> the function allowing us to call it from assembly.</p><h2 id="Compiling-and-Linking"><a href="#Compiling-and-Linking" class="headerlink" title="Compiling and Linking"></a>Compiling and Linking</h2><p>We now need to compile and link this function. To do this safely we need to create a <a href="https://en.wikipedia.org/wiki/Cross_compiler" target="_blank" rel="external">cross compiler</a> - this is safer than using your system’s C++ compiler since we can be certain about what instruction set and function call method the compiler uses. I also can’t for the life of me convince clang to use a linker script and stop adding loads of OSX specific stuff. Since we’re building a 32 bit operating system we also want the compiler to output 32 bit instructions - not 64 bit ones!</p><p>Compiling a cross compiler is an absolute pain - but luckily I’ve hacked a <a href="https://github.com/zanders3/homebrew-gcc_cross_compilers" target="_blank" rel="external">homebrew tap</a> you can use:</p><pre><code>brew tap zanders3/homebrew-gcc_cross_compilersbrew install --debug i386-elf-gcc</code></pre><p>Interestingly upgrading Mac OSX can mess gcc and all sorts of things up so try these commands if things fall over.</p><pre><code>xcode-select --installbrew reinstall gcc</code></pre><p>This will install <code>i386-elf-_g++</code> on your path which will compile and link stuff for us! Installing takes a while - you might want to grab a cuppa whilst it compiles.</p><h2 id="Linker-Script"><a href="#Linker-Script" class="headerlink" title="Linker Script"></a>Linker Script</h2><p>We need to tell gcc how to link our cpp file and asm files together. We want the <code>boot4.asm</code> code positioned at offset <code>0x7c00</code> so that the 510th bytes equal <code>0xAA55</code> which makes it a valid bootsector. We then want all of the C++ code placed after that in the file.</p><pre><code>ENTRY(boot)OUTPUT_FORMAT(&quot;binary&quot;)SECTIONS {    . = 0x7c00;    .text :    {        *(.boot)        *(.text)    }    .rodata :    {        *(.rodata)    }    .data :    {        *(.data)    }    .bss :    {        *(.bss)    }}</code></pre><p>The <code>ENTRY(boot)</code> means the entry point of the program is the <code>boot</code> symbol. <code>OUTPUT_FORMAT(&quot;binary&quot;)</code> tells <code>gcc</code> to output raw assembly directly. It will otherwise output a binary file in <a href="https://en.wikipedia.org/wiki/Executable_and_Linkable_Format" target="_blank" rel="external">ELF</a>. The <code>. = 0x7c00</code> tells it to start outputting code at that offset, similar to the <code>org 0x7c00</code> command.</p><h2 id="Calling-C-from-Assembly"><a href="#Calling-C-from-Assembly" class="headerlink" title="Calling C++ from Assembly"></a>Calling C++ from Assembly</h2><p>Next we need to modify our assembly so it can be linked with <code>gcc</code>. First we’re going to put everything in the <code>.boot</code> section so it’s placed first as well as define a global <code>boot:</code> symbol so the linker knows about the entry point.</p><pre><code>section .bootbits 16global bootboot:</code></pre><p>Next we’ll hack the disk reading function call to load more than one sector:</p><pre><code>mov al, 6      ;sectors to read</code></pre><p>Finally we set up a call stack for C++ to use and call the actual function. We reserve 16 KB for a kernel call stack.</p><pre><code>mov esp,kernel_stack_topextern kmaincall kmainclihltsection .bssalign 4kernel_stack_bottom: equ $    resb 16384 ; 16 KBkernel_stack_top:</code></pre><p>That’s it. We’re ready to compile and run this thing! Here are my versions of <a href="/2017/10/13/writing-a-bootloader/linker.ld">the linker script</a>, <a href="/2017/10/13/writing-a-bootloader/kmain.cpp">cpp file</a> and <a href="/2017/10/13/writing-a-bootloader/boot4.asm">bootsector assembly</a>!</p><h2 id="Compiling-and-Running"><a href="#Compiling-and-Running" class="headerlink" title="Compiling and Running"></a>Compiling and Running</h2><p>You want to compile the assembly, then link it all together.</p><pre><code>nasm -f elf32 boot4.asm -o boot4.oi386-elf-_g++ x86_64-elf-g++ -m64 kmain.cpp boot4.o -o kernel.bin -nostdlib -ffreestanding -std=c++11 -mno-red-zone -fno-exceptions -nostdlib -fno-rtti -Wall -Wextra -Werror -T linker.ld</code></pre><p>We can run <code>hexdump kernel.bin</code> to check it did the right thing:</p><pre><code>0000000 b8 01 24 cd 15 b8 03 00 cd 10 88 16 61 7c b4 020000010 b0 06 b5 00 b6 00 b1 02 8a 16 61 7c bb 00 7e cd0000020 13 fa 0f 01 16 5b 7c 0f 20 c0 66 83 c8 01 0f 220000030 c0 b8 10 00 8e d8 8e c0 8e e0 8e e8 8e d0 ea 220000040 7e 08 00 00 00 00 00 00 00 00 00 ff ff 00 00 000000050 9a cf 00 ff ff 00 00 00 92 cf 00 18 00 43 7c 000000060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00*00001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa0000200 48 65 6c 6c 6f 20 6d 6f 72 65 20 74 68 61 6e 200000210 35 31 32 20 62 79 74 65 73 20 77 6f 72 6c 64 210000220 21 00 be 00 7e 00 00 bb 00 80 0b 00 ac 08 c0 740000230 0d 0d 00 0f 00 00 66 89 03 83 c3 02 eb ee bc f80000240 be 00 00 e8 02 00 00 00 fa f4 55 48 89 e5 48 830000250 ec 20 c7 45 f8 00 0f 00 00 48 c7 45 f0 ad 7e 000000260 00 48 c7 45 e8 00 80 0b 00 c7 45 fc 00 00 00 000000270 83 7d fc 0f 7f 34 8b 45 fc 48 63 d0 48 8b 45 f00000280 48 01 d0 0f b6 00 66 98 80 cc 0f 89 c2 8b 45 fc0000290 48 98 48 83 c0 50 48 8d 0c 00 48 8b 45 e8 48 0100002a0 c8 66 89 10 83 45 fc 01 eb c6 90 c9 c3 48 65 6c00002b0 6c 6f 20 63 70 70 20 77 6f 72 6c 64 21 00 00 0000002c0 14 00 00 00 00 00 00 00 01 7a 52 00 01 78 10 0100002d0 1b 0c 07 08 90 01 00 00 1c 00 00 00 1c 00 00 0000002e0 6a ff ff ff 63 00 00 00 00 41 0e 10 86 02 43 0d00002f0 06 02 5e c6 0c 07 08 00                        00002f8</code></pre><p>Note the <code>55 aa</code> there near offset <code>0x200</code>? That means it’s a valid bootsector! Let’s try running it with <code>qemu-system-x86_64 -fda kernel.bin</code> and you should get this result.</p><p><img src="/2017/10/13/writing-a-bootloader/boot4.png" alt="Our Hello CPP world bootloader"></p><h2 id="Wrapping-Up"><a href="#Wrapping-Up" class="headerlink" title="Wrapping Up"></a>Wrapping Up</h2><p>That concludes this tutorial series! I hope this was useful to you.</p><p>There many more interesting low level things to explore such as setting up <a href="http://wiki.osdev.org/Paging" target="_blank" rel="external">virtual memory</a>, handling <a href="http://wiki.osdev.org/Interrupts" target="_blank" rel="external">interrupts</a> and writing your very own memory allocator! I hope to start exploring these in the future.</p>]]></content>
    
    <summary type="html">
    
      This third post describes how to go beyond 512 bytes and how to compile and load a C++ function into memory
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
      <category term="C" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="OSdev" scheme="http://3zanders.co.uk/tags/OSdev/"/>
    
      <category term="asm" scheme="http://3zanders.co.uk/tags/asm/"/>
    
  </entry>
  
  <entry>
    <title>Writing a Bootloader Part 2</title>
    <link href="http://3zanders.co.uk/2017/10/16/writing-a-bootloader2/"/>
    <id>http://3zanders.co.uk/2017/10/16/writing-a-bootloader2/</id>
    <published>2017-10-15T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.194Z</updated>
    
    <content type="html"><![CDATA[<p>In our <a href="/2017/10/13/writing-a-bootloader/">previous article</a> we described how to write a bootloader that prints ‘Hello World!’ to the screen in 16bit Real Mode. We’re now going to one up ourselves and print ‘Hello World!’ from 32 bit Protected Mode!</p><h2 id="Entering-32-bit-Mode"><a href="#Entering-32-bit-Mode" class="headerlink" title="Entering 32-bit Mode"></a>Entering 32-bit Mode</h2><p>In our previous article the CPU was still in Real Mode - this means you can call BIOS functions via interrupts, use 16 bit instructions and address up to 1 megabyte of memory (unless you use segment addressing). To access more than 1MB of memory we’re going to enable the <a href="http://wiki.osdev.org/A20_Line" target="_blank" rel="external">A20 line</a> by calling the ‘A20-Gate activate’ function. To do this we’ll create a new file called <code>boot2.asm</code> and put this in there:</p><pre><code>bits 16org 0x7c00boot:    mov ax, 0x2401    int 0x15 ; enable A20 bit</code></pre><p>Whilst we’re here we’ll also set the VGA text mode to a known value to be safe. Who knows what the BIOS set it to!</p><pre><code>mov ax, 0x3int 0x10 ; set vga text mode 3</code></pre><p>Next we’ll enable 32 bit instructions and access to the full bit 32 registers by entering Protected Mode. To do this we need to set up a <a href="http://wiki.osdev.org/GDT" target="_blank" rel="external">Global Descriptor Table</a> which will define a 32 bit code segment, load it with the <code>lgdt</code> instruction then do a long jump to that code segment.</p><pre><code>lgdt [gdt_pointer] ; load the gdt tablemov eax, cr0 or eax,0x1 ; set the protected mode bit on special CPU reg cr0mov cr0, eaxjmp CODE_SEG:boot2 ; long jump to the code segment</code></pre><h2 id="Global-Descriptor-Table"><a href="#Global-Descriptor-Table" class="headerlink" title="Global Descriptor Table"></a>Global Descriptor Table</h2><p>The GDT we’re going to set up involves 3 parts: a null segment, a code segment and a data segment. The structure of each GDT entry looks like this:</p><p><img src="/2017/10/13/writing-a-bootloader/gdt.png" alt="GDT Entry Layout"></p><p>Here’s what the fields mean:</p><ul><li><strong>base</strong> a 32 bit value describing where the segment begins</li><li><strong>limit</strong> a 20 bit value describing where the segment ends, can be multiplied by 4096 if <strong>granularity</strong> = 1</li><li><strong>present</strong> must be 1 for the entry to be valid</li><li><strong>ring level</strong> an int between 0-3 indicating the kernel <a href="http://wiki.osdev.org/Security#Rings" target="_blank" rel="external">Ring Level</a></li><li><strong>direction</strong> <ul><li>0 = segment grows up from base, 1 = segment grows down for a data segment</li><li>0 = can only execute from ring level, 1 = prevent jumping to higher ring levels</li></ul></li><li><strong>read/write</strong> if you can read/write to this segment</li><li><strong>accessed</strong> if the CPU has accessed this segment</li><li><strong>granularity</strong> 0 = limit is in 1 byte blocks, 1 = limit is multiples of 4KB blocks</li><li><strong>size</strong> 0 = 16 bit mode, 1 = 32 bit protected mode</li></ul><p>We’ll define this directly in assembly:</p><pre><code>gdt_start:    dq 0x0gdt_code:    dw 0xFFFF    dw 0x0    db 0x0    db 10011010b    db 11001111b    db 0x0gdt_data:    dw 0xFFFF    dw 0x0    db 0x0    db 10010010b    db 11001111b    db 0x0gdt_end:</code></pre><p>To actually load this we also need a gdt pointer structure. This is a 16 bit field containing the GDT size followed by a 32 bit pointer to the structure itself. We’ll also define the <code>CODE_SEG</code> and <code>DATA_SEG</code> value which are offsets into the gdt for use later:</p><pre><code>gdt_pointer:    dw gdt_end - gdt_start    dd gdt_startCODE_SEG equ gdt_code - gdt_startDATA_SEG equ gdt_data - gdt_start</code></pre><p>At this point we have enough to get into 32-bit mode! Let’s tell nasm to output 32 bit now. We’ll also set the remaining segments to point at the data segment.</p><pre><code>bits 32boot2:    mov ax, DATA_SEG    mov ds, ax    mov es, ax    mov fs, ax    mov gs, ax    mov ss, ax</code></pre><h2 id="Writing-to-the-VGA-Text-Buffer"><a href="#Writing-to-the-VGA-Text-Buffer" class="headerlink" title="Writing to the VGA Text Buffer"></a>Writing to the VGA Text Buffer</h2><p>Finally let’s write ‘Hello world!’ to the screen from Protected Mode! We can’t call the BIOS any more but we can write to the <a href="https://en.wikipedia.org/wiki/VGA-compatible_text_mode" target="_blank" rel="external">VGA text buffer</a> directly. This is memory mapped to location <code>0xb8000</code>. Each character on screen has this layout:</p><p><img src="/2017/10/13/writing-a-bootloader/vga.png" alt="VGA Character Layout"></p><p>The top byte defines the <a href="https://en.wikipedia.org/wiki/Video_Graphics_Array#Color_palette" target="_blank" rel="external">character colour</a> in the buffer as an int value from 0-15 with 0 = black, 1 = blue and 15 = white. The bottom byte defines an <a href="http://www.asciitable.com/" target="_blank" rel="external">ASCII</a> code point. Using this information we can write some assembly that writes ‘Hello World’ in blue text:</p><pre><code>    mov esi,hello    mov ebx,0xb8000.loop:    lodsb    or al,al    jz halt    or eax,0x0100    mov word [ebx], ax    add ebx,2    jmp .loophalt:    cli    hlthello: db &quot;Hello world!&quot;,0</code></pre><h2 id="Let’s-run-the-thing"><a href="#Let’s-run-the-thing" class="headerlink" title="Let’s run the thing!"></a>Let’s run the thing!</h2><p>We finally have everything! Save the whole thing as a <code>boot2.asm</code> file (<a href="/2017/10/13/writing-a-bootloader/boot2.asm">source available here</a>) then run it with <code>nasm -f bin boot2.asm &amp;&amp; qemu-system-x86_64 -fda boot.bin</code>. You should get something like this!</p><p><img src="/2017/10/13/writing-a-bootloader/boot2.png" alt="Protected Mode Hello World"></p><h2 id="Next-Steps"><a href="#Next-Steps" class="headerlink" title="Next Steps"></a>Next Steps</h2><p>Amazing! In <a href="/2017/10/18/writing-a-bootloader3/">part 3</a> of this series we’ll look at loading a C++ function that we’ve compiled into memory and then call it from our bootloader. Almost there!</p>]]></content>
    
    <summary type="html">
    
      This second post describes how to write a protected mode &#39;Hello World!&#39; bootloader
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
      <category term="C" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="OSdev" scheme="http://3zanders.co.uk/tags/OSdev/"/>
    
      <category term="asm" scheme="http://3zanders.co.uk/tags/asm/"/>
    
  </entry>
  
  <entry>
    <title>Writing a Bootloader Part 1</title>
    <link href="http://3zanders.co.uk/2017/10/13/writing-a-bootloader/"/>
    <id>http://3zanders.co.uk/2017/10/13/writing-a-bootloader/</id>
    <published>2017-10-12T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.171Z</updated>
    
    <content type="html"><![CDATA[<p>This article series explains how to write a tiny 32-bit x86 operating system kernel. We won’t do very much other than print <code>Hello world!</code> to the screen in increasingly complicated ways! We’ll start off in assembly and then build up to writing C++!</p><p>A <a href="/2017/10/13/writing-a-bootloader/writingabootloader.pdf">presentation</a> of this article series is also available.</p><p>To follow along you’re going to need the NASM assembler and <a href="https://www.qemu.org/" target="_blank" rel="external">QEMU</a> to emulate a virtual machine for us. QEMU is great because you don’t have to worry about accidentally destroying your hardware with badly written OS code ;) You can install these on <a href="https://msdn.microsoft.com/en-gb/commandline/wsl/install_guide" target="_blank" rel="external">Windows Subsystem for Linux</a> or Ubuntu with this command:</p><pre><code>sudo apt-get install nasm qemu</code></pre><p>On a mac you can use homebrew:</p><pre><code>brew install nasm</code></pre><p>On Windows 10 you’ll also want to install <a href="https://sourceforge.net/projects/xming/" target="_blank" rel="external">an X Server</a> which allows QEMU to open a window from the linux subsystem.</p><h2 id="A-Hello-World-Bootloader"><a href="#A-Hello-World-Bootloader" class="headerlink" title="A Hello World Bootloader"></a>A Hello World Bootloader</h2><p>We’re going to write a floppy disk bootloader because it doesn’t require us to mess about with file systems which helps keep things simple as possible.</p><p><img src="/2017/10/13/writing-a-bootloader/floppy.jpg" alt="Cutting edge 1970s technology!"></p><p>When you press the power button the computer loads the BIOS from some flash memory stored on the motherboard. The BIOS initializes and self tests the hardware then loads the first 512 bytes into memory from the media device (i.e. the cdrom or floppy disk). If the last two bytes equal <code>0xAA55</code> then the BIOS will jump to location <code>0x7C00</code> effectively transferring control to the bootloader. </p><p>At this point the CPU is running in 16 bit mode, meaning only the 16 bit registers are available. Also since the BIOS only loads the first 512 bytes this means our bootloader code has to stay below that limit, otherwise we’ll hit uninitialised memory!</p><p>Let’s get hello world printing to the screen. To do this we’re going to use the ‘Write Character in TTY mode’ <a href="https://en.wikipedia.org/wiki/BIOS_interrupt_call" target="_blank" rel="external">BIOS Interrupt Call</a> and the load string byte instruction <code>lobsb</code> which loads byte at address <code>ds:si</code> into <code>al</code>. Here goes:</p><pre><code>bits 16 ; tell NASM this is 16 bit codeorg 0x7c00 ; tell NASM to start outputting stuff at offset 0x7c00boot:    mov si,hello ; point si register to hello label memory location    mov ah,0x0e ; 0x0e means &apos;Write Character in TTY mode&apos;.loop:    lodsb    or al,al ; is al == 0 ?    jz halt  ; if (al == 0) jump to halt label    int 0x10 ; runs BIOS interrupt 0x10 - Video Services    jmp .loophalt:    cli ; clear interrupt flag    hlt ; halt executionhello: db &quot;Hello world!&quot;,0times 510 - ($-$$) db 0 ; pad remaining 510 bytes with zeroesdw 0xaa55 ; magic bootloader magic - marks this 512 byte sector bootable!</code></pre><p>If you save this file as <code>boot1.asm</code> (or <a href="/2017/10/13/writing-a-bootloader/boot1.asm">download it here</a>) we can now use <code>nasm</code> to compile it:</p><pre><code>nasm -f bin boot1.asm -o boot1.bin</code></pre><p>If we run <code>hexdump boot1.bin</code> we can see that NASM created some code, padded some zeros then set the final two bytes to the magic number.</p><pre><code>0000000 be 10 7c b4 0e ac 08 c0 74 04 cd 10 eb f7 fa f40000010 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 00 00 00 000000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00*00001f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa0000200</code></pre><p>We can now run this thing! You can tell QEMU to boot off a floppy disk using <code>qemu-system-x86_64 -fda boot1.bin</code> on Windows 10 you might need to stick <code>DISPLAY=:0</code> in front to open the window from WSL. You should get something like this!</p><p><img src="/2017/10/13/writing-a-bootloader/boot1.png" alt="Our Hello World bootloader"></p><h2 id="Next-Steps"><a href="#Next-Steps" class="headerlink" title="Next Steps"></a>Next Steps</h2><p>Next we can start investigating getting into Protected Mode in <a href="/2017/10/16/writing-a-bootloader2/">Part 2</a>!</p>]]></content>
    
    <summary type="html">
    
      This post describes how to write a simple Hello world bootloader
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
      <category term="C" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="OSdev" scheme="http://3zanders.co.uk/tags/OSdev/"/>
    
      <category term="asm" scheme="http://3zanders.co.uk/tags/asm/"/>
    
  </entry>
  
  <entry>
    <title>GB Emulator</title>
    <link href="http://3zanders.co.uk/2017/08/03/GBemulator/"/>
    <id>http://3zanders.co.uk/2017/08/03/GBemulator/</id>
    <published>2017-08-02T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.082Z</updated>
    
    <content type="html"><![CDATA[<p><img src="/2017/08/03/GBemulator/tetris.png" alt="My emulator playing Tetris in Demo Mode"></p><p>I’ve been messing about with emulators! The GB hardware is <a href="http://marc.rawer.de/Gameboy/Docs/GBCPUman.pdf" target="_blank" rel="external">very</a> <a href="http://gameboy.mongenel.com/dmg/opcodes.html" target="_blank" rel="external">well</a> <a href="http://imrannazar.com/Gameboy-Z80-Opcode-Map" target="_blank" rel="external">documented</a> with <a href="https://cturt.github.io/cinoop.html" target="_blank" rel="external">lots of interesting</a> <a href="http://imrannazar.com/GameBoy-Emulation-in-JavaScript" target="_blank" rel="external">blog posts</a> on the topic so I’ve decided to have a go at writing a gameboy hardware emulator myself.</p><p>The current status of the project is that I’ve implemented most of the CPU opcodes, GPU emulation and memory bank controller emulation required to get tetris up and running. I also wrote a GPU debugger, memory inspector and disassembler using <a href="https://github.com/ocornut/imgui" target="_blank" rel="external">imgui</a> that can be used to find emulator bugs. I’m also using my own <a href="https://github.com/zanders3/glwt2" target="_blank" rel="external">GLWT</a> library to create a window and make an OpenGL context.</p><p>So there is just about enough there for you to get through the menus, watch the demo mode and play a game of tetris! There are some crazy bugs though - I’ve not implemented the hardware used for random number generation so you only get square blocks falling from the top of the screen making for a less than entertaining game of tetris. In addition the sprite rendering has an off by one error somewhere (a faulty instruction somewhere?) meaning the blocks are shifted down by 1. Audio is also not implemented yet.</p><p><img src="/2017/08/03/GBemulator/debugger.jpg" alt="Debugging Tetris"></p><p>I’m currently focused on writing some cpu unit tests for the whole thing to find and fix those faulty instructions, but it is a huge task and is taking me a while. Overall it’s been a pretty fun project to hack around with so far.</p><p>I’ve thrown the whole source code of the thing up on github - take a look! <a href="https://github.com/zanders3/gb" target="_blank" rel="external">https://github.com/zanders3/gb</a></p>]]></content>
    
    <summary type="html">
    
      A gameboy hardware emulator that uses GLWT and imgui for rendering.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>GLWT</title>
    <link href="http://3zanders.co.uk/2016/07/10/GLWT/"/>
    <id>http://3zanders.co.uk/2016/07/10/GLWT/</id>
    <published>2016-07-09T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.085Z</updated>
    
    <content type="html"><![CDATA[<p>Inspired by the <a href="https://github.com/nothings/stb" target="_blank" rel="external">fantastic stb libraries</a> by Sean Barrett I got tired of spending hours messing about trying to get an OpenGL context up and running. Libraries such as <a href="https://www.libsdl.org/" target="_blank" rel="external">SDL</a> can manage this for you very well but feel overkill when you’re starting out.</p><p>So I’ve decided to write my own window and platform abstraction library which will grow over time as I develop my other personal projects. The whole thing is pretty bare bones at the moment so I wouldn’t recommend you actually use it right now. Take a look!</p><p><a href="https://github.com/zanders3/glwt2" target="_blank" rel="external">https://github.com/zanders3/glwt2</a></p><h2 id="Usage"><a href="#Usage" class="headerlink" title="Usage"></a>Usage</h2><p>This main.c will get you started:</p><pre><code>#include &quot;glwt.h&quot;void glwt_setup(){}void glwt_draw(float time){    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);    glClear(GL_COLOR_BUFFER_BIT);}int main(int argc, char *argv[]){    return glwt_init(&quot;Hello, GLWT!&quot;, 800, 600, false);}</code></pre><h2 id="Compiling"><a href="#Compiling" class="headerlink" title="Compiling"></a>Compiling</h2><p>Simply create a new empty XCode/Visual Studio project and add glwt.(cpp/mm) and glwt.h to the project.</p><p>On Mac you will need to go to the ‘Build Phases’ XCode project settings tab and add the Cocoa.framework and OpenGL.framework for the project to link. Also ensure the glwt.mm file is an mm file <em>not</em> a cpp file.</p><h2 id="Input"><a href="#Input" class="headerlink" title="Input"></a>Input</h2><p>Pressed keys are stored in the global <code>bool glwt_keydown[255];</code> structure as ascii keycodes. e.g. <code>glwt_keydown[&#39;a&#39;]</code>. This will work for a-z and 0-9 keys. There are additional keys defined in the Keys enum at the top of the header file. This currently only works on windows - I’ll be adding Mac support later!</p>]]></content>
    
    <summary type="html">
    
      The OpenGL window toolkit is a single file C++ library that creates an OpenGL context on Windows/OSX
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="C" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="Objective-C" scheme="http://3zanders.co.uk/tags/Objective-C/"/>
    
  </entry>
  
  <entry>
    <title>C# JSON Parser</title>
    <link href="http://3zanders.co.uk/2015/09/25/JSONParser/"/>
    <id>http://3zanders.co.uk/2015/09/25/JSONParser/</id>
    <published>2015-09-24T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.087Z</updated>
    
    <content type="html"><![CDATA[<h2 id="Motivation"><a href="#Motivation" class="headerlink" title="Motivation"></a>Motivation</h2><p>I’ve had a go at writing my own JSON parser. Why?</p><p>Unity Engine’s mono runtime doesn’t have JIT support on iOS and has a relatively simple garbage collection scheme. It is fiddly with existing parsers to get them up and running in Unity. DLLs in Unity are a pain, especially if they use JIT or the wrong .NET framework version and you also lose source access when debugging.</p><p>So my main goal here is to write the simplest JSON parser and writer, in as few lines as possible, whilst minimising memory usage. Speed and performance is less of a concern.</p><h2 id="Installation"><a href="#Installation" class="headerlink" title="Installation"></a>Installation</h2><p>Simply copy and paste the <a href="https://raw.githubusercontent.com/zanders3/json/master/src/JSONParser.cs" target="_blank" rel="external">JSON Parser</a> and/or the <a href="https://raw.githubusercontent.com/zanders3/json/master/src/JSONWriter.cs" target="_blank" rel="external">JSON Writer</a></p><h2 id="Documentation"><a href="#Documentation" class="headerlink" title="Documentation"></a>Documentation</h2><p>A really simple C# JSON parser in ~300 lines</p><ul><li>Attempts to parse JSON files with minimal GC allocation</li><li>Nice and simple <code>&quot;[1,2,3]&quot;.FromJson&lt;List&lt;int&gt;&gt;()</code> API</li><li><p>Classes and structs can be parsed too!</p><figure class="highlight csharp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">class</span> <span class="title">Foo</span> </div><div class="line">&#123; </div><div class="line">  <span class="keyword">public</span> <span class="keyword">int</span> Value;</div><div class="line">&#125;</div><div class="line"><span class="string">"&#123;\"Value\":10&#125;"</span>.FromJson&lt;Foo&gt;()</div></pre></td></tr></table></figure></li><li><p>Anonymous JSON is parsed into <code>Dictionary&lt;string,object&gt;</code> and <code>List&lt;object&gt;</code></p><figure class="highlight csharp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> test = <span class="string">"&#123;\"Value\":10&#125;"</span>.FromJson&lt;<span class="keyword">object</span>&gt;();</div><div class="line"><span class="keyword">int</span> number = ((Dictionary&lt;<span class="keyword">string</span>,<span class="keyword">object</span>&gt;)test)[<span class="string">"Value"</span>];</div></pre></td></tr></table></figure></li><li><p>No JIT Emit support to support AOT compilation on iOS</p></li><li>Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead.</li><li>Only public fields and property setters on classes/structs will be written to</li></ul><p>Limitations:</p><ul><li>No JIT Emit support to parse structures quickly</li><li>Limited to parsing &lt;2GB JSON files (due to int.MaxValue)</li><li>Parsing of abstract classes or interfaces is NOT supported and will throw an exception.</li></ul><h2 id="Example-Usage"><a href="#Example-Usage" class="headerlink" title="Example Usage"></a>Example Usage</h2><p>This example will write a list of ints to a File and read it back again:<br><figure class="highlight csharp"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">using</span> System;</div><div class="line"><span class="keyword">using</span> System.IO;</div><div class="line"><span class="keyword">using</span> System.Collections.Generic;</div><div class="line"></div><div class="line"><span class="keyword">using</span> TinyJson;</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">class</span> <span class="title">JsonTest</span></div><div class="line">&#123;</div><div class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">Main</span>(<span class="params"><span class="keyword">string</span>[] args</span>)</span></div><div class="line"><span class="function">  </span>&#123;</div><div class="line">    <span class="comment">//Write a file</span></div><div class="line">    List&lt;<span class="keyword">int</span>&gt; values = <span class="keyword">new</span> List&lt;<span class="keyword">int</span>&gt; &#123; <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span> &#125;;</div><div class="line">    <span class="keyword">string</span> json = values.ToJson();</div><div class="line">    File.WriteAllText(<span class="string">"test.json"</span>, json);</div><div class="line">    </div><div class="line">    <span class="comment">//Read it back</span></div><div class="line">    <span class="keyword">string</span> fileJson = File.ReadAllText(<span class="string">"test.json"</span>);</div><div class="line">    List&lt;<span class="keyword">int</span>&gt; fileValues = fileJson.FromJson&lt;List&lt;<span class="keyword">int</span>&gt;&gt;();</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p><p>Save this as <code>JsonTest.cs</code> then compile and run with <code>mcs JsonTest.cs &amp;&amp; mono JsonTest.exe</code></p>]]></content>
    
    <summary type="html">
    
      A really simple C# JSON Parser in 300 lines
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>New Shiny</title>
    <link href="http://3zanders.co.uk/2014/08/31/new-beginnings/"/>
    <id>http://3zanders.co.uk/2014/08/31/new-beginnings/</id>
    <published>2014-08-30T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.164Z</updated>
    
    <content type="html"><![CDATA[<p><img src="/2014/08/31/new-beginnings/giphy.gif" alt=""></p><p>Hi there!</p><p>I’ve taken the time to update my website again. This time I’ve kept the theme the same (so hopefully you won’t notice that too much has changed) but I’ve moved away from an <a href="https://angularjs.org/" target="_blank" rel="external">Angular JS</a> based site to a static one built using <a href="http://hexo.io/" target="_blank" rel="external">Hexo</a>. This should make adding new articles and portfolio bits much easier!</p><p>I’ve gone through all of my old portfolio stuff and cleaned it up and tidied everything up a bit. Have a look around!</p>]]></content>
    
    <summary type="html">
    
      I&#39;ve taken the time to update my website again. This time I&#39;ve kept the theme the same but I&#39;ve moved away from an Angular JS based to a new one using Hexo. Take a look around!
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
  </entry>
  
  <entry>
    <title>allRGB Rainbow Fractal</title>
    <link href="http://3zanders.co.uk/2014/03/15/allRGB/"/>
    <id>http://3zanders.co.uk/2014/03/15/allRGB/</id>
    <published>2014-03-15T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.159Z</updated>
    
    <content type="html"><![CDATA[<p>The challenge was simple: create an image containing all 16777216 RGB colours in a single image with not one colour missing or duplicated!</p><p><img src="/2014/03/15/allRGB/rainbowfractal.jpg" alt="Rainbow Fractal"></p><p>At the time there weren’t many mandelbrot fractal examples so I decided to try and find a way to create an all RGB image of the mandelbrot set. The resulting image is a 4096x4096 48.1Mb in PNG format. A compressed thumbnail is below; go to allRGB.com if you <a href="http://allrgb.com/rainbow-fractal" target="_blank" rel="external">want to see the full image</a>.</p><p>The code I wrote to create the image is <a href="https://gist.github.com/zanders3/9a690443bc4b22340e00" target="_blank" rel="external">available here</a>. It works by first calculating a color mapping representing every RGB color, which is then sorted by Hue.</p><p>Next we generate a grayscale mandelbrot image whilst generating a histogram of the range of values in this grayscale image. The histogram is then converted into a cumulative histogram which gives us an offset into the color map. This in effect means we have a bucket of colours to choose from for each grayscale value representing the mandelbrot image.</p><p>We can now generate the image at this point by looping through the grayscale mandelbrot image, looking up which histogram bucket the gray pixel is in, use up one of those RGB colours in the bucket and use that colour in the final image.</p><p>This simple algorithm does have a drawback of producing weird shapes due to the hue sorting so we randomise the colours contained within each histogram bucket to produce a more pleasing image when viewed from a distance!</p><p>I hope that all made sense! It certainly was a fun challenge to do; I can highly recommend giving this challenge a go!</p>]]></content>
    
    <summary type="html">
    
      The challenge was simple; create an image containing all 16777216 RGB colours in a single image with not one colour missing or duplicated!
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>Modern Open GL Drawing a Triangle</title>
    <link href="http://3zanders.co.uk/2014/02/19/modern-opengl-a-tutorial/"/>
    <id>http://3zanders.co.uk/2014/02/19/modern-opengl-a-tutorial/</id>
    <published>2014-02-19T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.163Z</updated>
    
    <content type="html"><![CDATA[<p>So. Let’s talk about OpenGL. What a mess when you compare it with how DirectX has evolved over the years. I first learnt the intricacies of the DirectX API with the <a href="http://xbox.create.msdn.com/en-US/" target="_blank" rel="external">XNA</a> framework which I used to create some simple games. This messing led me to start experimenting with shaders, ultimately leading to my work on <a href="http://www.sandswept.net/games/detour" target="_blank" rel="external">Detour</a> which had lots of fancy things like local point lights, realtime shadows, water reflection, particle systems and postprocessing effects.</p><p>One of the major problems with the DirectX API is that it only works on Windows. Microsoft no longer has the massive monopoly that it used to have and people expect games these days to run on every flavour of platform (Windows, Linux, OSX to name a few). So in practical terms this means you have to use OpenGL; an API that is supposed to work on every platform. What a brilliant idea! So.. how hard can it be to use OpenGL?</p><h2 id="Drawing-a-Triangle-to-the-Screen"><a href="#Drawing-a-Triangle-to-the-Screen" class="headerlink" title="Drawing a Triangle to the Screen"></a>Drawing a Triangle to the Screen</h2><p>Lets try something simple, like drawing a triangle to the screen. Sounds good!</p><p>First we need to open a window. This part is platform specific, and people usually resort to a libraries like <a href="http://www.glfw.org/" target="_blank" rel="external">GLFW</a>, <a href="http://glew.sourceforge.net/" target="_blank" rel="external">GLEW</a> and <a href="http://www.opengl.org/resources/libraries/glut/" target="_blank" rel="external">GLUT</a> to handle things like creating a window, loading the OpenGL functions and handling mouse and keyboard input. For this post I’ll be using my own library I’ve cooked up called <a href="https://github.com/zanders3/glwt" target="_blank" rel="external">GLWT</a>, the OpenGL Window Toolkit! The toolkit is very much a work in progress but enough stuff is working for me to be able to write this post. It only works for Macs at the moment, but I plan to make it work on Windows and Linux eventually.</p><p>Next we need to think about which version of the OpenGL API to use. OpenGL has a long history and a lot of old applications use the old, immediate mode API. These are the functions that pop up everywhere whenever you type ‘OpenGL tutorial’ into Google. For example, this is the old way of drawing a triangle to a screen:</p><pre><code>void Draw(){    glBegin(GL_TRIANGLE_STRIP);    glVertex2f(0.0f, 0.75f);    glVertex2f(-0.5f, 0.25f);    glVertex2f(0.5f, 0.25f);    glEnd();}</code></pre><p>The code above, whilst simple, is innefficient since you have to copy the triangles from the CPU to GPU every single frame. You also get loads of function calls and User -&gt; Kernel mode switches. You can’t do cool things with this setup like vertex and pixel/fragment shaders, or geometry shaders, or render to a texture, or add realtime shadows, etc. Ouch.</p><p>So what’s the solution? OpenGL Core Profile! This removes all of the old fixed pipeline calls and replaces them with buffer objects which you only update when you need to. It is a <em>lot</em> more complicated, but you can do way more cool stuff. Here’s how you draw a triangle to the screen:</p><pre><code>struct Vertex{    float x, y, z;};GLuint vertexBuffer, indexBuffer, vertexLayout;bool Game::Setup(int argc, const char** argv){    Window::Open(800, 600, false, &quot;Hello World!&quot;);    GL::ClearColor(0.0f, 0.0f, 0.0f, 1.0f);    Vertex verts[] =    {        { 0.0f, 0.75f, 0.0f },        { -0.5f, 0.25f, 0.0f },        { 0.5f, 0.25f, 0.0f }    };    unsigned short inds[] =    {        0, 1, 2    };    //Create the vertex buffer object, then set it as the current buffer, then copy the vertex data onto it.    GL::GenBuffers(1, &amp;vertexBuffer);    GL::BindBuffer(GL_ARRAY_BUFFER, vertexBuffer);    GL::BufferData(GL_ARRAY_BUFFER, sizeof(verts), &amp;verts, GL_STATIC_DRAW);    //Create the index buffer object, set it as the current index buffer, then copy index data to it.    GL::GenBuffers(1, &amp;indexBuffer);    GL::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);    GL::BufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(inds), &amp;inds, GL_STATIC_DRAW);    //Create the vertex layout    GL::GenVertexArrays(1, &amp;vertexLayout);    GL::BindVertexArray(vertexLayout);    //The vertex layout has 3 floats for position    GL::VertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), BUFFER_OFFSET(0));    GL::EnableVertexAttribArray(0);    return true;}void Game::Draw(float deltaTime){    GL::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);    GL::BindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);    GL::BindBuffer(GL_ARRAY_BUFFER, vertexBuffer);    GL::DrawRangeElements(GL_TRIANGLES, 0, 3, 3, GL_UNSIGNED_SHORT, NULL);}</code></pre><p>As you can see this is much more complicated, however the code above is not enough for the triangle to appear on the screen. We need to write a vertex shader and a fragment shader first. Blimey. Lets see how to do that.</p><h2 id="Shaders"><a href="#Shaders" class="headerlink" title="Shaders!"></a>Shaders!</h2><p>OpenGL shaders are written in a language called GLSL, the OpenGL Shading Language.</p><p>Vertex shaders are basically a function that gets executed by your graphics card for every vertex, and it is usually where you do things like multiply it by a world view projection matrix to get the 2D position on the screen. Here is an example which just returns the vertex position without doing any processing:</p><pre><code>in vec3 inVertex;void main(){    gl_Position = vec4(inVertex, 1.0);}</code></pre><p>Fragment shaders are a function that gives the colour for each pixel in the triangle being drawn. The example shown here gives the triangle a nice blue colour. Yum:</p><pre><code>out vec4 FragColor;void main(){    FragColor = vec4(0.0, 0.0, 1.0, 1.0);}</code></pre><h2 id="Putting-it-all-Together"><a href="#Putting-it-all-Together" class="headerlink" title="Putting it all Together"></a>Putting it all Together</h2><p>So we now have some GLSL code that will put the triangles onto the screen in a nice blue colour. We now need to tell OpenGL to load all of that shader code, turn it into a single shader object and apply it to the triangle we will draw to the screen. This code will load and compile the vertex and fragment shader, then put them into a shader program object:</p><pre><code>//Create the shader programshaderProgram = GL::CreateProgram();//Create the vertex and fragment shadervertexShader = GL::CreateShader(GL_VERTEX_SHADER);fragmentShader = GL::CreateShader(GL_FRAGMENT_SHADER);int vertexCodeLen = (int)strlen(vertexShaderCode);int fragmentCodeLen = (int)strlen(fragmentShaderCode);//Load the shader source code and compile itGL::ShaderSource(vertexShader, 1, &amp;vertexShaderCode, &amp;vertexCodeLen);GL::ShaderSource(fragmentShader, 1, &amp;fragmentShaderCode, &amp;fragmentCodeLen);GL::CompileShader(vertexShader);GL::CompileShader(fragmentShader);char log[255];int len;bool hadError = false;GL::GetShaderInfoLog(vertexShader, 255, &amp;len, (char*)&amp;log);if (len &gt; 0) {    std::cout &lt;&lt; &quot;Vertex Compile error:&quot; &lt;&lt; std::endl &lt;&lt; log &lt;&lt; std::endl;    hadError = true;}GL::GetShaderInfoLog(fragmentShader, 255, &amp;len, (char*)&amp;log);if (len &gt; 0) {    std::cout &lt;&lt; &quot;Fragment Compile error:&quot; &lt;&lt; std::endl &lt;&lt; log &lt;&lt; std::endl;    hadError = true;}if (hadError)    return false;GL::AttachShader(shaderProgram, fragmentShader);GL::AttachShader(shaderProgram, vertexShader);//Bind the vertex position to the inVertex variable in the vertex shaderGL::BindAttribLocation(shaderProgram, 0, &quot;inVertex&quot;);//Link the shader programGL::LinkProgram(shaderProgram);GL::UseProgram(shaderProgram);</code></pre><p>Putting this code into the Game::Setup() function will cause a nice blue triangle to draw on the screen.</p><p><img src="/2014/02/19/modern-opengl-a-tutorial/opengl.jpg" alt="A Blue Triangle drawn to the screen" title="An incredible feat of programming. AMAZING."></p><p>So obviously this is a teeny tiny first step into the exciting world of graphics programming. Now that the low-level faffing is finished with we can get into more interesting stuff like lighting models, shadows and so on to get a more accurate image. I hope to cover this sort of stuff in future articles!</p>]]></content>
    
    <summary type="html">
    
      A basic tutorial on creating a modern OpenGL context and getting a simple triangle drawn to the screen.
    
    </summary>
    
      <category term="Articles" scheme="http://3zanders.co.uk/categories/Articles/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="OpenGL" scheme="http://3zanders.co.uk/tags/OpenGL/"/>
    
  </entry>
  
  <entry>
    <title>CSR Classics</title>
    <link href="http://3zanders.co.uk/2013/10/05/CSR-Classics/"/>
    <id>http://3zanders.co.uk/2013/10/05/CSR-Classics/</id>
    <published>2013-10-04T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.052Z</updated>
    
    <content type="html"><![CDATA[<p><a href="https://itunes.apple.com/gb/app/csr-classics/id598603610?mt=8" target="_blank" rel="external">CSR Classics</a> is a free to play game by <a href="http://bossalien.com" target="_blank" rel="external">Boss Alien</a> in collaboration with <a href="http://www.madatomgames.com/" target="_blank" rel="external">Mad Atom Games</a> for iOS and Android devices. You purchase, upgrade and then drag race your own car against your friends list, the world and crews across a fictional city in classic cars.</p><p><img src="/2013/10/05/CSR-Classics/screen1.jpg" alt=""></p><p><img src="/2013/10/05/CSR-Classics/screen2.jpg" alt=""></p><p><img src="/2013/10/05/CSR-Classics/screen3.jpg" alt=""></p>]]></content>
    
    <summary type="html">
    
      CSR Classics is a free to play game by Boss Alien in collaboration with Mad Atom Games for iOS and Android devices.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Unity" scheme="http://3zanders.co.uk/tags/Unity/"/>
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="iOS" scheme="http://3zanders.co.uk/tags/iOS/"/>
    
      <category term="Android" scheme="http://3zanders.co.uk/tags/Android/"/>
    
  </entry>
  
  <entry>
    <title>Dungeon Heart</title>
    <link href="http://3zanders.co.uk/2013/01/27/Dungeon-Heart/"/>
    <id>http://3zanders.co.uk/2013/01/27/Dungeon-Heart/</id>
    <published>2013-01-27T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.070Z</updated>
    
    <content type="html"><![CDATA[<p>Dungeon Heart was a game made in 48 hours with <a href="http://alextrowers.blogspot.co.uk/" target="_blank" rel="external">Alex Trowers</a> and <a href="http://huhjustablog.blogspot.co.uk/" target="_blank" rel="external">Leanne Bayley</a> as part of the 2013 <a href="http://globalgamejam.org/" target="_blank" rel="external">Global Game Jam</a> game jamming competition. We even managed to get a good 7 hours sleep and got the game we planned to make finished on time!</p><p>Since we used Unity you can <a href="/dungeonheart">play the full game here</a>!</p><p><img src="/2013/01/27/Dungeon-Heart/screen2.png" alt="The Title Screen"></p><p>The theme was ‘Heartbeats’ so naturally as big fans (and for some of us ex-employees) of Bullfrog we made a Dungeon Keeper clone, since Dungeon Keeper has a heart in the middle. The game was built with the Unity Game Engine using C#. I find Unity one of the easiest game engines to use, and it is the perfect tool for prototyping and game jamming.</p><p>At first we decided how to best split up the work. It was decided that I would focus on the code, Leanne on the Art and Trowers would handle the game design and jump into the other two disciplines where needed. </p><h2 id="Day-1"><a href="#Day-1" class="headerlink" title="Day 1"></a>Day 1</h2><p>To start with I focused on getting a basic tile based map engine going, and we made a decision to go 3D. Leanne started cranking out some monsters whilst Trowers searched for sound effects and started throwing some particle effects together. Each level used a really simple text file to define each level layout, with each different character in the text file representing a tile in the map in the level. This allowed us to create a whole bunch of levels really quickly.</p><p>So I got that all up and running and then started to focus on the biggest, scariest task - AI Pathfinding! Whilst I knew about the A* pathfinding algorithm and how it worked, I had never attempted to write one from scratch during a game jam before. Luckily thanks to <a href="http://www.policyalmanac.org/games/aStarTutorial.htm" target="_blank" rel="external">this fantastic explanation</a> and some fixing of a few off by one errors I managed to get a basic pathfinding system working.</p><p><img src="/2013/01/27/Dungeon-Heart/screen1.jpg" alt="Attack and Defence of your Dungeon Heart"></p><p>I then spent the next few hours setting up a basic AI system. None of the characters in the game were controlled directly and instead needed to decide for themselves where they needed to go. This was done using <a href="Dijkstra&#39;s_algorithm">Dijkstra’s algorithm</a>, a variant of A* to find the nearest target. For good characters their targets involved other creatures as a first priority, followed by the Dungeon Heart itself. For the evil creatures they simply targeted the nearest (in map steps) good creature.</p><p>The AI system also had a really simple animation system that made the characters jump and move between tiles to the time of the Dungeon’s Heartbeat.</p><p><img src="/2013/01/27/Dungeon-Heart/screen3.png" alt="We &lt;3 Dragons Team Logo"></p><p>There were 6 character types implemented in the game - 3 good and 3 evil. Naturally the good guys are sneaking into your dungeon and trying to smash up your Dungeon Heart whilst the evil player needs to defend the Dungeon by setting trapdoors (a last minute inclusion, but one of the best bits) and clicking on spawn points at the correct time. If you clicked the spawn point on the beat of the heartbeat three times in row then you would spawn the most powerful creature, two times for the second most powerful and once for the least. Mess up your timing and nothing would happen! The balancing and implementation of the spawn timing system was done by Trowers whilst I was sorting out the pathfinding and character AI system.</p><p>By the end of the first night we were in a pretty good position - we had a basic pathfinding system with good creatures pathfinding to the Dungeon Heart but not doing any damage.</p><h2 id="Day-2"><a href="#Day-2" class="headerlink" title="Day 2"></a>Day 2</h2><p>So with the solid start from the previous day things were looking pretty good the following morning! The final day was spent implementing the final gameplay design making the two different sides attack each other by introducing an attack system and hit points to each character. I also set up the victory and loss conditions, making the Dungeon Heart beat faster when you are about to lose, creating lots of tension in the final moments.</p><p><img src="/2013/01/27/Dungeon-Heart/screen4.png" alt="Outnumbered by Knights"></p><p>The rest of the day was spent getting multiple levels with multiple waves of enemies working and fixing lots of bugs that had popped up over time. Trowers also got the sound effects plugged in and threw some quick designs for multiple levels together as well as the coding for the spawn pads. Leanne had by this point finished all of the art so was making papercraft of the characters in the game.</p><p>The final few hours were spent manically bug fixing, as a few hours before the end a load of really strange bugs reared their heads giving us an exciting dash for the finish! At the final deadline naturally the Global Game Jam servers got overloaded but we were allowed to put our entries on a Dropbox instead which we were assured would count.</p><p><img src="/2013/01/27/Dungeon-Heart/screen5.png" alt="A Good Defence!"></p><p>A few hours later we had the judging, done by the very scientific method of whooping and arm waving, and we were positioned in second place. We were all quite happy with that as the competition was fierce! </p><p>In summary the global game jam was great fun and opened my eyes to how much fun a game jam can be! It is a nice change of pace from what sometimes feels like the snails pace of normal game development during your day job, since in your job the software you write has to actually work and not have some really nasty bugs lurking in there! ;)</p>]]></content>
    
    <summary type="html">
    
      Dungeon Heart was a game made in 48 hours with Alex Trowers and Leanne Bayley as part of the 2013 Global Game Jam game jamming competition.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Unity" scheme="http://3zanders.co.uk/tags/Unity/"/>
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>CSR Racing</title>
    <link href="http://3zanders.co.uk/2012/12/12/CSR-Racing/"/>
    <id>http://3zanders.co.uk/2012/12/12/CSR-Racing/</id>
    <published>2012-12-12T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.054Z</updated>
    
    <content type="html"><![CDATA[<p><a href="https://itunes.apple.com/gb/app/csr-racing/id469369175?mt=8" target="_blank" rel="external">CSR Racing</a> is a free to play mobile game by <a href="http://bossalien.com" target="_blank" rel="external">Boss Alien</a> for iOS and Android devices. You purchase, upgrade and then drag race your own car against your friends list, the world and crews across a fictional city in modern, fast cars.</p><p><img src="/2012/12/12/CSR-Racing/screen1.jpg" alt=""></p><p><img src="/2012/12/12/CSR-Racing/screen2.jpg" alt=""></p><p><img src="/2012/12/12/CSR-Racing/screen3.jpg" alt=""></p>]]></content>
    
    <summary type="html">
    
      CSR Racing is a free to play mobile game by Boss Alien for iOS and Android devices.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Unity" scheme="http://3zanders.co.uk/tags/Unity/"/>
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="iOS" scheme="http://3zanders.co.uk/tags/iOS/"/>
    
      <category term="Android" scheme="http://3zanders.co.uk/tags/Android/"/>
    
      <category term="OSX" scheme="http://3zanders.co.uk/tags/OSX/"/>
    
  </entry>
  
  <entry>
    <title>Wikitime</title>
    <link href="http://3zanders.co.uk/2012/04/12/Wikitime/"/>
    <id>http://3zanders.co.uk/2012/04/12/Wikitime/</id>
    <published>2012-04-11T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.141Z</updated>
    
    <content type="html"><![CDATA[<p>Wikitime was my final year project of my BSc Computer Science degree at the University of Southampton. The system took the full english text from the whole of the english wikipedia which is freely <a href="http://en.wikipedia.org/wiki/Wikipedia:Database_download#English-language_Wikipedia" target="_blank" rel="external">available to download</a> and attempted to position historical events on a timeline. <a href="http://wikitime.herokuapp.com/" target="_blank" rel="external">A demo</a> based on the <a href="http://simple.wikipedia.org/wiki/Main_Page" target="_blank" rel="external">Simple English Wikipedia</a> is available thanks to <a href="https://www.heroku.com/" target="_blank" rel="external">Heroku</a>.</p><p><img src="/2012/04/12/Wikitime/screen1.jpg" alt="Famous Scottish Scientists"></p><h2 id="Historical-Event-Extraction"><a href="#Historical-Event-Extraction" class="headerlink" title="Historical Event Extraction"></a>Historical Event Extraction</h2><p><img src="/2012/04/12/Wikitime/diagram1.png" alt="Extraction Overview"></p><p>To generate a timeline of every event in history the processing system first removed all syntax and formatting from the text. Since the raw text contains wikimedia formatting which is an undocumented and messy format with no official documentation this was achieved through use of lots of regular expressions. Next the text was split into sentences with the <a href="http://nlp.stanford.edu/ner/" target="_blank" rel="external">Stanford Named Entity Recogniser</a> which also pulls out named entities giving additional information useful for later.</p><p>At this point we could start looking at the sentences in detail. The final algorithm ran a regular expression over each sentence searching for four consecutive numbers, e.g. 1990. It would then attempt to parse the date in the location around the number looking for months and days.</p><p><img src="/2012/04/12/Wikitime/diagram2.png" alt="Event Extraction and Indexing"></p><p>This system is clearly not foolproof and was very easily confused by pretty much all of the Maths pages in Wikipedia. This issue was resolved by doing a statistical analysis of the dates extracted from the page. If a date fell outside of two standard deviations of all of the dates of the page it would be discarded. In addition any events set more than 50 years in the future (e.g. 2050) or with negative years would be discarded. This really helped to clean things up.</p><p><img src="/2012/04/12/Wikitime/screen2.jpg" alt="The Life of Christopher Columbus"></p><p>Finally all of these events were indexed into a <a href="http://lucene.apache.org/" target="_blank" rel="external">Lucene</a> index which could happily search over and retrieve the millions of events produced. A <a href="http://en.wikipedia.org/wiki/PageRank" target="_blank" rel="external">page rank algorithm</a> based upon each wikipedia page ranking was applied to each event to bring the important events to the top and duplicate detection and removal was applied based upon the <a href="http://doi.acm.org/10.1145/1390334.1390431" target="_blank" rel="external">spot signatures</a> algorithm.</p><p><img src="/2012/04/12/Wikitime/diagram3.png" alt="Page Rank Algorithm"></p><p>Processing the entire text of the english wikipedia was quite a challenge, since the file was around 44 GB uncompressed. To make the time to process this sane a threaded pipeline was written that splits the work over multiple threads, with queues between them. This allowed the whole wiki to be processed in around 12 hours on a reasonably powerful 12 core server my university left lying around ;)</p><h2 id="The-Website"><a href="#The-Website" class="headerlink" title="The Website"></a>The Website</h2><p>The next challenge was the website needed to display the events in a web browser in an understandable way. I ended up using the <a href="http://simile-widgets.org/timeline/" target="_blank" rel="external">Simile Timeline</a> Web Widget to visualise the events which I then glued to the lucene index using a bit of JQuery and Javascript. This resulted in a nice and reasonably easy to use interface.</p><p><img src="/2012/04/12/Wikitime/screen3.jpg" alt="Website Homepage"></p><p>So in conclusion it was a fun final year project for my degree which pushed my interests far beyond the graphics and game design which I had being doing in my free time up until that point. In case you missed the link above I highly recommend <a href="http://wikitime.herokuapp.com/" target="_blank" rel="external">checking out the demo</a> which uses the simple english wikipedia. If you are still interested in how the whole thing works, you can read <a href="/2012/04/12/Wikitime/finalreport.pdf">my project report</a>.</p><p><img src="/2012/04/12/Wikitime/screen4.png" alt="Pixar"></p>]]></content>
    
    <summary type="html">
    
      Wikitime was my final year project of my BSc Computer Science degree at the University of Southampton.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Java" scheme="http://3zanders.co.uk/tags/Java/"/>
    
      <category term="Javascript" scheme="http://3zanders.co.uk/tags/Javascript/"/>
    
      <category term="Lucene" scheme="http://3zanders.co.uk/tags/Lucene/"/>
    
  </entry>
  
  <entry>
    <title>Kinect Sports: Season Two</title>
    <link href="http://3zanders.co.uk/2011/11/25/Kinect-Sports-Season-Two/"/>
    <id>http://3zanders.co.uk/2011/11/25/Kinect-Sports-Season-Two/</id>
    <published>2011-11-25T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.088Z</updated>
    
    <content type="html"><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Kinect_Sports:_Season_Two" target="_blank" rel="external">Kinect Sports: Season Two</a> was a Xbox 360 game developed by <a href="http://www.rare.co.uk/" target="_blank" rel="external">Rare</a> and <a href="http://bigpark.com/" target="_blank" rel="external">Big Park</a> for the Kinect as a direct sequel to the BAFTA award winning <a href="http://en.wikipedia.org/wiki/Kinect_Sports" target="_blank" rel="external">Kinect Sports</a> title. I worked on the game at Rare as an intern software engineer between my second and third year of University.</p><p><img src="/2011/11/25/Kinect-Sports-Season-Two/logo.jpg" alt="Kinect Sports: Season Two Logo"></p><p>I arrived at the studio during the final few weeks of Kinect Sports bug testing before release, so I was pulled in to assist with some of the servers that would support the final game when launched. After that I was put onto the pre production tools team helping to prepare Kinect Sports: Season Two for production. This involved fixing bugs and improving the art content, localisation and performance metrics reporting pipelines working mainly in C++ and C#.</p><p><img src="/2011/11/25/Kinect-Sports-Season-Two/screen1.jpg" alt="Golf"></p><p>After this the game moved into production and I was moved onto the core engine team working in C++ where I wrote a new GPU and CPU profiler for the internal game engine. I was then put on the multiplayer team where I worked directly with Artists and Designers on the ‘Challenge Play’ gameplay mode. This mode glued all of the various game modes together into a new mode which allowed you to challenge your Xbox Live friends and local profiles on the same Xbox asynchronously.</p><p><img src="/2011/11/25/Kinect-Sports-Season-Two/challengemode.jpg" alt="Challenge Gameplay Mode"></p><div class="video-container"><iframe src="//www.youtube.com/embed/rehYmXTp9yU" frameborder="0" allowfullscreen></iframe></div><p>Implementing this feature involved modifying the game code for each game to support async challenges and implementing the user interface using a combination of C++ and Actionscript since Scaleform was used for the UI. Each game mode was implemented differently and in some cases by a team working from a remote office so this presented a challenge at times. There was also an online server component that  delivered notifications of a challenge from an Xbox Live friend directly from the main menu screen.</p><p><img src="/2011/11/25/Kinect-Sports-Season-Two/screen2.jpg" alt="Tennis"></p>]]></content>
    
    <summary type="html">
    
      Kinect Sports Season Two was a Xbox 360 game developed by Rare and Big Park for the Kinect as a direct sequel to the BAFTA award winning Kinect Sports title.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="Actionscript" scheme="http://3zanders.co.uk/tags/Actionscript/"/>
    
      <category term="Xbox 360" scheme="http://3zanders.co.uk/tags/Xbox-360/"/>
    
  </entry>
  
  <entry>
    <title>Trapped</title>
    <link href="http://3zanders.co.uk/2011/11/12/Trapped/"/>
    <id>http://3zanders.co.uk/2011/11/12/Trapped/</id>
    <published>2011-11-12T00:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.136Z</updated>
    
    <content type="html"><![CDATA[<p>Trapped was my entry for <a href="http://www.ludumdare.com/compo/" target="_blank" rel="external">Ludum Dare 22</a>; a game making competition where you have 48 hours to make a game independently from Scratch! You can <a href="/trapped">play the game here</a>. It was placed within the top 10 for graphics and in the top 50 overall, pretty good considering it was my first attempt at a game jam!</p><p><img src="/2011/11/12/Trapped/screen1.jpg" alt=""></p><p>The competition theme was ‘Alone’ - a tough one for sure! I ended up trying to create a spooky first person castle exploring game where you had to escape from a Castle. This was my first time using Unity game engine so it was quite a learning curve. I decided to focus mainly on graphics and art over gameplay quality for this jam.</p><p><img src="/2011/11/12/Trapped/screen2.jpg" alt=""></p><p>To start with I set about creating a basic tileset for the Castle, the plan being that I would snap all of the different castle assets together in different ways to form a much bigger and more complicated building. I created a castle wall, floor, ceiling, carpet, door, light, portcullis and some crates to throw around.</p><p>Next I got all of these lovely art assets imported into Unity and I started placing and combining them into a large Castle scene. This seemed to work quite well when combined with some point lights and some linear fog in the distance to make the Castle all dark and spooky. I wish I had known about Unity’s Lightbaking tools at the time as this would have made the graphics look a lot better! Creating all of these assets and getting them imported correctly took me most of the first day.</p><p><img src="/2011/11/12/Trapped/screen3.jpg" alt=""></p><p>The final day was spent getting some basic gameplay working. This involved setting up a basic first person camera and a mouse drag system that would let you drag objects in the world realistically to allow the player to look and move around the world.</p><p>I also set up the door levers and the portcullis animations along with some tutorial text and a simple trigger to reset the level at the end of the game.</p><p><img src="/2011/11/12/Trapped/screen4.jpg" alt=""></p><p>In summary I think I hit the target I aimed for which was to create a nice looking game within such a short timeframe, however due to a massively over sensitive first person camera the controls left a lot to be desired! I plan to focus much more on gameplay in future game jams.</p>]]></content>
    
    <summary type="html">
    
      Trapped was my entry for Ludum Dare 22; a game making competition where you have 48 hours to make a game independently from Scratch!
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Unity" scheme="http://3zanders.co.uk/tags/Unity/"/>
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>Detour</title>
    <link href="http://3zanders.co.uk/2011/05/11/Detour/"/>
    <id>http://3zanders.co.uk/2011/05/11/Detour/</id>
    <published>2011-05-10T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.063Z</updated>
    
    <content type="html"><![CDATA[<p>Detour was an indie game developed in <a href="http://en.wikipedia.org/wiki/Microsoft_XNA" target="_blank" rel="external">XNA</a> and released on <a href="http://store.steampowered.com/app/92100/" target="_blank" rel="external">Steam</a> in October 2011. It was made by <a href="http://www.sandswept.net/" target="_blank" rel="external">Sandswept Studios</a>, a small team at the time mostly based in Utah - not counting myself of course who worked remotely! I worked on Detour part time during my first and second year at University.</p><p><img src="/2011/05/11/Detour/screen1.jpg" alt="Trucks leaving the map in glorious victory"></p><p>The game involves you delivering trucks from your factory to the other side of the map by building roads. You must deliver the trucks before your competitors do, so to get a monopoly on the truck delivery market you sabotage your opponents roads with nails, dynamite and bombs. It is often described as a chess game with bombs. There is also a infinite runner mode where you need to keep your truck on the map as it scrolls down the screen. It sure was a weird game design.</p><p><img src="/2011/05/11/Detour/screen2.jpg" alt="Expanding over the river"></p><p>I was completely responsible for the graphics and wrote all of the content pipelines, shaders and special effects from scratch. I also helped out with some of the in game UI. The shaders were written in HLSL and the graphics pipeline used the DirectX 9.0 SDK provided by XNA.</p><p><img src="/2011/05/11/Detour/screen3.jpg" alt="Nighttime truck chaos"></p><p>The renderer batched draw calls into buckets and used static mesh instancing to draw the tiles quickly. It had support for multiple geometry passes and the final game had some sweet effects implemented such as realtime reflections on the water, realtime soft shadows, local lighting, model recolouring, smoke particles, grass billboards, lasers, shield distortion, fog of war desaturation, bloom, tone mapping and a fullscreen explosion blur. I learned a lot about graphics programming in the process.</p><p><img src="/2011/05/11/Detour/screen4.jpg" alt="Crossing another river"></p><p>Looking back I wish I had known more of the tricks to speed things up such as combining meshes dynamically to reduce the total number of draw calls and state switches. I did know some of the tricks such as doing a Z-buffer pre-pass to allow hidden fragments to be discarded. All in all it was a fun project to work on.</p><div class="video-container"><iframe src="//www.youtube.com/embed/AAcREayEcv0" frameborder="0" allowfullscreen></iframe></div>]]></content>
    
    <summary type="html">
    
      Detour was an indie game developed in XNA and released on Steam in October 2011.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C#" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="XNA" scheme="http://3zanders.co.uk/tags/XNA/"/>
    
      <category term="HLSL" scheme="http://3zanders.co.uk/tags/HLSL/"/>
    
  </entry>
  
  <entry>
    <title>Book Galaxy</title>
    <link href="http://3zanders.co.uk/2009/08/09/Book-Galaxy/"/>
    <id>http://3zanders.co.uk/2009/08/09/Book-Galaxy/</id>
    <published>2009-08-08T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.048Z</updated>
    
    <content type="html"><![CDATA[<p>Book Galaxy was my winning entry in the <a href="http://www.sero.co.uk/jisc-mosaic-competition.html" target="_blank" rel="external">JISC MOSIAC Developer Competition</a> which challenged entrants to visualise library usage data and library books in an interesting new way. You can view <a href="/bookgalaxy">a demo of it here</a> and the <a href="http://bookgalaxy.sourceforge.net/" target="_blank" rel="external">source code</a> is available on source forge.</p><p><img src="/2009/08/09/Book-Galaxy/screen1.jpg" alt="Galaxy View"></p><p><img src="/2009/08/09/Book-Galaxy/screen2.jpg" alt="Book View"></p><p><img src="/2009/08/09/Book-Galaxy/screen3.jpg" alt="Course View"></p><p><img src="/2009/08/09/Book-Galaxy/screen4.jpg" alt="Search Results View"></p>]]></content>
    
    <summary type="html">
    
      Book Galaxy was my winning entry in the JISC MOSIAC Developer Competition which challenged entrants to visualise library usage data and library books in an interesting new way.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="Java" scheme="http://3zanders.co.uk/tags/Java/"/>
    
  </entry>
  
  <entry>
    <title>PlayWithYourPeas</title>
    <link href="http://3zanders.co.uk/2009/06/10/PlayWithYourPeas/"/>
    <id>http://3zanders.co.uk/2009/06/10/PlayWithYourPeas/</id>
    <published>2009-06-09T23:00:00.000Z</published>
    <updated>2018-02-24T22:26:50.097Z</updated>
    
    <content type="html"><![CDATA[<p><a href="http://www.lostgarden.com/2008/02/play-with-your-peas-game-prototyping.html" target="_blank" rel="external">PlayWithYourPeas</a> was a game protoype design challenge posted by Daniel Cook on his <a href="http://www.lostgarden.com" target="_blank" rel="external">Lost Garden blog</a>. He provided the design and art assets and all you had to do was implement it so I had a go! You can either <a href="/2009/06/10/PlayWithYourPeas/PlayWithYourPeasSetup.exe">download the installer</a> (windows only) or take a look at the <a href="/2009/06/10/PlayWithYourPeas/NinjaPeasSource.zip">source code</a>.</p><p><img src="/2009/06/10/PlayWithYourPeas/screen1.jpg" alt=""></p><p>The design is pretty awesome - you place peas who are convinced they are ninjas on a dinner plate assualt course of your own design. The ninja peas will climb to the top of your towers and jump. The longer they jump and the higher they fall (without squishing themselves) the bigger the score. Score the most points to win!</p><p>I implemented the design in C++ using the DirectX 9.0 and Win32 APIs for Window and Mouse Input as well as the <a href="http://box2d.org/" target="_blank" rel="external">Box2D library</a> to do physics collisions and response and the <a href="http://www.ambiera.com/irrklang/" target="_blank" rel="external">irrKlang library</a> to play the sound effects and music. The sounds effect were recorded and processed by myself using <a href="http://audacity.sourceforge.net/" target="_blank" rel="external">Audacity</a> and the music was from <a href="http://incompetech.com/" target="_blank" rel="external">incompetech</a> - a fantastic source of gameplay music.</p><p><img src="/2009/06/10/PlayWithYourPeas/screen2.jpg" alt=""><br><img src="/2009/06/10/PlayWithYourPeas/screen3.jpg" alt=""><br><img src="/2009/06/10/PlayWithYourPeas/screen4.jpg" alt=""></p>]]></content>
    
    <summary type="html">
    
      PlayWithYourPeas was a game protoype design challenge posted by Daniel Cook on his Lost Garden blog.
    
    </summary>
    
      <category term="Portfolio" scheme="http://3zanders.co.uk/categories/Portfolio/"/>
    
    
      <category term="C++" scheme="http://3zanders.co.uk/tags/C/"/>
    
      <category term="DirectX" scheme="http://3zanders.co.uk/tags/DirectX/"/>
    
  </entry>
  
</feed>
