Thursday, November 21, 2013

Orbital Mechanics

This past few weeks I've been working on a game in Computer Game Programming, Jerbal Space Program.

You design a space ship, and then you fly around in it, trying to land on the moon, or what have you. It's a pretty open sandbox game.

During it's development, I had to dive into orbital mechanics, to figure out the orbit of the spaceship, and then to render that orbit.

I though it was pretty neat, but it was hard to figure out from wikipedia, so I thought I'd write a post about it.

Lets dive into the function:

Ship.prototype.updateOrbit = function() {
    //Calculate orbit from orbital state vectors
    //Get the primary body the ship is orbiting
    var terr = entityManager.getTerrain(this.cx,this.cy);
    
    //One focus is in the center of the primary body 
    var focus = terr.center;
    var M = terr.mass;

    //Mu in the equations
    var mu = consts.G*(M+this.mass)
    
    //The posistion and velocity vectors.
    //Note that posistion is relative to the focus,
    //But the velocity is just the current velocity of the ship
    var r = util.vecMinus(this.center,focus)
    var v = [this.velX,this.velY];

    //Calculate the orbit specific energy, and from that we find the
    //semi-major axis. Note that this makes sense, as the semi major axis
    //basically tells us how high we'll go.
    var speed = this.getSpeed(); 
    var eng = (speed*speed)/2 - (mu/util.lengthOfVector(r));
    var a = -mu/(2*eng);
    
    //Calculate the eccentricity vector, and from that the eccentricity
    var tripleprod = util.tripleProduct(v,r,v);
    var vtimeshovermu = util.mulVecByScalar(1/mu,tripleprod); 
    var unitr = util.normalizeVector(r)
    var eccVec = util.vecMinus(vtimeshovermu,unitr);
    var ecc = util.lengthOfVector(eccVec);
    
    //ae is the distance from the center to a;
    var ae = a*ecc;
    //semi minor axis

    var b = a*Math.sqrt(1-ecc*ecc);
    //Find the center from the distance
    var cen = [f[0]-ae,f[1]];
    
    //Here we find the rotation of the eccentricity,
    //which tells us where the orbit is from the focus
    var angl = util.angleOfVector(eccVec);

    //rotate the center around the focus according to the angle
    cen = util.rotatePointAroundPoint(cen,angl,focus[0],focus[1]);

    //Set the properties of the orbit
    this.orbit = [cen[0], cen[1],a,b,angl,focus[0],focus[1]];
}

Now, using this we can plot our ellipse, knowing the center, and the angle of it. And it works, just zoom far enough out in the game, and take off! Happy flying!

Monday, October 21, 2013

Function for quick adding tasks or events to google calendar.

I have written a function so that you can quick add tasks as well as events to google calendar, using Google script.

"use strict";
/*
01234567890123456789012345678901234567890123456789012345678901234567890123456789
*/
/*
 * @author Matthias Pall Gissurarson
 * @usage quickAddTaskOrEventFromString(quickadd);
 * @param quickadd A String describing the event to quickadd
 */
function quickAddTaskOrEventFromString(quickadd) {
  //Add a task if the string includes " due ", otherwise add an event.
  if(quickadd.indexOf(" due ") !== -1){
    //Use the already implemented quickAdd to create an event.
    var event = CalendarApp.createEventFromDescription(quickadd);
    //This event gets automatically added to the users calendar, remove it.
    event.deleteEvent();

    /*
    Create a new task, and have it have the same properties as the event.
    Tasks don't have dueTime as of now, so we add that to the note of the task.
    Also add the events location and description, these are often empty.
    */
    var task = Tasks.newTask();
    task.setDue(event.getStartTime().toISOString());
    task.setTitle(event.getTitle());

    task.setNotes([event.getStartTime().toString(),
                   event.getLocation(),
                   event.getDescription()].join("\n"));

    //Add to the users default tasklist.
    Tasks.Tasks.insert(task,'@default');
  } else {

    //Add the event as normal
    CalendarApp.createEventFromDescription(quickadd);
  } 
}

function main() {
  var s = "Homework due tomorrow";
  var e = quickAddTaskOrEventFromString(s);
}
This function takes in a string, and if it contains " due ", it creates a task instead of an event on the default task list. Might this get implemented in the actual calendar?
I have posted a topic for this on the Google product forums. Let's see what happens.

Monday, June 10, 2013

Markdown blog posts via emacs/vim and pandoc

Using Markdown on google blogs from the Commandline


As per the comment on my last post from Matthías Ragnarsson, I'm using pandoc to generate html from a md file, albeit I'm not using vim, but rather emacs (as setting up markdown-mode is simpler, and with evil, it's pretty much the same thing, only more easily extensible. It also fits better with the Unix philosophy of using external tools to do tasks, rather than hardcoding them into the program itself.


Saturday, June 08, 2013

Google calendar from the desktop, and posting through vim

Posting trough vim

Here I am, writing a blog post in vim. If this actually gets posted, I'll be pretty impressed, as this makes posting to the google blogs extremely simple to implelement via a server. The api program itself is just a python program, so porting the functionality over to haskell shouldn't be hard at all. I might even make it and put it on hackage. It'd be neat to have a package there!

Anyway, I hope this test works, as it'll make code examples way simpler.

Google calendar on the desktop

I recently made some commits so that it can display arbitrary colors in conky, and used it to create a neat display of my google calendar on the desktop, and you can see a picture of it included in the pull.

My .gcalclirc is as follows:

--calendar
icetritlo@gmail.com
--military
--monday
#Tomorrow-Night Palette
--conky_color0
    #282A2E
--conky_color8
    #373B41 
--conky_color1
    #A54242 
--conky_color9
    #CC6666 
--conky_color2
    #8C9440 
--conky_color10
    #B5BD68 
--conky_color3
    #F0C674 
--conky_color11
    #DE935F 
--conky_color4
    #5F819D 
--conky_color12
    #81A2BE 
--conky_color5
    #85678F 
--conky_color13
    #B294BB 
--conky_color6
    #5E8D87 
--conky_color14
    #8ABEB7 
--conky_color7
    #707880 
--conky_color15
    #F0C673 

#Viljum auka vidd ef a ad vera a isl
#--locale
#is_IS.UTF-8
#-w
#12

I have that last part if I should want to have the dates and day names in Icelandic, but as neither are capitalized (correct in the middle of a sentence, but not standalone), and the english version suits me fine, I don't think I'll bother fixing it.

[Edit: Rewrote this post in markdown, and used pandoc to translate it into html, as per the comment below. N.B. you need my fork of gcalcli for this to work, as the --conky_color options were added by me.]

Wednesday, June 05, 2013

Using GoogleCL to post from the terminal

I'm really just testing out using googleCl to post from my terminal to the blog. As simple as pacman -S googlecl, then authenticate via oauth (almost totally automatic, just enter your username and password in the browser window, grant access and done), and then $ google blogger post etc. Very basic. I wonder if I can post a text file....

Saturday, April 20, 2013

Using xmobar to display rcirc status from emacs

I use the emacs rcirc as my main irc client, and via BitlBee, facebook and skype chat. I use XMonad as my window manager, and xmobar as my display bar. Today I added the rcirc status line to my xmobar, so that I can see if I have new messages on any channels/facebook chat/skype. I wrote a short bash scriptlet that I execute in xmobar with

Run Com "~/.scritpstouse/rcircActivity" [] "rcirc" 100

the script is as follows:

#!/usr/bin/env bash
if  emacsclient -e rcirc-activity-string > rcirc-string;then
    if ircstr=$(cat rcirc-string | tr '"' '\n' | grep '\[');then
        echo "<fc=#00ff00>"$ircstr"</fc>"
    else
        echo "<fc=#0000ff>[]</fc>"
    fi
else
    echo "<fc=#ff0000>[]</fc>"
fi

This contacts my running emacs server and asks for the status string, and then displays it. I'd have it in the .xmobarrc, but it doesn't handle escaped " so well. If my server isn't running or rcirc isn't, there is no field that contains [, so the output will be empty and my xmobar will just have a few spaces. The echos give me different colors on the xmobar based on what happened, green and the status if rcirc on, blue if emacs on but rcirc not, and red if emacs turned off. Try it!

[Edit: I've decided to try and use erc instead. The command is almost the same (the ircActivity), but the if clause is replaced with:
i
f  ercBuffers=$(emacsclient -e "(if (functionp erc-track-shorten-function) (funcall erc-track-shorten-function (mapcar 'buffer-name (mapcar 'car erc-modified-channels-alist))) (nil))");then
    if ircstr=$(echo ${ercBuffers:1:${#ercBuffers}-2} | tr ' ' ',' | tr -d '"');then
        echo "<fc=#00ff00>["$ircstr"]</fc>"


A little more complicated, but it works, and I believe erc is more feature rich.]

I'll later try to explain my xmonad config, and include the (current) file. It handles everything for me, from handling my workpaces, windows etc.. to changing my keyboardlayout and handling my media keys. It rocks!


Sunday, February 03, 2013

The MIT License

When I make code publicly available, I usually do it under the MIT License. Why? Because it is a so called copyfree license, which, in contrast to copyright, merely states that anyone is free to use the provided code, if they include the license (and thus preserving my name in the codebase). It is as follows:

Copyright (C) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

This, in contrast to copyright, does not restrict use of my code in other work, and in contrast to copyleft, does not force them to apply a specific license to their own code. It is thus a true free software license, allowing anyone to use my ideas for free - as long as they acknowledge my participation by including the license. Thus I enrich society by showing more examples of code, maybe help someone out on the project, and gain better reputation - instead of burdening it with pointless legal battles about something no one can really own. If you ever give out any code, use the MIT License, or at least a copyfree license.

[Edit 2013-04-24:  After reading tldr;legal, I've decided that the GPL is actually a better license, by making more software free as in freedom. I have thus changed most of my projects to the GPL, and I recommend that you read up on tldr;legal and decide for yourself what license fits your project best. I hope that you'll choose the GPL, though anyone should of course be free to do with their work as they please.]