Deleting old articles, refactoring articles and re-formatting some older ones. Generally getting things into order. Publishing this version

launchpad/website
Katharina Fey 6 years ago
parent 68010226f8
commit c12a6259c7
  1. 10
      content/blog/000_jolly_christmas.md
  2. 18
      content/blog/001_jolly_christmas_update.md
  3. 28
      content/blog/002_open_plantbot.md
  4. 14
      content/blog/00_introduction.md
  5. 8
      content/blog/050_gsoc_1.md
  6. 16
      content/blog/051_gsoc_2.md
  7. 22
      content/blog/052_gsoc_3.md
  8. 20
      content/blog/094_post_camp2015.md
  9. 16
      content/blog/095_recovering_luks.md
  10. 12
      content/blog/096_another_blog_update.md
  11. 44
      content/blog/097_post_33c3.md
  12. 12
      content/blog/098_super_ui.md
  13. 0
      content/blog/099_moonscript.md
  14. 4
      content/blog/100_rebooting.md
  15. 15
      content/blog/101_rust_is_awesome.md
  16. 57
      content/blog/hardware/001-omnitool-introduction.md
  17. 21
      content/blog/hardware/004-ws2812b-breakouts.md
  18. 89
      content/blog/miscellanious/000-newdawn.md
  19. 45
      content/blog/miscellanious/001-lonelyrobot.md
  20. 53
      content/blog/miscellanious/002-reedb-c-port.md
  21. 91
      content/blog/miscellanious/004-getting-started-with-xmmpp.md
  22. 127
      content/blog/miscellanious/005-getting-started-with-reedb.md
  23. 116
      content/blog/miscellanious/008-libgdx-super-ui.md
  24. 60
      content/blog/miscellanious/009-moonscript-adventures.md
  25. 112
      content/kookie.txt
  26. 114
      content/pgp/kookie.txt
  27. 16
      content/pgp/msg
  28. 296
      content/teaching/gameofcodes/01-goc-setup-basics.md
  29. 270
      content/teaching/gameofcodes/02-goc-input-movement.md
  30. 159
      content/teaching/gameofcodes/03-goc-input-rotation.md
  31. 110
      content/teaching/jni/01-jni-intro.md
  32. 29
      crumbs/static/css/crumbs.css
  33. 2
      develop_server.sh
  34. 2
      pelicanconf.py
  35. 70
      teaching/encryption/01-encryption-101-basics.md
  36. 366
      teaching/encryption/02-encryption-101-pgp-on-mac.md
  37. 161
      teaching/encryption/03-encryption-101-pgp-on-ios.md
  38. 227
      teaching/encryption/04-encryption-101-pgp-on-windows.md
  39. 142
      teaching/encryption/05-encryption-101-pgp-on-linux.md
  40. 365
      teaching/gameofcode/01-libgdx-game-of-codes-the-setup-basics.md
  41. 345
      teaching/gameofcode/02-libgdx-game-of-codes-input-movement.md
  42. 476
      teaching/gameofcode/03-libgdx-game-of-codes-input-movement-2-0.md
  43. 216
      teaching/gameofcode/04-libgdx-game-of-codes-textures-and-asset-management.md
  44. 455
      teaching/gameofcode/05-libgdx-game-of-codes-cameras-their-controllers-and-more-input.md
  45. 333
      teaching/gameofcode/06-libgdx-game-of-codes-creating-a-world-more-refactoring.md
  46. 359
      teaching/gameofcode/07-game-of-codes-user-interfaces-and-the-power-of-scene2d.md
  47. 381
      teaching/gameofcode/08-libgdx-game-of-codes-screens-subscreens.md
  48. 326
      teaching/gameofcode/09-libgdx-game-of-codes-modifying-libgdx-part-i.md
  49. 28
      teaching/gameofcode/09.5-libgdx-game-of-codes-continuation.md
  50. 7
      teaching/gameofcode/10-libgdx-game-of-codes-shaders.md
  51. BIN
      tutorials/series2/framelife.odg

@ -1,7 +1,7 @@
Title: Jolly Christmas Decoration
Category: OldBlog
Category: Blog
Date: 2015-09-17 15:30
Tags: Dev Diary, Hardware
Tags: /dev/diary, hardware
Christmas is getting closer (not really but let's just roll with it) and I wanted to learn [KiCad](www.kicad-pcb.com) a software that let's you create circuits and design PCB for manufacture.
@ -9,7 +9,7 @@ I found a tutorial series online by a guy named [Ashley Mills](https://www.youtu
The series focused on getting to know KiCad and all it's features. And while I did that in the first revision of my board, I've diverged from it since. I can however recommend his videos on KiCad to anyone who wants to dive into PCB design, has no clue about the software and could use a little chuckle while also learning some really awesome software (youtube channel link above).
### My Christmas Bauble
# My Christmas Bauble
So this is what I've got.
@ -23,11 +23,11 @@ It took me two more revisions to get the board to a state where it's not too com
It uses a round cell battery on the back of the board to hide it away and has a hole at the top to actually hang off a christmas tree. Theoretically the battery should lasta few days, so maybe have a few spare ones around in the christmas season.
### What now?
# What now?
I haven't manufactured this yet. I am still thinking about refining the design slightly. I have the **entire** back to work with and add things. I was thinking about adding a simple bluetooth chip so that patterns could be pushed to the device via an android app. But that's the future. For now it should actually be functional and maybe I'll order some `Revision 3` boards just to see that everything worked.
Here is a dynamic render from KiCad as well.
![Kookies Christmas Bauble Rendered](/images/christmas_bauble_render.png "Kookies Christmas Bauble Rendered")
And be sure to checkout my Github repo for the project if you want the KiCad files. Either to play around with them or to manufacture some baubles yourself. If you do, I'd be interested in pictures of the decorations on your christmas trees so I can add them to this article as a slideshow :)
And be sure to checkout my Github repo for the project if you want the KiCad files. Either to play around with them or to manufacture some baubles yourself. If you do, I'd be interested in pictures of the decorations on your christmas trees so I can add them to this article as a slideshow 😊

@ -1,7 +1,7 @@
Title: [Update] Jolly Christmas Decoration
Category: OldBlog
Category: Blog
Date: 2015-11-27 15:30
Tags: Dev Diary, Hardware
Tags: /dev/diary, hardware
You might remember I played around with Kicad a few months ago and made this [tacky little thing](/hardware/jolly-christmas-decoration/). Just about 2 1/2 weeks ago I went onto [DirtyPCB](http://dirtypcbs.com/) to get them actually made. I wanted to have gone through the production process and get something built before I started doing more complicated projects.
@ -19,20 +19,20 @@ Now, I have another smaller electronics project in the making where I am, again,
[But realistically for the production quality I saw with these, I'd be happy to give them my money again for future projects. Especially at that price, just unbeatable.](https://www.youtube.com/watch?v=d36wUmJGzvA)
:)
😊
Anyways, enough ramblings. Read you later.
### Update...update
# Update...update
Right...so after tinkering with the bauble a bit I found out a few things. The most important one being that I made some mistakes. Some big ones :)
- Pin 9 of the shift register was connected to both input A and input B of the XOR gate. Which meant that both inputs were always the same...which also meant that the output was always 0.
- The 555-timer clock ran at several hundred kilohertz. I had to change the capacitor down to ~12µF and the resistors to ~4.7 ohms.
- The coin-cell battery didn't have enough juice to run it. Two had to be put in parallel. Even then, two batteries would not be able to run for very long.
- Pin 9 of the shift register was connected to both input A and input B of the XOR gate. Which meant that both inputs were always the same...which also meant that the output was always 0.
- The 555-timer clock ran at several hundred kilohertz. I had to change the capacitor down to ~12µF and the resistors to ~4.7 ohms.
- The coin-cell battery didn't have enough juice to run it. Two had to be put in parallel. Even then, two batteries would not be able to run for very long.
To make the bauble work I bridget the xor gate completely, so just feeding back the shift register end to the beginning.
To make the bauble work I bridget the xor gate completely, so just feeding back the shift register end to the beginning.
In addition to those things some of the LED's sometimes didn't work. I'm not sure if that is due to broken shift registers, traces or LEDs. All in all I do consider it to have tought me quite a lot about electronics, going through the process of producing a PCB and debugging electronics once it arrived and inevidably goes wrong :)
In addition to those things some of the LED's sometimes didn't work. I'm not sure if that is due to broken shift registers, traces or LEDs. All in all I do consider it to have tought me quite a lot about electronics, going through the process of producing a PCB and debugging electronics once it arrived and inevidably goes wrong :)
I am currently in the process of redesigning the entire circuite from scratch. And making it easier to solder. I want to make it into a beginner soldering kit that people can both learn how to solder with and also have something to hang off their christmas tree in the jolly season.

@ -1,24 +1,22 @@
Title: Open Plantb0t - Rev A
Category: OldBlog
Title: Open Plantbot – Rev A
Category: Blog
Date: 2016-03-16 12:08
Tags: Dev Diary, Hardware
Illustration: banners/plantb0t_revA.png
Tags: /dev/diary, hardware
Howdy everybody,
Spring is coming in Berlin and thus my thoughts - as every year - are with plants. And growing shit. I live in an appartment with a tiny tiny balcony so I don't have much space but that has never stopped me from wanting to cram as many plants into the space as possible to the point of starting nuclear fusion.
Spring is coming in Berlin and thus my thoughts – as every year – are with plants and growing them. I live in an appartment with a tiny tiny balcony so I don't have much space but that has never stopped me from wanting to cram as many plants into the space as possible to the point of starting nuclear fusion.
In addition to that I have a few house-plants and very water-sensitive trees in my appartment. My current approach is to go around with a jug of water every couple of days and water them individually - making sure the soil has a certain moisture and doesn't exceed a certain limit - but I've always had the dream of being able to automate away as much as possible. That's where the idea of `Plantb0t` started. And I want to tell you a little bit about it.
In addition to that I have a few house-plants and very water-sensitive trees in my appartment. My current approach is to go around with a jug of water every couple of days and water them individually – making sure the soil has a certain moisture and doesn't exceed a certain limit – but I've always had the dream of being able to automate away as much as possible. That's where the idea of `Plantb0t` started. And I want to tell you a little bit about it.
The basic idea is to have a little controller in each plant-pot that measure the moisture of the soil and reports that back to me via an ESP-12 SOM (System on a Module). The ESP has WiFi capabilities and would log to an MQTT server on my home media server. This way (when I'm at home - none of that IoT shit) I can see how my plans are doing.
The basic idea is to have a little controller in each plant-pot that measure the moisture of the soil and reports that back to me via an ESP-12 SOM (System on a Module). The ESP has WiFi capabilities and would log to an MQTT server on my home media server. This way (when I'm at home none of that IoT shit) I can see how my plans are doing.
### Current state
# Current state
So that's what Revision A of Plantb0t is. I also added a second sensor slot which is meant to be populated by a temperature sensor but could theoretically house a second moisture sensor. In the end the probes are only sticks in the ground that have a resistance between them.
Here is a dynamic render of the board (that went into prototype production on the 29th of march, 2016).
![Plantb0t Rev A](/images/plantb0t_RevA_front.png Plantb0t Revision A)
![Plantb0t Rev A](/images/plantb0t_RevA_front.png)
As you can see it's powered by an ESP-12 and comes with it's own programmer (The lovely CP2102) and micro-USB header. The USB-Port is currently the only way to power the board.
@ -30,13 +28,13 @@ GPIO pin headers are included for external gismoz such as a pump to act on the m
In total the board is only 5x5cm big!
### Future plans
# Future plans
A few things I want to realise with this project in the next coming weeks:
- Primarily the Rev A board needs to be tested to make sure that the programmer works
- Figure out a good way to calibrate the sensors. Maybe drive a button via GPIO?
- Design a power board that generates 3.3V for the board (but not the programmer!) from a solar panel and a battery to decouple the entire sensor-board from all power-sockets.
- Primarily the Rev A board needs to be tested to make sure that the programmer works
- Figure out a good way to calibrate the sensors. Maybe drive a button via GPIO?
- Design a power board that generates 3.3V for the board (but not the programmer!) from a solar panel and a battery to decouple the entire sensor-board from all power-sockets.
For the next revision of the board (Rev B) I want to include more sensor slots. Maybe work on the part spacing a bit and increase footprint sizes. It should be easier to solder and someof the parts are ridiculously small. I mean...I have the whole back to work with?
@ -46,6 +44,6 @@ Either way...I'm excited for my boards to get here (hopefully in the next 7-8 da
I leave you with a screenshot from KiCad where you get to see under the hood of the board. Cheers o/
![Plantb0t Rev A](/images/plantb0t_RevA_naked.png Plantb0t)
![Plantb0t Rev A](/images/plantb0t_RevA_naked.png)
(The project has a [Github](https://github.com/spacekookie/open_plantb0t) repo where I will try to populate the wiki with as much info as possible)

@ -1,14 +0,0 @@
Title: An open source GPU
Category: OldBlog
Tags: OpenMPU, matrices, opengl, hardware
For as long as I can remember I've wanted to build my own computer. Sorta from scratch.
And there is something I want to do even more: build a GPU. Something that can process vectors and matrecies in an efficient manner, build a graphics rendering pipeline in hardware. Sorta from scratch.
And that's what this project is about. OpenMCU stands for "Open Matrix Computation Unit" and will be a part of the OpenGPU (working title).
## The basic architecture
`<insert picture>`

@ -1,11 +1,11 @@
Title: I got accepted to GSoC 2016
Category: OldBlog
Category: Blog
Date: 2016-04-27 18:47
Tags: GSoC2016
Tags: /dev/diary, gsoc2016
![Acceptence Mail](/images/gsoc/00_acceptance.png "Acceptence Mail")
The title should be self explanatory about that one :)
The title should be self explanatory about that one 😊
But let me go back a little bit. A couple of weeks ago I sat in the basement of my local hackerspace talking to a friend about crypto when somebody joined the conversation, asking if I was a student and if I might be interested in Google Summer of Code.
@ -18,7 +18,7 @@ And so this is it. The next month or so I will have time to get to know the code
I will be posting three blog posts on the official [Freifunk Blog](http://blog.freifunk.net/), one in a couple of days/ weeks, one in the height of the project and one that will go into the aftermath of the project.
But in the meantime I will be keeping my blog up to date about what I am doing, how things are going, my challenges and things I learn.
In the hopes that people might find it useful and lean things from it. Or just to save my insane ramblings in some narcissistic pleasure...to think that I am relevant in the world :P
In the hopes that people might find it useful and lean things from it. Or just to save my insane ramblings in some narcissistic pleasure...to think that I am relevant in the world 😜
Read you soon,

@ -1,7 +1,7 @@
Title: First steps...baby steps
Category: OldBlog
Category: Blog
Date: 2016-06-02 19:56
Tags: GSoC2016
Tags: /dev/diary, gsoc2016
So it's been almost two months, the community bonding period has passed, blog posts were written, talks held and slowly but surely I'm working myself into the qaul.net codebase.
@ -11,7 +11,7 @@ I'm currently working myself into [mbed.tls](https://tls.mbed.org/) which is the
That includes some code that will probably not make it into a later version of my branch: the debugger.
### The De-bugger?!
# The De-bugger?!
![Debugger Pro 2016](/images/gsoc/01_debugger.png "Debugger")
@ -19,14 +19,14 @@ Well...debuger might be a bit of a strong word, it's basically a way to develop
There I am currently busy writing a wrapper around a new namespace added to libqaul: `qcry` (short for qaul crypto) and properly integrate all the mbed.tls sources into the library so they can be accessed by libqaul. The idea being that I don't have to leave vim and the terminal to develop on the core cryptographic components such as:
- Key generation
- Identify generation (with private key fingerprints)
- Identity verification
- ???
- Key generation
- Identify generation (with private key fingerprints)
- Identity verification
- ???
Only in the last step of the last bulletin do I actually have to involve the GUI of qaul.net. And until that point I wish to not come in contact with it (if avoidable).
So most of next week will be getting to know mbed-tls as I have never worked with it before. But hey...can't be worse than the gcrypt documentation¹ :')
So most of next week will be getting to know mbed-tls as I have never worked with it before. But hey...can't be worse than the gcrypt documentation¹ 😂
Hope to read you soon with more updates (probably rants).

@ -1,23 +1,23 @@
Title: What I have done in GSoC 2016
Category: OldBlog
Category: Blog
Date: 2016-08-19 18:13
Tags: GSoC2016
Tags: /dev/diary, gsoc2016
Google Summer of Code is coming to an end. And as the final bugs are getting squashed and more code is being prepared for the big merge, I am sitting here, trying to think of how to represent my work.
I thought I would write up a little blog post, explaining what I've done and what still remains to be done.
### The TLDR
# The TLDR
My main contributions are all available [here](https://github.com/spacekookie/qaul.net/commits/qaul_crypto?author=spacekookie) (spacekookie/qaul.net on the `qaul_crypto` branch). I did a lot of small commits. Most of my code can be found in this [sub-directory](https://github.com/spacekookie/qaul.net/tree/qaul_crypto/src/libqaul/crypto).
In addition to that I ported an existing project (from python) to C to be relevant for future front-end endevours of the client. It's called [librobohash](https://github.com/spacekookie/librobohash). I didn't end up finishing the port because there were more pressing issues in qaul.net and the UI was delayed.
While most of my work has been in hidden backend systems there is a demo you can run. The source compiles and has been tested under Linux (Ubuntu 16.04 and Fedora 24) and is located under the `src/client/dbg/` directory. The demo creates two new users (to simulate communication between two nodes), adds the public keys to the keystore and then continues to sign and verify messages. If the demo returns lots of "0" and "OK" it went okay :)
While most of my work has been in hidden backend systems there is a demo you can run. The source compiles and has been tested under Linux (Ubuntu 16.04 and Fedora 24) and is located under the `src/client/dbg/` directory. The demo creates two new users (to simulate communication between two nodes), adds the public keys to the keystore and then continues to sign and verify messages. If the demo returns lots of "0" and "OK" it went okay 😊
Feel free to play with the demo; for example, switch out `message` for `fakemessage` during verification :) The source for the demo can be found under `src/libqaul/qcry_wrapper.c`
Feel free to play with the demo; for example, switch out `message` for `fakemessage` during verification 😊 The source for the demo can be found under `src/libqaul/qcry_wrapper.c`
### The good (aka what I have done)
# The good (aka what I have done)
<img class="dual" src="/images/gsoc/02_cryptoui.png" align="left">
@ -34,7 +34,7 @@ A keystore was added in addition to the user store already existing in qaul.net
In total the crypto submodule adds another ~2.2k lines of code to the project.
### The bad (aka what I haven't yet done)
# The bad (aka what I haven't yet done)
So far completely un-implemented is encryption. Unfortunately working with the crypto library selected for the task turned out to be more challenging than expected. With almost no documentation and a few very niche examples I basically went through the library line-by-line to understand how it worked.
@ -49,11 +49,11 @@ Signatures (and also encryption) of private messages (so messages that aren't fl
I have talked to my mentor and he said that they were currently in the process of re-writing the communication sub-system in libqaul. This means two things:
1. I need to wait for those changes to be done until I can finish what I set out to do
2. Some of the code I wrote (hooking into the current communication system) is being made obsolete :(
1. I need to wait for those changes to be done until I can finish what I set out to do
2. Some of the code I wrote (hooking into the current communication system) is being made obsolete 😞
### In conclusion
# In conclusion
What I can say is this: qaul.net has gotten a very big step closer to becoming a more secure network of communication. The crypto submodule is tested and easy to use. What might happen is that parts of the code get merged (the crypto submodule itself) without merging any of the code that hooks into the communication stack.
@ -61,7 +61,7 @@ I had a lot of fun working on this project and I am looking forward to more cont
I was interested in open source before and I contributed to my own projects on github. But the experience I gained this summer will be helpful for me, not just for my own work, but to be less reluctant to join other developer communities.
And I look forward to seeing my code get merged into qaul.net :)
And I look forward to seeing my code get merged into qaul.net 😊
Read you soon,

@ -0,0 +1,20 @@
Title: Chaos Communication Camp 2015
Category: Blog
Date: 2015-08-25 15:30
Tags: /dev/diary, ccc, c3
Hey everybody, long time no read.
As I returned from vacation on the Chaos Communication Camp 2015 (Not sure if I'll post more about that) and probably starting a new job next week (*pssst* not sure if I should talk about it 😉 ) the rest of my summer is still ahead of me and I'm booming with ideas and inspiration to do stuff.
I've started more intensively coding on the `newdawn` branch of Reedb, the C port of the database and planning some features for the old codebase via the `backports` branch. Because the new codebase will use a different crypto backend (from OpenSSL to gnu_crypt) a migration agent will be neccesary to migrate between 0.11.x to 0.12+ vaults. But as very few people currently use Reedb and most setups are for testing purposes only that isn't a very big priority right now. Depends on how the current version of reedb develops :)
But that's talk for another day. What else has been going on? After the Chaos Communication Camp 2015 I've been playing around a bit with my rad1o badge.
![Rad1o Badge](/images/rad1o_badge.png "Rad1o Badge")
But not much has resulted from that yet. The distribution I'm using (Fedora 22) at this time unfortunately has a broken arm-gcc package which means that a linker for embedded systems isn't working properly. So hacking on that will have to wait a little bit. But I will very likely post more stuff about that in the future.
Until another day,
Kate

@ -1,23 +1,23 @@
Title: Recovering a destroyed LUKs container
Category: OldBlog
Category: Blog
Date: 2015-11-19 11:41
Tags: Dev Diary
Tags: /dev/diary, data recovery, linux
So...funny thing happened to me the other day. And by funny I mean not funny. Actually I mean quite the oposite of funny. I booted my computer after a normal night of sleep (after I had actually shut down my laptop after several weeks of activity) and...nothing.
So...funny thing happened to me the other day. And by funny I mean not funny. Actually I mean quite the oposite of funny. I booted my laptop after shutting it shut down for the first time after several weeks of activity and...nothing.
I stared at my plymouth boot screen while nothing prompted me to type in my passphrase to decrypt my harddrive and the first thought through my mind was:
> Fuck...I don't have backup.
> Fuck...I don't have a backup.
### How to debug
# How to debug
Now...not to worry, after some time I was dropped into a recovery console where I could ask very simple questions like what kernel modules were present and what Systemd had been up to. And at first I thought the problem was clear: `Module failed to load: vboxdrv` and other messages populated my screen – all about VirtualBox kernel modules.
So the problem was clear. I had fucked up something when installing a new kernel or VirtualBox or anything else. So I blacklisted the modules and moved on...just...that it didn't. The problem persisted. Thinking that I had fucked something up when dealing with the GRUB config or the GRUB recovery console I got my trusty Fedora 22 live-USB out and booted off that.
### How not to panic
# How not to panic
To the realise that my 256GB SSD was only 500MB full (which was rightfully detected as an `ext4` formatted volume. The rest of my drive was marked as `unpartitioned space`. \jawdrop.
Looking at the partitioning on the disk I realised that my 256GB SSD was only 500MB full (which was rightfully detected as an `ext4` formatted volume. The rest of my drive was marked as `unpartitioned space`. 😱
Now...here is where things get and got interesting. But first let's have a look at my setup.
@ -34,7 +34,7 @@ So as you can see my boot drive is outside the LUKS container and unencrypted wh
Knowing this didn't help very much though and it took me a few hours to fix this.
### Restoring the Partition Table
# Restoring the Partition Table
So the main problem was that my partition table was broken. I don't want to start speculating as to why this happened. Maybe my SSD just lost a few blocks, maybe it was bombarded by solar radiation or maybe (just maybe) I was obducted by aliens in the night, refused to give out my master passphrase in my sleep and because of frustration of not being able to get to my data they deleted some junks from my partition table just to spite me.

@ -1,6 +1,6 @@
Title: Winter update
Category: OldBlog
Tags: Dev Diary, Meta
Category: Blog
Tags: /dev/diary, meta
Date: 2016-12-2 10:43
Howdy everybody!
@ -13,15 +13,15 @@ And so, for the last few days I have tweaked the layout (and design - as some mi
I was also considering to change theme but after not finding anything I liked I decided to hack the fuck out of my current one instead. You can check out all of my horrible changes [here](https://github.com/spacekookie/nest).
I've also finally done some stuff that I've wanted to do for ages - such as pimping up the front page, adding a proper projects page and go through some of my old tutorial series, fix their formatting (yea right "perfect wordpress import...") and update them to newer API's of libraries. Some articles have just been dropped because I would have had to re-work their formatting and they were no longer relevant. Stuff will slowly be introduced again, with proper formatting :)
I've also finally done some stuff that I've wanted to do for ages - such as pimping up the front page, adding a proper projects page and go through some of my old tutorial series, fix their formatting (yea right "perfect wordpress import...") and update them to newer API's of libraries. Some articles have just been dropped because I would have had to re-work their formatting and they were no longer relevant. Stuff will slowly be introduced again, with proper formatting 😊
### Everything else
## Everything else
In the terms of literally everything except my blog: I'm looking forward to the **33C3**. I'll be joining with the c-base assembly. My first congress in almost a decade! Expect maybe an update from that. And maybe there might be some christmas hacking. It's always more fun to do silly RGB LED stuff if it ends up annoying people on the tree!
Also, with the blog now in a bit better shape I will try to keep a closer journal of what I'm doing. But hey...no promises, right? ;)
Also, with the blog now in a bit better shape I will try to keep a closer journal of what I'm doing. But hey...no promises, right? 😉
I shall leave you with this piece of relaxing GIF.
<img class="padded" src="http://i.imgur.com/KZquOZM.gif" align="center">
<img class="original" src="http://i.imgur.com/KZquOZM.gif" />

@ -1,6 +1,6 @@
Title: Post 33C3, what next?
Category: OldBlog
Tags: Dev Diary, Congress, CCC, Hamburg
Category: Blog
Tags: /dev/diary, c3, ccc
Date: 2017-01-03 12:28
Howdy everybody,
@ -13,55 +13,59 @@ More importantly, I loved the chance to get in touch with some other women in th
I also found out that I am in no way, shape or form a dancing person. Although electronic club music is fun!
## Some talks I went to
# Some talks I went to
Following is a non-comprehensive list of the talks I went to. I am filling this from memory, so some talks might have been missed or dropped. And maybe I'll just edit them in later without anyone ever knowing.
<br/>
**[How Do I Crack Satellite and Cable Pay TV?](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8127.html)**
## [How Do I Crack Satellite and Cable Pay TV?](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8127.html)
A really quite epic lecture about using glitching to extract keys from a very dated security layout. Not that anyone should do this (it's not worth doing it anyways...never anything good on) but it will teach you a lot of stuff about hardware security
**[Bootstraping a slightly more secure laptop](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8314.html)**
A talk about the flip-side of TAILS which aims to introduce trusted computing into a world where the machine can't be trusted. HEADS on the other hand uses coreboot and cleverness to create a verifiable machine environment to build an OS on top of. Made me want to get an old thinkpad on ebay to play with :)
## [Bootstraping a slightly more secure laptop](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8314.html)
**[The Nibbletronic](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7925.html)**
A talk about the flip-side of TAILS which aims to introduce trusted computing into a world where the machine can't be trusted. HEADS on the other hand uses coreboot and cleverness to create a verifiable machine environment to build an OS on top of. Made me want to get an old thinkpad on ebay to play with 😊
## [The Nibbletronic](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7925.html)
A relatively short talk about the creation of a musical instrument. Learning by doing and failing. Quite interesting for me as a hardware designer (as a hobbyist) but also a musician.
**[Shut Up and Take My Money!](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7969.html)**
## [Shut Up and Take My Money!](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7969.html)
If you have a bank account with N26...stop having a bank account with N26. Their security is absolutely horrible. And while, yes, all of these security issues have been fixed, it shows a rather lacking attitude towards security from their engineering team. Best demonstration of client-side security gone wrong. And why ReST APIs are fucking aweful!
**[Untrusting the CPU](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8014.html)**
## [Untrusting the CPU](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8014.html)
This was a great talk given by a close friend of mine about one of his super crazy projects. The idea being to construct an FPGA powered PCI-E device for laptops and/ or desktop computers that intercepts messages to the display, encodes and decodes text into them to provide an interface for encrypted messages without using the CPU. It's really quite interesting and I can't wait to see what he does with it.
**[Making Technology Inclusive Through Papercraft and Sound](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7975.html)**
## [Making Technology Inclusive Through Papercraft and Sound](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7975.html)
One of my favourite talks was about an engineering toy kit that was aiming to be more inclusive. The problem it attempts to tackle are the incredible low numbers of women in computer science and engineering (significantly lower than in other scientific fields). There are a lot of reasons why women aren't well represented in the fields and they are all cultural. This talk was about trying to change the culture around teaching people about electronics and code to be more inclusive towards groups of people (mostly girls/ women) who would otherwise be missed.
I really enjoyed the talk on a lot of different levels. One was the technical aspect of creating a childrens toy on the cheap that is inclusive and universally programmable through audio encoding. Quite worth a watch.
I don't think that just with projects like this the culture around women in tech will change. But it's a start. What we realistically need is a change in culture throughout all layers of society. I think the problems around women in tech are quite complicated. And unfortunately usually result in a bunch of assholes starting to shout either about how feminism is evil or how diversity isn't important. And biases aren't actually thaaaaat bad, right? */s*
I don't think that just with projects like this the culture around women in tech will change. But it's a start. What we realistically need is a change in culture throughout all layers of society. I think the problems around women in tech are quite complicated. And unfortunately usually result in a bunch of assholes starting to shout either about how feminism is evil or how diversity isn't important. And biases aren't actually thaaaaat bad, right? 😝
I could rant here forever and it's questionable how many people would actually care :) I can recommend this talk. Let's leave it at that :)
I could rant here forever and it's questionable how many people would actually care 😅 I can recommend this talk. Let's leave it at that :)
**[The Moon and European Space Exploration](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8406.html) and [Interplanetary Colonization](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7942.html)**
## [The Moon and European Space Exploration](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/8406.html), [Interplanetary Colonization](https://fahrplan.events.ccc.de/congress/2016/Fahrplan/events/7942.html)
Those were just the first two talks from a series of space talks. The first one was from one of the heads of ESA about their plans to colonise the moon for profit! And science of course... It was quite funny and definately worth watching.
The second one I almost liked more, though mostly the first part of it. Liz George manages to explain incredibly well in a very short amount of time what challenges exist when discovering exo-planets. The second part (by somebody else) is a bit more vague about how to actually get there and is less science, more fiction. But hey :P
The second one I almost liked more, though mostly the first part of it. Liz George manages to explain incredibly well in a very short amount of time what challenges exist when discovering exo-planets. The second part (by somebody else) is a bit more vague about how to actually get there and is less science, more fiction. But hey 😝
## Going into 2017
# Going into 2017
So in short: 33C3 was pretty epic! And I honestly can't wait for next year. It's not clear yet where it will be held but it will be epic non-the-less. And who knows, maybe I have a talk to hold by then :)
So in short: 33C3 was pretty epic! And I honestly can't wait for next year. It's not clear yet where it will be held but it will be epic non-the-less. And who knows, maybe I have a talk to hold by then 😊
Which brings me to this year. Last year was fucking shitty. Politically...On a personal level it actually went quite well. And I got a lot of shit done. I did Google Summer of Code, I made *huge* progress on my game project (yes, I will post about that at some point). And especially in the last months of the year, I redesigned and rerouted the Open Plantb0t board. On january 1st, 2017 the revision A2 design went into production.
I hope to get all my parts together soon and build up a second prototype series which (hopefully) works better than the last ;) I will keep y'all updated on that.
Until then, I hope you've had a happy new years eve and not an all too terrible year...yet ;)
I hope to get all my parts together soon and build up a second prototype series which (hopefully) works better than the last 😉 I will keep y'all updated on that.
pel
Until then, I hope you've had a happy new years eve and not an all too terrible year...yet 😉

@ -3,19 +3,15 @@ Category: Blog
Tags: /dev/diary, libgdx, game dev, java
Date: 2017-01-24 00:14
**Let me tell you a factual statement**
**Let me tell you a factual statement**: UI programming is terrible
*UI programming is terrible*
**Let me tell you an even more factual statement**
*UI programming in LibGDX is even more terrible*
**Let me tell you an even more factual statement**: UI programming in LibGDX is even more terrible
I am a big fan of LibGDX. It's a really nifty library/ framework to get started with game development if you're more comfortable inside a code editor than a full blown game engine that is more targeted towards designers and artists. And I put my money where my mouth is: I have a series about LibGDX development for beginners on this blog and work almost exclusively with it when it comes to my own projects.
Yet, there is something that bothers me and there didn't seem to be a great solution to fix it. UI code structure. In this post I want to highlight a utility I have written for LibGDX which is very easily embeddable into your existing projects which will you help structure UI code more efficiently.
## The root problem
# The root problem
The reason I dislike UI programming with LibGDX is that it usually results in very long code files or passing dozens of parameters into sub-classes that are needed to update the UI for button presses, etc.
@ -29,6 +25,8 @@ Looking at this structure we have three main components that interact with each
Implementing this structure with Scene2D and LibGDX will result in a lot of very ugly code. Because the network signals need to know everything about the UI (how it is structured, etc). And our window state can be written to by two different sources which means that we need to mutex it to avoid race conditions.
# Maybe a solution
So, what was I trying to solve? First a bit of limitation of scope. Because a lot of UI problems have been solved over and over again and usually at the cost of runtime performance or with a *lot* of extra code.
1. UI code doesn't have to be embedded in a screen

@ -1,7 +1,7 @@
Title: Rebuilding my Website (again)
Category: Blog
Tags: /dev/diary
Date: 2018-01-25
Tags: /dev/diary, meta
Date: 2018-01-3 01:31
It's winter, rebuilding my website is a tradition...right? **Happy new year everybody.**

@ -1,7 +1,8 @@
Title: Failure. Or: why Rust is probably the best programming language ever created
Category: OldBlog
Tags: Dev Diary, Rust, Programming, Reflections
Date: 2017-12-20
Category: Blog
Tags: /dev/diary, reflections, programming, rust
Date: 2018-01-28
Status: Draft
*This post is two stories.* One is about accepting and recognising personal failure, reflecting and growing from it; the other is about an incredibly and seemingly endlessly powerful programming language, called *Rust*.
@ -9,7 +10,7 @@ Date: 2017-12-20
The details of development aren't too important. About 6-8 months into the project I had written something rather cool and functional. It wasn't very fast, the code base was a bit of a mess and I was having issues with packaging. But, at the core, I really liked what I had made, which had shifted from just being a password manager to being a universal, platform-independant secrets manager, close to a keychain. In my mind applications could write sensitive information into a "vault" which was managed by this project, without having to worry too much about access rights, authentication or anything else.
## So far so good; this is how both stories start.
# So far so good; this is how both stories start.
Over the next few years this project would take me over and, ultimately, destroy me. I had gotten it into my mind that the cryptography should have been handled by something more low-level, something more "advanced". I talked to people, I looked at languages and in the end, thinking I had more experience now, chose C++ to re-write the project in. *This was the beginning of the end.* It took me another six months to get the basics done, getting caught up on nitty gritty details.
@ -21,13 +22,11 @@ What this project had turned into wasn't maintainable. It didn't even really mak
As hackers, we are often compelled to take on the world. Everything seems plausible, sometimes trivial. We understand technology in a way that most people don't and in that, we gain confidence in our abilities past the point of reality. Hubris. We want to make things, break things, modify things. And we forget our own limitations, time and scope. We end up starting so many things that we never finish. Or we get obsessed with something that doesn't make any sense.
<br/>
It took me over 2 years to understand that I can't let my impulse to adventure drive the way I work. I love open source and I love working on things that are just *free* and out in the open. I want to help build an ecosystem of tools and applications that help people, without any cost or baggage of being for a closed down system. But learning, that there were things that I can't do, that maybe the way that I viewed work, problems and how to tackle them was *fallable*, that took some more time to understand. In the end, everything I did on this project was a collosal waste of time. It's still on my github, more as a reminder to myself of how failure works...
It has nothing to do with not knowing how to solve a problem. It has nothing to do with failing to understand code or a language or a toolkit... It has *everything* to do with not knowing how to limit a project, **and when to stop...**
## This is the end of story one
# This is the end of story one
It's been nearly a year since I worked on this project (or the 5th iteration of a re-write anyways), in the meantime I've worked on many small things, trying to keep in mind what I want to do, what is plausible and also useful. And in the meantime I've come into contact with a magical programming language: *Rust*!
@ -45,7 +44,7 @@ I remembered what I had thought about before. Limitation of scope, accepting lim
Rust makes it incredibly simple to do rapid prototyping. Yes, the language is very strict sometimes. Yet it has this feeling of "throwing shit against the wall" and seeing what sticks. With the added benefit that there are compile-time checks that make sure that there are no serious issues with your program. You can still write bad code, it just seriously limits the damage you can do. And that makes it incredibly fun to write with.
## What's the point of all this?
# What's the point of all this?
Well, first that I love Rust 😝.

@ -1,57 +0,0 @@
Title: 01. Omnitool - Introduction
Slug: 01-omnitool-introduction
Category: OldBlog
Tags: Dev Diary, Hardware
Date: 17-09-2015 15:45
Status: published
Illustration: omnitool_background2.jpg
Any good fan of the game, book, comic, stuff series will now jump up and down in excitement. The omnitool is a constant companion, helper and friend for Commander Shepard and a life saver in several situations. Whether it be hacking doors, turning into a plasma blade and cutting peoples faces open or just plain transferring a bribe credit to the slimy Vorcha in front of you.
But please, settle down, I haven't invented holographic technology. Nor have I invented plasma tubings or even solved the financial crisis by coming up with a perfect currency (of couse generically called 'credits') that everybody wants to use.
### Then why waste your time
That's a good question :) I would hope that this series doesn't turn into a waste of time for anyone. Because...well, while I haven't done any of those things. I am planning on building an omnitool. Just a bit more low-tech.
I was actually inspired by something on Adafruit, called the Flora. It's a round gimmick with a ring of RGB LED's, GPS (I think) and an arduino to program it.
![Adafruit Flora](/images/flora_pinout.png "Adafruit Flora")
I was only really inspired to do this project when a friend of mine showed off his Flora on the CCCamp2015.
He did some minor modifications to it, including a wristband (IDE cable) and a battery on the underside and programmed a few modes for displaying time (as an analogue clock) and a flashlight by just dialing the LED's up to full power.
![Adafruit Flora 2](/images/flora_withleds.jpg "Adafruit Flora2")
And that's kinda what gave me the idea for an omnitool. The idea of circular rings of LED's as display elements are pretty cool.
### Basic concept
So the basic conceptis a simple. Create a wrist accessory with one or two LED rings (using shift register RGP LED's to display patterns, colours and different brightness settings), include a generic SOC to program, probably something single core ARM. Give it a bunch of RAM to run applications and a embedded systems linux.
Include GPS, blutooth, a sensor package such as temperature, preasure, accelerometer, etc.
Include extention slots where, with a simple click, the tool can be expanded to include speakers, a microphone, a bigger screen, a bigger battery, etc.
And all this in the form factor of the so beloved omnitool from Mass Effect.
I know this is a bit of a crazy project. And it will take months, if not years to complete.
Because this is the thing: I want to do it all as custom cut PCB and maybe some custom cut plastic for casings.
I've been getting into KiCad recently, with my first project the Christmas Bauble ([Click here for details](/dev-diary/jolly-christmas-decoration/)) and have fallen in love with the tool – Don't worry Ashley, not *that* much :)
But it is pretty awesome and I urge everybody who wants to get into that sort of electronics stuff to checkout it out! [KiCad](http://www.kicad-pcb.com)
### What to expect
So what will this series be? (Hopefully) regular status reports about what I've been doing, writing about my experimences with the project, letting you guys know what I'm learning and generally just let people follow the project.
All stuff about the project will be in a Github repo. From the KiCad files to the C firmware I'll have to write. Everything you would potentially need to make your own, study it and learn from it is in there.
**[Omnitool Repository](https://github.com/spacekookie/omnitool)**
I hope that you follow along. And I'm looking forwards to comments from all of you. Have a lovely day and read you soon.
~Kate

@ -1,21 +0,0 @@
Title: WS2812b LED breakouts
Category: OldBlog
Date: 2016-03-16 12:08
Tags: Dev Diary, Hardware
You all know I have a fetish for [ws2812b RGB-LEDs](http://rgb-123.com/wp-content/uploads/2013/08/PinLayout.jpg). I admit that. They're just awesome. And recently I've found myself wanting to do some projects with them (*cough* programmable alarm clock *cough*). But I dislike the strips, although they're pretty cheap they are usually just very messy and horrible. And making a PCB for every project can be weird. Especially if gigantic PCBs would be required.
So I designed this little doodad.
![ws2812b Single Mount](/images/ws_2812b_single.png ws2812b Single Mount)
The idea is the following: Sometimes you just need a few ws2812b (I'm saying that word too often in this post) somewhere. But you don't want to lay a strip. Or make a big PCB for it.
So here is an alternative. Easily make ~800 of these for 25$, screw them to a surface, connect **PRETTY** wires between them, such as [Ribbon cables](http://cdn.usdigital.com/assets/images/galleries/ca-c10-f-c10_0.jpg) and boom. You're done.
### One to rule many
Now...I mentioned that programmable alarm clock earlier. And while I'm not quite done designing what will go into it all, I do know that I want to have a ~ 21x9 Pixel display, each individually addressable. And instead of building a way too big PCB that will be insanely expensive to manufacture...why not split them up? Then I have these "tiles" of LEDs that I screw to a backplate, wire everything together and from the outside you can't tell the difference.
With 21:9 (Aspect ratio and pixels) in mind, this is my prototype:
<TO BE CONTINUED>

@ -1,89 +0,0 @@
Title: Static sites vs Wordpress
Category: OldBlog
Date: 2015-08-14 20:59
Tags: Dev Diary, Meta
Regular readers will notice slight differences in my blog from the last time they were here. A lot has changed in the last two years since I started this website. Back then I decided to use Wordpress to host the stuff I wanted to write about because it offered lots of plugins and an easy to use CMS + editor to write articles. But over time I noticed that wordpress, while nice, can be more trouble than it's worth.
So for the last couple of months I've had a look at different web frameworks. Django, Ruby on Rails and some static site generators like Nikola and now Pelican. The last one is now powering this website.
The advantages of a static site generator is significantly less server load, simpler design and less overhead with updates and security issues. With no database to hold any kind of data and only static `html` documents being generated at "compile time" and dealt via a very simple html server using exploits or manipulating the website to gain access to my server is almost impossible.
So...while you can read a lot about why static site generators are cool and what their limitations are, I wanted to use this article to write a little bit about the challenges that I had to deal with porting my old website to a new framework. Because I didn't want to start from scratch. I wanted to keep all my stuff.
### Creating basic site layout.
Most of my website are blog posts of different categories and streams. For example, I had one page that displayed all blog posts while I then had other pages that displayed only certain categories. Most static site generators don't really support that. On Pelican I am now using one category for Blogs (Blog) and then have other categories displayed on pages that I statically link in my config:
```python
MENUITEMS = (
('Home', '/'),
('About Me', '/about-me/'),
('Blog', '/blog/'),
('Projects', '/projects/'),
('LibGDX', '/libgdx-game-of-codes/'),
('Linux', '/linux/'),
('Teaching', '/teaching/')
)
```
So essentially the menu items link to the category pages that then display articles. By default these pages only displayed a list of posts so I had to modify the category template in my theme. But more about that later.
Right now I still don't have a work-around for having different categories on the "Blog" page. But my current idea is to not link to a category page but rather a "tag" page. Then give every article that should show up on that page the "blog" tag (or use some voodoo setting that automatically adds tags to articles).
To get pretty links you can set some options to save pages and posts under different URLs in the config:
```pytho
nARTICLE_URL = '{category}/{slug}'
ARTICLE_SAVE_AS = '{category}/{slug}/index.html'
PAGE_URL = '{slug}'
PAGE_SAVE_AS = '{slug}/index.html'
CATEGORY_URL = '{slug}'
CATEGORY_SAVE_AS = '{slug}/index.html'
```
### Theming with [Pelican Themes](http://www.pelicanthemes.com)
Obviously a website should be something personal. And on my old wordpress site I spent several weeks tweaking the Wordpress Theme to my liking. Static site generators like Nikola or Pelican do offer theming where people much better at writing CSS and html put together something nice. I would recommend cloning a template that you want to use (most of them are on Github) and then modifying it however you like. For example, my template and the modifications I'm making on it can be found here: [github.com/spacekookie/nest](https://github.com/SpaceKookie/nest).
The first thing I did was tweak the dynamic content filling a bit. I mentioned earlier that I had to modify some stuff to make sure that I didn't just get a list of entries in my blog page but rather either the content or a summary of the page. With a little plugin called "summary" that becomes even nicer but I'm getting ahead of myself.
```html
{% for article in articles %}
<dt>{{ article.locale_date}}</dt>
<dd>
<a href="{{ SITEURL }}/{{ article.url }}"><h2>{{ article.title }}</h2></a>
<p>{{ article.summary }}</p>
</dd>
{% endfor %}
```
As you can see you can embed data from your pelican site into HTML via curly braces, aka Jinja. So the above snippet is obviously a loop that takes an article from articles (which is provided by Pelican in my case) and then renders a "h2" link to the article with the title (`article.title`) and then adds the `article.summary`.
If you wanted to display the entire content of the post it's as trivial as changing the summary to article.content. That's the beauty of Jinja: it's ridiculously easy :)
### Next up
Another thing you might wanna have a look at is the static/css folder of your theme. In the one I use there is a `nest.css` file that contains a lot of modifications to the underlying bootstrap theme. Including changing paddings, colours as well as overriding headers to not have these weird dashes (that look pretty cool for some parts. But not so cool for others).
But that's all details then. Other things you might want to consider if you move your Wordpress blog to a static site generator is that Wordpress sets up a lot of metadata that then ends up in your Markdown files (if you choose Markdown). Which means that you might want to go through all your articles cleaning out unwanted metadata that might just screw things up.
I'm using Sublime Text for the multi-cursor/ multi-file edits and regex searching which made editing my article metadata less of a pain in the bum.
As for this site: I still have a lot of things to work out. For example I still don't have a projects page. Markdown is nice for writing articles but I'm thinking about adding Restructured Text (`.rst`) files for static pages. It's a lot more powerful but also more annoying to write.
**-EDIT-**
A quick insertion a few weeks after having created but not yet published this site.
Alternatively, something I've now started using for my front page is a dedicated template for certain pages. You can set a template via `Template: <template_name>` into a files metadata. Then create a corresponsing `<template_name>.html` in your themes template folder.
That way I can have special settings for certain pages without having to work with embedded if statements in a sinle html template.
**-EDIT-**
But for today that shall be it. I hope you like my new website. Enjoy the new comment system as well (which I just moved to Disqus because that's pretty cool). Until another day.
~ Kate

@ -1,45 +0,0 @@
Title: Lonely Robot and the future
Category: OldBlog
Date: 2015-08-25 15:30
Tags: Dev Diary, Lonely Robot
Hey everybody, long time no read.
As I returned from vacation on the Chaos Communication Camp 2015 (Not sure if I'll post more about that) and probably starting a new job next week (*pssst* not sure if I should talk about it ;) ) the rest of my summer is still ahead of me and I'm booming with ideas and inspiration to do stuff.
I've started more intensively coding on the `newdawn` branch of Reedb, the C port of the database and planning some features for the old codebase via the `backports` branch. Because the new codebase will use a different crypto backend (from OpenSSL to gnu_crypt) a migration agent will be neccesary to migrate between 0.11.x to 0.12+ vaults. But as very few people currently use Reedb and most setups are for testing purposes only that isn't a very big priority right now. Depends on how the current version of reedb develops :)
But that's talk for another day. What else has been going on? After the Chaos Communication Camp 2015 I've been playing around a bit with my rad1o badge.
![Rad1o Badge](/images/rad1o_badge.png "Rad1o Badge")
But not much has resulted from that yet. The distribution I'm using (Fedora 22) at this time unfortunately has a broken arm-gcc package which means that a linker for embedded systems isn't working properly. So hacking on that will have to wait a little bit. But I will very likely post more stuff about that in the future.
Now, what was this post supposed to be about? Not Reedb. Or my new job. Or the Rad1o Badge or even the cccamp. It's supposed to be about a new software studio I created.
### Lonely Robot
So far we have a website at [lonelyrobot.io](https://www.lonelyrobot.io), an issue tracker at [bugs.lonelyrobot.io](https://bugs.lonelyrobot.io) and are expanding our web prescence but mostly working on projects.
Two things that we currently have going on are an Android game called **Graviton** (which started out as a tech demo that got out of hand) and, more exciting, LRGE, the `Lonely Robot Game Engine`.
The whole thing got started between my boyfriend and me who wanted to make video games together. And after a few months of day-dreaming, talking about ideas late at night and bitching about the current state of the gaming industry. But only after a few months of talking we actually started doing something.
Over the last couple of months we've been working with the LibGDX framework, making some minior and other major modifications to it and writing the specification for an engine.
We decided to use C++ for it and build it on top of SDL (the Simple DirectMedia Layer) with a very modular design which will allow for modules to be swapped in and out.
While we are still early in the planning phase of the engine it is what we want to focus our efforts on for the next couple of months, possibly the next year.
While we do make (free) software most of our ideas are for games. Our vision is that with this game engine we will be in a position where we can create them.
We decided to go for a self-written engine over something like Unreal or Unity because of a multitude of reasons. One of which is that neither of us are very great at blackbox development (that is the development of systems with another system that the developer doesn't fully understand). It is a problem I've always had with game modding but have also run into when playing around with the Unreal Development Kit.
Even with LibGDX I've always wanted to understand the inner workings of the framework which in the end lead me to modifying large chunks of it.
So that's that. I wanted to write about it here but will probably move other thoughts about the studio to my Lonely Robot dev blog on [lonelyrobot.io](https://www.lonelyrobot.io/blog).
That'll be it for now. I have an idea for a different project brewing in my head but I don't want to talk about it for now. All you should know now is: `hardware` :D
Until another day,
Kate

@ -1,53 +0,0 @@
Title: All aboard, it's a C port
Category: OldBlog
Date: 2015-10-21 18:02
Tags: Dev Diary, Reedb
It's been a long time coming. This blog post, not what I am writing about. Though...what I am writing about has also been a long time coming. So in a way, yes, I guess I was right.
### Anyways.
Over a year ago I switched to Linux. I was a Mac fangirl before. I loved the ecosystem, the OS, loved the convenience and the idea of having a system that just *worked* and the power of a root terminal.
But something changed. The garden of bliss grew smaller and smaller and as I realised that I didn't own or understand my computer, that Apple was in charge of what icons I used on my Desktop, I was drawn towards Linux.
I had used the OS on servers before and even my gaming computer ran Ubuntu to play the 64bit variant of *Kerbal Space Program*. But that last step...that took a bit longer.
One of the issues I was faced with was compatibility of software. And while most of the things I used (Eclipse, Sublime Text, Spotify, etc.) were also available on Linux, one thing wasn't: my password manager.
I shall not name it by name because I don't want to advertise a product I no longer want to use. But my password manager was a problem.
So just over a year ago I set out to write my own password manager. > How hard could it be < I remember myself saying. Oh could I have been more wrong? Probably. But it wasn't easy.
### The Origin
Back in the day (and I know it's silly because it's only been a year. But still - a lot of things have changed since then) I knew Java, some Python and wanted to learn Ruby. My brother told me about a mobile framework with which I could easily make a mobile version of the password manager and I was convinced:
I wanted to write it in Ruby.
7 months of development, feedback, discussions in a variety of hackerspaces with an even larger variety of people later - Reedb 0.10, the first usable version of what was once a password manager and had migrated into something bigger, something much cooler than I ever thought it would be: a database.
And as I added more and more features and this database became more and more intelligent I suffered from the limits of Ruby. Speed was terrible, packaging was practically impossible and it became obvious to me that Ruby was a language for the web (not because of the language. But rather because of the people that used it. The rails hipsters and web devs).
After mucking around with it for at least a month, trying several build systems and desperately trying to get this application to work I had enough. I wanted to port it.
Only around 3000 lines of code it wouldn't be too difficult to port Reedb into a different langauge. After all, most of the work had gone into the design process, not the actual coding. And while I wrestled with myself and tried a variety of languages, in the end I settled for C.
With it came a wave of problems. Conventient datastructures that just existed in Ruby such as the Hash (`{}`) or dynamic types made it easy to prototype something and quickly work with large amounts of data. All of that was different in C. And it took me a few months to really start to understand the C ways.
In the end I made a breakthrough with the design process when I finally discovered unions. And it's been a few weeks since. For now the C port of the project lives on the `newdawn` branch of the [github repo](https://github.com/reepass/reedb/tree/newdawn). The issue tracking has since been migrated to the [Lonely Robot Redmine](https://bugs.lonelyrobot.io/projects/reedb/issues) where you're welcome to fly by and check out the progress.
### The Future
I don't know how long it will take for me to finish this port. I'm making good progress, wind is in my favour. But there are still questions to be answered. Especially when it comes to the encryption of things.
But overall I'm happy with my descision. C is definately different. But it's a good kind of different where you can feel the control you have over your code. The performance is brilliant and a pure C binding makes integrating it into other languages or writing extentions for it as easy as pie.
I'll wrap this article up for now, it's gotten rather long. I hope that I can post updates about Reedb soon. Plus, I also have some other cool stuff lining up in the hardware section of my mad projects. I still want to do the Omnitool project and I'll definately keep that series alive. But it's a rather large undertaking. And I want to get some experience with smaller projects before I try to do something as mad as that. + it isn't exactly cheap to fuck up a prototype ;)
---
Anyways, I have to sail back into the C...
Kate
P.S. Sorry for the bad sailing puns. I promise there won't be any more, for shore.

@ -1,91 +0,0 @@
Title: Getting started with XMPP/ Jabber
Category: OldBlog
Date: 2015-11-24 12:14
Tags: Dev Diary
So after having spoken to a friend the other day and trying to get him to start using XMPP (aka as Jabber) instead of facebook messenger I realised that even while I thought it was trivial to set up other people might disagree with me. So here a little guide :)
Now...this isn't just a step-by-step instruction of what to do. In fact this article is more about getting you to understand XMPP than registered with a specific server. XMPP (formerly known as Jabber, just so you know why some people use the terms interchangably) is a chat protocol, not a chat service. It is based on XML and was originally created for near instantanious message delivery (chats). However since then it has been extended to also be able to VoIP and video (more or less good, that all depends on your client).
So XMPP is a protocol that anyone can just use. However...when I say "get started with XMPP" I don't mean set up your own servers and chat system. I mean Jabber, which is still the name of a chat service.
### A network instead of a server
The current open Jabber infrastructure is built around a bunch of servers (actually quite a **lot** of servers) that can communicate with each other. While inside the network it doesn't matter what server someone is registered with. As long as both people are part of the network they can chat with each other. And that's that. (Cryptographically and version wise it becomes a bit more complicated than that. But for the end user, that's what it boils down to).
There is a list of servers in the Jabber network (also called directory) available [here](https://xmpp.net/directory.php). As you can see there are quite a few servers out there that will allow you to register. Now...when picking a server please make note of a few things.
- Check the software has had updates in at least the last year. You don't want to trust your private chats to outdated software, especially because that will usually mean that the server admin can't be bothered to update to newer versions of plugins and protocols.
- Check that the server passes both "Server to Server" and "Client to Client" security tests. (Both in the green).
- You like the domain. You don't want to have a domain "@kinkymotherfucker.com" if you don't like it :D
### Register with a server
So let's asume you've found a server you like. Scolling through the list I would probably register at [blah.im](https://blah.im). Note that you will have to import an SSL certificate. You will have to if you don't have the CA [Cert Root certificate installed](https://www.google.com/search?q=What+is+CA+Cert&ie=utf-8&oe=utf-8#q=What+is+CACert).
But you will also notice that the server doesn't actually have anything on it's website. To register on servers in a lot of cases you will need a jabber client to do it for you. I am using Pidgin and will thus also demonstrate it with that client. Pidgin is free open source software and runs on almost any platform. But feel free to use a different client if you find one you like more. The features should all just be transferable.
To install Pidgin please go to their website and follow download and installation instructions for your platform. For mine (Fedora) it's as simple as typing `dnf install pidgin`. I will assume you managed to install it and we
move on :)
In Pidgin navigate to accounts and Manage your accounts.
![Pidgin Manage Accounts](/images/jabber/pidgin1.png "Manage accounts")
In the opening window click on **add** and then select XMPP from the list of possible accounts to add.
Fill in your desired username, the server you want to register with and a passphrase. You can leave the resource blank. Also make sure you tick the box "Create this new Account on the Server".
Servers provide different ways to register. Some just have a registration webpage, some have an API that pidgin can talk to. Some make pidgin open a browser window and guide you to their registration site. This is something unique to the server you choose to register on.
In the case of the *blah.im* server pidgin opens a new website where I can register my nickname (which I will not do because I already have an account I like to use). Check your input with the example picture below.
![Creating new Account](/images/jabber/pidgin2.png "Create new account")
And that's that. You should be registered and ready to log in and chat with other people who also use Jabber/ XMPP, no matter what server they're on.
### Encryption via Jabber (OTR)
Jabber by itself can be secured via SSL and several transport layer security measures but that makes it no more secure than any other service. The server provider can still read all messages and log them without you ever knowing it.
Because of that a lot of people use separate encryption with Jabber called "Off the Record", short "OTR".
What OTR does is encrypt messages on your computer, sends them to your friend and then locally on their computer decrypts them again. This has however two drawbacks.
1. Both you and your friend need to be online to chat with each other over OTR. You can't send them an offline message and let the server cache it until they come back online to read it.
2. OTR does not support multiple devices. That means you can't start chatting on your PC, have to leave and pick up the conversation on your phone. You will need to start a new conversation. And a lot of mobile clients don't properly support OTR because they shut down the session when you lock your screen.
To address both these issues there is a new crypto protocol called "Axolotl" which fixes both of these issues. Axolotl is however a generic protocol and can be used with literally anything. To adapt it to XMPP and integrate it into the already existing infrastructure of servers there is a second protocol called "OMEMO" which implements Axolotl for XMPP. It is however still very new and *very* few clients support it at this time. In fact, the only Jabber client I know of is **Conversations** on Android.
But let's assume the downsides of OTR don't bother you (they don't bother most people). How would you go about using it? OTR in Pidgin is a plugin that needs to be enabled. Depending on what platform you install it to you might have to install the plugin yourself which can be more or less work. (On Fedora it's just `dnf install pidgin-otr`)
But [you can figure that out yourself, I hope.](http://lmgtfy.com/?q=Install+Pidgin+OTR+plugin).
*Waits for you to install the plugin*
Good, now what needs to happen. First you need to active the plugin and generate yourself a key. Go to **Tools** and then **Plugins**, search for the OTR plugin and enable it. Then go to it's configuration page.
<img class="dual" src="/images/jabber/pidgin3.png" align="left"><img class="dual" src="/images/jabber/pidgin4.png" align="right">
You will need to generate a key. A key in this case means a private key, if you're already somewhat familiar with cryptographic concepts. It's a key that is unique to you, should be protected, private and *never* shared with anyone. It is thus called your **private key**.
When clicking the button to generate a key Pidgin will make one for you and save it somewhere on your filesystem. It allows you to encrypt and decrypt data (chats, files, etc.) that people send to you.
Afterwards a key fingerprint will show up and the generate button will be greyed out.
A key fingerprint is sort of a signature. It can identify you as you. So if someone sees your fingerprint they can be sure they're talking to the right person (if they've verified the fingerprint via another medium, e.g. meeting in person). But the fingerprint doesn't expose any secure information about your key.
You can also change some basic information about how OTR should work on your system. I won't go over these for now.
![OTR Configuration](/images/jabber/pidgin5.png "OTR Config")
And that's it. You're done. You can initiate new private conversations with people via the **OTR** submenu in the chat screen. And know that everything you say to the person in that session is secure. And here is the best thing: OTR provides something known as "forward secrecy". That means that if at some point someone steals your laptop or phone and you loose your private key that doesn't mean that, even if someone logged every single piece of encryted text going over the network between you and a certain person and has all the information needed to theoretically decrypt your messages, they can't!
Because while you chat with OTR the key continously changes. So if you ever loose your key, you don't have to worry about old chats becoming public or visible for others to see.
(As long as you don't log them in cleartext of course).
![Let's go off the record](/images/jabber/pidgin6.png "Let's go OTR")
#### Happy chattin'
~ Kate

@ -1,127 +0,0 @@
Title: Hacking on Reedb
Category: OldBlog
Date: 2016-03-14 10:43
Tags: Dev Diary, Reedb
So...it's been a while :) Exams are over, code has been written, bugs have been fixed, frustrations have been had. Terrible christmas gifts have been sold off on ebay and found a new owner with a misguided sense of style. I've also gone a bit mad with one of my other projects: The Christmas bauble. As you might recall it started as a harmless joke to learn KiCAD, ended up actually being manufactured (I never saw that bonus from dirtypcb for mentioning them a lot :c) and has now gone into planning phase for Revision B.
![Reedb Banner](/images/reedb_banner.png "Reedb Banner")
But more on that later. I'm back, in the spring with new energy and drive. To talk to you about Reedb (yet again).
With `0.12` coming closer and closer to being a reality I wanted to quickly draft up something how to interact with Reedb. The API is basically stable at this point and while the C-binding isn't quite done the C++ interface is ready to be used (and almost actually hooked up :) ).
### Initialising a context
Getting started with reedb requires a context which holds a bunch of information about what vaults exist, what tokens haven been scoped, users active, watchdogs, etc. etc.
In addition to that there are vault interfaces that get attached to a context that can then actually interact with vaults. This way different vaults can get handled by different interfaces that are completely separated from each other.
```C++
reedb *rdb = new reedb();
rdb->set_os(LINUX);
rdb->set_distro(SYSTEM_D);
rdb->set_verbose(true);
rdb->finalise();
```
The OS and sitro flags determine what configuration paths and formats are specified as well as how to launch reedb at system startup (if such a behaviour is wanted/ set up).
After defining all the parameters required or wanted to initialise the Reedb context call finalise to make it official and make the context usable. Before `finalise()` is called, trying to access other functions via the context will result in an error being thrown.
### Vault interfaces
So after having a Reedb context you have to register a vaults interface to it. Multiple interfaces can be registered and separated which means that certain vaults can be accessed that require different settings (for example a minimum passphrase length). Generally it just offers more flexibility to the developers.
```C++
rdb_vaults *v = new rdb_vaults();
rdb->register_vinterface(v);
vault_meta meta = v->create("fancy_vault", "~/Documents/", "MyD0gisnot!mypassword!"); // P.S. I don't have a dog :)
```
The create function will generate a key, encrypt the Master key with the provided passphrase and dump it to disk. In addition a folder structure and configuration is written. The config is mostly future proofing - none of the values are actually currently used. But it will hold information about zones, users and cipher modes in the future.
---
After creating a vault you still need to authenticate on it. The unencrypted key might still be held in RAM (in secure memory that is) but just because you created a vault doesn't automaticaly mean you have access to it. So after calling `create` you need to call:
```C++
// A token is malloced for you in secmem. Do not free it yourself. Let Reedb do it for you!
rdb_token *token = v->authenticate(meta.id, "MyD0gisnot!mypassword!");
```
You need the UUID from the interface we are addressing the vault via - we can find the UUID in the vault_meta we were handed during creation. Alternatively we can ask the vaults interface.
From the docs:
> A UUID is provided from the management wrapper and isn't stored in the vault itself. A vault doesn't care about its own ID, nor does it even know it has one.
>
> Do not try to hard-code UUIDs into your program as they might be non-persistent across runtimes.
Authentication only takes the ID and passphrase at the moment. However a user-auth function will be added in at least the next version. Both return a token that will be required for **every** operation that follows.
And that's it...you can now interact with your shiny new Reedb Vault :)
```C++
std::string file_id = "Reedb.org";
map<std::string*, std::string*> content();
content["Username"] = "Peter Pan";
content["Passphrase"] = "flower123";
/* Then take all that data and insert it */
v->insert(meta.id, token, &file_id, &content); // Takes the pointer to a content map to save memory during inserts.
```
As you can see you need a vault-id and a token to even be allowed to the next step. Then to insert a piece of data you need to give it a name. Reedb is object-oriented which means that every dataset has a name and is an "object" on the FS ( Blockdevice mode is in planning :) ). So from that day on your piece of data will be available if you query for "Reedb.org".
```C++
map<std::string*, file_meta*> data;
data = query_file(meta.id, token, "Reedb.org");
```
That will put a query return into your map. A query return isn't quite data. It's basically a name of a data-set mapped to it's head. A file head contains a bunch of metadata that isn't exactly deemed "important". Like it's name, a category, some tags and whatever else you might want to save in there.
In fact you can extend header fields at will.
```C++
map<std::string*, std::string*> meta_delta();
// ...
v->migrate_headers(&meta_delta);
```
From the docs (again):
> A meta_delta is the name of a meta-field that should be inserted mapped to its type in a std::map<?,?>.
> If a meta should be removed set the type to "-1".
>
> When removing meta fields from active vaults data needs to be migrated via rdb_meta_migr(...). Also be aware that removing active meta fields can cause terrible memory corruption. Be warned!
A file_meta is exactly that: a vault header. It can be further searched and filtered with RQL (Reedb Query Language) that we will not go into further in this blog post. Just know that it exists :)
*hint hint* `"$CATEGORY: [Social | Website | Online] $TAGS:[Private & Friends] $NAME: ~[Face]"` :)
Deleting, updating files and updating vaults is analogue to what we already saw. Basically you always keep your vault ID and token on you, then provide the interface with some data.
Some of the steps might seem a bit verbose but that's just so that the user (aka developer) gets maximum control over what she is doing with her code. It also allows for more precice error handling - narrowing down the source of the error further for the end-user.
### A tiny last thing
There are two interfaces for Reedb. A C++ and a C one. And you pick which one you want to use by either doing
```C++
#include<reedb/core.hpp>
```
or
```C
#include<reedb/core.h>
```
The C Interface is pretty much analogue to the C++ one (with obvious slight differences).
```C
vault_meta *meta;
rdb_vaults *vaults = rdb->create(&meta, ...);
```
That's it for today. I hope this article gave you a quick introduction to the native interface and makes you at least a little curious or excited to work with it :)

@ -1,116 +0,0 @@
Title: LibGDX UI utility: Super UI
Category: OldBlog
Tags: Dev Diary, LibGDX, Game Dev, Lonely Robot
Date: 2017-01-24 00:14
**Let me tell you a factual statement**
*UI programming is terrible*
**Let me tell you an even more factual statement**
*UI programming in LibGDX is even more terrible*
I am a big fan of LibGDX. It's a really nifty library/ framework to get started with game development if you're more comfortable inside a code editor than a full blown game engine that is more targeted towards designers and artists. And I put my money where my mouth is: I have a series about LibGDX development for beginners on this blog and work almost exclusively with it when it comes to my own projects.
Yet, there is something that bothers me and there didn't seem to be a great solution to fix it. UI code structure. In this post I want to highlight a utility I have written for LibGDX which is very easily embeddable into your existing projects which will you help structure UI code more efficiently.
## The root problem
The reason I dislike UI programming with LibGDX is that it usually results in very long code files or passing dozens of parameters into sub-classes that are needed to update the UI for button presses, etc.
This goes so far that I have written an editor for game assets before just to realise that (once the development was complete) it had become completely unmaintainable and I had to start from scratch with better structure. It is incredibly easy to just throw out a UI design with Scene2D and LibGDX but unfortunately it is equally easy to produce very bad code which will turn into a big spaghetti mess.
Let's look at an example problem that I wanted to solve.
![LibGDX UI design problem](/images/libgdx_ui/01_base_problem.png)
Looking at this structure we have three main components that interact with each other. We have a class that handles UI logic (setting up actors in tables, adding listeners, etc), we have a window state which in the particular case which made me write an alternative was a "Lobby Handle" which coordinated what players were going to enter a match, the map, game mode and if everybody in the multiplayer match was set to "Ready". Lastly we have the actual network signal handlers that listen to TCP/ UDP packets and execute code to write/ read from the window state as well as update UI elements.
Implementing this structure with Scene2D and LibGDX will result in a lot of very ugly code. Because the network signals need to know everything about the UI (how it is structured, etc). And our window state can be written to by two different sources which means that we need to mutex it to avoid race conditions.
So, what was I trying to solve? First a bit of limitation of scope. Because a lot of UI problems have been solved over and over again and usually at the cost of runtime performance or with a *lot* of extra code.
1. UI code doesn't have to be embedded in a screen
2. All UI code can access the shared context of the screen
3. UI elements can update each other
4. Clean API that can be called on from anywhere (with a reference to the handle) that triggers range of functions.
So with that in mind, this is what I did.
```java
class MyUIHandle extands UIHandle {
public static enum UI implements UI_BASE {
PLAYER_LIST;
}
{ /** Initialiser block for new objects */
registerHandle(new PlayerList(), UI.PLAYER_LIST);
// ... more handles
}
@Override
public void initialise(Stage s, Object ... var) { ... }
public class PlayerList extends UIContainer {
@Override
public void initialise(Stage s) { ... }
// Define more API here ...
}
}
```
When we initialise a new `UIHandle` the initialiser block will create our `PlayerLists` and register them with the `UIHandle`. That code is hidden away from you. You can see that we're implementing a different enum type that we overload with values so that we can address submodules via a compile-time checkable value (such as enums). From inside (and outside) this class `UIContainer's` are available via `handle.get(UI.SUB_HANDLE)`. Obviously keeping your enum labels short will make your function calls snappier :)
The following graphic will sort-of explain the layout in more detail.
![Super UI fixing attempt](/images/libgdx_ui/02_ui_structure.png)
What you might also notice is that the `UIHandle` has an initialise function with variadic parameters while the `UIContainer` class only takes a stage. That is because window context is stored once in the `UIHandle` and then accessable from all `UIContainer` classes. This way we only need to do the inversion of control pattern once instead of for every sub-component.
You can keep the `UIContainer` classes outside this code-file. Then you might however want to provide a construct that does another inversion of control so that an external `UIContainer` can access the context provided via initialise!
```java
public class PlayerList extends UIContainer {
private MyUIHandle parent;
public PlayerList(MyUIHandle parent) { this.parent = parent; }
// ...
}
```
Now let's talk about that public API. In our original example we wanted to have networking code update some UI elements. And we want UI elements to update other UI elements. So first of all, we keep context in each `UIContainer` about what UI elements are accessable to it. So what we can do in every of our submodules is this:
```java
parent.get(UI.PLAYER_LIST).updatePlayers(playerList);
```
It also means that if we get new data from – say – a network socket or AI simulation, we can very easily update data in some random UI element.
```java
handle.get(UI.PLAYER_LIST).populate(playerList);
```
So all in all, we have solved the following problems:
1. We have access to all game state in the UI code without passing too many parameters into lots of sub-classes
2. UI code can be moved into lots of files for easier understandability
3. Context isn't duplicated
4. UI code can update other UI code without needing a direct reference to it.
The individual `UIContainer` instances are essentially independant of each other via dependency injection.
This library isn't done yet. Most of this is kinda hacked together to fit into **my** game. But I'm interested in making it more generic and putting it on Github. Especially because I can see myself using it again in the future.
Hope this might be useful to somebody out there. If you have questions, comments, hatemail...
[Twitter](https://twitter.com/spacekookie) or [E-Mail](mailto:kookie@spacekookie.de)

@ -1,60 +0,0 @@
Title: Dabbling with Moonscript
Category: OldBlog
Tags: Dev Diary, moonscript, programming
Date: 2017-05-06 11:55
![Lua means moon in portuguese](/images/lua_moon_banner.png)
Recently I've started learning/ using Moonscript. It's a language that compiles to [lua](https://www.lua.org/) and as such can run in the LuaJIT, an alternative lua engine which allows very easy and *fast* ffi calls into native code. This makes lua code capable of writing very performant applications and games that use native rendering, window creation or general libraries.
But in my opinion lua has always felt a bit cumbersome. I use awesomewm so I had to write it occasionally to customise my UI layout. And this is where Moonscript comes in. It's a lot of syntactic sugar on top of lua as well as some other concepts such as object orientation which lua just plain out doesn't have. And while yes, you can write good code without OO (*cough* **C** *cough*) it is a nice tool to have in your pocket, especially when writing GUI applications or games.
## The language
```Moonscript
class Thing
name: "unknown"
class Person extends Thing
say_name: => print "Hello, I am #{@name}!"
with Person!
.name = "MoonScript"
\say_name!
```
As you can see Moonscript is an indentation based language which (in my opinion) combines syntactic elements from lua and ruby together. In the snippet above (which is from the [moonscript website](http://moonscript.org/)) you can see classes, inheritance as well as the `with` keyword which allows you to initialise/ work with objects without typing it's variable name over and over again.
If you want to learn more about the language, I can only recommend you have a look at the [Moonscript in 15 minutes guide](https://github.com/leafo/moonscript/wiki/Learn-MoonScript-in-15-Minutes)
## How to use it
You can just write Moonscript files, add `#!/usr/bin/env moon` to them and get going. Obviously that's pretty cool for little scripts that you just want to get going. But not so great for larger applications because a) you don't have access to `ffi` via luaJIT and b) it adds additional startup cost.
So instead for my projects so far (which so far are a [game](https://github.com/spacekookie/dinodino) and a desktop app) I use a `Makefile` to build and run the Moonscript compiler and then execute the `init.lua` with luajit.
```Makefile
SOURCES := $(wildcard *.moon) $(wildcard **/*.moon)
LUAOUT := $(SOURCES:.moon=.lua)0
.PHONY: all run build
all: run
build: $(LUAOUT)
%.lua: %.moon
moonc $<
run: build
luajit init.lua
```
## Wrapping up
So...I'm kinda excited about this. Most of the code I write is either in C or Java (depending on what exactly I'm doing). And those two strongly typed and compiled languages have served me well and will continue to be my go-to solutions for a lot of problems.
But I've long been looking for a dynamicly typed, interpreted/ just-in-time compiled language that I can use for anything from little scripts to medium-sized desktop applications. I used to use python for this but have recently (over the last 6-9 months) fallen out of love and developed a rather passionate dislike of it and it's ecosystem.
My current project will get it's own little article at some point but I don't mind teasing the progress here. I'm writing a new UI for redshift which works with X11 linux backends and is heavily inspired by f.lux on MacOS. It's written in moonscript, with my own forked version of redshift (which I call [libredshift](https://github.com/spacekookie/libredshift)). It's on [github](https://github.com/spacekookie/redshift_ctrl) and licensed under MIT.
Hope I've made you a little curious about Moonscript. And stay tuned for updates on future projects with it :)

@ -1,112 +0,0 @@
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
❤ (rayya) ~> cat msg
Following are my public gpg key as well as Threema Fingerprint and others.
Threema
=======
ID: 77WYDHA2
Fingerprint: AB2A 4F8A 8FF9 6335 75C2 4E0C 175B C0D6
Public Key Cryptograpy (GnuPG)
==============================
Plain copy of my key can be found here
https://spacekookie.de/pgp/6FE1BBF3.asc
It is also available on the MIT keyserver.
This document was last changed/ signed at around
❤ (rayya) ~> date
Sun 7 May 14:09:59 CEST 2017
❤ (rayya) ~> gpg2 --fingerprint 6FE1BBF3
pub rsa4096 2017-02-02 [SC] [expires: 2019-02-02]
9F18 A093 CF65 F938 E4C8 EFA4 29E0 5751 6FE1 BBF3
uid [ultimate] spacekookie c-base <spacekookie@c-base.org>
uid [ultimate] spacekookie (Using computers to create weird random patterns...) <kookie@spacekookie.de>
sub rsa4096 2017-02-02 [E] [expires: 2019-02-02]
❤ (rayya) ~> gpg2 --armor --export 6FE1BBF3
- -----BEGIN PGP PUBLIC KEY BLOCK-----
mQINBFiTCvcBEADHjyVbz7g3OBehkRxyfCBQY5MIBl45YINzVSO5wneNi5OgUs0F
7XVRlgv43iOIk77pC0DyfnODkEQ2r+uxsnFAtgBcULDrEwsNa/npGiV3byHohAQW
ELMB/yJu6A6ZkVp2MQmKanieSfgS8FNe7Dmc728uTu0pbQjpXVwfgqbDAuKeGPX7
ANSy448FNqS3UDhwmnqMFG1Q0BraimqBHDbzpKvqUSmpNwxo92gGJdupZHzgZzfr
KaekzKbcWN98AI7qTedc2c21uOVA5sLH3ue01Ql34/ScalPGMWJghdbQRCFqkQ2B
AeSvKWvd9BCi/stDVnoQ6v5MlyEQIKd1N4VeZ2aNwNSHcc79hP0T1WCsoemfK+jt
L+DtjpDm3cLhraHEF9VKrKGtaUBrYdkLM/E6y65lRCMP0Sav3tdb5aqB5ZdeJkzA
AbAWFkXpbNWlLOQuhWKJhmgs8j5XMzsJU92Z/X7VlAN+yRGKyARBDVKKjpKiH4Ml
Wp58kaSp9wNSHunTUMANAvsVpcF/RtXPyXxs24KdzkMtuwQKKNbV5P+dUFOq7efq
/oFru3uij6NznV5KpczwtlO9RAKgzg8g9FQMEv+xpRN+00QzAfB8wTAwdCw9bFSA
577TEhV57bKW1so4IdrfNHOD6nxInH0iLSagFt+5/PyW5CGv95E7//8lGwARAQAB
tFhzcGFjZWtvb2tpZSAoVXNpbmcgY29tcHV0ZXJzIHRvIGNyZWF0ZSB3ZWlyZCBy
YW5kb20gcGF0dGVybnMuLi4pIDxrb29raWVAc3BhY2Vrb29raWUuZGU+iQJUBBMB
CAA+FiEEnxigk89l+TjkyO+kKeBXUW/hu/MFAliTCvcCGwMFCQPCZwAFCwkIBwIG
FQgJCgsCBBYCAwECHgECF4AACgkQKeBXUW/hu/OTcw/8CFUEn7Zpkbax54Ie4LF6
uvtoKNhdoSCoh6fk404X1MPaGA0P0t4psRNQGVhCUXDPosMGre2ljWOApPBtutlD
cbVhicqdfiXHyIXudhwV54zj+XoRfNg32sWOrm7Kewo8AiCxEbscJ1o8RBoEGp2Y
KIXV4/6Ngh43Ok9VQr6rakvHVeSlUyo84CFrqOk88mzFuvuG6zzU1+ilGVGs8tlu
Q0K2Cmt+3yq9pFch3uwoGKE0w6lO+CI6vh4jqgNq8kNVBw3V0JTgZogOeuoZD1Rd
JGCBLkVR41qvhR0Es6COgTaS6dlRAcRO0e1KmZxzWepAgkm+HtmWAfF03zyCGYu5
MnVX6wMo8vSfSaor0KfjyqUiJ6nWjYCQ874AW8wqQAmJ8HXdRcnXazzbXBdB8Mpy
bLhn2wM7dDYBG8lRjWssMDOyqsqtkw9/Fm2LCDaonBD5VN7vg8aWt2MOdrjSSnT3
5uH5d+fCLALCVcl6TFvWXia3KcKLfBUR3XfT0gHaGo/fBe2SGt/LYNWj3Ww95W/7
6Ftz6D6Pzlq0AEvdpuBzx+h4EAiTTC5GDWhgyq3GO1o76ty4wXUL6/r4jk0Htec0
Y9vfCcS+jD3Z9wprglUB98UWUpPlBbwQ/5ukgN+AjMqR1m56SUb0L6ePEAGNTB1L
xn4ufMGOAvUoQ19QYGVoMqK0K3NwYWNla29va2llIGMtYmFzZSA8c3BhY2Vrb29r
aWVAYy1iYXNlLm9yZz6JAlQEEwEIAD4WIQSfGKCTz2X5OOTI76Qp4FdRb+G78wUC
WJMMCQIbAwUJA8JnAAULCQgHAgYVCAkKCwIEFgIDAQIeAQIXgAAKCRAp4FdRb+G7
89woD/wPKuieSmCj/PH+7JfUB7l+J+VtDdLGoDCziLmZPTCasPOcaIqHuxN4Xa4/
SNCauVuRf0XMjh1slcUqK0yfV4HcSJSMw5kMk/DYIlz9cNsntjaHrgmD9HxZNHd/
6Y+VpPMaYhoubJs18yir+kGcSANJUb03BS9YdYj1Oua0YhPis7/wehTVACehc0ZT
wntYSwn/U/KXEsUQzOgO0dij54f5MrS9VFBoXmQLJKMPSja3Mj70+mBIrsyQqnaK
+nja9NoMO1ExZHqgpXhkiEnTYEhFi20olRhuxbMPrtLcmLkLlYJ5tOQ59pM3BmYh
aYDH2/wqT8m9mfXeLJ3NFJxibGCnmPlpfc3/rCLuz/bljI9D2OX4MfH8HZcX39tO
rOgCaAExztCV6dIprmksy/4QHXTgkguxIveAQEuZscNdCcCZ3OgVCBcynuVIS5gw
kylHs8odvym3X2EAH8iAK2XtNrnTBUvSaRHei6/PgGnyFwIapRIQqeuiGw4v0Y8H
KphzOEMDULA0SRg7yaiNQIU4OYUeazhbkYAuQvyr3Qh7BFZJO4Vh1uNXtvspm+u+
K2mFHBFMFPCdafZSjDHqgDhdIk6vOQGchOPEk4tc9vOBi8oynWmPpRHtrE0sVNCm
8pecsSkTJlODKtx7gyBUdbzhbZuDp3NcLna8oH/Y193QlLWe5bkCDQRYkwr3ARAA
wiTra2jJpDOd+EIWFKp1Rc9zoFXKL8/sWQp5348kjept+h9TAuy6FXXoUksFxWuz
R3N5meL04YxAMzjLMu6V9zeAGIpnc29LJG1GAnVGmZwsqh9xWctvyRU0ha/OIsWH
DD5uvXaEjwNCiAYIYjZTBTQZYCoCn8LEgOp/U1bYH4FbB9SUMNVWw4Df2qnmza3Z
MW51auCjVjHiXxhgJjMvsgFHXY4wJlmUPCNf7h5fjopzbWl5eT6aW99r5wnd3anM
MHQoCvY9+/jynSdIh/YLwZD46QTl25zLAq8zvc/zLQUrseaI0IBrU9RY9JAaJ2i0
2PrOcoJ6VisD7a08n/1AfULrt6qTzZAetRU7uY2/hNv8Qfk+a7uIQ6J5IjT6Porf
1k2iIjbBJPUrE9nv+5eJhip/B061lsab2uRYmDTjNo03mvT7+kCc0ueMQHdJkt7r
YG1mMSAbXcXr3ayaShUTqK6ZA+62xrGTdIBV7bJ/i3r++CK6OTO3svQrSAw5kP5T
1/tofXJaXc8YAyD4AZgjEbmJ6nKPDVuiyZH6RWrqgWAXddO3w4RuMEkEcAUyG8Ow
sy7yAGKl3Pv1iSd2rNzewBVRb/igJx0Pi/TGmfAJ7YXT6wfMZAayBnGYtn2kS9i4
JQiyJee1afpmaoYjOC2zpfMcpKauyoqDo2rHE/GbzvMAEQEAAYkCPAQYAQgAJhYh
BJ8YoJPPZfk45MjvpCngV1Fv4bvzBQJYkwr3AhsMBQkDwmcAAAoJECngV1Fv4bvz
ktkP/2JJRdF/yW+OR0Njo+ZTGhBVNaaOzfhi2VQu+XbpDS8ymdJqmL0v7i+wGZ/D
hTwLTmRMQBYopEm5jU+HGBTbAwu0LF3r7ecUDx+7QUqw/u7rZco/IZws26wxhbyZ
pMWLm3iIffzkpQJ9mz3Y4HUFozV6tq5fr1NCt/cF/AknzUDzvZTif7wOAeiCh9Ad
fKf4w3sxig/7Vx4Up8qfCE4W0momjF7yS0DQxgz4O483eSUZ2dvazqYP7a9FBYfM
JmXLD2hfM5a7uGrBvnaUDODWPnWpcvySzAvsg/aw3ckbg6NGe4h3VnnzLy/u9DI9
qtCTTCyKIfjixTN+Lxd7YyG6/G0C68moy45MRpxiuZldwDk6JDLHe8B7581V8WlJ
gBX+LwFjzcKAE0FkkXX5MbBM8sGn48phRlLc43VD+oOgIB5P6cbprbOrQ9Y/mQty
0Qvxdy7AzJGFrnZo+UMHc2JOuWBHcMvJcWGbppCpalpgmNjXTkDg0JzzhSj84nay
MLuEoA6FuF/Zo5PBvGOtFViLb3MMnsndZfjlm4QrRrWiLxYvdnqG4elFMJuVWsYA
J3ydeRpI7N3tQg6XA+pPiAeSn6evBR19n/W6h8dZN6vvFG4vlvUdm8P+dGhhxTB1
Oc0zZg7qrYqTQnCZxPB0AltH8ZUCq2iBGFMS5UYBidPdw3e5
=vSgE
- -----END PGP PUBLIC KEY BLOCK-----
-----BEGIN PGP SIGNATURE-----
iQIzBAEBCAAdFiEEnxigk89l+TjkyO+kKeBXUW/hu/MFAlkPFaQACgkQKeBXUW/h
u/NbgQ/+LRikzv8yFpVzbNZTg1mEQ+wFDZEnrwSDvdEL/+iqZ8X8V3NWz9svUIF/
mMjQeYH3XcZqJ19XpyfSd+1MiFoNRCU04aaOwopmWrok0qYoKW7zdwTHmiBnftCs
vctvO5o0INN2Qfrhwjzot2EfBiuo6LBG3lV6rWdMZFkJFlzoCqlFrMVWBAYBtXlN
QhPgxfanp3Fg7hKGS5sYjtGlGEY6Qu1nkbU/92sHtCnSb+2TM8fRij4Su/5B+XMH
e2UbmMcSY2iS2tn46sG0hAVky5+BF2JHKWVOECrszqVwxDRhqPBdVOKD3biXrQsM
9NistBGaFoYcVxN7wvhVdOd07pqc6HV1Dmv3ngro6kX3j9KsB/70OvKntsVWbnph
kEwoOVAhPs8f6zNo/lGhs9vYsLgkbSpzflKYlEqHlOFOPSGzHAAeM7eMi6aWVMWB
LnVxaKtogE1m7lPdgkHt0V6sqHUFf+j7eHrWp0J8w514FcO9dhhNiY0Yvn1xJCBM
tEkemLyMfk8gx3M1lz8p7RkKR601GcXi6mtpetREPL40zUt8IhRDwUwXM6Pvuspl
pKUxhkbE8CeJ9vvyqVhoAjTfEGDpXI6sb53le7RXkw8JdQ9ueoJyt4Fk/zXXxvdC
3XMB6dIEFQ979IHp04Pb8njdWEokzNOMlUPyrTR0UvYXUPeDmhs=
=ZvDg
-----END PGP SIGNATURE-----

@ -1,114 +0,0 @@
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256
❤ (idenna) ~/pgp> cat msg
Following are my public gpg key as well as Threema Fingerprint and others.
Threema
=======
ID: 77WYDHA2
Fingerprint: AB2A 4F8A 8FF9 6335 75C2 4E0C 175B C0D6
Public Key Cryptograpy (GnuPG)
==============================
Plain copy of my key can be found here
https://spacekookie.de/pgp/6FE1BBF3.asc
It is also available on the MIT keyserver.
This document was last changed/ signed at around
❤ (idenna) ~/pgp> date
Thu 2 Feb 11:52:00 CET 2017
❤ (idenna) ~/pgp> gpg2 --fingerprint 6FE1BBF3
pub rsa4096 2017-02-02 [SC] [expires: 2019-02-02]
9F18 A093 CF65 F938 E4C8 EFA4 29E0 5751 6FE1 BBF3
uid [ultimate] spacekookie c-base <spacekookie@c-base.org>
uid [ultimate] spacekookie (Using computers to create weird random patterns...) <kookie@spacekookie.de>
sub rsa4096 2017-02-02 [E] [expires: 2019-02-02]
❤ (idenna) ~/pgp> gpg2 --armor --export 6FE1BBF3
- -----BEGIN PGP PUBLIC KEY BLOCK-----
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
=vSgE
- -----END PGP PUBLIC KEY BLOCK-----
-----BEGIN PGP SIGNATURE-----
iQIzBAEBCAAdFiEEnxigk89l+TjkyO+kKeBXUW/hu/MFAliTEe0ACgkQKeBXUW/h
u/Pb1w/+IYx8RUaxGQxq8jphBaCwAfUvOOl3DQwPLETsvz1UYQPcNTmXbKK8GziJ
ki69eizxMcikVwTT0CinRX0NtE1qeGKmPiTT9Zxoi688QeXdDZDksOrLHGS+bqfV
WxwQG2hGUjLUqCjKsBIz4OwiZ8xqff+Z3HqYhTc1GpdwbIXG43l+tLFkU5eTaERU
u/uSPjnmbxrZRGLzv0fnrppEKXPTBmm8O3hIM9Cp+rZIQw9rbbkGSGeRXtSDDsC/
6dkBKvM7YDqw/9/EnFbrw1vMBnVDdmMvMH/KQIxDuF+mEkq9eNOvR8QCJa8SDMOH
Hdhi8sJqS7oX91kH0TU86Uym+/GKlUfq/VDZCGssOqPlFLc0ZOWKL1VoReVwb+34
hkowMP5i4XieXuY4JtBTuDjvGbauZDorFqONosAzq67zf2FTY3JrGZay0Q+3/rs9
q3FbU8esjM/q64XltuWmZfGnbRU3Xdfr+V/YCqLiUXfsLJ38WZBXruL31ar9CjcL
PMN/YipyvSkSze8IBHBtyonDg5Zug7ntL6Ku58XitQBHRy8KDuJL74RiABmri2DM
Tpo1kwGokd3Sj24VX4JEg/jAczC93x/F9B2BKCY1tvqSDCdavrToSbSOva7//9sC
MV2oN8slEE5fPgxT9A8DTORImfstI9AnUBUn+julhMer3FSaNWk=
=MXQM
-----END PGP SIGNATURE-----

@ -1,16 +0,0 @@
Following are my public gpg key as well as Threema Fingerprint and others.
Threema
=======
ID: 77WYDHA2
Fingerprint: AB2A 4F8A 8FF9 6335 75C2 4E0C 175B C0D6
Public Key Cryptograpy (GnuPG)
==============================
Plain copy of my key can be found here
https://spacekookie.de/pgp/6FE1BBF3.asc
It is also available on the MIT keyserver.
This document was last changed/ signed at around

@ -1,296 +0,0 @@
Title: 01. (LibGDX) Game of Codes: The Setup & Basics
Category: Game of Codes
Tags: LibGDX, Tutorial, Game Dev
Slug: 01-libgdx-game-of-codes-the-setup-basics
Status: published
**Hey everybody and welcome to a new/ old series on this blog about LibGDX.**
LibGDX is a Java game development framework based on LWJGL and OpenGL which makes it relatively easy to make a game from scratch without requiring a big engine. It supports Desktop, Android, iOS and HTML as export targets which means that your game is automatically cross platform.
Getting to know the framework can be challenging in the beginning, which is why I wanted to make a little series about it. Before I moved my blog to a static site generator I had a rather popular series about LibGDX called "Game of Codes". Unfortunately large parts of the guides are now outdated and no longer relevant. And the Wordpress export destroyed most of the formatting.
Which is why I decided to rewrite them. Here it is: the Game of Codes! *plays theme song*
NOTE: This tutorial requires a basic level of programming/ scripting skills. General Java knowledge is required or at the very least knowledge of how coding works. If you don't know that yet then I
recommend [Bucky Roberts Java Programming series on Youtube](https://www.youtube.com/watch?v=Hl-zzrqQoSE&list=PLYJQBQw9Wdiid6eT1_DqBP3lnbJCzo3s8).
It's very good!
### Setting up LibGDX
Now that we've got that out-of-the-way let's set up our workspace to make some neat games. I am writing and testing these tutorials on Linux. So if there are some platform specific issues you encounter, please give me feedback at [kookie@spacekookie.de](mailto:kookie@spacekookie.de).
1. First of all you'll need to have Java and an IDE (Integrated Development Environment) installed on your computer. In this series I will be assuming that you're using **Eclipse**. For pointers on how to install that, please use Google!
- LibGDX uses Gradle as a build system. The latest version of eclipse has it integrated but older versions might require a plugin!
3. Go to [libgdx.badlogicgames.com](http://libgdx.badlogicgames.com/) and download the libgdx setup app. It will help you configure your project with Gradle so you can either develop on it in a text editor of your choice or import it into an IDE.
<img class="dual" src="/images/gameofcodes/series01/02_setup_ui.png" align="left">
<img class="dual" src="/images/gameofcodes/series01/01_setup_ui.png" align="right">
Let's step through the setup UI on your left real quick. We have some base settings. You can fill out the name of the game, the name of the main class as well as the package. If you're new to Java, the convention is that every application has a unique package root. And it's usually the reverse of a web-address. So for me it's `de.spacekookie` and then the project name. In homage to the original tutorial series I will call it `de.spacekookie.starchaser`.
Also important to choose are the directory where to setup the project as well as your Android SDK location (if you want to build on Android). I will be ignoring Android for now and focus on the Desktop.
<br/><br/><br/>
<!-- Introduction to the module we need -->
Make sure that you tick the following extentions (and extentions from the "third party" visible below the main window):
- Ashley (Entity management library)
- Box2D (2D physics)
- Box2DLights (2D realistic lighting)
- VisUI (Good looking skin for UI elements)
Also make sure that if you want to use an IDE (such as Eclipse or IntelliJ) to select the project export from under "Advanced". When you're done with the configuration, hit that lovely "Generate" button and let's get going with development :)
I will skip the importing step because that will be different for different IDE's. All I will say is that in Eclipse you should avoid putting your workspace *inside* your project directory as it will cause issues for you in the future (or during import).
> **Tip**
> While there are many ways to work on LibGDX, in this series I will assume that the project was added to Eclipse via Gradle while the building is done via a normal "Java Application" launch target in Eclipse. This is (in my opinion) the best of both worlds with a quick and easy build but the dependency management of Gradle built int the IDE.
### Working with LibGDX
So assuming that you were able to follow until here, you should now have a Java development IDE in front of you
<!-- Add a picture of Eclipse here? -->
> **Tip**
> LibGDX is very closely entangled with Android. For example, if you create a project to have an Android target, all of the game assets will be stored in the "Android" subfolder because of who the system handles file imports. This means that the Desktop/ iOS and HTML versions only use symlinks to the Android assets directory.
> If you don't have an Android project (only Desktop for example) assets are simply stored in your core project with all your game code!
Now that everything is ready to go, let's investigate a little into what code was already generated for us and what we can do with it. Feel free to just hit that "build" button and get started but we're taking a more scientific approach :)
<img class="dual" src="/images/gameofcodes/series01/04_eclipse.png" align="left">
As you should already have noted there are several projects that were created for you. One project without a suffix and multiples with suffixes. The one project without a suffix is called the "meta" project (it contains relatively uninteresting things), while the other projects have to be divided into "core" and "targets". The idea is simple: you write all your logic, rendering and gameplay into the "core" while platform dependant code is used in the "targets". If this is complicated to understand, don't worry. It'll become clearer when using it.
So as explained above, we will write most of our code in the highlighted "core" module. It is where you should in fact write all of your game code that isn't platform-specific to launch the game (for example getting the screen size or setting a custom icon).
Please go ahead and open up the two files marked by arrows. They are the only code files that were generated for me. The lower one labelled `DesktopLauncher.java` contains the main function which will actually launch our game. The code should be very straight forward and we will look at the configuration settings later.
<!-- Explain the basic structure of the project & function lifetimes -->
The second file, labelled `StarChaser.java` in my case (and whatever you named your main class in the setup tool) contains much more interesting goodies: game code!
Inspecting the code from the StarChaser class you can see a few functions in there that are responsible for describing the lifetime of our game object. These function are `create`, `render` and `dispose`. The create, play and, when we're done, destroy our game object. Everything else we do lives in between those functions.
In fact, there are a few extra steps in between that are hidden from you by default. Check out the following list:
```java
/** Called when the game is created **/
public void create();
/** Called after create and every time the window is resized (if that is allowed) **/
public void resize(int width, int heights);
/** Starts calling after create() and resize() and will be
* recalled every frame. This is your game loop! **/
public void render();
/** Called when the game is closed on Android **/
public void pause();
/** Called when the game is re-opened on Android **/
public void resume();
/** Called when the game is closed. **/
public void dispose();
```
This layout allows for very structured game code that walks through stages. You can of course allocate new objects in any of these functions to move functionality away from one class but in the end, you are always bound by the lifecycle of your game object. Note that all of these functions are provided by the `ApplicationAdapter` super-class that our main game class implements.
> **Tip**
> If you're ever curious about something you use/ extend/ implement works under the hood, don't be afraid to right-click on the part in question and click "Open Declaration" (when using Eclipse). This will open the source file for this module and you can see what is happening behind the scenes. In fact, I highly recommend being curious throughout this entire series.
<!-- Explain the awefulness that is Eclipse run configurations -->
If you haven't already launched the game to see what it does, I would recommend you do that now. Click the small black arrow next to the green "play" symbol in the top bar (or F5 in Eclipse), select "Launch Configurations" and create a new "Java Application" config. Check out the picture below for reference on how to fill it out. And if you have issues in this step, there are plenty of tutorials that go into depth online!
![Eclipse Launch](/images/gameofcodes/series01/05_eclipse.png)
<div class="alert alert-warning">
<h1>Fixing an Eclipse error</h1>
<br />
<p>By default LibGDX uses Gradle. This means that paths are considered differently than when you're using Eclipse. For example, the above code will not by default work with Eclipse unless you tweak something. In fact, you might encounter an error like this:</p>
<pre>
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: badlogic.jpg
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:148)
at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:88)
at de.spacekookie.starchaser.StarChaser.create(StarChaser.java:17)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:147)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:124)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: File not found: badlogic.jpg (Internal)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:136)
at com.badlogic.gdx.files.FileHandle.readBytes(FileHandle.java:222)
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:145)
... 7 more
</pre>
<p>While when you build your project with <code>gradle run</code> it will work. This is because Eclipse handles import scopes differently and we need to respect that. You now have two choices:</p>
<ol>
<li>You hard-code import paths from the filesystem root (i.e. "/home/spacekookie/.../artpack1/uss_pixel.png"</li>
<li>You add your assets folder to the source path in Eclipse. <strong>This is what I will be doing in this series!</strong></li>
</ol>
<p>Right-click on your desktop project and navigate to "configure build path" as shown in the picture below.</p>
<img src="/images/gameofcodes/series01/06_eclipse.png">
<p>Select "Add Folder" in the window that should have opened and in that dialog select "assets". Close the dialog and try to run the game again. It should now work!</p>
<p>If you're having issues with this step, feel free to e-mail me at <a href="mailto:kookie@spacekookie.de">kookie@spacekookie.de</a></p>
</div>
### Understanding the Code
*waits for you to launch the game*
Cute, eh? Not exactly a game but it's a start. The example demonstrates a few basic principles as well as *super* basic 2D rendering. However, before we go, throw it all away and implement our own cool stuff we should try to understand how the current code works.
```java
//...
public class StarChaser extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
@Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
}
@Override
public void render () {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
}
@Override
public void dispose () {
batch.dispose();
img.dispose();
}
}
```
Let's ignore the package definition and import statements and jump straight into the class declaration. We're creating a class, extending the `ApplicationAdapter` which is responsible for turning the class into an actual game object (as described above).
The first function that would be invoked is the Constructor. Because there is none here, we will skip it. The next function being called is `create()`. It initialises a new SpriteBatch and afterwards a texture for "badlogic.jpg".
You will be able to find the texture in the assets folder. And, if you change it, you will notice the changes in game as well. So far so good. What the hell is a SpriteBatch?
A `SpriteBatch` is an object which is used to keep context during 2D render calls. Basically, you give it a positional and transformational reference frame (in our case DEFAULT) and then tell it to draw 2D images. But I'm getting ahead of myself. Because in this function we only create a new SpriteBatch. So all is good.
Moving swiftly on to the `render()` function. This one is more interesting. The first two lines are two OpenGL calls which prepare a frame to be drawn. The first line sets up a colour while the second line tells the graphics processor to take the prepared colour and paint the entire frame with it. The colour representation is in RGBA (Red, Green, Blue, Alpha) with floating numbers between 0 and 1. So (1, 0, 0, 1) is red. *Try to change the colour and see the result!*
The last three lines in the `render` function tell the SpriteBatch we created early to start, draw our texture and afterwards stop again. This marks the end of the frame at which point the next one will begin shortly.
> **Tip**
> Try to copy the `batch.draw(...)` command and change the coordinates from (0,0) to (200, 0). You will notice how a second instance of our texture is drawn at a different location. Cool, eh?
The last function in the file is `dispose()`. It is only called when we close the game and usually only has other dispose calls in it. In our case, we make sure to properly dispose of the SpriteBatch and the Texture as both of them allocate memory on the graphics processor and we don't want to leak memory!
### Adding to the game
Phew! That was quite a lot to take in, I'm sure. And don't worry if you're a bit fuzzy on some of the details. We will go over some of these things again when we use it. Additionally there are a lot of great resources out on the internet for you to help you out.
But before we wrap up this (way too long) article, I want to do something to make the game feel more like...well, a game. So go ahead and open the image processor of your choice (I will be using GIMP) and create a 128x128 pixel texture that one might consider a spaceship.
<!-- ADD PICTURE OF USS PIXEL HERE -->
You don't have to neccessarily make it 128x128 (I will) but the dimentions of the picture need to be a power of two (so 2, 4, 8,
16, 32, 64, 128, 256, 512, 1024, 2048, 4096, ...). This has to do with how computers load textures (details later).
What is that you say? You're too lazy? You don't have an image processing application? You managed to delete Paint from your computer? Kudos. Fine, you can use my graphics (contains the USS Pixel, a laser burst and a background image from the web).
**Download [my artpack here](/downloads/gameofcodes/artpack1.zip).**
I would suggest you create a new directory inside your games "assets" folder so that we don't get confused about what's what. So this is how your core/assets/ folder should look like now:
<pre>
❤ (idenna) ~/P/p/c/starchaser/core> tree assets/
assets/
├── artpack1
   ├── background.png
   ├── pixel_blast.png
   └── uss_pixel.png
└── badlogic.jpg
1 directory, 4 files
</pre>
First, why don't you go and change the line
```java
img = new Texture("badlogic.jpg");9
```
to
```java
img = new Texture("artpack1/uss_pixel.png");
```
and marvel at the amazingness that is my art skills :)
When launching the game now you will notice that the face texture has been replaced with a spaceship. However, this doesn't feel very space-y or even game-y yet. So let's not stop here! Reserve a new texture variable in your class and create it with a different resource file during the create function. Your source code should resemble something like the following
```java
Texture img, background;
@Override
public void create() {
batch = new SpriteBatch();
img = new Texture("artpack1/uss_pixel.png");
background = new Texture("artpack1/background.png");
}
```
Then in the render function, before drawing the ship, draw the background texture first! This will make sure that the background is always behind the ship and not vice versa.
```java
batch.begin();
batch.draw(background, 0, 0);
batch.draw(img, 0, 0);
batch.end();
```
Run the game and feel your jaw drop. It should look a lot nicer now. There is still no game logic or advanced rendering but we're getting there. Try to flip the draw calls around and see what happens to the ship.
Also, you might have played around with the draw calls earlier and realised that `batch.draw(...)` in it's simplest form takes a texture and a coordinate. We will use more advanced draw calls later as this (for example) can't consider rotation.
![StarChaser Mk1](/images/gameofcodes/series01/07_gamechange.png)
<hr/>
Wow! That ended up being longer than I expected :)
In the next tutorial we will look at how to bring movement into the game. This consists of actually updating certain parts of the game as well as handling user input. See you then!
Kate
[[Next post about Input & Movement](/game-of-codes/02-input-and-movement/)]

@ -1,270 +0,0 @@
Title: 02. (LibGDX) Game of Codes: Input & Movement
Category: Game of Codes
Tags: LibGDX, Tutorial, Game Dev
Slug: 02-input-and-movement
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX framework. In the last edition we learned how to set up LibGDX with a new Java project and draw simple pictures onto the screen. We used textures to import that image and then drew it via a SpriteBatch.
Today we will look at basic input handling and how to make things move on screen. And though we won't be able to cover everything in this article we will explore the basic input stack that LibGDX has to offer and how to make things in your game move.
Exciting! :)
A little note: all the code that gets shown off here is available in a [Github repository](https://github.com/spacekookie/starchaser) for you to tinker with. After each tutorial I tag the commit so that it's obvious what got changed when!
You can also use that repository to report issues or give feedback if you'd like. Otherwise, my email is always available!
### Registering input
Before we talk about inputs, we need to think about what it even means to register an input. When the user presses a button in our game, we want that button press to notify us so we can affect some behaviour. To understand what is going on here, we should consult the following graphic.
![Life of a Frame](/images/gameofcodes/series02/01_framelife.png)
You can see that LibGDX (obviously) considers the main run loop of our game...a loop :) In this series we only really care about the purple boxes. And in this article in particular, we are only considering the first purple box: "Input". What LibGDX does during this step is poll all input hardware for activity. It then writes this activity into a buffer and signals all registered input adapters to handle their input.
So with that in mind, there are two ways of checking for input. The first is essentially polling the hardware again yourself during the "Render" step, while the other hooks into the "Input" step and is called asynchronously.
Both ways of handling input are slightly unique. And we will start with the polling aproach first to demonstrate some basic functions.
First, go into the main game class and add a position variable into the class body:
```java
import com.badlogic.gdx.math.Vector2;
public class StarChaser extends ApplicationAdapter {
//...
Vector2 position;
// ...
}
```
Furthermore, in the `create` block of the game, initialise the position to some value that is greater than `(0,0)` and not too big to be off window :)
```java
position = new Vector2(250, 150);
```
If you're not too familar with Java, what this means is that we declare `position` to be a object variable which means that every function in an instance of this class can access it (Object-Oriented Programming). In the `create` function we then initialise it to have a value other than `null`.
What that means now is that we can use the position variable (which has an `x` and a `y` component) in our draw calls to tell the picture where to go. The main advantage of this is that when we change the position variable (say...via a button press), the picture gets an updated position!
```java
public void render() {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
updateInputs();
batch.begin();
batch.draw(background, 0, 0);
batch.draw(img, position.x, position.y);
batch.end();
}
```
So far so good...wait. Do you see that `updateInputs()` function call there? That wasn't there last time. In fact, it doesn't yet exist. But it should soon. Why don't you go and create a new function in the class somewhere with the signature `void updateInputs() { ... }`. We will fill it's body with some stuff soon.
So fundamentally, we want to poll inputs and then when we have determined that an input is pressed we want to enact some functionality. The simplest form of polling buttons is with the `Gdx.input.isKeyPressed(key)` function where `key` is an integer variable that corresponds to a key-code. Don't worry, there are bindings that make it easier and you don't have to manually check for numbers ;)
> **Tip**
> Other input polling functions include `isButtonPressed(button)` for mouse buttons as well as `getX()`, `getY()` which give you the cursor position in your game window!
So why don't you add the following lines of code to your `updateInputs` function and see where it gets us.
```java
if (Gdx.input.isKeyPressed(Keys.W)) {
position.y++;
} else if (Gdx.input.isKeyPressed(Keys.S)) {
position.y--;
} else if (Gdx.input.isKeyPressed(Keys.A)) {
position.x--;
} else if (Gdx.input.isKeyPressed(Keys.D)) {
position.x++;
}
```
You can run this now and see what happens. When we press the keys in question the image on screen will move all over the place. Cool! But...it's not particularly pretty, is it?
For one, we can only move in one direction simultaniously. But even if we split the X-Y axis into two different if-blocks, there is still the problem that `W` will always have precedence over `S` and `A` will have precedence over `D`. Which means that if we press all keys, we will *always* move top-left. And that's not particularly great :(
> **Tip**
> Also consider the following: when you move in one direction you apply 1 to the axis you're moving along. But if you move in two directions, you apply 1 in both x and y direction. Which means that (via trigonometry) you actually move **~1.41** in total. This means your game isn't consistent about rules.
> It's clear that more logic is required to move!
So how do we fix this? We can of course add more logic to our `updateInputs()` function but it will result in a lot of dirty hacks. And while game development is often about making dirty hacks that work, starting a project off some will quickly make your code-base unmaintainable.
### Using Input Adapters
The second method of getting input from the user I mentioned earlier is via an input adapter. It can be considered faster because we only do input polling once and it allows us to use input signals between different game components (gameplay, game HUD, etc.)
So how do we use this awesome functionality? Well, it's simple. We need an InputAdapter. So first, create a new class via Eclipse. If you don't know how, consult the *suuuuper* helpful screenshot below :')
![Life of a Frame](/images/gameofcodes/series02/02_createclass.png)
Give it a useful name like `InputHandle` or `ShipInputHandle` or something. You can be quite specific in the naming because you very often have multiple input adapters for different aspects and parts of your game. So being specific in the naming just helps you out in the long run.
Once you've done that you should be greeted with a very boring and empty class in your editor. So we need to add some basic code to get going. I took the liberty of doing that and will now show off what I did (and you'll finally get to see what name I chose...).
```java
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Vector2;
public class ShipInputHandle extends InputAdapter {
Vector2 shipPosition;
public ShipInputHandle(Vector2 shipPosition) {
this.shipPosition = shipPosition;
}
}
```
So, as you can see we have a class that extends `InputAdapter` as a subclass. With that comes free functionality we don't have to implement ourselves. Additionally I create a constructor that takes a vector and stores it as an instance variable (like before in the game class). Note that we're not copying the value here but rather storing a reference to the "original" variable in the game.
> **Tip**
> If you're coming from a language like C or C++ this can be quite confusing. What is a copy, what is a reference? In general: java always passes by reference (pointer) unless it is a primitive value. What is a primitive value? `int`, `float`, `double`, `boolean`, `byte`, `long` and all other lower-case types that become purple in the IDE (keywords).
Next up, let's handle some inputs! The principle is similar to the polling: we check what input we are handling (because we only have generic functions - this will become obvious in a second), then invoke some behaviour. But as we have already seen before, we need to store some state. And that's why this is perfect: we have a new class where we can store the input state to check against. But at the same time, it's contained and doesn't clutter our main game class.
Now...to solve the problem of moving in multiple directions at the same time, without letting one direction take precidence over another we can use a tri-state variable. In Java this can easily be done with an enum. Create a enum titled `TS` (or TriState if you feel verbose) in our `ShipInputHandle` class and create two values `x` and `y` that use it. The initial value should be `NEUTRAL`
```java
enum TS { POS, NEG, NEUT };
TS x = TS.NEUT, y = TS.NEUT;
```
In the `keyDown(int keycode)` and `keyUp(int keycode)` functions we can then use a switch statement to flick the `x` and `y` variables in their favour. We *can* also perform a simple check if the `x`, `y` variables are already set to avoid another direction overwriting our current movement. But then again, maybe you consider this preferred behaviour. I chose to perform the check in the following code!
```java
public boolean keyDown(int keycode) {
switch (keycode) {
case Keys.W:
if (y == TS.NEUT)
y = TS.POS;
break;
case Keys.S:
if (y == TS.NEUT)
y = TS.NEG;
break;
case Keys.A:
if (x == TS.NEUT)
x = TS.NEG;
break;
case Keys.D:
if (x == TS.NEUT)
x = TS.POS;
break;
}
return true;
}
```
Notice that `return true` at the end of that function? That's what you could call "Input Cascade". It is a concept that we will use extensively in later articles of this series. In short, it is the concept of letting an input signal cascade through different input adapters until it is ended. Returning true in this function signals the core input controller that we are ending the signal: it will not cascade to lower ranking controllers. This means that if you replace it with a `return false`, controllers down the stack will be able to pick up on the signal and use it.
But again, this will become important in later tutorials. For now, let's just end the signal and get it over with. Next up, we can implement the `keyUp` function very simply by checking what axis our key-presses affect and then resetting that direction back to `NEUT` if it is applicable. Not a perfect solution but something that will definately work is implemented below.
```java
public boolean keyUp(int keycode) {
switch (keycode) {
case Keys.W:
if (y == TS.POS)
y = TS.NEUT;
break;
case Keys.S:
if (y == TS.NEG)
y = TS.NEUT;
break;
case Keys.A:
if (x == TS.NEG)
x = TS.NEUT;
break;
case Keys.D:
if (x == TS.POS)
x = TS.NEUT;
break;
}
return true;
}
```
Now we're almost done. One thing is missing however! We keep a state depending on the inputs of our user. But we don't apply anything to the vector we stored based on that state. This is where we will need to build something slightly custom because the InputAdapter doesn't force you into any workflow.
I recommend you create a new function `void update() { ... }` in the input class and make it public. We consider this function to be called every frame and apply values to the x and y components of the position vector, depending on the state of our inputs.
The following code very quickly checks if we need to apply movement at all (is not NEUT) and then does a conditional application of 1 or -1 to each component.
```java
public void update() {
if(x != TS.NEUT) shipPosition.x += (x == TS.POS) ? 1 : -1;
if(y != TS.NEUT) shipPosition.y += (y == TS.POS) ? 1 : -1;
}
```
Now we're done modifying the ShipInputHandle...for now :) Go back to the main game class. There are two more things to do before we can enjoy our new input handles. First, remove the old `handleInputs()` function. We don't need or want it anymore. Also make sure to remove it's function call from the `render()` function.
Secondly, create a ShipInputHandle object and initialise it with our vector. Take the following code segment as reference.
The last line in the `create()` function is key and not to be forgotten! It registers our custom input handler with the LibGDX input system and makes sure that our functions are *actually* being called :)
```java
public class StarChaser extends ApplicationAdapter {
// ...
ShipInputHandle input;
@Override
public void create() {
// ...
position = new Vector2(250, 150);
input = new ShipInputHandle(position);
Gdx.input.setInputProcessor(input);
}
@Override
public void render() {
// ...
input.update();
// ...
}
// ...
}
```
And that's it! Run that code and you'll be able to move the image around in a much nicer fashion! Again, this is far from perfect. And you will notice that switching quickly from going-left to going-right can make the whole thing just stop on "Neutral". You can remove the additional check which I added. Realistically, you need a lot more state to mirror what the user is putting into your system if you want real-feedback and logical behaviour from your units. But this will do for now!
And more importantly...it should have given you a glimpse at how to use the InputAdapters.
<hr />
And that's it for this article! Originally I wanted to talk a little bit about rotation. But I realised that I would have had to make a lot of assumptions about systems and not be able to go into too much depth without making the article *waaaayy* too long.
So that'll be handled in the [next issue](https://media.giphy.com/media/z85AlA6CBKxEI/giphy.gif).
Have a good day/ night,
Kate

@ -1,159 +0,0 @@
Title: 03. (LibGDX) Game of Codes: Rotation & Advanced Movement
Category: Game of Codes
Tags: LibGDX, Tutorial, Game Dev
Slug: 03-rotation-and-advmovements
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX framework. In the öast edition we learned how to listen for user input, keep it's state for consistency and apply it to the world we are building. We did this by simply using a vector as a position for an image to align to.
Today we will have a look at some more input but more importantly: rotation! And with that, also look at some more advanced movement concepts like momentum and some advice how to implement certain movement patterns.
A little note: all the code that gets shown off here is available in a [Github repository](https://github.com/spacekookie/starchaser) for you to tinker with. After each tutorial I tag the commit so that it's obvious what got changed when!
You can also use that repository to report issues or give feedback if you'd like. Otherwise, my email is always available!
### Naïve approach
So let's just take a naïve approach here. We have a vector that is essentially the position of our "ship". And it can have a rotation. So what we do is listen for two new key presses (in my case for `Q` and `E` - left and right rotation) and then create another tri-state variable `rotation` that we can use to determine whether we should rotate left or right.
```java
switch (keycode) {
case Keys.W:
// ...
/** Handling rotation */
case Keys.Q:
rotation = TS.NEG;
break;
case Keys.E:
rotation = TS.POS;
break;
}
```
The inverse applies for the `keyUp(...)` function.
```java
switch (keycode) {
// ...
case Keys.Q:
if (rotation == TS.NEG)
rotation = TS.NEUT;
break;
case Keys.E:
if (rotation == TS.POS)
rotation = TS.NEUT;
break;
}
```
Our update code needs to be appended slightly. This isn't the most pretty way to do this but for now it'll be alright.
```java
public void update() {
// ...
if (rotation == TS.POS)
shipPosition.rotate(1);
else if (rotation == TS.NEG)
shipPosition.rotate(-1);
}
```
Now. What does this actually mean. We rotate the *positional* vector for the ship. You might have an inkling of what is about to happen but if you don't start the game and look at it. Not quite what we had in mind, is it?
![Bad rotation GIF](/images/gameofcodes/series03/01_badrotation.gif)
So what's happening here? Well, our positional vector points to where the ship is. From the origin. Which is in the bottom left of the screen. At coordinates `(0, 0)`... So when we rotate the positional vector, we rotate the ship around the origin. Furthermore, we never told the `SpriteBatch` to rotate the image we're drawing. That's why the ship orientation stays exactly the same: pointed upwards.
### Using TextureRegions
So let's fix this one problem at a time. Let's actually make the ship texture rotate depending on some value (in our case, the phony vector angle). For this we need to look at how we draw things. Right now, that's a texture.
A texture is essentially a raw memory map of an image, loaded onto the GPU. That's why the texture needs to be a power of two because that's how GPU's handle textures in their memory. But what this also means is that if we have multiple textures this will cause a lot of overhead because loading textures in and out of memory from the GPU is expensive.
Also, all transformations to the texture we need to apply manually. Transformations include scaling, moving and rotation. And especially the last one can be challenging.
**Enter: TextureRegion!**
Now, a `TextureRegion` is a collection of textures, essentially a large texture with bits cut out of it. This way we can bundle all our textures together into one large one (or several large ones) while marking different parts of the texture as regions so that we can handle them in the future.
What this also means is that simple transformations can be done on the CPU which is slower but much easier than performing them on the GPU. This means the textures are still stored on the GPU but we get more control over how to transform them. Let's use this in our game!
```java
public class StarChaser extends ApplicationAdapter {
// ...
TextureRegion img;
// ...
@Override
public void create() {
batch = new SpriteBatch();
img = new TextureRegion(new Texture("artpack1/uss_pixel.png"));
// ...
}
```
The code above creates a TextureRegion instead of a Texture. In this case, we aren't using any of the memory saving benefits of using TextureRegions but that doesn't matter. We can still take advantage of it.
Specifically, we will change the `batch.draw(...)` function to take more parameters. But first, create a second vector, call it "direction" and initialise it with `(0, 1)`.
```java
final float sizeX = img.getRegionWidth();
final float sizeY = img.getRegionHeight();
batch.draw(img, // The TextureRegion we draw
position.x, // Root X position
position.y, // Root Y position
sizeX / 2, // Rotation origin X (center point)
sizeY / 2, // Rotation origin X (center point)
sizeX, // Draw width
sizeY, // Draw height
1, 1, // Scaling factor (1 is fine)
direction.angle()); // Region angle (around origin)
```
Additionally, we need to adjust our ShipInputHandle class because we need to make it use our direction vector. The code snippet below will outline what you need to change. Essentially: we rotate our direction vector and noramlise it after every step because rotating vectors actually changes their length.
```java
public class ShipInputHandle extends InputAdapter {
Vector2 pos, dir;
// ...
public ShipInputHandle(Vector2 shipPosition, Vector2 direction) {
this.pos = shipPosition;
this.dir = direction;
}
// ...
public void update() {
if (rotation == TS.POS)
dir.rotate(1);
else if (rotation == TS.NEG)
dir.rotate(-1);
dir.nor();
// ...
}
}
```
If you launch this configuration you will notice that the ship rotates around it's centre point correctly! YAY! You will notice that you can still move your ship independant of it's rotation. You might consider this a feature because it allows you to fly one way and shoot backwards (think Battlestar Galactica Vipers!). But in our case, we want the ship to always fly in the direction that it's pointing towards.
![Proper rotation](/images/gameofcodes/series03/02_rotating.gif)
This is relatively simple. We only need to change the position update code to make this happen. In fact, we only need to consider the direction vector when applying a new position.

@ -1,110 +0,0 @@
Title: 01. (Java Native Access) The basics
Category: JNI
Tags: Java, Tutorial, Programming
Slug: 01-jni-the-idea-foreign-function-interfaces
Status: draft
Regular readers of my blog (or listeners of my afk ramblings) will know that I like Java. I'm sometimes not quite sure why but there it goes, let's just assume that as an axiome for a second.
Java is pretty damn good at a lot of stuff. It compiles to a high performant byte-code and it's JIT compiler is smart, fault-tolerant and self optimising. It has a plethora of libraries and toolkits to choose from and making nearly anything is pretty damn if you don't mind writing a verbose language or [cheating](https://projectlombok.org/) a bit.
Then so far so good. What is this about then? Well...many things that Java doesn't do in it's standard lib you can still do. And it's something too many people to know about. For good reasons. Fault tolerance and optimisation on the side of the JIT compiler goes out the window and existing documentation is lackluster at best, in most cases outdated by decades at this point. Java is (among other things) an enterprise language and the tech hipsters have *looong* moved on from it. And so have people writing guides about it.
That is about to change (to some small extent)
### What is JNI?
The **J**ava **N**ative **I**nterface is a foreign-function-interface to the JVM, the virtual machine and JIT compiler environment that all Java code runs in. It allows you to write C/C++ code that is called by your existing Java project and even make calls *back* into your java code for callbacks (for example for logging).
It features a very low overhead, practically non-existant safety checking and allows for pretty performant Java-native interop. In fact, switching from the Java context to a native function context only takes [a few nanoseconds](http://stackoverflow.com/a/13977914/2443595). After that you get the raw performance of native code and all the beautiful header bindings that come with that.
Unfortunately setting this up isn't trivial and outdated documentation/ tutorials, that ignore modern build systems, don't make it easier. And while I will get into the nitty-gritty of what you should do/ avoid in the next article (or two), first I want to outline how java-native interop generally works.
### Writing a "native" class
Everything in Java is a class and this is no exception. Thus we first need to provide one that has a few `native` functions that we can then later implement. Other than native functions this class can contain normal java code although I would recommend you don't do that for the sake of readability.
```java
class JniSomething {
static {
// TODO: Load library
}
private long something;
public native void initSomething(String name, int count);
public native void doSomething();
public static native void status(int mode);
}
```
Two things that you should notice
1. We have a static initialiser block which we will later use to load a native library
2. We have a `long` type field in our class which will become important later. For now it shows that "native" classes can have fields just like any other class.
You can also see that we can have static and non-static native functions. Parameters can be primitives and classes although I only demonstrated `String` as a class here (which is a bit of a special case in JNI land)
### Native code generation
We are about a third of the way there. Unfortunately this is where it becomes a little less clean and easy to manage. From our class definition that includes native functions we will now generate a header that we can build native function implementations for.
The tool we will use is called `javah` so make sure it's included in what your operating system packages as java. On most Linux distributions it should come installed with the JDK, on Windows and Mac...I have no idea. Figure it out and e-mail me so I can add it to the article.
Assuming that your "project" structure looks something like this and your current directory is `src`
```
🚀 (normandy) ~> tree project/
project/
└── src
└── de
└── spacekookie
└── JniSomething.java
```
then you can generate the jni header file in the project root directory as follows
```console
javah -verbose -jni -o ../JniSomething.h de.spacekookie.JniSomething
```
So far so good. You can look at the file now if you want. It's actually pretty ugly code. The function names are designed to *never* clash with anything else because of how Java and C++ have *very* different approaches when it comes to scoping things. The last part of this intro will be writing code that uses these headers to do something in native code.
### Writing & linking native functions
Aaaaand this is where things get really complicated real fast. There are a few things we need to do at this point and none of them are trivial
1. We need to setup our build environment so that we can find the `<jni.h>` utility header
- Platform specific problems I might add
- Also very dependant on the build system we might be using later
2. Write and compile the native code that does *something* and make a library (for us that is an `.so` because Linux)
3. Load the library correctly as to not crash the JVM
Easy as pie :)
First things first, we need to find the Java home directory. Again, I can only speak from a Linux perspective. But the `$JAVA_HOME` environment variable was depreciated years ago by most distributions. This might not be the best way to find out but it works.
```bash
# Bash
echo $(dirname $(readlink -f $(which javac)))
```
```fish
# fish
echo (dirname (dirname (readlink -f (which javac))))
```
From the directory we get with these queuries we need to go up one directory and then into a other directory. In the end the path we want to build should look something like this. The second one will obviously be different depending on your platform.
```
/usr/lib/jvm/java-8-openjdk-amd64/bin/../include
/usr/lib/jvm/java-8-openjdk-amd64/bin/../include/linux
```

@ -216,9 +216,38 @@ code { padding: 3px 3px; }
text-indent: 25px;
}
.card-content img {
width: calc(100% - 50px);
max-width: 1200px;
}
.card-content img.original {
max-width: 100%;
width: auto;
}
.article-meta p {
font-style: italic;
font-size: 16px;
line-height: 16px;
text-align: right;
}
.card-content blockquote {
background: #EFEFEF;
border-left: 10px solid #ccc;
margin: 1.5em 10px;
padding: 0.5em 10px;
quotes: "\201C""\201D""\2018""\2019";
}
.card-content blockquote:before {
color: #ccc;
content: open-quote;
font-size: 4em;
line-height: 0.1em;
margin-right: 0.25em;
vertical-align: -0.4em;
}
.card-content blockquote p {
display: inline;
}

@ -2,7 +2,7 @@
##
# This section should match your Makefile
##
PY=${PY:-python3}
PY=${PY:-python}
PELICAN=${PELICAN:-pelican}
PELICANOPTS=

@ -23,7 +23,9 @@ READ_TIME = 180
PATH = 'content'
STATIC_PATHS = ['images', 'downloads', 'kookie.txt']
SITE_LOGO = 'favicon.ico'
SUMMARY_MAX_LENGTH = 140
# SUMMARY_END_MARKER = "( ... )"
#############################################
#############################################

@ -1,70 +0,0 @@
Title: 01. Encryption 101: Basics
Date: 2013-07-26 20:31
Category: Data Privacy
Tags: Guides
Slug: 01-encryption-101-basics
Status: published
If you haven't lived under a rock for the past few weeks you'll have
heard about the NSA and PRISM essentially spying spying on the entire
world. Now, I will write an article about why this is actually upsetting
and there are good reasons to protect ones privacy even if you have
"nothing to hide". In this tutorial I want to show you that encrypting
your communications and computers is a good way to protect yourself but
hardly the only thing you can do. And even if you encrypt everything in
your life you will leave behind a lot of meta data on the internet.
Enough to reconstruct what you were doing, what you think, who you would
vote for etc.
In this series I want to show you a little bit how you can protect
yourself. However, in this first post I want to explain you the basics
of cryptography. I won't go into detail about mathematical constructs,
you can read that on Wikipedia. But as an average person you won't need
that. Let's begin.
There are different ways how to encrypt things. The two big ways I want
to talk about now is **symmetric** and **asymmetric** encryption.
Let's look at symmetric encryption first:
![tutorial\_encryption\_symmetric](http://www.spacekookie.de/wp-content/uploads/2013/07/Screen-Shot-2013-07-26-at-22.13.29.png)
In symmetric encryption the user creates a key. That key is then being
used to encrypt but also decrypt a file. This makes the process of
encryption and decryption very fast, however also creates the problem
that the key needs to be transferred safely. If somebody got hold of the
key they could encrypt and decrypt files that they might not be able to.
Symmetric encryption is great for hard drive and large chunks of data.
However this isn't very practical in communication with others. You want
others to be able to encrypt messages sending to you but be the only one
that can decrypt them again. This is the basic idea of asymmetric
encryption. The following schematic will explain.
![tutorial\_encryption\_assymetric](http://www.spacekookie.de/wp-content/uploads/2013/07/Screen-Shot-2013-07-26-at-22.14.54.png)
There is a pair of keys: one public, one private. The public key is
being used to encrypt a file. In practise this is the key that you send
out to other people. They encrypt the messages they send to you and then
send them to you.
The private key is the one you keep to yourself (private) and under no
circumstances send to any computer or device. Only transport it on
offline drives like USB sticks, SD cards or external hard drives. This
is the key that will allow you to decrypt messages sent to you.
If you use asymmetric encryption in your communication you can encrypt
messages for others with their public keys and decrypt messages others
sent you with your private key.
 
In following tutorials I will quickly show you how to encrypt messages
using PGP on Mac OS X, Windows and Linux, how to encrypt your hard drive
on Mac and Windows and also how to use encrypted instant messaging
services. After that I will show you ways to stay anonymous on the
internet and leave behind fewer clues about who you are and what you
were doing. Even if you have nothing to hide that doesn't mean that you
need to invite everybody into your private life!
P.S. This tutorial series was inspired by my brothers short descriptions
about security [here](http://www.leandersabel.de/itsecurity/).

@ -1,366 +0,0 @@
Title: 02. Encryption 101: PGP on Mac
Date: 2013-10-16 16:26
Category: Data Privacy
Tags: Guides
Slug: 02-encryption-101-pgp-on-mac
Status: published
Hello Internet,
I started this series about encryption a few weeks ago but then kinda
ran out of time to actually do something with it so now I want to
continue it. Essentially this is about PGP and email encryption. This
tutorial is being inspired by my brothers (much shorter) article about
the whole thing:
<http://www.leandersabel.de/itsecurity/e-mail-encryption/>)
What is PGP, you might ask? Well, it's a good question. PGP stands for
Pretty Good Privacy and uses an asymmetrical encryption concept that you
should have learned about in the [last blog
post](http://www.spacekookie.de/01-encryption-101-basics/ "01. Encryption 101: Basics")in
this series. If you haven't...shame on you!
I want to focus on installing this email encryption on Mac Computers
first. This is compatible for several versions back.
The asymetric email encryption is based on a zero knowlege principle:
you send data through the web and except for the recipient of that data
NOBODY will be able to know what it is. Due to that the encryption needs
to happen on your device (in this case a Mac computer) and be decrypted
on an end device again (for example a Windows computer).
It doesn't really matter what e-mail provider you use as you will be
downloading the mails anyways. The easiest way to do that on a Mac is
with the pre-installed *Mail* program. If you haven't already get your
Mail to download mail from your account. If you've done this already you
can skip ahead to **[Encrypting your Mail](#encryption).**
**Setting up Mail with your account** {style="text-align: justify;"}
-------------------------------------
Open Mail and click on Mail --\> Preferences
[![mailpgp1](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp1.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp1.png)
In the upcoming window click on Accounts and then select the "+" sign on
the bottom
[![mailpgp2\_1](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp2_1.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp2_1.png)Another
window will pop up where you need to enter the apropriate information.
For large e-mail providers like gmail, yahoo, hotmail, etc. this is
quite trivial. If you are using a different webhoster you might have to
**check their FAQs for server information!**
**[![mailpgp3](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp3.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/mailpgp3.png)**After
this is done you should be able to download the e-mails from your
account to your computer. You may start a celebratory dance now!
Next up:
<a name="encryption"></a>
**Encrypting your Mail
** {style="text-align: justify;"}
-----------------------
Now that your emails are being downloaded to your computer we can set
you up with the encryption software. The one that is the easiest to use
is called GPG, standing for *GNU Privacy Guard* (with GNU being a linux
distribution). The software comes in an easy to install package that can
be found at: [https://gpgtools.org](https://gpgtools.org/) Just scroll
down to the download button and download the suite to your computer.
Double click the .dmg file you downloaded and wait for the following
window to pop up:
[![gpginstall1](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall1.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall1.png)
This should be trivial but double click install :) Another window will
come up. Be sure to select the right harddrive. It should be installed
on the harddrive that also contains your operating system. In my case
the Harddrive is called *TARDIS* (It's bigger on the inside).
[![gpginstall2](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall2.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall2.png)
When the installation is complete eject the installation drive by
dragging it onto the trash. It's not needed anymore. Open GPG (by either
searching for it in your Applications folder or using spotlight in the
top right corner)
[![gpginstall3](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall3.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall3.png)
When you open GPG for the first time it will look somewhat like this for
you: (Except you won't have any keys in it).
[![gpfinstall4](http://www.spacekookie.de/wp-content/uploads/2013/10/gpfinstall4.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/gpfinstall4.png)
Enter your name, your email adress and check the "Upload public key
after generation" to make it easier for people to be able to find your
key. This means that they will be able to send you e-mails encrypted. If
you don't want that, don't tick it. I recomend it for regular users
because it makes exchanging keys easier. Press **Generate key**
to…generate the key (duh). During the generation process move your mouse
as much as possible and even type random letters on your keyboard.
[![gpginstall5.png](http://www.spacekookie.de/wp-content/uploads/2013/10/Screen-Shot-2013-10-16-at-17.40.57.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/Screen-Shot-2013-10-16-at-17.40.57.png)When
a window comes up and promts you to enter a password do that so.
**Choose a strong password as it will be the foundation of your e-mail
encryption**. The longer and more complicated, the better. The
application will then take your passphrase and the random input from
mouse and keyboard to generate a pair of keys: one private, one public.
If you checked it accordingly the public key will be uploaded to the MGU
servers for other people to find. The public key is used to encrypt
emails. Other people that have your public key can thus send you a
message that is encrypted. To decrypt the messages you need your private
key **that should under no circumstances be sent via the internet or any
network!**
If you need to move your private key to a second computer for use do so
on a USB drive or local, external harddrive. **DO NOT STORE YOUR PRIVATE
KEY IN A CLOUD SERVICE**
[![gpginstall6](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall6.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/gpginstall6.png)
The "sec" indicates that there is a secure (private) key. The "pub"
stands for a public key. The two combined make a key pair which you
should only have one of. So far you should be set to communicate so
let's move onto the next topic:
{style="text-align: justify;"}
**Sending encrypted Mail** {style="text-align: justify;"}
--------------------------
Now that this is all set up, what can you do with this? First of all,
this encryption only works if the other person you're communicating with
is also using a PGP system (no matter what implimentation or operating
system).
First of all be sure to restart your Mail application after you
installed GPG. Otherwise the plugin won't start. Go ahead and compose a
new email. This is what it should look like now:
[![mailtest1](http://www.spacekookie.de/wp-content/uploads/2013/10/mailtest1.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/mailtest1.png)
The green space on the top right indicates that OpenPGP is active with
the selected email adress. The little tick in the middle confirmes that
a signature will be attached to the mail. You can disable to sign your
emails by clicking on the tick.
If you then enter an email adress of somebody that you own the public
key from (in my case let me write a mail to my brother Leander) things
will change a bit:
[![mailtest2](http://www.spacekookie.de/wp-content/uploads/2013/10/mailtest2.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/mailtest2.png)
The lock icon will become active and you will be able to lock it. The
lock indicates that the email will be encrypted. As the picture also
indicates the subject of a message is not being encrypted, **only the
content (including attachments).** Oh and please note that sending
attachments of multiple gigabytes might take a while to encrypt :)
If I send this message now, let's see what it looks like for the NSA:
``` {.lang:default .decode:true}
-----BEGIN PGP MESSAGE-----
Comment: GPGTools - http://gpgtools.org
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
qJNMy4CS6/L22o/yiUw=
=hOZe
-----END PGP MESSAGE-----
```
Yea...not very much :) The longer your key (and message obviously) the
more and longer jibberish the message will be. And the best thing? It is
mathematically impossible to reverse engineer the message by generating
random keys. Because for each encrypted message there is a key that can
make the original message into any other message. Literally the message
I just sent my brother could be translated into Shakespeares Hamlet with
the right key.
A little note: What you see above is what you will see in your mail
inbox if you access your mails without the Mail program or GPG
installed. So be sure to follow the tutorial again for any computer you
might use this on. In my opinion this is the best part, as copanies like
Google or Microsoft that store your emails will have no idea what you're
sending things about.
{style="text-align: justify;"}
<a name="exporting"></a>
{style="text-align: justify;"}
**A few last pointers** {style="text-align: justify;"}
-----------------------
Right clicking onto your key pair in GPG will get you a context menu
with which you will be able to do a variety of things. Now an
explanation for the most important ones:
1. Export: saves the key as a text file to a location on your computer.
You can either export your public key or the pair (public and
private). Use this to move your private key to a new computer.
2. Send public key to key server: If you have made changes to your key
or haven't checked the option before you can upload your key to a
public server for people to find you.
3. Update a public key from the keyserver in case you accidentally
deleted it. You can't update your private key. **You loose it, it's
gone!**
4. Show info: displays all kinds of information about the key. You will
be able to add a new e-mail adress to the key, in case you want to
send encrypted emails from multiple adresses or change the
expiration date of the key, etc.
One last important thing: What if you want to import a key to your GPG
keychain? Take my public key for example:
``` {.lang:default .decode:true}
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.19 (Darwin)
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
kM773MWawwH7Z3VRQLYT/oweYc6Pd1A=
=NBpw
-----END PGP PUBLIC KEY BLOCK-----
```
(Downloadable here:
<http://spacekookie.de/pgp/katharina-sabel-public.asc>)
First open a text editor of your choosing. In my case I will use the
standard Mac **Text Edit.** Now you need to copy and paste the key
(From --BEGIN-- to --END--) and paste it into your text
editor.[![importkeymac1](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac1.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac1.png)
Looks kinda scary, I know. Hang in there. Now save the file with CMD +
S. In the following popup you need to select to save the file locally
and not on Apples iCloud servers. They can be great but not for this!
[![importkeymac2](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac2.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac2.png)
Give the file a random name (it's not really important) and save it.
Next up close the Text Editor and navigate to your saved file. Right
click on it to bring up the context menu and choose **Get Info**
[![importkeymac3](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac3.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac3.png)In
the upcoming window then search for the name field and change the
extention from .rtf to **.asc**
.RTF is a file format for text files and great for stuff. But we want
the GPG application to recognize all the jibberish as a key and for that
we need to change the extention to .asc
When your computer prompts you if you're sure you agree and change the
extention to **.ASC**
[![importkeymac4](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac4.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac4.png)
Now we're almost done. Go to your GPG application, click the IMPORT
button in the top left and navigate to your key.asc file on your
computer you just created. Press open and see the magic happen as the
key is being added to your keychain.
[![importkeymac5](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac5.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkeymac5.png)
Now...there is a much easier way to import new keys and that's why I
kind of insisted on your uploading your public key to a keyserver. If
you go to your GPG application, select **Key** (in the menu bar on top
of the screen) and then **Search for key** you will be promted with a
little window:
[![importkrymac6](http://www.spacekookie.de/wp-content/uploads/2013/10/importkrymac6.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/importkrymac6.png)In
that window you can search for an email adress or parts of it to find a
key. To find my public key simply search for katharina.sabel.
I kinda fucked up my keys a few months ago so I have two keys on the
server. Select the one that was created last (\~August 2013) to add the
key to your keychain. You won't have to deal with any of the hassle
including file formats, copy pasting, etc. It's all done.
Feel free to hit me up with a random message to
sabel.katharina@gmail.com. Be sure to encrypt it, just to test things
out. And I hope that this tutorial will encourage you to encourage more
of your family and friends to use encryption. If not for transmitting
sensible documents like contracts, bills or whatever just to piss off
the NSA :)
Have a lovely day,
\~Kate

@ -1,161 +0,0 @@
Title: 03. Encryption 101: PGP on iOS
Date: 2013-10-17 12:46
Category: Data Privacy
Tags: Guides
Slug: 03-encryption-101-pgp-on-ios
Status: published
Next up in this series: iOS. I discovered this application by accident
today and wanted to write about it. First up three things you will need:
1\. A keypair of private/ public key already generated on your computer.
It's easier this way.
2\. This application for money:
<https://itunes.apple.com/us/app/ipgmail/id430780873>
3\. An iOS device (duh!)
![iospgp1](http://www.spacekookie.de/wp-content/uploads/2013/10/DSC_0170.jpg)First
of all install the app on your device (in my case an iPhone). In the
meantime you should search for your connection cable because you'll hook
up your device to your computer.
While you wait for the installation to be finished you can also export
your keypair on your computer. If you're using a Mac click
[here](http://www.spacekookie.de/02-encryption-101-pgp-on-mac/#exporting)
to find out how. If you're using Windows click here (To be added with
the future tutorial!)
Unlock your phone, open the IPGMail App and on your computer open
iTunes. In iTunes, select your iOS Device in the top right
corner[![iospgp2](http://www.spacekookie.de/wp-content/uploads/2013/10/iospgp2.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/iospgp2.png).
Select "Apps", scroll down until you reach the area shown in the
screenshot. There select the iPGMail App and select "Add". Navigate to
the directory on your computer where you exported your key pair and add
it. Note that for this to work you need to have the IPGMail App open on
your device, otherwise you might get an error about writing
persmissions!
[![iospgp3](http://www.spacekookie.de/wp-content/uploads/2013/10/iospgp3.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/iospgp3.png)With
that done close iTunes and turn your attention towards your iOS device
again.
In the application you will see a few tabs. Most of them are self
explanatory: Keys, Compose, Decode and Settings. The "Files"tab  holds
the key that you just moved into the app. Tap on the tab, select the key
pair you imported and select "decode" in the upcoming context menu.
**THIS WILL TAKE A WHILE!** So be sure to get some coffee or read a book
in the mean time.
At some point the application will prompt you for a password. Enter the
passphrase that you chose for your PGP key during generation. For some
advice on how to handle your keyphrase (if it's longer) click
[here](#passphrases-storage).
You're almost done. You will see the freshly imported Private key in the
Keys-tab. You can either import public keys the same way OR you can
search for them. That's why it's important to upload your key to a
keyserver ;)
Go to the public Keys tab, press the "+" and for the server select
"pgp.mit.edu:11371". That's where I store my key on (and that is AFAIK
the most common). Then you can search for an email adress again, like
mine: sabel.katharina@gmail.com.
When composing an email you need to select your private key as the
sender, a public key as the recipient and wether you want to sign and
encode or just do one of the two. Type your message and hit the
"export"[![iospgp4](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0056-169x300.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0056.png)
symbol in the top right corner of the screen.
The application will promt you for a password again. This is your
keyphrase, so have fun typing it in :) Again, later in this tutorial
I'll give you a bit of advice on that!
After the encryption the content will be exported into the standard Mail
App of iOS where you will be able to set a subject that isn't encrypted
and then send the message. This is what that should look like with an
example message to my brother again:
[![iospgp5](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0057-576x1024.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0057.png)
<a name="passphrases-storage"></a>
**How to handle your passphrase for Email encryption** {style="text-align: left;"}
------------------------------------------------------
If you're like me and have a massive passphrase for your PGP key it can
be a bit of a pain to enter it each time you want to do anything. Having
a long passphrase is good but entering is annoying. There are multiple
ways to store your passphrase for copy-paste use. Here in descending
order of security:
[![1passwordios](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0060-576x1024.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0060.png)**1.
1Password
** [http://agilebits.com/**
**](http://agilebits.com/)
1Password is a password management application for Mac, Windows,
Android, iOS and webbrowsers. You store your passwords in an encrypted
keyfile that can be unlocked using a different password, that needs to
be pretty secure as well. I use the app for all my password managing and
can thus generate random strings of characters of 30 to 50 bits of
length for any account I make. my PGP passphrase is 32 bits long.
Just keep your PGP passphrase in there and it's as secure as it can be.
The keyfile for 1Password can be synced via WiFi, local file transfer or
stored in Dropbox. Dropbox is pretty unsecure however as the keyfile is
encrypted with your (hopefully endless) password as well it's manageble.
Unfortunately this is pretty pricy. The iOS App is 16€ in addition to
the Desktop bundle which is another 50€
 
**[![spideroakis](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0061-576x1024.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0061.png)2.
SpiderOak
** <https://spideroak.com/>
SpiderOak is a zero-knowlege encrypted Cloud storage service. Every file
you upload is locally encrypted on your computer using a passphrase and
then uploaded and stored on the servers of SpiderOak in encrypted form.
The basic account offers a 2GB of space for free (for life) with all the
clients included. Additional space is 10\$/100GB!
Store your passphrase in a text file in your spideroak hive folder
(which is kinda like a shared instance between all your devices) to copy
and paste it whenever you need to send an encrypted email. The
passphrase will be 100% secure in your cloud storage (you could actually
place your private key in here!) but the problem is that anyone with
access to your phone will have access to your spideroak files unless you
want to enter that password on each login again as well.
If you're interested you can use my referral link and get 1GB
additonally for life:
<https://spideroak.com/download/referral/7ed9de0ea80f09d88e97f90f23830dde>
 
**[![IMG\_0062](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0062-576x1024.png)](http://www.spacekookie.de/wp-content/uploads/2013/10/IMG_0062.png)3.
Evernote (Really unsecure!!!)**
<https://evernote.com>
I'm just including this to make the list complete but don't actually do
this if you can do anything else. Evernote has a horrible horrible
horrible [...] horrible encryption and it's just about as saving your
passwords in plain text. I have to admit, I did this a while ago because
of the lack of other options but it's really not a good thing. Evernote
has a lot of amazing tools and for clipping articles found on the web,
sharing notes with others etc it's a great tool. Just for privacy issues
I wouldn't recommend storing any sensible information in an Evernote
file.
 
That's it for today. If you have any questions/ sugestions/ whatever,
post them in the comments below. And until next time.
 
\~Kate

File diff suppressed because one or more lines are too long

@ -1,142 +0,0 @@
Title: 05. Encryption 101: PGP on Linux
Date: 2015-10-27 09:00
Category: Data Privacy
Tags: Guides
Published: false
Slug: 05-encryption-101-pgp-on-linux
Status: published
It's only been around a million years since I last wrote about this stuff :) Back when I started this series I was still using OSX and obviously focused very heavily on Mac, iOS and the likes and could barely get myself to write a little tutorial about e-mail encryption for Windows (only because friends nagged me about it).
But that's all different now. I've been almost exclusively using Linux for the last year (maybe 1 1/2 years) and I thought I'd give the PGP toolchain on Linux also called Gnu Privacy Guard (GPG) some love. So shall we begin?
### Setting up GPG with Thunderbird
So most people will be using a mail client - I use Thunderbird because *reasons* - so let's focus on that for now. And to be honest...that's kinda boring. Please have a look at my guide on how to set up Thunderbird with Enigmail on Windows because on Linux (because of Thunderbird) it works pretty much the same way.
**The jist**
`sudo $package_manager install thunderbird`
With
Fedora 22+ `dnf`
Fedora 21 and earlier `yum`
Ubuntu `apt-get`
New Debian stuff `apt`
Arch `pacman` or `yaourt`
You get the idea...
Install the Enigmail plugin like described [here](http://spacekookie.de/data-privacy/04-encryption-101-pgp-on-windows/)!
### Getting to know the CLI
`gpg2` is a command that is installed on basically any modern Linux Distribution. And it comes with a plethora of options. It can do signing, message encryption with RSA, symmetric ciphers, hashing and compression.
Let's start with creating a new key. Like you might have read in the other tutorials GPG/ PGP uses asymetric encryption which means that you need a key-pair to use it. One key is public, for everybody to have and use, the other one is private, only for you to decrypt messages.
`gpg2 --gen-key` drops you into a nice interactive program that helps you generate a keypair and automatically adds it to your personal keychain. For all the other commands in this post to make sense you should have a keypair around to try everything out for yourself.
After you have a keypair you can go and list your keychain.
```
❤ (idenna) ~> gpg2 --list-keys
/home/spacekookie/.gnupg/pubring.gpg
------------------------------------
pub rsa4096/0022A74E 2014-08-16 [expires: 2020-08-16]
uid [ultimate] spacekookie (Hack the planet!) <spacekookie@c-base.org>
sub rsa4096/FEAAFEA5 2014-08-16 [expires: 2020-08-16]
sub rsa4096/3B1D08AC 2014-10-30 [expires: 2016-10-29]
```
You can of course also just get the fingerprint off a certain key. For that you either need your e-mail address or your key ID.
```
❤ (idenna) ~> gpg2 --fingerprint 0022A74E
pub rsa4096/0022A74E 2014-08-16 [expires: 2020-08-16]
Key fingerprint = 6B93 6393 9583 E61C 9AD7 16AE 64EF 9E1B 0022 A74E
uid [ultimate] Katharina Sabel (Personal) <katharina.sabel@mailbox.org>
uid [ultimate] spacekookie (Hack the planet!) <spacekookie@c-base.org>
sub rsa4096/FEAAFEA5 2014-08-16 [expires: 2020-08-16]
sub rsa4096/3B1D08AC 2014-10-30 [expires: 2016-10-29]
```
I usually end up using my fingerprint ID just because it's shorter to type. And I actually have quite a nice one to remember C:
### Import & Export
We can also export keys from our keychain.
```
gpg2 --export 0022A74E
\(j<EFBFBD>ڀ<EFBFBD><EFBFBD><EFBFBD>sO<EFBFBD>έ5'<EFBFBD>bQ<EFBFBD>6
<EFBFBD>U\<EFBFBD>1<EFBFBD><EFBFBD><EFBFBD>~ꢟSSÜu<EFBFBD><EFBFBD>-<EFBFBD><EFBFBD><EFBFBD><|<EFBFBD>1<EFBFBD><EFBFBD><EFBFBD><EFBFBD>Gd{<EFBFBD>&K<EFBFBD>c<<EFBFBD>.
?<EFBFBD><EFBFBD>r<EFBFBD>&,s<EFBFBD><EFBFBD>
:<EFBFBD>\<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ـo<EFBFBD>T'e<EFBFBD><EFBFBD>kT<EFBFBD><EFBFBD>g<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>g<EFBFBD>p.
U<EFBFBD><EFBFBD><EFBFBD>d)<EFBFBD>V<EFBFBD><EFBFBD>?Sk<EFBFBD><EFBFBD>0w<EFBFBD><EFBFBD><EFBFBD>o<EFBFBD><EFBFBD>6<EFBFBD> <EFBFBD>%<EFBFBD>i<EFBFBD>N<EFBFBD>M<EFBFBD><EFBFBD>$%ڶr_2q<EFBFBD><EFBFBD><EFBFBD>
o~<EFBFBD><EFBFBD>'<EFBFBD><EFBFBD>0<EFBFBD><EFBFBD>p)<EFBFBD><EFBFBD><EFBFBD>5<EFBFBD>k]<EFBFBD><EFBFBD>F<EFBFBD>L<EFBFBD>ks<EFBFBD><EFBFBD><EFBFBD>ؙ<EFBFBD><EFBFBD>z<EFBFBD><EFBFBD>J<EFBFBD>Pt}?<EFBFBD>*<EFBFBD>
<EFBFBD>'6<EFBFBD><EFBFBD><EFBFBD>q<EFBFBD>8<EFBFBD>f<EFBFBD>]<EFBFBD>m8m<EFBFBD>s:ӕ<EFBFBD>pԾz<EFBFBD>?<EFBFBD>ϴ|<EFBFBD><EFBFBD>f<EFBFBD>B<ѹ<EFBFBD>#<EFBFBD>m<EFBFBD><EFBFBD><EFBFBD><EFBFBD>q5<EFBFBD><EFBFBD><EFBFBD>Y<EFBFBD>sAIV<<EFBFBD><EFBFBD>.^$ޘ<EFBFBD><EFBFBD><EFBFBD>f}<EFBFBD>/<EFBFBD>?<EFBFBD><EFBFBD>(<EFBFBD><EFBFBD>B<EFBFBD>
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>%0068b<EFBFBD><EFBFBD>dAK><EFBFBD><EFBFBD> {'<EFBFBD><EFBFBD><EFBFBD>n<EFBFBD>
<EFBFBD>c<EFBFBD><EFBFBD><EFBFBD>JT<EFBFBD>qz<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
<EFBFBD>NM<EFBFBD><EFBFBD><EFBFBD>U9<EFBFBD><EFBFBD>UP<EFBFBD>諤wĸ<EFBFBD><EFBFBD>ds<EFBFBD>CW_<EFBFBD>)<EFBFBD>s<EFBFBD><EFBFBD><EFBFBD>Qc<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(<EFBFBD><EFBFBD><EFBFBD>!<EFBFBD>lv<EFBFBD><EFBFBD><EFBFBD><EFBFBD> <EFBFBD><EFBFBD>
```
But you'll notice that's in binary. To get something more human readable you can pad it in ASCII Armour with `-a` for something more managable.
```
❤ (idenna) ~> gpg2 -a --export 0022A74E
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG v2
mQINBFPvZQMBEADMRx7NgsAUBPHR4V5rNvANXChqs9qA+oqvc0/Izq01J+xiUcEM
31VcGKoxxv3Bfuqin1OPkFPDnHUOxecti5H15KGYPHylMdbD5M4UR2R7uiZLoGM8
yi4LP8GjcsAmBSxzA4H0DI83OqJc+YX5tNmAb+VUcggPJw4BZaO8a1SYDt5npRWA
DqPL72f2cC4Luhj4XngN5xim5if7myiqK9mY6FJhmJKzBxwD+mPgd+GMp2kCmQc5
JeKkQRmagN+b2Q1VEpL51WQpoFao4T9Ta5eqMHf7vZtvF4S2Nt4dILklu2n1TqtN
mq0kJdq2cl8yBXEWqp8T1AxvfsYU2CfnnzDh33Ap5BKstRc1imsHXdbFRuZMgmtz
```
The same way you can import keys either from a server
```
gpg2 --keyserver gpg.mit.edu --recv 0022A74E
```
or if you received an e-mail with someone elses key (or you nicked it off their website *hint hint*) you can import them as well
```
gpg2 --import 0022A74E.asc
```
and it'll show up in your keychain.
### Signatures
You can of course also sign messages with your private key to let people know that it was really you who sent a message. Maybe a public statement or a blackmailing threat. Whatever floats your boat.
```
gpg2 --clearsign file.txt
```
It will result in a file like you can find [here](https://spacekookie.de/pgp/spacekookie-on-the-tubes.txt).
You can of course also sign keys or not have clear signed messages but only signatures for specific messages with `--detach-sign` and `sign-key`.
### Encryption
Of course the primary idea of GPG is to provide e-mail/ message encryption. It's fairely straight forward with
```
gpg2 -a --encrypt message.txt
```
You can combine that command with a signature and even remove the ASCII Armour if you want the binary output of the file.
And that's that. You can send that to someone now. Or print it out and hang it on your wall or whatever.
---
I don't think most people will ever care about using GPG as a commandline tool but I think it's important that people understand how to, if they ever end up in a situation where they do. I also hope that this post has been somewhat useful to you. And wish you happy message encrypting :)
~Kate

@ -1,365 +0,0 @@
Title: 01. (LibGDX) Game of Codes: The Setup & Basics
Category: Game of Codes
Tags: Guides
Slug: 01-libgdx-game-of-codes-the-setup-basics
Status: published
Hey everybody and welcome to a new/ old series on this blog about LibGDX.
LibGDX is a Java game development framework based on LWJGL and OpenGL which makes it relatively easy to make a game from scratch without requiring a big engine. It supports Desktop, Android, iOS and HTML as export targets which means that your game is automatically cross platform.
Getting to know the framework can be challenging in the beginning, which is why I wanted to make a little series about it. Before I moved my blog to a static site generator I had a rather popular series about LibGDX called "Game of Codes". Unfortunately large parts of the guides are now outdated and no longer relevant. And the Wordpress export destroyed most of the formatting.
Which is why I decided to rewrite them. Here it is: the Game of Codes!
NOTE: This tutorial requires a basic level of programming/ scripting skills. General Java knowledge is required or at the very least knowledge of how coding works. If you don't know that yet then I
recommend [Bucky Roberts Java Programming series on Youtube](https://www.youtube.com/watch?v=Hl-zzrqQoSE&list=PLYJQBQw9Wdiid6eT1_DqBP3lnbJCzo3s8).
It's very good!
### Setting up LibGDX
Now that we've got that out-of-the-way let's set up our workspace to
make some neat games.
1. First of all you'll need to have Java and an IDE installed on your computer. I recommend Eclipse. For pointers on how to install those please use Google.
2. Go to [http://libgdx.badlogicgames.com/](http://libgdx.badlogicgames.com/) Downloads and download the framework. You can either go for a nightly build (that will contain more awesome features but probably bugs) or the stable version. Current stable at the time of writing this is 0.9.9 and the version that I will be using (and am using for all my projects).
3. Save and extract the libgdx-0.9.9.zip file somewhere on your computer and open up the folder. You'll see a multitude of things. Now…we could set up an Eclipse project, import all the right files and  write some dummy code but there is an easier way to do this and it's called the Setup-UI. The following two screenshots will explain the basics. This should be trivial but I'll still go over it. Feel free to skip to the next part below.
![](http://www.spacekookie.de/wp-content/uploads/2013/12/libgx_install_1.png)
The following steps will be conducted in the .Jar setup UI. On the upcoming window click on CREATE and then fill out the information on the next screen. Everything you need to consider is being marked as red in the next screenshot.
![libgdx\_install\_2](http://www.spacekookie.de/wp-content/uploads/2013/12/libgdx_install_2.png)
Make sure you already have the directory created that you want to put the project in. The java UI can NOT create folders. Be sure to disable the iOS project. It won't break anything if you leave it ticked but we won't be working with it.
During the selection of the libraries you need to select the folder icon  and then point the application at the archived .zip file you downloaded in the beginning for LibGDX and press the other little arrow button for the Universal Tween Engine to download it. The Jar isn't included in the LibGDX package by default but it can come in handy later. When you're ready to continue everything should light up green. Click on OPEN THE GENERATION SCREEN to continue, click LAUNCH and watch the magic happen.
### Working with LibGDX
Now that we have an auto generated LibGDX project it's time to import it into Eclipse and look at the actual code. Go into Eclipse, File --\> Import. Select General --\> "Existing Projects into Workspace". Navigate to the path and check that all your LibGDX projects are shown as in the screenshot below. Afterwards you should be set to do some serious coding!
![LibGDX\_install\_3](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-14-at-11.00.37.png)
NOTE: LibGDX works very close with Android and when you import the
project you will see the Android project having exploded because of
various issues. Make sure that you have Android set up on your computer.
If you don't, may I refer you to an older blog post of mine: This will
explain the setting up of Android.
That's important, as LibGDX uses the Android assets folder as a link to
the main project. You can change that, if you want. But we'll leave it
as is for now! If you're having issues with this step, post your problem
in the comments below and I'll try to help you resolve it.
 
Now that everything should be ready to go, let's check what kind of code
we have here and understand the basic structure of LibGDX. As you've
already seen there are several projects that were just created: three
projects with suffixes (-android, -desktop, -html) and a core project
without a suffix. All the actual coding will be done in the core project
while the other projects are called "deployment projects". In them you
can adjust platform specific code to deploy your software. But for now,
we will only be working with the Core project and use the desktop
deployment for debugging.
NOTE: Make sure that you leave your Android project open, as LibGDX uses
the androids Assets folder for all the other projects.
 
Now, that we have this figured out, go to your core project and open up
the only class that there should currently be in there. Mine is called
TutorialsLauncher and it has a certain layout of methods in it that
LibGDX always uses.
- **public void create()** - Called when the game is created
- **public void resize()** - Called after create and every time the
window is resized (if that is allowed)
- **public void render()** - Starts calling after create() and
resize() and will be recalled every frame. This is your game loop!
- **public void pause()** - Called when the game is closed on Android
- **public void resume()** - Called when the game is re-opened on
Android
- **public void dispose()** - Called when the game is closed.
This layout allows for very structured code to be written. An
interesting thing to note is that this layout comes from the
implementation of the **ApplicationListener** interface. So when you
create your own main game class you just implement that interface and
it'll suggest the code layout for you automatically.
Before we look at the code in more detail and see what it actually does
we should launch the application though and see what it looks like. For
that you'll need to create a Run Configuration for a Java Application
and point it at the Main class in your \*\*-Desktop project. A new
window will open and TADA! The dummy "game" :)
![LibGDX\_instllation4](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-14-at-12.29.10.png)
Now let's look at the actual code that does stuff:
``` {.width-set:false .lang:java .decode:true title="Create Method"}
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(1, h/w);
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("data/libgdx.png"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);
sprite = new Sprite(region);
sprite.setSize(0.9f, 0.9f * sprite.getHeight() / sprite.getWidth());
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);
}
```
First thing the code does is log the current resolution of the game and
store them in two float variables.
Next up we create a camera, set up with the ratio of the resolution we
just stored in the variables. (We'll talk more in-depth about cameras
later)
The next block loads a texture from the data folder which is stored in
the Androids assets folder and applies a linear filter (If you want to
learn more on that click
[here](http://gaming.stackexchange.com/questions/48912/whats-the-difference-between-bilinear-trilinear-and-anisotropic-texture-filte)).
Don't worry if the rest of that class looks like alien text. I'll
explain renderings, drawings, textures etc. in more detail in a later
article. For now you just need to know: it's setting up a sprite
(texture).
Next up in the code we have dispose:
``` {.width-set:false .lang:java .decode:true}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
}
```
Objects that use anything with OpenGL need to be disposed (should. it's
good practise). It's not that important if you quit the application but
rather when changing screens (more on that later too).
Which brings us to the main method doing stuff in this "game". Render():
``` {.width-set:false .lang:java .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
batch.end();
}
```
The first two calls are OpenGL specific and absolutely need to be in
there. It clears the screen completely and then draws over with a colour
(actually ClearColor only sets a colour and the glClear clears the
screen and draws the colour but more to that later too).
Then comes the tricky part.
"batch" is the SpriteBatch that was created earlier in the create();
method. It's essentially handling texture mapping to the screen and uses
the cameras viewport (aka what the camera is looking at and how many
pixels it contains) to properly map the texture to the screen. It's
begun, then a sprite is drawn and then it's ended. (That's how you draw
things low-level with OpenGL). And that's the game loop.
Depending on how the window is scaled this means that the texture will
always look (more or less) right because it's being adjusted to the
camera viewport (which is essentially just the entirety of the
application window.
 
I know that this was a lot to take in for now. But I'll touch these
topics in later articles (again). And if I don't then there are plenty
of great resources out there (probably better than these :) to help you
around.
However, I want to do one more thing here and that is give this Game a
more Game-y feeling. First of all you should head to the image processor
of your choice (in my case Photoshop) and sketch up something that might
look like a spaceship.
![LibGDX\_Tutorial\_PS](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-14-at-22.55.25.png)
Make sure that the size of the image is by the power of 2 (so 2, 4, 8,
16, 32, 64, 128, 256, 512, 1024, 2048, 4096, etc. because that's how
LibGDX works.
What you say? You're too lazy? You don't have an image processing
application? You managed to delete Paint from your computer? Kudos. Use
[this](http://www.spacekookie.de/downloads/Tutorials/LibGDX1/USS_Pixel.zip "USS Pixel")
then! Next up we want a picture of space. I'm not gonna make something
myself here. And neither will you (most likely). How about
[this](http://www.wallsave.com/wallpapers/1024x1024/galaxies/236804/galaxies-cool-galaxy-and-space-ipad-236804.jpg "Space")?
Save both of these on your computer and import them into your
Android-projects assets folder (copy, not link!) Next up we want to
adjust a bit of our code. If you use external resources they always need
to be as power-of-two pictures. And to overcome that there is a thing
called a TextureAtlas (SPOILERS). But I'll touch that later.
For now, we just need to change the path in one line:
``` {.width-set:false .lang:java .decode:true}
texture = new Texture(Gdx.files.internal("space.jpg"));
```
I made it easy on me and just renamed the picture into "space" and moved
it into the assets folder which in LibGDX internal files is being
referenced as root. If you compile this you'll see two white bars on the
sides. So first, we might want to change that to black to make it
more…space-y but secondly we might want to change the starting
resolution of the game. If you were observant before you know where to
change the OpenGL colour. That's right. Here:
``` {.width-set:false .lang:java .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
```
It uses R-G-B composition colours referenced with floats. The fourth is
the alpha channel. So to get Black we want to set it to
``` {.width-set:false .lang:java .decode:true}
Gdx.gl.glClearColor(0, 0, 0, 1);
```
For the resolution we need to check our platform-specific launcher. In
our case we have to check the Main method in the \*\*-Desktop project
and adjust two things. First, we want the starting resolution to be
800x600 as that's what the TextureRegion cuts from the original texture.
And we want to disable the ability for the window to be resized (for
now) as it adds a whole mess to take care of.
``` {.width-set:false .lang:java .decode:true}
cfg.resizable = false;
cfg.width = 800;
cfg.height = 600;
```
So essentially we need to add one line to the configuration and change
two.
However, we're not done yet. We gave the texture the new path to import.
But that's not all. We need to tell the texture region what part of the
cake to slice from the original texture. And we also need to change some
of the positioning that happens. Essentially you want your code to look
like this:
``` {.width-set:false .lang:java .mark:6,12,15 .decode:true}
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(w, h);
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("space.jpg"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 0, 0, 800, 600);
sprite = new Sprite(region);
sprite.setPosition(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
}
```
I changed the camera setup to just simply use the width and height as
it's viewport, told the texture region to cut a 800x600 part from our
1024x1024 texture and removed the size and origin manipulation. Now
compile this and BOOM.
![Screen Shot 2013-12-15 at
00.19.23](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-15-at-00.19.23.png)
Shiny! \<3 Now we need some slick advertisement and EA will sell this
for 60\$ (+ DLC of course).
Now…we have that ship. Let's just quickly add the ship in idle state in
the middle of the screen before this post gets too long. You should know
how to add the space ship texture by now:
``` {.width-set:false .lang:java .mark:4-5,21-25,32,43 .decode:true}
public class TutorialLauncher implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture texture, shipTexture;
private Sprite sprite, ship;
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(w, h);
batch = new SpriteBatch();
texture = new Texture(Gdx.files.internal("space.jpg"));
texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(texture, 0, 0, 800, 600);
sprite = new Sprite(region);
sprite.setPosition(-sprite.getWidth() / 2, -sprite.getHeight() / 2);
shipTexture = new Texture(Gdx.files.internal("USS_Pixel/ship_idle.png"));
TextureRegion shipRegion = new TextureRegion(shipTexture, 0, 0, 64, 64);
ship = new Sprite(shipRegion);
}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
shipTexture.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
ship.draw(batch);
batch.end();
}
```
And voila :)
![LibGDX\_Tutorial\_Final](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-15-at-00.32.03.png)
But this is it for today. I will start working on the next post
immediately where we will discuss input and movement on the screen (all
very basic) as well as TextureAtli (maybe, if you're lucky)
Until then have a good day/night,
Kate
 

@ -1,345 +0,0 @@
Title: 02. (LibGDX) Game of Codes: Input & Movement
Date: 2013-12-18 18:45
Category: Game of Codes
Tags: Guides
Slug: 02-libgdx-game-of-codes-input-movement
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we learned how to set up LibGDX in our
Java project and draw pictures onto the screen. We used Textures to
import the image and then drew a Sprite from a specific TextureRegion.
This would allow for multiple assets to be saved in a single texture and
thus saving time when loading assets.
In this edition I want to show you LibGDXes abilities to handle input
and move things on the screen. This will be all very basic but hang in
there with me. Let's begin.
Two ways of registering input
-----------------------------
There are two ways to register input events. The first one is to
directly listen to input events in your main game loop and execute code
depending on what happens.
[![input\_raw](http://www.spacekookie.de/wp-content/uploads/2013/12/input_raw.png)](http://www.spacekookie.de/wp-content/uploads/2013/12/input_raw.png)
 
The other method is to create an input processor that sorts through all
the input (not just certain types), allows for more complex features
(like dragging gestures on Android)
 
![input\_handler](http://www.spacekookie.de/wp-content/uploads/2013/12/input_handler.png)
For now, we'll just use the first method. It'll make the process of
input handling very clear. In the second part of this tutorial we'll
have a look at input processor that are mostly needed for mouse and
gesture tracking.
 
Listening for simple button events
----------------------------------
The easiest way to listen for a button-pressed event is by calling
``` {.lang:java .decode:true}
Gdx.input.isKeyPressed(Keys.W)
```
where Keys is an enum index that contains all keys on a regular
keyboard, excluding international characters (Like Ö, æ or å). This
method returns a boolean that can simply be the argument of an
if-statement:
``` {.lang:java .decode:true}
if (Gdx.input.isKeyPressed(Keys.W)) {
}
```
Will run, when the a-key is pressed, if we put this into our games
"render" method. By polling the state of the boolean for the Key "W"
every frame we can get its status whenever the game is running. However
note that this is getting the value indirectly. When a button is pressed
this triggers an event listener to set the boolean to "true" and to
"false" again, once the listener detects that the button has been
released.
But back to our example. In our case we want the spaceship to fly up,
whenever the "W" key is pressed. Let's take a look at the render method
of our game.
``` {.lang:java .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
ship.draw(batch);
batch.end();
}
```
We already use the "ship" sprite in the method. All we need to do now is
update the position before drawing it onto the screen. Unfortunately
there is no direct way to add values to the position of a sprite, only
to overwrite it. So we need to fetch the position first, add our desired
value and then set that new position. The code for that looks something
like that (using the example above where we want the "W" Key to move the
ship up):
``` {.lang:java .decode:true}
if (Gdx.input.isKeyPressed(Keys.W)) {
Vector2 updated = new Vector2(ship.getX(), ship.getY() + 5);
ship.setPosition(updated.x, updated.y);
}
```
Now compile this and press the "W" key and watch what happens. The ship
is moving up. Why? Because with each frame it is being checked if the
"W" key is pressed and if that is the case we add 5 pixels to the
Y-coordinate of the ship sprite.
We can now continue and do this for all four directions:
``` {.lang:java .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isKeyPressed(Keys.W)) {
Vector2 updated = new Vector2(ship.getX(), ship.getY() + 5);
ship.setPosition(updated.x, updated.y);
}
if (Gdx.input.isKeyPressed(Keys.S)) {
Vector2 updated = new Vector2(ship.getX(), ship.getY() - 5);
ship.setPosition(updated.x, updated.y);
}
if (Gdx.input.isKeyPressed(Keys.D)) {
Vector2 updated = new Vector2(ship.getX() + 5, ship.getY());
ship.setPosition(updated.x, updated.y);
}
if (Gdx.input.isKeyPressed(Keys.A)) {
Vector2 updated = new Vector2(ship.getX() - 5, ship.getY());
ship.setPosition(updated.x, updated.y);
}
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
ship.draw(batch);
batch.end();
}
```
Note that the "updated" vector is only a local variable inside the
if-statement and can't be used outside of it. Re-using the name inside
each if-block won't have any weird side effects or break the code.
If you now compile this you'll see that you can move the ship around on
both axis and in all directions but this isn't really a great game yet.
Why? Well...while this might be enough for a retro-side-scroller where
the player only faces up (down) or right (left) for tall intention
purposes, we want the ship to fly around more realistically. So it's
time to introduce rotation to our little game.
As you might have expected we can simply choose two other keys on our
keyboard (let's take Q and E) and use them to check for other if
statements. In addition to that there is a sprite-method called
"rotate". It should be fairly obvious now :)
``` {.lang:java .decode:true title="Add this to your render() method!"}
if (Gdx.input.isKeyPressed(Keys.Q)) {
ship.rotate(-5f);
}
if (Gdx.input.isKeyPressed(Keys.E)) {
ship.rotate(5f);
}
```
And that's it. Compile and see what happens. Fly around a bit. I'll be
waiting here.
------------------------------------------------------------------------
Oh. You're back quickly. Do I see a hint of disappointment on your face?
:) That's okay. See…we might have changed the rotation in the code,
however the displacement vectors (aka the direction that the ship will
be moved into) isn't in correlation with the rotation, just x and y
values. So the rotation doesn't matter, pressing "W" will move the ship
up, etc.
Now...there is an easy way to do this and a hard one. I want you to be
familiar with the mathematical basics first before I show you the easy
way.
[caption id="" align="aligncenter"
width="256"]![libgdx1\_vectoring](http://www.spacekookie.de/wp-content/uploads/2013/12/vectoring.png)
x = tan(α) \* y[/caption]
For each movement the angle of the ship needs to be considered before
moving the ship into the direction of the rotation-vector. Now the easy
way:
First create a new global vector that holds the speed of the ship and
the direction that the speed should be applied to. In this case 5 pixels
on the Y-axis.
``` {.lang:java .decode:true}
Vector2 move = new Vector2(0f, 5f);
```
Now you need to add a bit of code to the if-statement that checks if the
"W" key is pressed.
``` {.lang:java .mark:3 .decode:true}
if (Gdx.input.isKeyPressed(Keys.W)) {
Vector2 temp = new Vector2(ship.getX(), ship.getY());
temp.add(move);
ship.setPosition(temp.x, temp.y);
}
```
We're almost done. The last thing we need is to actually rotate the
movement vector by the amount that the ship has rotated.
``` {.lang:java .mark:2 .decode:true}
if (Gdx.input.isKeyPressed(Keys.A)) {
move.rotate(5f);
ship.rotate(5f);
}
```
You can adjust the if-statement to check if the "S" key is pressed but I
removed it from my code for now.
So this is the full code
``` {.lang:java .mark:1,9,13-14,17-18 .decode:true}
Vector2 move = new Vector2(0f, 5f);
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isKeyPressed(Keys.W)) {
Vector2 temp = new Vector2(ship.getX(), ship.getY());
temp.add(move);
ship.setPosition(temp.x, temp.y);
}
if (Gdx.input.isKeyPressed(Keys.A)) {
move.rotate(5f);
ship.rotate(5f);
}
if (Gdx.input.isKeyPressed(Keys.D)) {
move.rotate(-5f);
ship.rotate(-5f);
}
batch.setProjectionMatrix(camera.combined);
batch.begin();
sprite.draw(batch);
ship.draw(batch);
batch.end();
}
```
Compile the game and enjoy flying around a bit. This is a very elegant
way to handle rotation of an object because the movement logic (move
vector) is disconnected from the rendering logic (Sprite).
One last thing I want to add in this post is some eye candy. In the next
post we'll have a look at the InputAdapter and get some mouse
interaction into our game.
First you should add three more texture regions: shipIdle, shipFly1 and
shipFly2 and refactor the code for the textures and the regions a bit to
be less confusing. My refactored code below as reference but you don't
have to do it exactly as I do.
``` {.lang:java .mark:4-6,22-27 .decode:true .crayon-selected}
public class TutorialLauncher implements ApplicationListener {
private OrthographicCamera camera;
private SpriteBatch batch;
private Texture background;
private Sprite space, ship;
private TextureRegion shipIdle, shipFly1, shipFly2;
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
camera = new OrthographicCamera(w, h);
batch = new SpriteBatch();
background = new Texture(Gdx.files.internal("space.jpg"));
background.setFilter(TextureFilter.Linear, TextureFilter.Linear);
TextureRegion region = new TextureRegion(background, 0, 0, 800, 600);
space = new Sprite(region);
space.setPosition(-space.getWidth() / 2, -space.getHeight() / 2);
shipIdle = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_idle.png")), 0, 0, 64, 64);
shipFly1 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly1.png")), 0, 0, 64, 64);
shipFly2 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly2.png")), 0, 0, 64, 64);
ship = new Sprite(shipIdle);
}
@Override
public void dispose() {
batch.dispose();
background.dispose();
}
```
So we're essentially creating three TextureRegions and mapping the
different pictures of the USS Pixel to it. Lastly, we want the game to
randomly pick one of these three textures when the ship is flying around
to generate an animation effect. For that purpose you should change some
code in the if-statement that checks whether the "W" key is pressed.
``` {.lang:java .mark:11-20 .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
if (Gdx.input.isKeyPressed(Keys.W)) {
Vector2 temp = new Vector2(ship.getX(), ship.getY());
temp.add(move);
ship.setPosition(temp.x, temp.y);
int i = new Random().nextInt(2);
if (i == 0)
ship.setRegion(shipIdle);
else if (i == 1)
ship.setRegion(shipFly1);
else if (i == 2)
ship.setRegion(shipFly2);
} else {
ship.setRegion(shipIdle);
}
```
Now compile this and enjoy.
![LibGDX\_stargame\_1](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-18-at-19.59.03.png)
You should now know how to handle basic keyboard input, how to properly
process it and also to move things on the screen more intelligently than
just to adjust their pixel coordinates manually. In the next issue I
want to introduce you to the InputAdapter but I feel that it would drag
this post out too much. So until next time, keep coding.

@ -1,476 +0,0 @@
Title: 03. (LibGDX) Game of Codes: Input & Movement 2.0
Date: 2013-12-19 13:12
Category: Game of Codes
Tags: Guides
Slug: 03-libgdx-game-of-codes-input-movement-2-0
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we learned how to listen for keyboard
input, move things on the screen and do some basic game logic with
vectors. In this issue I want to re-touch that subject, but in a more
advanced manner. This time we'll have a look at InputProcessors and
their ability to listen for any kind of input, including mouse and
touchscreen gestures. If you haven't already worked through the last
issue of this tutorial series, you should do that
[now](http://www.spacekookie.de/02-libgdx-game-of-codes-input-movement/ "02. (LibGDX) Game of Codes: Input & Movement")!
I'll wait here.
Oh, you stayed. Well then, let's get started.
 
First of all we'll want to create a new class that extends the
InputAdapter.
``` {.lang:java .decode:true}
package de.spacekookie.libgdxtutorial;
import com.badlogic.gdx.InputAdapter;
public class InputHandler extends InputAdapter {
}
```
You can name yours whatever you want, I chose InputHandler, as for any
managing class that HANDLES things in my software :) Handlers and
Dealers, the criminal underworld in my source code is real.
We will add things to this class later, first of all we should tell our
game that it exists. And we can do that by adding the following code
into the games creation method.
 
``` {.lang:java .decode:true}
private InputHandler handler;
@Override
public void create() {
. . .
handler = new InputHandler();
Gdx.input.setInputProcessor(handler);
. . .
}
```
Great. Now that we told our game to actually use the InputAdapter we
created we can start and add some actual code to it. If you look at the
class that we're extending you can see a few methods that we can
override. Why don't you add this method to the InputAdapter class.
``` {.lang:java .decode:true}
@Override
public boolean keyDown(int keycode) {
return true;
}
```
Remember when I told you in the last post that polling
Gdx.input.isKeyPressed(. . .); was only an indirect way to get the
status of a key and would only react to a listener event? Well guess
what...that's an event listener that will react t ANY key-down event.
The keycode passed into the listener specifies the key in question.
Go ahead and check if keycode is the same as the integer representing a
key (Keys.\*) like SPACE.
``` {.lang:java .decode:true}
if (keycode == Keys.SPACE) {
System.out.println("If this game had gravity I would want to JUMP!");
}
```
If you compile this you'll see that the game will of course still
recognize the inputs handled in the Games render() method but in
addition to that will react to keystrokes being handled in our
InputAdapter. However...we have a problem. To actually handle the input
in the Adapter we need to pass on some information into it. We can
either pass the Sprite along but I would say something much better is to
create a custom Object to hold all the important information to render,
move and manipulate the ship (or other entities we might add later). So
why don't you go ahead and create a new class called "Entity". I went
ahead and added some code to it to actually make it useful.
``` {.lang:java .decode:true}
package de.spacekookie.libgdxtutorial;
import java.util.Random;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
public class Entity {
public static enum EntityType {
PLAYER, ENEMY;
}
public static enum ShipState {
IDLE, MOVING, DEAD;
}
private EntityType type;
private Sprite self;
private TextureRegion shipIdle, shipFly1, shipFly2;
private Vector2 moveVector = new Vector2(0f, 1f);
private float speed = 5f;
public Entity(EntityType type) {
this.type = type;
moveVector.scl(speed);
loadResources();
}
public void loadResources() {
if (type.equals(EntityType.PLAYER)) {
shipIdle = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_idle.png")), 0, 0, 64,
64);
shipFly1 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly1.png")), 0, 0, 64,
64);
shipFly2 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly2.png")), 0, 0, 64,
64);
self = new Sprite(shipIdle);
}
}
public void idle() {
self.setRegion(shipIdle);
}
public void fly() {
int i = new Random().nextInt(2);
if (i == 0)
self.setRegion(shipIdle);
else if (i == 1)
self.setRegion(shipFly1);
else if (i == 2)
self.setRegion(shipFly2);
}
/** Used to get access to methods */
public Sprite getSelfSprite() {
return self;
}
public Vector2 getMovement() {
return moveVector;
}
public void setMovement(Vector2 moveVector) {
this.moveVector = moveVector;
}
/** Will be called in the @render() method */
public void draw(SpriteBatch batch) {
self.draw(batch);
}
}
```
If you actually look at the code you won't see anything you haven't seen
before. What I did was move all the texture loading, sprite setup and
region swapping when flying and idling into this class as well as
creating a few getters to access the information from outside the class.
The only two new things are the two enums, ShipState and EntityType
which will become more useful in the future. But laying the groundwork
now for a more complex game will become handy later.
Next up we need to take a look at the InputAdapter and change it in a
way that it uses flags on keyDown and keyUp (as in setting a flat to
"true" on down and "false" to up). Then move all the movement logic into
a method called "update()" that will be called in the games render()
method.
Here is my code as reference.
``` {.lang:java .decode:true}
package de.spacekookie.libgdxtutorial;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.math.Vector2;
public class InputHandler extends InputAdapter {
private Entity entity;
private boolean moving, clock, counterClock;
public InputHandler(Entity entity) {
this.entity = entity;
}
@Override
public boolean keyDown(int keycode) {
if (keycode == Keys.W) {
moving = true;
}
if (keycode == Keys.A) {
counterClock = true;
}
if (keycode == Keys.D) {
clock = true;
}
return true;
}
@Override
public boolean keyUp(int keycode) {
if (keycode == Keys.W) {
moving = false;
}
if (keycode == Keys.A) {
counterClock = false;
}
if (keycode == Keys.D) {
clock = false;
}
return true;
}
public void update() {
if (moving) {
Vector2 temp = new Vector2(entity.getSelfSprite().getX(), entity
.getSelfSprite().getY());
temp.add(entity.getMovement());
entity.getSelfSprite().setPosition(temp.x, temp.y);
entity.fly();
} else {
entity.idle();
}
if (counterClock) {
entity.getMovement().rotate(5f);
entity.getSelfSprite().rotate(5f);
}
if (clock) {
entity.getMovement().rotate(-5f);
entity.getSelfSprite().rotate(-5f);
}
}
}
```
And the games render() method.
``` {.lang:java .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
handler.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
space.draw(batch);
player.draw(batch);
batch.end();
}
```
Make sure to remove all calls from the main game class that we have
already moved to our Entity. And that's it. Compile this and see what we
made (a huge mess, I know).
So? Well done, we just remade what we already had, just in less
clustered and more shiny. But this isn't very impressive, is it now?
Sure this code looks much cleaner than before but InputAdapters are a
lot more powerful than that. Why don't you go ahead and add a new method
to our InputAdapter.
``` {.lang:java .decode:true}
@Override
public boolean mouseMoved(int screenX, int screenY) {
System.out.println(screenX + " : " + screenY);
return false;
}
```
When you compile this you'll see the coordinates of your mouse output in
the console as you move the cursor over the game window. That's because
the listener is being called every time the mouse is moved and without
any further filtering it of course. Now it's gonna get rough, so put on
your thinking hats and try not to go mad. Because we'll have to go and
mock around with Vectors quite a bit and I will have to introduce you to
camera vectors already. I will only brush the subject here and retouch
it in a later version to go more in depth.
First up we need to change a few things in our main game class. First,
change the OrthographicCamera variable to "static".
``` {.lang:java .decode:true}
private static OrthographicCamera camera;
```
And then write a little getter for that camera variable that's also
static, so that we can access it without having to worry about a
constructor.
``` {.lang:java .decode:true}
public static OrthographicCamera getCameraInstance() {
return camera;
}
```
 
Now, go ahead and create three more global variables in the
InputAdapter.
``` {.lang:java .decode:true}
private boolean clicked;
private Vector3 vec;
private Vector3 target;
```
The boolean will be used to flag whether the mouse button has been
clicked and the ship is still en-route. The two 3D vectors will be used
to pinpoint the target we're trying to approach and the movement vector
that the ship will be using. They need to be Vector3 objects (3D
vectors) because they need to interact with our camera, which is a 3D
object. Don't forget! LibGDX is a 3D game development framework, so we
need to ignore the third dimension most of the time. Just set it to "0"!
Now we need to handle the mouse actions. Go and delete that line of code
from the mouseMoved method and create a touchDown() method. It will be
used to register mouse events but can also be used to register touches
on Android devices.
``` {.lang:java .decode:true}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
if (pointer == 0) {
if (button == 0) {
}
}
return false;
}
```
The pointer is "0" in case of the mouse but can be something else, when
we're dealing with touchscreen input. The button "0" is the left mouse
button, "1" is the right one. Nest those two if-statements, so that both
need to be true for our code to be executed. I will go through what we
do here line by line because it's not exactly trivial.
``` {.lang:java .decode:true}
vec = new Vector3(x, y, 0);
```
First we take that Vector3 (vec) we created before and put some
information into it. X and Y are the mouse coordinates that are passed
into the listener (where the click occurred) and put 0 for the
Z-Coordinate.
``` {.lang:java .decode:true}
TutorialLauncher.getCameraInstance().unproject(vec);
```
Next up, we need to call that static method we created in our main game
class to get the camera and call "unproject" onto it. Unprojecting means
associating a coordinate in the camera space with a pixel coordinate on
the screen. When the camera is moving around it will change the
coordinates quite drastically. So a camera coordinate (5000, 10000)
could still correlate to a pixel coordinate that's more like (255, 128),
etc. Unprojecting the camera and passing our Vector3 object into it
aligns the camera space with the pixel space on-screen. We WILL talk
about cameras and matrix projection in a later issue. For now, I hope
that this is at least somewhat clear.
Next up, store the unprojected vector in our target Vector3 that we
created, set the boolean and return from the method.
``` {.lang:java .decode:true}
target = new Vector3(vec);
clicked = true;
return true;
```
The target Vector3 will not change and serve as a reference where the
original click was made and when we want our ship to stop flying. We're
almost done. We already flag our button clicks in the listener, now we
just need to use that flag in our update() method that gets called every
frame.
``` {.lang:java .decode:true}
if (clicked) {
entity.fly();
} else {
entity.idle();
}
```
You should understand what that does, just registering the clicked flag
and setting the textures accordingly.
``` {.lang:java .decode:true}
Vector2 temp = new Vector2(entity.getSelfSprite().getX(),
entity.getSelfSprite().getY());
```
Log the current position of our sprite and save it in the temp Vector.
And now it's getting kinda tricky. There is a Vector method called lerp,
which interpolated two vectors. We will touch Vectors again in a later
issue. If you want to read the mathematical principles of interpolation
you can click [here](http://en.wikipedia.org/wiki/Linear_interpolation).
(If you're masochistic like that).
``` {.lang:java .decode:true}
temp.lerp(new Vector2(vec.x, vec.y), 0.1f);
entity.getSelfSprite().setPosition(temp.x, temp.y);
```
Vec starts as the target and gets shorter and shorter as the temp vector
approaches the target more and more. Afterwards we do the normal jazz
and adjust the entities Sprite position with the new temp vector (which
isn't the target position but rather the first step on the way to the
target.
Lastly we need to deactivate the ships engines when the ship has reached
the target position (that's why we saved it in the target vector :) )
``` {.lang:java .decode:true}
if (target.dst(temp.x, temp.y, 0) < 2)
clicked = false;
```
Add this to the end of the if(clicked)-statement. dst(. . .) returns the
range between two vectors (target and temp, where we only look at the X
and Y coordinates) and we can then compare that range to a number, in my
case 2. So when the temp vector gets into a range of 2 pixels to the
target vector the if-statement is true and sets the clicked boolean to
"false" and stops moving the ship (and then the else-statement is called
and sets the texture to idle again). It also corrects the rotation
correction that we used before.
 
And that's that. Compile the game and try out the two methods of
movement we now have. Rotating the ship properly when clicking would be
too long and difficult for this tutorial so I left it out. (Well
actually rotating isn't too difficult but making the click-rotation and
the keyboard rotation compatible is a bit tricky).
What we did in this issue was refactor our input handling and add some
more code to interact with the game using the mouse. I don't know what
we'll touch on next but I think we'll end this issue here. I hope you
learned something and until next time, keep coding!
 

@ -1,216 +0,0 @@
Title: 04. (LibGDX) Game of Codes: Textures and asset management
Date: 2013-12-19 19:18
Category: Game of Codes
Tags: Guides
Slug: 04-libgdx-game-of-codes-textures-and-asset-management
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we learned how to use InputAdapters and
used the keyboard and mouse to order our little space-ship around on the
screen. In this issue I want to take a step back from our actual game
and have a look at our surroundings. Data files, assets and resource
imports. Where to put them to make the game code as practical and
readable as possible. LibGDX has a few quirks and also tools to make
asset management as easy as it can be. So without further ado, let's
begin.
Collecting all Asset imports in one class {style="text-align: justify;"}
-----------------------------------------
The first thing we'll want to do is create a new package in our project.
I named mine "Util" to symbolize that everything in there has to do with
utility classes and tools that don't have a direct effect on gameplay
but are substantially important in using the game. If you're not
familiar with naming conventions for packages here is the rundown.
``` {.lang:java .decode:true}
SUFFIX.DOMAIN.PROJECT.PACKAGE.SUB-PACKAGE
In my case:
de.spacekookie.libgdxtutorial.util
```
If you don't have website where you would publish your code just use
your name with a com or de or whatever your language code is (or you
want it to be to confuse people).
![Screen Shot 2013-12-19 at
15.18.59](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-19-at-15.18.59.png)
Be sure to select your source folder to create the package. And then in
the next dialogue type the entire package tree, not just the name of the
end package you want to name. Because Eclipse will create folders from
these sub-trees.
[![Screen Shot 2013-12-19 at
15.19.16](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-19-at-15.19.16.png)](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-19-at-15.19.16.png)And
to not confuse us in the long run r-click on that other package that so
far holds all other classes and add the subpackage-name "core" to it. It
will symbolize that it holds our darkest secrets (aka the most important
classes in our game, like the main game class or the InputAdapter).
When you're done with that go ahead and create a new class in the "util"
package named along the lines of "ResourceLoader" or "TextureLoader" or
whatever takes your fancy. I'm gonna call it "**ResPack**" short for
"ResourcePacker", because it will be filled with static variables that
we will have to call from all over the game...LOTS of times. So I want
it to be as short as it can be. Once created go and fill it up with our
texture loading and save them into "public static final" variables. We
wan them to be accessible from anywhere in the game "public static" but
we also want them to be fixed and never changed again (by accident or by
an evil hacker that uses texture hacks) aka "final".
``` {.lang:java .decode:true}
package de.spacekookie.libgdxtutorial.util;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
/** Class to load all assets for the game */
public class ResPack {
public static final TextureRegion shipIdle = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_idle.png")), 0, 0, 64, 64);
public static final TextureRegion shipFly1 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly1.png")), 0, 0, 64, 64);
public static final TextureRegion shipFly2 = new TextureRegion(new Texture(
Gdx.files.internal("USS_Pixel/ship_fly2.png")), 0, 0, 64, 64);
}
```
Alright, that's that so far. In addition to that I've made a little
texture called "blast\_small" that we will be adding later, which is
essentially just a little laser shot. You can download it
[here](http://www.spacekookie.de/downloads/Tutorials/LibGDX1/blast_small.png)
and add it to your USS\_Pixel folder in the assets directory.
But you can already see a problem, the texture isn't in power of two
measurements and we would have to manually cut out the blast from a, say
32x32 texture. But we don't really want that, do we? We're gonna have a
lot more textures later on and if we have to cut out each one
individually we're gonna have a hard time. And that's why we have such a
handy thing called the
[TextureAtlas](http://en.wikipedia.org/wiki/Texture_atlas).
Working with TextureAtli {style="text-align: justify;"}
------------------------
A TextureAtlas is essentially a file that contains all resources in it
packed into one image and an .atlas file that keeps tabs on what
resource can be found at what exact pixel location (and it's size, etc).
To create a TextureAtlas we need a TexturePacker which isn't included in
its GUI form in the LibGDX distribution (we can learn how to use the
command-line class from within our game later). Go
[here](https://code.google.com/p/libgdx-texturepacker-gui/downloads/list)
to download the GUI and add it somewhere in your project folder, why not
inside the asset folder.
The texturepacker is a .jar that can be run as a UI application that
needs no setting up. Run it and get a look around. First we want to
create a new pack, so do that on the top-left corner of the window.
Select a project name, an input, an output directory and of course a
file-name pattern. Input is the USS\_Pixel folder in our assets folder,
the output is the assets folder itself (in my case). Leave all the other
settings as they are. Then select "Pack 'em all" and wait for a
confirmation to pop up.
![TexturePackerDemo1](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-19-at-16.39.00.png)
Go and check the output folder where you should see a .png and an .atlas
file. If you have a look at the .png you will see that all the single
textures we had in our USS\_Pixel directory have been molded into a
single file that has the power-of-two resolution so that our game won't
die on us. The .atlas file should just be a bunch of numbers and words
with parameters. We'll have a look at those in a minute. First I want
you to update Eclipse so that it sees the new files in our asset folder
and direct your attention back at the ResPack class that we started in
the beginning of this tutorial.
We'll want to create a TextureAtlas object, private, static and final
and give it the .atlas file to read. I will call mine "\_PIXEL"
*(It's my naming convention to give variables that are only used in very
very (VERY) specific context an underscore as a beginning so that they
show up first on the list of recommended variables but also to filter
them out quickly and give them somewhat of a specific look. You don't
have to do it this way, I think it's even considered bad practise. But
it's something that I like to do).*
After we have our private static and final TextureAtlas we can find
textures in it by calling "findRegion(. . .)" on it. Here is some code
as reference.
``` {.lang:java .decode:true}
private static final TextureAtlas _PIXEL = new TextureAtlas(
Gdx.files.internal("USS_Pixel.atlas"));
public static final TextureRegion shipIdle = _PIXEL
.findRegion("ship_idle");
```
As you can see we no longer have to bother around with pixel coordinates
in our textures because they've all be stored in the .atlas file by the
TexturePacker. All there is left to do now is remove the TextureRegion
calls from our Entity class and change it the fly() and idle() methods
as well.
``` {.lang:java .decode:true}
public void loadResources() {
if (type.equals(EntityType.PLAYER)) {
self = new Sprite(ResPack.SHIP_IDLE);
}
}
public void idle() {
self.setRegion(ResPack.SHIP_IDLE);
}
public void fly() {
int i = new Random().nextInt(2);
if (i == 0)
self.setRegion(ResPack.SHIP_IDLE);
else if (i == 1)
self.setRegion(ResPack.SHIP_FLY1);
else if (i == 2)
self.setRegion(ResPack.SHIP_FLY2);
}
```
And that's that. Isn't it neat? We cleaned up our code and even made the
loading of textures easier and more efficient as well. The only downside
is that you will have to re-pack your TextureAtlas for every texture
that you add. In practise I usually have 2-3 atli that hold different
kinds of textures together to keep some orientation over the textures
involved.
For that purpose I created three more textures, the Deep\_Pixel\_Nine,
the Pixel\_Sun and Pixel\_Earth to be part of an "environment" atlas (as
well as a more low-profile space picture :p ). You can download the
whole .zip file with everything inside
[here](http://www.spacekookie.de/downloads/Tutorials/LibGDX1/world.zip)!
Go and add that to the ResPacker. You should know how ;)
After setting up your ResPacker to properly import all the
TextureRegions you should go and change the image that we're currently
using and clean up your code in a way that it won't crash and doesn't
contain calls that aren't being used anymore. With the ResPacker you
have all your resources in one place and collected in two Texture Atli.
Lastly, I went ahead and refactored the assets folder a little to be
less clustered and deleted some of the files that we didn't need any
more. Also note that I'm always keeping the raw files in case I need to
update something.
![refactored\_assets\_1](http://www.spacekookie.de/wp-content/uploads/2013/12/refactored_assets_1.png)
And that's that for our rather short issue this time (I would want to
say this week but I'm writing these so quickly right now). Next time I
want to have a look at...I'm not sure yet. Probably cameras, controlling
cameras, moving cameras around, etc. And of course some lovely camera
theory. But until then have a lovely day and keep coding!

@ -1,455 +0,0 @@
Title: 05. (LibGDX) Game of Codes: Cameras, their controllers and more Input
Date: 2013-12-20 02:21
Category: Game of Codes
Tags: Guides
Slug: 05-libgdx-game-of-codes-cameras-their-controllers-and-more-input
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we learned how to use Texture Atli and
sort our assets in a way that we don't get lost in them (and also import
them all in one place, our ResourcePacker). In this issue I promised you
something about cameras and I realised that this would be the perfect
opportunity to add some more action into our game. Let's begin!
The first thing we'll want to do is create a new class in our utility
package and call it something along the lines of CameraController,
CameraInputAdapter or CameraManager. Let the class extend the
InputAdapter and already create a few variables in it. An
OrthgraphicCamera called camera and 4 Vector3 objects called current,
mouse, last and delta. We'll need these to handle the scrolling logic
for our camera.
``` {.lang:java .decode:true}
public class CameraController extends InputAdapter {
final OrthographicCamera camera;
private final Vector3 current = new Vector3();
private final Vector3 mouse = new Vector3();
private final Vector3 delta = new Vector3();
private final Vector3 last = new Vector3(-1, -1, -1);
}
```
Be sure to give last three "-1" values and the rest you can leave empty.
That's that, now create a constructor that takes the camera and stores
it into the camera variable in our controller.
Add the highlighted code into your games create() method to set up the
CameraController. **Notice how we replaced the InputAdapter as the Input
Processor and are now using the camController!!!**
``` {.lang:java .mark:3-4 .decode:true}
camera = new OrthographicCamera();
camera.setToOrtho(false, w, h);
camController = new CameraController(camera);
Gdx.input.setInputProcessor(camController);
camera.update();
```
And that's where we'll take a step back and look at cameras for a
moment. I already mentioned "unprojecting" in a previous tutorial and
the term "Orthographic" has been flying around quite a lot recently. So
I actually wanted to take the time and explain a few things about
cameras because they'll make the whole ordeal less complicated (and also
give you the ability to come up with your own camera code).
![zyGF1](http://www.spacekookie.de/wp-content/uploads/2013/12/zyGF1.gif)
These are the two camera types, left perspective and right orthographic.
The main difference is that the perspective camera actively uses the
third dimension to create the effect of depth while orthographic cameras
will project everything onto the screen in a straight line. The third
dimension can be used to move things behind one another but there is no
effect of depth. Two objects could be apart by 500 pixels in the z-axis
and still have the same size on-screen.
![unprojectcameras](http://www.spacekookie.de/wp-content/uploads/2013/12/unprojectcameras.png)
Camera projection is a bit tricky but it boils down to using two
different coordinate sets. When you draw something on the screen every
point in your window has a pixel coordinate from an origin (either top
left or top right corner). But when you're using a camera that camera
can scroll around, it can zoom and move. Therefor every point in the
camera space has a different coordinate than the pixel coordinates on
the screen. In the example of the picture above it is visible that the
point on the screen (in pink) has a different coordinate on the map than
on the screen (because the map and screen origin aren't the same).
When registering clicks, drags or any kind of interaction all those
coordinates will be in the screen-coordinate system. But we don't want
the game to just set place in one screen width/ height so we move around
and by calling "unproject" with a Vector3 we can translate the screen
coordinates (with help of the camera) into world coordinates. Those two
can be the same if the origins are the same but they can also be vastly
different when on the other side of the game world.
Don't forget to remember this! Your camera space will always move around
while your pixel space will stay the same.
If you have questions about that, post them in the comments below. But I
hope this should be clear now. Now we should get back to the matter at
hand.
Controlling the Camera {style="text-align: justify;"}
----------------------
We're gonna have a look at zooming the camera first and limiting zoom
range so that the player can't zoom out to see the entire world or zoom
too far in that one pixel of the ship takes up the entire screen. But
first up, I want you to do one things: go into the games Main method
(the one that starts the Desktop client) and change three things.
``` {.lang:java .decode:true}
cfg.useGL20 = true;
cfg.width = 1280;
cfg.height = 720;
```
Using OpenGL2 isn't important for now but we should do it anyways. It
will make things look smoother and work faster but not be compatible
with older (Android) devices. The second thing is just upgrading the
game to 720p resolution which in 2013 is probably better. Aaaaaand JUST
like that we have the same resolution as the Xbox One :')
``` {.lang:java .decode:true}
@Override
public boolean mouseMoved(int screenX, int screenY) {
mouse.set(screenX, screenY, 0);
return false;
}
@Override
public boolean scrolled(int amount) {
float newZoom = camera.zoom * (1 + (amount < 0 ? 0.1f : -0.1f));
changeZoom(newZoom, mouse.x, mouse.y);
return true;
}
```
Add these two methods to our camera controller. The mouseMoved method
should be fairly trivial, we only log the current mouse location into
our lovely vector, with the z-axis set to "0" and return with false.
The second method is the scrolled(. . .) method that gets passed in an
amount (-1 or 1, depending on the mouse-wheel direction) and executes
some code to calculate the zoom.
First up we create a new float called newZoom and take the current
camera zoom and multiply it by 1 + either 0.1 or -0.1, depending on
whether amount was 1 or -1. This is a general syntax that can be used, a
shortened if-statement:
``` {.lang:java .decode:true}
(a < b ? 1 : 2)
means:
"Is a smaller than b? If that's the case return 1, if not, return 2"
```
We could have written a whole nestation of if-statements for it but why
do that if we can just write one line.
The next line calls "changeZoom" which is a method that we have yet to
implement and gives it the newZoom value, as well as the latest
mouse-pointer-coordinates. This means that the picture will zoom towards
the mouse, like in any decent game. If you wanted it to zoom towards the
center of the screen you could use this.
``` {.lang:java .decode:true}
changeZoom(newZoom, Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);
```
Now let's have a look at what we need to do in the changeZoom(. . .)
method we have yet to write.
- We need to log the current screen position to translate the screen
by amount x and y to fit the new zoom position
- We need to check if zoom should be applied (aka if inside the zoom
boundaries)
- Apply the zoom, update the camera and check the new camera position
- Then calculate how to move the camera to its new position
So there will be a tiny tiny delay between zooming and panning to a side
but in practise it's not noticeable. So let's get to work.
First you should add another vector to the list, this time just a
Vector2, that will hold our zoom boundaries for us. I just went with two
hardcoded values that I found worked out quite well in practise. But
you're free to experiment around.
``` {.lang:java .decode:true}
/* x = min, y = max */
Vector2 zoomBounds = new Vector2(0.45f, 0.75f);
```
Next up, we can go create our method and tackle the first two bulletins
on our list.
``` {.lang:java .decode:true}
public void changeZoom(float zoom, float x, float y) {
Vector3 before = new Vector3(x, y, 0);
camera.unproject(before);
if (zoom <= zoomBounds.x || zoom >= zoomBounds.y) {
return;
}
}
```
Returning from a void method with no value will just jump out of the
method. It's an easier why than to nest the entire algorithm into an if
or the following else-statement. The statement just checks if the zoom
value that we pass into the method.
Now that we've shown that the zoom is valid we can apply it and update
the camera. Then we can store the new location vector, unproject it and
afterwards translate the camera from the old position to the new by
subtracting the two vectors and thus getting the connection vector.
``` {.lang:java .decode:true}
camera.zoom = zoom;
camera.update();
Vector3 after = new Vector3(x, y, 0);
camera.unproject(after);
camera.translate(before.x - after.x, before.y - after.y, 0);
```
Go ahead and try that for a bit. You'll see that the camera won't zoom
past our barriers which means that the player can be focused on their
ship and the environment at times and still zoom out a bit and get some
sort of overview. It was important to having implemented this first
because now we're gonna tackle the much harder subject of scrolling
around (by clicking and dragging) and also setting boundaries around the
map that limit the player from scrolling past our beautiful star map and
into the nothingness that is the white background colour :O
Start by adding two more methods: touchDragged, touchUp and update().
``` {.lang:java .decode:true}
@Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(current.set(x, y, 0));
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
return false;
}
public void update() {
}
```
And start by setting the current vector to the x and y values passed
into the method as they'll be updating the current vector. Then
unproject that bad girl to get the world coordinates of the actions.
Next we want to check if we've already dragged. And that's why I wanted
you to give the last vector the value (-1,-1,-1) because this now allows
us to use this value as a flag. See, because we're only using 0 in the
z-dimention we can assume that if it's set to -1 it's one of our flags.
So go ahead and check if last is (-1,-1,-1) and if it is NOT! set the
delta vector to the last coordinates and unproject that as well.
``` {.lang:java .decode:true}
if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
camera.unproject(delta.set(last.x, last.y, 0));
}
```
Afterwards add two more things: we want delta to be the difference
between the last point and our current point, so we need to subtract the
two. And lastly we want to apply that manipulated delta vector to the
camera so that it actually moves from our last position to the current
position (on the delta vector). (Full if-statement to prevent confusion,
I will add the full code again afterwards. This is really non-trivial).
``` {.lang:java .decode:true}
if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
camera.unproject(delta.set(last.x, last.y, 0));
delta.sub(current);
camera.position.add(delta.x, delta.y, 0);
}
```
After we're done with this we want the last vector to be set to our
current coordinates because in the next call those need to be updated
(as current will have been updated to our next position). Then we return
with false because we want the event to trickle through every listener
we have. What is that? I know...I'm getting ahead of myself, I will
explain that in a bit!
Now we can scroll around the camera but there is one thing we need to do
and that is set last to (-1,-1,-1) again so that it can't activate the
if-statement on the first call of touchDragged and gets assigned with
the current coordinates.
``` {.lang:java .decode:true}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
last.set(-1, -1, -1);
return false;
}
```
And here the full touchDragged(. . .) again as reference.
``` {.lang:java .decode:true}
@Override
public boolean touchDragged(int x, int y, int pointer) {
camera.unproject(current.set(x, y, 0));
if (!(last.x == -1 && last.y == -1 && last.z == -1)) {
camera.unproject(delta.set(last.x, last.y, 0));
delta.sub(current);
camera.position.add(delta.x, delta.y, 0);
}
last.set(x, y, 0);
return false;
}
```
Now...if you try this out you'll see that we can zoom and scroll around
on our lovely landscape. But the problem is that there are no bounds to
keep us inside the landscape and the player can easily scroll too far
and see the white background. Yikes.
To fix this we need to go back to our main game class for a second and
change the render() method a tiny bit.
``` {.lang:java .mark:6-7 .decode:true}
@Override
public void render() {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
handler.update();
camController.update();
batch.setProjectionMatrix(camera.combined);
batch.begin();
space.draw(batch);
player.draw(batch);
batch.end();
}
```
What did I do here? I stopped updating the camera in the render method
but instead started calling that update() method we created in the
CameraController. We could of course have this code in the render method
but it's good practise to not cluster that thing up too much. Go back to
the camera controller and add that camera.update() call to the update()
method again so that we don't break everything.
And that's the point where I will once again bore you with mathematical
theorems. (Actually it's not too bad). The subject at hand is clamping.
For everybody familiar with this, go ahead and skip this paragraph. For
everybody that is not, let me quote Wikipedia for you:
*"In computer graphics, clamping is the process of limiting a position
to an area. Unlike wrapping, clamping merely moves the point to the
nearest available value."*
So essentially we have a method called clamp(value, min, max); and the
method tries to keep our value between the minimum and the maximum. In
LibGDX this is done by calling the MathUtils class and asking for (the
drunken) clamp.
We will be clamping the cameras x and y position manually but we have
another problem. See...we have our origin in the bottom left, but the
camera position is measured at its center. And because we're zooming in
and out the center doesn't always have the same position. So we need to
adjust the boundaries for the camera dynamically. And we can do that by
taking the size of the screen, multiplying it with the camera zoom and
then dividing it by 2 to get the center.
In code example.
``` {.lang:java .decode:true}
camera.position.x = MathUtils.clamp(camera.position.x, (Gdx.graphics.getWidth() * camera.zoom) / 2, max);
```
Now..for the maximum, we want the camera to stop on the other side of
the texture, so we need to get the size of the texture from the
ResPacker. But we also need to take the same offset we added to the
minimum, because the center is still moved to its center. So instead of
adding to "0" we now subtract from the size of the texture.
``` {.lang:java .decode:true}
ResPack.WORLD_BACKGROUND.getRegionWidth() - (Gdx.graphics.getWidth() * camera.zoom) / 2
```
And that's that. Here is the full code if you wanna check that you did
it right. Of course we want to do this for both the X and the Y axis and
we of course want to take the HEIGHT for the Y axis, not the width
(looks at self in shame after not having found a bug with this).
``` {.lang:java .decode:true}
public void update() {
camera.position.x = MathUtils.clamp(camera.position.x, (Gdx.graphics.getWidth() * camera.zoom) / 2,
ResPack.WORLD_BACKGROUND.getRegionWidth() - (Gdx.graphics.getWidth() * camera.zoom) / 2);
camera.position.y = MathUtils.clamp(camera.position.y, (Gdx.graphics.getHeight() * camera.zoom) / 2,
ResPack.WORLD_BACKGROUND.getRegionHeight() - (Gdx.graphics.getHeight() * camera.zoom) / 2);
camera.update();
}
```
is now our update method and it's glorious, isn't it? Try it out and
marvel at our limitless glory and genius. And then realise that you can
no longer move the ship. Well....remember? We kinda replaced the
InputAdapter as our InputProcessor. But don't worry, there is a way
around it! Remember when I spoiled you a few lines ago with trickle down
something? Well..turns out that LibGDX offers you a way to add multiple
InputProcessors with something called a *Multiplexer*.
![Input
Multiplexer](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2014-01-10-at-23.57.26.png)
Go into our main game class and add a new Object
``` {.lang:java .decode:true}
private InputMultiplexer plex;
```
And then in the create() method.
``` {.lang:java .mark:6,12-14 .decode:true}
@Override
public void create() {
. . .
plex = new InputMultiplexer();
handler = new InputHandler(player);
camController = new CameraController(camera);
/* Input Controllers */
plex.addProcessor(camController);
plex.addProcessor(handler);
Gdx.input.setInputProcessor(plex);
}
```
Adding the CameraController first will give it a higher priority in the
MultiPlexer. Meaning that it will first trigger the events in the
CameraController and then trickle down to the other controllers. That's
why I didn't want to return true in our drag-methods because that would
stop the event and not pass it onto the next InputProcessor.
And that's that, compile this and you'll see that you can fly the ship
around and drag the camera over the map at the same time. And this is
where I'll end this tutorial, I think I've loaded your brain with enough
new stuff right now.
Next time I want to take a look at actual gameplay. Letting the camera
pan after the ship, letting the ship also have boundaries (same as the
camera) and placing those other textures I made around in the world, as
well as some well needed refactoring if we're gonna expand our feature
list. But until next time, keep coding!

@ -1,333 +0,0 @@
Title: 06. (LibGDX) Game of Codes: Creating a world & more refactoring
Date: 2014-01-10 22:30
Category: Game of Codes
Tags: Guides
Slug: 06-libgdx-game-of-codes-creating-a-world-more-refactoring
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we learned how to write a camera input
processor (which is really just like a normal input processor) and do
some freaky matrix calculations in order to move around. In this issue I
want to go back to the roots (so to say) and work on features. Our code
is already pretty slick but I think it can be improved in order to make
room for more features. Let’s begin!
First off we should change a few things in our Entity class. Remember
that EntityType that I added despite you shaking your and saying "what
the hell is she up to again?" Well...go in there and add some more
values into the enum. And also create a public getter for the type and a
private setter. This is only a temporary solution, in the long run we
want things to be saved in a database. But it'll do for now!
``` {.lang:java .decode:true}
public static enum EntityType {
PLAYER, ENEMY, STATION, PLANET, STAR;
}
. . .
public EntityType getType() {
return type;
}
private void setType(EntityType type) {
this.type = type;
}
```
Right now we only have one station, one planet and one star. So if we
ever decide to create more bodies we'll have to come up with a new
system (Plot twists: I already have, I'm just not telling you ;) )
Next up we want to do something else. Go ahead and create a new package
called objects (Remember to name it with the full package-tree so that
it's a child of "libgdxtutorial" and not "src") We'll use this package
to store all our gameplay objects in here. Go ahead and drag the
"Entity" into it as well before creating a new class called "World".
This is what your project tree should look now. Well...more or less.
![LibGDX\_Tutorial\_tree](http://www.spacekookie.de/wp-content/uploads/2014/01/Screen-Shot-2014-01-10-at-22.39.30.png)
Our world class will have an overview of all entities in existence,
coordinate collision detection with the player (later maybe between
non-player entities as well) and generally just know everything
important. For that to work we need to give it all the entities there
are. So go ahead and create a new Set and a few methods to actually use
those. My code, as always, as reference below.
``` {.lang:java .decode:true}
package de.spacekookie.libgdxtutorial.objects;
import java.util.HashSet;
import java.util.Set;
import com.badlogic.gdx.Gdx;
public class World {
private Set entities;
public World() {
entities = new HashSet();
}
public Set getEntities() {
return entities;
}
public Entity getEntitityWithType(Entity.EntityType type) {
for (Entity e : entities) {
if(e.getType() == type)
return e;
}
return null;
}
public void addEntity(Entity e) {
if (!entities.contains(e))
entities.add(e);
else
Gdx.app.log("World", "Entity already in Set!");
}
public void removeEntitity(Entity e) {
if (entities.contains(e))
entities.remove(e);
else
Gdx.app.log("World", "Error! No such entity in world!");
}
}
```
The constructor just initializes the HashSet, we have a few getters and
setters, a way to individually add a single entity (e.g. if we're
spawning a pirate ship, maybe?) We'll be expanding on this code heavily
in the future but it's as complex as it needs to be right now. (Note how
I'm using Gdx.app.log to log two cases when adding and removing
entities. That's not required but it's a good way to keep tabs of
potential errors when playing the game or debugging something.)
Next, we should go into our main game class and start using the World
object. Make sure to actually use OUR world object, not the Box2D world
(which is great for physics and lighting and we might use it later but
not right now!)
``` {.lang:java .decode:true}
world = new World();
world.addEntity(new Entity(EntityType.PLAYER, new Vector2(200, 150)));
```
And we of course need to teach our InputProcessor to use the world to
handle input!
``` {.lang:java .decode:true}
handler = new InputHandler(world);
```
And in the InputHandler we need to change the constructor and some
methods.
``` {.lang:java .decode:true title="Constructor"}
public InputHandler(Object o) {
if (o instanceof World && o != null)
this.world = (World) o;
if (o instanceof Entity && o != null) {
this.e = (Entity) o;
return;
}
for (Entity e : world.getEntities()) {
if (e.getType() == EntityType.PLAYER) {
this.e = e;
}
else {
Gdx.app.log("InputHandler", "NO PLAYER IN WORLD!");
}
}
}
```
(Be sure to rename the entity in that class to "e")
And that should be all the changes we need to make. If I missed anything
or something is unclear, just leave me a comment below and I'll get back
to you. If you compile this it should still be the same game as before,
with the difference that under the hood it has a lot more horsepower
(kilowatts) and we'll be able to do some really cool things with this in
a moment.
Here is an idea. Why don't we go ahead and plan our solar system a
little. I know, I know, you're lazy again. I get it. You just wanna read
these, absorb the knowledge via a USB3 port in your skull and eat
Cheerios all night. Still. I hope you can be bothered to check out the
picture below :)
![Each grid square is exactly 100x100
pixels](http://www.spacekookie.de/wp-content/uploads/2013/12/Screen-Shot-2013-12-20-at-13.04.57.png)
You can see the background image that is currently our game world and
our other objects scattered around the world. The grid lines in
Photoshop (Adjustable under Preferences --\> Guides, Grids &
Sliders --\> Grid) will give us a little help when trying to find places
to place these objects. But for that to happen we need to add a little
more to our Entity class.
See, right now we just check if the EntityType is the player and if it
is we draw the space ship. But what we really want to do is also take a
set of coordinates in the constructor to pass down to the rendering. In
fact, we kinda want the pixel coordinate to be saved in the object
itself rather than having to check the sprite for information. Because
that's what the object is for, to hold all the information needed and
provide a sort of "interface" to access and store the information. We
don't want to be digging around in a sub-object or OpenGL logic object
to get information.
So I added a new vector called position, created a new constructor that
now also takes a vector (left the old one to not break things) and
created a method called "updatePosition()" that takes the position
vector and gives the coordinates to the sprite.
``` {.lang:java .decode:true}
private Vector2 position;
public Entity(EntityType type) {
this.type = type;
moveVector.scl(speed);
position = new Vector2();
}
public Entity(EntityType type, Vector2 position) {
this.type = type;
this.position = position;
moveVector.scl(speed);
updatePosition();
}
public void updatePosition() {
self.setPosition(position.x, position.y);
}
. . .
public Vector2 getPosition() {
return position;
}
public void setPosition(Vector2 position) {
this.position = position;
}
```
Next up we want the loadResources method to be able to not just load the
ship textures but check all the EntityTypes and load textures
accordingly. For that I changed the whole thing to a Switch statement.
If you're not familiar with Switch...get familiar with
[Switch](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html).
It's awesome!
``` {.lang:java .decode:true}
public void loadResources() {
switch (type) {
case PLAYER:
self = new Sprite(ResPack.SHIP_IDLE);
break;
case PLANET:
self = new Sprite(ResPack.WORLD_EARTH);
self.setScale(2f);
break;
case STATION:
self = new Sprite(ResPack.WORLD_STATION1);
self.setScale(1.5f);
break;
case STAR:
self = new Sprite(ResPack.WORLD_SUN);
self.setScale(2f);
break;
default:
Gdx.app.log("Entity", "EntityType not found!");
break;
}
}
```
I added the "setScale" in order to simulate size. A star should
be \*slightly\* larger than a space station. This is only a temporary
measure but I think it'll look better this way. You can of course leave
it out.
There is one thing we'll have to do to restore the game as it was before
and that is to actually use the "updatePosition" method that we created.
So in the input processor, instead of calling "setPosition" on the
sprite we should use our object methods.
``` {.lang:java .decode:true}
if (moving) {
Vector2 temp = new Vector2(e.getPosition().x, e.getPosition().y);
temp.add(e.getMovement());
e.setPosition(temp);
e.updatePosition();
e.fly();
}
```
So far so good. Our code can now handle different types of objects,
though we will still need to create the objects at some point. And
because we want the world to keep tabs on everything going on we'll have
to update some code in our world method. See, we can add entities by
calling that 2nd lovely constructor and passing them into our world
object. We do that by calling.
``` {.lang:java .decode:true}
world.addEntity(new Entity(ENTITY_TYPE, ENTITY_POSITION));
```
Where Type and Position are of course one of our lovely EntityTypes that
we defined and the position is a Vector2 object. And where will we use
this dark magic you ask? Well simple. Where do we already add the player
to our world.
``` {.lang:java .mark:8-10 .decode:true}
@Override
public void create() {
float w = Gdx.graphics.getWidth();
float h = Gdx.graphics.getHeight();
world = new World();
world.addEntity(new Entity(EntityType.PLAYER, new Vector2(200, 150)));
world.addEntity(new Entity(EntityType.STATION, new Vector2(600, 300)));
world.addEntity(new Entity(EntityType.PLANET, new Vector2(1200, 600)));
world.addEntity(new Entity(EntityType.STAR, new Vector2(650, 750)));
}
```
In our main game create() method. Now render this and marvel at its
glory. You can of course change the coordinates. Note that those are
camera-world coordinates, not pixel-coordinates. Compile this, it
shouldn't throw any errors. (Unless I forget to mention something in the
post ;)
 
And well...that's it for this time, really. I hope that you learned a
thing or two and have also seen that the BEST way of implementing a new
feature is often to take a step back, look at the big picture and then
think about how it would be easiest to do something. Next issue I want
to show you how to UI which is an important thing when it comes to
creating a game. Also note, that all of my source code can be viewed on
my open repository on
[BITBUCKET](https://bitbucket.org/LaGemiNi/star-chaser "BITBUCKET") (which
is the name I've given to this name). There is also a video on my
[youtube](http://www.youtube.com/watch?v=ocYqXyM9v2Y "youtube") channel
from a week ago or so. Go check both things out.
Sorry that it took me a bit longer to get this one out. I had a lot on
my plate the last week. I'll try bring out two posts on here per week. I
have something slightly special planned for next Tuesday. Hint, it
involves a lot of hardware, FreeBSD and a RAID :)
But until next time, keep coding!

@ -1,359 +0,0 @@
Title: 07. (LibGDX) Game of Codes: User Interfaces and the power of Scene2D
Date: 2014-01-14 21:31
Category: Game of Codes
Tags: Guides
Slug: 07-game-of-codes-user-interfaces-and-the-power-of-scene2d
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we added new features to our game and
learned that the best step forward is often a step to the side (or back)
to get a view over what's going on. In this tutorial I want to show you
something that has absolutely nothing to do with features but will be
among the most important things in the game: the UI. We'll talk about
stages (like the acting stages, not rocket stages), UI elements and
something called Scene2D. Let's begin!
Any game will be composed of several layers. In the background you want
to draw a map or textures to let the players know where they are
(relatively). In the actual scene you want to draw all sorts of objects
including the player themselves to show what's going on. And in the
foreground you want to draw the UI with which the player can interact to
manipulate the game. Sure, we already have our input listeners set up in
a way that we can manoeuvre around our ship. But what about a UI?
Buttons? An inventory? This is something we'll tackle in this tutorial.
It's gonna be a long one too so be sure to bring some time and maybe
re-read it at a later point again.
In LibGDX we can use a UI-package called "Scene2D" which is perfect for
anything UI. It uses a layer of our game called the "Stage" that will be
populated by "Actors". In the beginning we'll stick with standard actors
but we can soon expand and write our own Actors by expanding that
superclass and doing own things with it. The stage will gladly welcome
our new Actor object into its ranks and manage everything there is to
manage about it. Just like our world-class. So you can see that it's
always a good idea to implement a managing parent class, followed by a
bunch of child objects.
![Scene2D](http://www.spacekookie.de/wp-content/uploads/2014/01/Screen-Shot-2014-01-13-at-17.08.28.png)
But before we get some stuff done with Scene2D and the stage I need to
explain you a few things about skins. A skin is a way to tell the game
how a UI should look. It includes fonts, graphics and textures to
describe how things have to be drawn. And creating beautiful skins is a
tutorial of its own (with which I'm honestly not very familiar. I'm a
programmer, not a designer ;) ). But luckily the creators of LibGDX
provide us with a standard skin that we can just download and use. It's
not exactly pretty and I wouldn't recommend using it in your games end
release. But it'll get the job done until then. And if you at a later
stage decide that you want to use your own skin, you will only have to
change the skin files and everything else remains the same. Pretty cool,
eh?
------------------------------------------------------------------------
So first off we'll need some files that make up the skin:
[A
FONT](https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests-android/assets/data/default.fnt)
[AND IT'S
RESOURCE](https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests-android/assets/data/default.png)
[A TEXTURE
FILE](https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests-android/assets/data/uiskin.png)
[AND IT'S
ATLAS](https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests-android/assets/data/uiskin.atlas)
[A JSON
FILE](https://github.com/libgdx/libgdx/blob/master/tests/gdx-tests-android/assets/data/uiskin.json)
(To actually download the text-files just view their content in "Raw"
and copy them into a text editor of your choice. However use something
that let's you set your own file types. TextWrangler or TextMate on macs
and Notepad++ on Windows)
------------------------------------------------------------------------
Download these from the LibGDX github repository. In general, if you're
ever stuck or want to look at some samplecode or just get to know what's
under the hood of the latest nightly build, check the github repository
for answers. It's a great tool! Put them all into a new folder in your
assets directory called "Skin" or something and then go into your
Resource packer class and create a new public final static object there.
``` {.lang:java .decode:true}
public static final Skin _SKIN = new Skin(Gdx.files.internal("data/skin/uiskin.json"));
```
And that's that. LibGDX will do the rest. From now on, every time we
want to use anything related to the UI we will have to pass in this skin
to make it work (and look the same as the rest of the game). Now we'll
be doing some stuff in LibGDX's Scene2D. It's all very basic but
necessary to understand. Again...I might not cover everything. But if
you google "Scene2D + anything" you'll find your answers quite quickly.
90% of coding: googling how to do things :)
Basics of Tables
----------------
We'll want to go into our main game class and create a new object called
"Stage". Make it private and initialize it just after the camera. And
then set the viewport in the resize method. Confused? Look below.
``` {.lang:java .decode:true}
/** UI */
private Stage stage;
@Override
public void create() {
. . .
/** UI */
stage = new Stage();
. . .
}
. . .
@Override
public void resize(int width, int height) {
stage.setViewport(width, height);
}
```
This way the stage will be resized every time we resize the viewport of
the game. Which currently is only at launch because we don't allow for
user resizes. But that could change. That's a pretty good idea, we
should actually do the same with our camera. So remove our two variables
"w" and "h" and move "camera.setToOrtho(...)" to the resize method so it
looks like this.
``` {.lang:java .decode:true}
@Override
public void resize(int width, int height) {
stage.setViewport(width, height);
camera.setToOrtho(false, width, height);
}
```
Now...enough spontanious refactoring, let's actually get into our
tables. The stage itself is an invisible object, much like our world. It
won't draw anything unless we actually add some actors and then act out
the stage in our render method.
Why don't we create a button that says "Menu" in the top-right corner? I
think that's a nice start to our UI and actually useful. In LibGDX there
are many button implementations, including some with pictures and an
abstract type that you can implement your own types on. But the regular
"TextButton" is sufficient for us at this time. So go create a global
variable of the type TextButton, give it a name and then, after
initializing the stage, initialize the button. How? Like this.
``` {.lang:java .mark:1,10 .decode:true}
private TextButton menu;
@Override
public void create() {
. . .
/** Setting up the UI */
stage = new Stage();
menu = new TextButton("Menu", ResPack._SKIN);
. . .
}
```
You can see that the button wants a string to display on itself and of
course a skin. So far so good. But how do we tell it to go to the
top-right corner of the screen? Well...that's not so simple and I
actually want to show you this way first so you NEVER think about doing
this manually again :) We will need to take the size of the stage and
then substract the size of the button from it and set that as its new
position.
``` {.lang:java .decode:true}
menu.setPosition(stage.getWidth() - menu.getWidth(), stage.getHeight() - menu.getHeight());
stage.addActor(menu);
```
Pretty complicated, eh? That second line adds the menu-button to the
stage. It's essentially the same thing that we're doing with our world:
creating a bunch of objects and passing them into a large-scale manager.
But, if you remember correctly, our world needs something in the render
method to work. And the same applies to our stage. First we need to act
out the stage which means moving things that need to be moved, animating
things that need to be animated, etc. And then draw the stage. So in our
render method we add.
``` {.lang:java .decode:true}
stage.act();
stage.draw();
```
Be sure to put this at the very bottom of our rendering so that it ends
up on TOP of our stack. (Laying a stack of papers, the sheet you put
onto it first will be on the bottom (the background) while the one you
put on last will be on top (the UI).
![StarChaser\_UI\_Test1](http://www.spacekookie.de/wp-content/uploads/2014/01/Screen_Shot_2014-01-12_at_11_14_13-2.png)
Now compile this and marvel at its glory. Well...kind of. See...when we
now need to add a second button to that menu maybe titled "Inventory"
we'll have to do very complicated mathematics in order to line up the
buttons. Which isn't great and which is why Tables were created.
Just after creating your button, why don't you go and create a "Table"
object, initialize it after the stage and then add the button to the
table and the table to the stage.
``` {.lang:java .mark:1,10,12-13,16 .decode:true}
private Table buttons;
@Override
public void create() {
. . .
/** Setting up the UI */
stage = new Stage();
buttons = new Table(ResPack._SKIN);
buttons.setFillParent(true);
buttons.top().right();
menu = new TextButton("Menu", ResPack._SKIN);
buttons.add(menu);
stage.addActor(buttons);
```
So instead of adding the button to the stage we add it to the table, we
tell it to fill its parent (which is important for the validation of the
table during render) and then call "top" and "right"...see, instead of
working with pixel coordinates here we can just tell the table to go to
any corner of the window (center, top, bottom, left, right). And the
coolest thing is that the table will try to stay on-screen, even if we
add more buttons. Let's do that now honestly, create a new button called
"Inventory" and add it to the table just as the menu button. Note that
the table will be populated from left to right meaning that if you want
the Inventory button to be to the left of the menu button you'll have to
add it first.
And that's that for tables for now. There are more advanced things
concerning tables but I won't cover them here (and now). If you're
curious or this isn't specific enough for what you have planned, why
don't you go [here](https://github.com/EsotericSoftware/tablelayout) and
read about it :)
Handling input
--------------
Something you might have noticed is that our current buttons don't react
to any kind of input. That has to do with the fact that we never
register the stage as an input processor. Usually you call
Gdx.input.setInputProcessor(stage) but as we already have an input
multiplexer set up we can just add the stage to that.
``` {.lang:java .decode:true}
plex.addProcessor(stage);
```
And voila you'll see that the buttons now react to our clicks, even with
just a red glow. Because to actually HANDLE the input we need something
to listen to it. In our input processors we have listeners to certain
events, like moving the mouse or pressing a certain button. And we use
these events to manipulate our game. For the UI it's no different.
Well...it's slightly different. We don't want to create a UI
InputProcessor. It's not only completely ridiculously complicated but
actually inadvisable. Instead we'll set up the listeners for each button
manually in our game class and tuck them away in a method somewhere at
the bottom of the class to be out of sight and out of mind.
``` {.lang:java .decode:true title="Clicklistener - innertype"}
private void setupListeners() {
menu.addListener(new ClickListener() {
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
Gdx.app.log("Stage", "Menu button pressed");
}
});
}
```
What you see above is known as an inner-type. If you've worked with my
Android series before you'll know them. it's essentially a way to create
a class inside another class (in the parameter brackets of a method) to
define how a passed down to the "addListener" method.
The ClickListener extends the InputListener where we can manually
override one of the listeners. In my case I decided to override the
"touchUp" method with all the parameters it takes and log the case. Now
create a second listener for the second button, just as the one I showed
you above. Compile it and see what happens. Pretty cool, eh (again)?
Okay, maybe not that cool. Initially I wanted to go on here and make
options and inventory screens but I think we should do this at a later
time because it would take hours and not really have anything to do with
Scene2D anymore. Let's just check out some other elements we have in
Scene2D before wrapping this up.
So create a new table with a name of your choosing and add a few thing
to it.
``` {.lang:java .decode:true}
temp = new Table(ResPack._SKIN);
temp.setFillParent(true);
TextureRegionDrawable trd = new TextureRegionDrawable(new TextureRegion(new Texture(
Gdx.files.internal("graphics/image_button.png"))));
imageButton = new ImageButton(trd);
checkbox = new CheckBox("This is a checkbox", ResPack._SKIN);
field = new TextField("This is a textfield", ResPack._SKIN);
temp.add(imageButton);
temp.row();
temp.add(checkbox);
temp.add(field);
temp.top().left();
stage.addActor(temp);
```
Oh boy, I know. Let's go trough it line by line. Temp is just a table
that we set to fillparent = true. The next thing we do isn't really
important for now, just note that we're doing it. A
TextureRegionDrawable extends a Drawable that we need for our button.
Ideally you want to have all your button images in your skin. But the
default skin doesn't. So because I didn't want to add stuff to the skin
I went with the "hard" but quick way. Afterwards we initiate a checkbox
and a textfield.
[![image\_button](http://www.spacekookie.de/wp-content/uploads/2014/01/image_button.png)](http://www.spacekookie.de/wp-content/uploads/2014/01/image_button.png)
Note how we're adding things to the table and using "row()" only once.
Each time you call row() it will create a new row. So in effect the
first item will be on it's own row and then the checkbox and textfield
on another. If you put another row between them that will change of
course. Above you have the button image that I used. Go import that into
your project if I want it to work OR of course just create your own
Button image.
I hope that this tutorial has shown you how powerful Scene2D can be.
With just a few lines of code we created a whole layout and added
listeners to it. The process remains that easy and you ca of course
still add and subtract offsets to tables to fine-tune their position. If
you have further questions about Scene2D, go ahead and post them below.
But in general the API is relatively well documented and if you have
questions you can always check out the LibGDX forums or the IRC.
Thats it for today, I'll continue with this next time but we'll have our
focus on something called Screens. They're nifty little things that can
make our life a whole lot easier (and more difficult actually ;) ).
I actually wanted to do something \*slightly\* different today (that
involved computer hardware) but I actually ordered a wrong part. So
that'll be delayed. Not sure when it'll come out.  So until next time,
keep coding.

@ -1,381 +0,0 @@
Title: 08. (LibGDX) Game of Codes: Screens & Subscreens
Date: 2014-01-19 09:30
Category: Game of Codes
Tags: Guides
Slug: 08-libgdx-game-of-codes-screens-subscreens
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last edition we looked at user interfaces with Stages
and Scene2D. Today I want to show you how to make your game a LOT better
and more functional by adding *Screens *(I already spoiled this last
tuesday ;) ). Let's begin!
First of all we should take a step back and look at our game. We have
our main-game class that currently extends "ApplicationListener" and
does a whole lot of stuff. It's the main game loop, it populates and
updates the world and handles input. So essentially it's a class that is
tied into everything that LibGDX does to make a game runnable. Well...an
"Application". That's a very broad term and there is another subclass of
that main class that we currently extend, that we need to use in the
future. it's almost the same as the ApplicationListener but \*slightly\*
different. And we need that. The class is called "Game". So what I want
you to do now is go into the main "Game" class and change the extend
from "ApplicationListener" to "Game". In my case it's the line below.
``` {.lang:java .decode:true}
public class StarChaser extends Game {
```
Eclipse might give you some trouble with implementing the new methods.
Usually you just have to clean your project (Project --\> Clean --\>
All) and it'll calm down. In the worst case scenario just copy all your
code into a different editor, delete all the code from the class (except
the class definition and package of course, let Eclipse import
everything for you again, implement the methods and then paste your code
into the methods it create (that will be EXACTLY the same as the ones we
had before. But you know...Eclipse is weird sometimes :) ).
What did this get us? Well...if you added the sources to your Libraries
you can right-click that "extends Game" and show it's declaration to see
the Game class that we now extend. It extends the ApplicationListener
and adds something we want to use now: a *Screen!*
A screen is a layer of our game. It gets shown, rendered, paused and
destroyed. It acts very much like a fragment on Android (if you're
familiar with the Android API) and can be an overlay or replacement of
the entire game. using screens is a much better solution in switching
between "screens" than creating new games or trying to use a lot of
booleans and flags to determine what part of which GUI is supposed to be
visible.
So why don't you go and create a new package called "screens" and add a
new class to it and let it implement "Screen". I called mine
"MenuScreen".
``` {.lang:java .decode:true}
package de.spacekookie.starchaser.screens;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.scenes.scene2d.Stage;
public class MenuScreen implements Screen {
/** UI */
private Stage stage;
@Override
public void render(float delta) {
stage.act();
stage.draw();
}
@Override
public void resize(int width, int height) {
stage.setViewport(width, height);
}
@Override
public void show() {
stage = new Stage();
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
}
```
This is what your class should look like (more or less). I took the
liberty of already adding a stage to it because we want to draw a menu
screen, something with buttons and text and the easiest way to do that
is with Scene2D (as we've learned in the last tutorial).
Next up we'll want to populate that stage. I prepared something and am
just gonna paste it in here. You can arrange your buttons in whatever
order you want. I went for something very simple and centric.
``` {.lang:java .mark:25 .decode:true}
@Override
public void show() {
stage = new Stage();
table = new Table(ResPack._SKIN);
table.setFillParent(true);
table.center();
title = new Label("MAIN MENU", ResPack._SKIN);
title.setFontScale(2.5f);
resume = new TextButton("RESUME GAME", ResPack._SKIN);
options = new TextButton("OPTIONS", ResPack._SKIN);
exit = new TextButton("RAGE QUIT", ResPack._SKIN);
table.add(title).center().pad(25f);
table.row().height(75);
table.add(resume).center().width(500).pad(5f);
table.row().height(75);
table.add(options).center().width(500).pad(5f);
table.row().height(75);
table.add(exit).center().width(500).pad(5f);
stage.addActor(table);
Gdx.input.setInputProcessor(stage);
}
```
You should understand what I'm doing here and it's nothing more advanced
than what we did in the last tutorial. Except that I set a row height,
give buttons a specific size and add padding around them to make it look
more smooth.
<span style="text-decoration: underline;">Note how we overwrite the
input processor from the main game to the stage. This means that the
game will be unresponsive, We'll have to change that back later!</span>
So far so good. But what do we now actually do with this? We want to add
this screen to the main game class in a way that we don't have to create
new instances of it all the time. So go ahead and create a global
variable in the main game class and initialize it on create().
``` {.lang:java .decode:true}
/** Screens */
private MenuScreen menuScreen;
@Override
public void create() {
. . .
/** Setting up support screens */
menuScreen = new MenuScreen();
. . .
}
```
And another global variable we'll have to create is "self" which has the
type of our main game class (which in my case is "StarChaser"). We can
do that by creating an object with the class name and initializing it
with the following.
``` {.lang:java .decode:true}
private StarChaser self = this;
```
We will need this global variable in our click-listener, because
there the scope is different. See, while we can easily call "this" or
"super" in our main game class to access anything in the class or that
we inherit from, in the Clicklistener we're technically in a different
class (the ClickListener class) and thus we can't access things we
inherited outside of it. To circumvent this we add a global variable
that we can still see, access and Boya!
In the ClickListener you can throw out the Log call and add this.
``` {.lang:java .decode:true}
self.setScreen(menuScreen);
```
When you now compile this you'll see that you don't see anything. :)
Because we're not actually rendering the screen. For that to happen you
have to add this line of code to the bottom (the very end) of your
render() method (in the main game class that is).
``` {.lang:java .decode:true}
super.render();
```
This will ensure that if there is a screen visible that their
appropriate render method is being called at the right time (You can
look at the super-render() method when you look at the super-class. It's
sometimes interesting).
Now compile this and see, that we have a neat overlay of our buttons
over the game. And we can no longer move our ship around and we're also
kinda stuck in that menu screen because we haven't set up any listeners
yet. Now...resetting the screen works in a very similar way: we take our
main game, call setScreen(null) on it and the screen will disappear.
However...we don't have that inheritance in our Screen object, do we?
No. So we'll have to pass it in via the constructor.
So first we create a constructor in the MenuScreen class.
``` {.lang:java .decode:true}
public MenuScreen(StarChaser self) {
this.parent = self;
}
```
And of course a global variable in the class called "parent" or
"cupcake" or whatever you want to store the information. Also make sure
to update the constructor call (in the ClickListener) from no parameters
to "self".
With this new variable in our screen we can go ahead and create a new
Clicklistener for one of our lovely buttons. I only chose the "Resume"
one for now but we can add functionality to the other ones as we move
along with our game.
``` {.lang:java .decode:true}
resume.addListener(new ClickListener() {
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
parent.setupInput();
parent.setScreen(null);
}
});
```
You'll probably go "Woooah, easy there girl, what's that setInput()??"
and well...you're right. See, when we get back to our game and the
screen is hidden somewhere in memory we can't control the game anymore.
We haven't told our game yet that we want to resume using the input
Multiplexer so that we can actually control our ship again.
For that to happen I created this public method that sets the input to
the Multiplexer and sets up the Stage-listeners (for our buttons). In
the main game simply call this method instead of the actual calls (so
after adding things to the Multiplexer). Because the InputAdapters still
exist in memory, we don't want to re-initialize them. That'd be a waste
of resources and memory.
``` {.lang:java .mark:10,13-17 .decode:true}
@Override
public void create() {
. . .
/** Input Controllers */
plex.addProcessor(stage);
plex.addProcessor(camController);
plex.addProcessor(handler);
this.setupInput();
}
public void setupInput() {
Gdx.input.setInputProcessor(plex);
this.setupListeners();
}
```
And that's it. If you compile this you'll have a functional button that
takes you to the MenuScreen and back again when you press the
appropriate button. I hope you understand the logic behind this. We show
a screen, we use it, we hide it. Think of the screens like overlays that
you put over your main "game-layer". But just because we can
conveniently draw over our main layer that doesn't mean that we won't
have to change a few things, pass parameters along and manually reset
the input (as an example). LibGDX is a framework that allows for the
complicated stuff to be easy (the drawing a new screen over the current
game etc.). The rest is up to you, how you want to handle it, how you
want your game (or just application) to look. Below is a picture that
shows the current setup we have.
![rt7obekn-1](http://www.spacekookie.de/wp-content/uploads/2014/01/rt7obekn-1.jpg)
Speaking of looks...I don't actually like how that menu screen is
looking. I'd much rather have it be semi-transparent in the background
so the game gets grayed out. Luckily that's easily possible.
Well...possible :)
First you should create a Camera object in our MenuScreen and get the
camera from the main game in the constructor. (We already have a static
method called "getCameraInstance()" that we used a couple of issues back
for our input processor to do things. After that create a
"ShapeRenderer" and initialize it in the "show()" method.
``` {.lang:java .mark:1,2,5,13 .decode:true}
private Camera camera;
private ShapeRenderer render;
public MenuScreen(StarChaser self) {
this.camera = StarChaser.getCameraInstance();
this.parent = self;
}
. . .
@Override
public void show() {
render = new ShapeRenderer();
. . .
}
```
ShapeRenderers are used to draw very simple polygon shapes onto the
screen. In our case we want a rectangle, filled with a colour, that
spans over the entire screen (+10 pixels or so for border) and blends
the background colours with our colour that we give an alpha channel.
Confused? Don't worry, check out the code below (the new render method)
and then I'll go over it bit by bit.
``` {.lang:java .decode:true}
@Override
public void render(float delta) {
Gdx.gl20.glEnable(GL20.GL_BLEND);
render.setProjectionMatrix(camera.combined);
render.begin(ShapeType.Filled);
render.setColor(0, 0, 0, 0.5f);
render.rect(-10, -10, Gdx.graphics.getWidth() + 20, Gdx.graphics.getHeight() + 20);
render.end();
stage.act();
stage.draw();
}
```
First we have to call an OpenGL function called "glEnable" which will
enable certain features during render. We pass in the "GL\_BLEND"
parameter (in the GL2.0 package) which will trigger OpenGL to blend
colours together (so allowing two colours to merge slowly instead of
being absolute values).
Afterwards we take the projection matrix from our camera and set it for
the renderer so that the drawn shapes are in the same reference frame as
the rest of our game. And then we begin the magic.
We set the Type (Filled), we set a colour (black with 50% alpha), we set
the border (the screen + 10 pixels padding over the screen). And then we
end the renderer. That's it.
Compile this and look at how it looks. In my opinion a lot better! For
reference, this is what my menu now looks like. Again...you can have
your buttons in different orders, sizes, whatever.
![StarChaser\_Menu](http://www.spacekookie.de/wp-content/uploads/2014/01/Screen-Shot-2014-01-19-at-10.57.46.png)
But I hope you understand now how you can create different screens to
make have different tasks. And in the same way that we've now created
this Menuscreen we can make an options screen (We just need to pass
along the Game again and call "setScreen(whatever)" when we're done).
And at some point I want to make an inventory and trade screen like
this. But that's a long way out. Because next up I actually want to do
some bug-fixing. Things that I missed a few "episodes" ago and thought
it'd be a good learning opportunity. And also teaching you about game
structure a bit more.
I hope you enjoy this series so far, leave me your feedback in the
comments and I'll see you guys (and gals) next time. Keep coding!

@ -1,326 +0,0 @@
Title: 09. (LibGDX) Game of Codes: Modifying LibGDX — Part I
Date: 2014-04-04 13:57
Category: Game of Codes
Tags: Guides
Slug: 09-libgdx-game-of-codes-modifying-libgdx-part-i
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. It's been a while since my last post and I want to make up
for that today. Last time we were talking about Screens and subscreens
for a game that made showing new information a whole lot faster and more
intuitive as it didn't require more UI elements to be written into the
same class.
Well…despite what you might think I HAVE been very busy coding on my own
project (\*hinthint\*
[www.spacekookie.de/projects/empires](http://www.spacekookie.de/projects/empires/ "Interstellar Empires") \*hinthint\*
;) ) and have started modifying the LibGDX core a few months ago to
better suit my needs. Well…most of my modifications are pretty specific
to my case. Changing the hexagon renderer to account for my custom data
types, changing the input handling method, etc... But in the last 2
weeks I have done something that I think can be quite handy and I want
you to see it. Additionally I will be using that example to show you how
modding LibGDX to your own needs can be very productive and even fun. It
will give you the ability to learn and understand how that framework
we've only been using so far is structured and works. And it will remove
some of the magic that you might feel is involved ;) So shall we begin?
 
First of all I want to show you a graphic again from my last post of the
Game of Codes.
![rt7obekn-1](http://www.spacekookie.de/wp-content/uploads/2014/01/rt7obekn-1-1024x576.jpg)
This is how I thought our menu would be, have a screen in front of our
game that then showed some stuff. Well…that's all nice and good IF you
only use one game-screen. But most games aren't that simple. Usually in
a complex game you want to have your background code for music and input
handling or whatever jazz you're doing running in your game but then
have different screens for the Menu, the game, the settings, maybe an
inventory? Who knows? And well…that's all very 1-dimentional. So what I
did first was look at how things were structured in LibGDX.
``` {.lang:java .decode:true}
public abstract class Game implements ApplicationListener {
private Screen screen;
. . .
public void setScreen (Screen screen) {
if (this.screen != null) this.screen.hide();
this.screen = screen;
if (this.screen != null) {
this.screen.show();
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
}
. . .
}
```
As you can see the "Game" class that we extend with our MainGame-Class
where we have our ship and station and input and all those lovely assets
implements the ApplicationListener, JUST as our MainGame-class did
before we started working with Screens. Oh and look! There is some of
that code that we use to set a Screen.
Now…what can we do with this? Well first of all we can create a new
class in our Core package and call it "CustomGame" or anything you like.
But it should be clear that it's something very specific. Make it
abstract and let it implement the ApplicationListener interface, just
like the example above.
We can also actually just copy most of that code in the stock-Game class
into our own.
``` {.lang:java .decode:true}
public abstract class CustomGame implements ApplicationListener {
private Screen screen;
@Override
public void create() {
}
@Override
public void resize(int width, int height) {
if (screen != null)
screen.resize(width, height);
}
@Override
public void render() {
if (screen != null)
screen.render(Gdx.graphics.getDeltaTime());
}
@Override
public void pause() {
if (screen != null)
screen.pause();
}
@Override
public void resume() {
if (screen != null)
screen.resume();
}
@Override
public void dispose() {
if (screen != null)
screen.dispose();
}
public void setScreen(Screen screen) {
if (this.screen != null)
this.screen.hide();
this.screen = screen;
if (this.screen != null) {
this.screen.show();
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
}
public Screen getScreen() {
return screen;
}
}
```
All that does is exactly what the other class did before. If you now go
into our main-game class and let it extend "CustomGame" instead of
"Game" and compile the game it will run JUST like it did before. Because
nothing has changed. And that's what we'll change RIGHT NOW.
What do we want? Well…we want to use Screens in our game for the actual
game screens (menu, in-game, settings, cut scenes, etc.) as well as
Screens to display information OVER the current one (for example for an
Inventory screen or dialogue options or WHATEVER!). Now…there are two
things we could do right now:
The first would be to only add one more screen, call it "overlay" and
copy the same code as for the other screen into the class. That would
give us two screens to work with. But I don't like that idea at all.
Instead I want to do something different. I want to be able to have a
stack of Overlays over each other. And that's why we'll use a
Stack\<Screen\>!
``` {.lang:java .decode:true}
private Stack<Screen> overlays;
@Override
public void create() {
overlays = new Stack<Screen>();
}
```
Put this code under the declaration of the private Screen variable and
initialize the stack in your create() method that was (so far) not used.
Now we of course need to make sure we actually call "super.onCreate()"
in our child-class (So our main game-class).
So far so good. But, we can't actually do anything with that yet. First
we will want to write two access methods for the stack.
``` {.lang:java .decode:true}
public void addOverlay(Screen overlay) {
overlays.add(overlay);
overlay.show();
overlay.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
public void removeOverlay() {
if (!overlays.isEmpty())
overlays.pop().dispose();
}
```
What this will do is add a new overlay to the stack when we need one and
also call the show and resize method on the overlay (which is really
just a screen) to set up everything correctly!
The second method will remove the last overlay (if it exists) by
popping it off the stack and calling dispose() on it to finalize. This
is important so that we avoid having un-used and non-removed resources
in our memory.
So far so good. The problem now is that our screen won't actually be
shown anywhere. Sure, we add it to our stack and show() and resize() it.
But it's not getting rendered. For that to happen we'll have to add some
more code. And in addition to that I would recommend more code to then
dispose of the screens again as well.
For every action that we take on our main-screen we need to add this
code to it as well.
``` {.lang:java .decode:true}
if (!overlays.isEmpty())
for (Screen o : overlays)
o.ACTION_HERE();
```
Essentially iterating over the stack to apply it to every overlay. This
way we can have stacking UI-overlays while the ones in the background
still get rendered. And this is how the final CustomGame class then
looks.
``` {.lang:java .decode:true}
import java.util.Stack;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
public abstract class CustomGame implements ApplicationListener {
private Screen screen;
private Stack overlays;
@Override
public void create() {
overlays = new Stack();
}
@Override
public void resize(int width, int height) {
if (screen != null)
screen.resize(width, height);
if (!overlays.isEmpty())
for (Screen o : overlays)
o.resize(width, height);
}
@Override
public void render() {
if (screen != null)
screen.render(Gdx.graphics.getDeltaTime());
if (!overlays.isEmpty())
for (Screen o : overlays)
o.render(Gdx.graphics.getDeltaTime());
}
@Override
public void pause() {
if (screen != null)
screen.pause();
if (!overlays.isEmpty())
for (Screen o : overlays)
o.pause();
}
@Override
public void resume() {
if (screen != null)
screen.resume();
if (!overlays.isEmpty())
for (Screen o : overlays)
o.resume();
}
@Override
public void dispose() {
if (screen != null)
screen.dispose();
if (!overlays.isEmpty())
for (Screen o : overlays)
o.dispose();
}
public void setScreen(Screen screen) {
if (this.screen != null)
this.screen.hide();
this.screen = screen;
if (this.screen != null) {
this.screen.show();
this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
}
public Screen getScreen() {
return screen;
}
public void addOverlay(Screen overlay) {
overlays.add(overlay);
overlay.show();
overlay.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
}
public void removeOverlay() {
if (!overlays.isEmpty())
overlays.pop().dispose();
}
}
```
This is it for part 1. I don't want to let this get too long so in PART
2 of this post I'll be showing you what exactly we can do with this. If
you have any questions or suggestions, leave them in the comments below.
Until then, keep Coding!
 
==== EDIT ====
Do you want this series to get picked up again? Go here:
http://www.spacekookie.de/continue-libgdx-game-of-codes/

@ -1,28 +0,0 @@
Title: 09.5 (LibGDX) Game of Codes: Continuation - Post ideas
Date: 2015-05-02 12:12
Category: Game of Codes
Tags: Guides
Slug: continue-libgdx-game-of-codes
Status: published
Welcome back to the Game of Codes, an introduction series to the LibGDX
framework. In the last post we started messing around with the inner
workings of LibGDX a bit more...
\*static\* \*voice cracking\* \*buzzing from speakers\*
"Hello? Can anyone hear me? I think I'm in space...Hello?"
Right...it's been about a year since I wrote on this series, a lot of
things have changed and I don't nearly have as much time anymore. BUT
people keep messaging me all over the place that they liked my LibGDX
series. SO...if you really do, I will continue it. Though, I'm slightly
out of ideas what to do. And I really have lost interest in continuing
that Star Chaser thing I started.
So....if you want to see something from me, post it on the comments
below, twitter at me, send me emails or smoke signals. If I get enough
feedback about this I will do it. If not, I'm sure there are better and
more up to date resources out there :)
So yea, would be cool to hear from you guys \<3

@ -1,7 +0,0 @@
Title: 10 (LibGDX) Game of Codes: 50 Shades of Code
Category: Game of Codes
Tags: Guides
Slug: libgdx-game-of-codes-50-shades-of-code
Status: draft
SHADERS!

Binary file not shown.
Loading…
Cancel
Save