Sunday, September 30, 2012

Installing Python libraries in Mac OS X

Thanks to the post in http://ashearer.com/blog/2011/xcode/ 
was trying to install Python Imaging Library (PIL), failed. 
basically from the post linked:
'enter the following command line once and the effect will last across multiple builds or installations for the remainder of the terminal session.'

export ARCHFLAGS="-arch i386 -arch x86_64"


Saturday, September 29, 2012

python + socket + xml

made a silly error:
xmldom = xml.dom.minidom.parseString(xml)
xml is a string containing the xml doc.
but its name clashes with the xml.dom.minidom package
xmldom = xml.dom.minidom.parseString(xml_string)

xml processing:
elements = xmldom.getElementsByTagName("mytag")
print elements.length                  # return number of elements
element.getAttribute("myattr")


using multiple line for code. use "\"
eg.: print "this, " + "that, " \
                + "those"

Dictionary
mydictionary = {"mykey":"hehe"}
mydictionary["newkey"] = "hello"       # can be number too
for k, v in mydictionary.iteritems():
   print k + "= " + v
if  "key" in mydictionary:
   print "key exists in dictionary"


Socket client:
import socket
socket = socket(AF_INET, SOCK_STREAM)
socket.connect(("127.0.0.1", 5000))   # address and port
data = socket.recv(4096)              # 4096 bytes buffer


binary data
data = bytearray(socket.recv(4096))
size = (data[3]<<24 | data[2]<<16 | data[1]<<8 | data[0] ) # to 32-bit or 4 byte integer


python imaging (PIL)

all thanks to the link: http://yufu.co/wordpress/?p=15

JPEG decoding from binary data using PIL. Documentation is lacking in official PIL site: http://www.pythonware.com/library/pil/handbook/image.htm

import Image
f = open("myimage.jpg", 'rb')
data = f.read()
im = Image.fromstring('RGB', (640,480), data, 'jpeg', 'RGB', '')



Tuesday, August 28, 2012

Android: Activity, View, onDraw, Canvas

Drawing on canvas overriding onDraw() method
Assuming using RelativeLayout in xml and with id "layout1"


public class SecondActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        //setContentView(new MyView(this));
        RelativeLayout layout = (RelativeLayout)(this.findViewById(R.id.layout1));
        layout.addView(new MyView(this));
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_second, menu);
        return true;
    }
    class MyView extends View{
   public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

// if required to add this custom view using xml or the graphical layout in eclipse. have to add this constructor
         public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

protected void onDraw(Canvas canvas){
    System.out.println("draw canvas");
    Paint paint = new Paint();
    paint.setColor(0xFFFF0000);
    Rect rect = new Rect();
    rect.set(100, 100, 200, 150);
    canvas.drawRect(rect, paint);
   }
    }
}


C#: Console


To capture key press, print at specific position of console window

class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            bool running = true;
            int pos = 0;
            int lengthOfLine = 1;
            int diff = 0;
            while (running)
            {
                //Console.Clear();
                if (Console.CursorTop - pos > diff)
                {
                    pos = Console.CursorTop;
                }
                else
                {
                    Console.CursorTop = pos;
                }
                Console.WriteLine("i = " + (i++));
                diff = Console.CursorTop - pos;
             
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo key = Console.ReadKey(true);
                    if (key.Key == ConsoleKey.I)
                    {
                        Console.WriteLine("I pressed");
                        //running = false;
                    }
                    else if (key.Key == ConsoleKey.X)
                    {
                        Console.WriteLine("Exit");
                        running = false;
                    }
                }
                Thread.Sleep(40);
            }

        }
    }

Tuesday, August 21, 2012

android: loading and displaying images on canvas


copy and paste image into res\drawable folder in project folder
R.java in "gen" should include this image with an id. Note: filename to be all lower-case

// loading, assuming written in a View class
Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.image_id); 
// displaying
canvas.drawBitmap(bmp, 50, 30, null);

Android: 2d drawing surface

To create a canvas for custom drawing, eg,: for 2d games without using opengl
Create a new class extending SurfaceView, add constructor with 2 arguments (so that it can be used in graphical editor in eclipse too), implement interface SurfaceHolder.Callback

import android.content.Context;
import android.util.AttributeSet;
import android.view.*;

public class MySurface extends SurfaceView implements SurfaceHolder.Callback{
SurfaceHolder holder;

public MySurface(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
holder.addCallback(this);

}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
System.out.println("surface changed");
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface created");
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface destroyed");
}

}


This new custom UI will be available for the xml layout file in Eclipse

can create a draw() method to contain all drawing code in there. then call draw() when surfaceCreated(...)

void draw(){
canvas = holder.lockCanvas();
Paint paint = new Paint();
paint.setColor(0xFFFF0000); // ARGB, red
canvas.drawRect(new Rect(10, 20, 100, 50), paint);
holder.unlockCanvasAndPost(canvas);
}


Threading can be used if animation is needed, for example for games.

Sample code snippet:

public class MySurface extends SurfaceView implements SurfaceHolder.Callback, Runnable{
SurfaceHolder holder;
Canvas canvas;
MySprite s = new MySprite();
boolean isRunning = true;
long time = 0;

static final int DELAY = 10;

public MySurface(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
holder = this.getHolder();
holder.addCallback(this);

}

synchronized void draw(){
canvas = holder.lockCanvas();
canvas.drawColor(0xFFDDDDDD); // ARGB , fill whole canvas

// call draw in sprite
s.draw(canvas);

holder.unlockCanvasAndPost(canvas);
}

synchronized void update(){
s.update();
System.out.println((System.currentTimeMillis() - time) + " ms");
time = System.currentTimeMillis();
}

public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
System.out.println("surface changed");
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface created");

isRunning = true;
Thread thread = new Thread(this);
thread.start();

time = System.currentTimeMillis();
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
System.out.println("surface destroyed");
isRunning = false;
}

public void run() {
// TODO Auto-generated method stub
try{
while(isRunning){
update();
draw();
Thread.sleep(DELAY);
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

MySprite is a custom class which contains x, y, width, height, its own draw(), update(), init(), cleanup() methods.


Monday, August 20, 2012

wxpython with new WebView

using version 2.9.4

import wx
import wx.html2

app = wx.App(False)
frame = wx.Frame(None, -1, 'A Simple Frame')
browser = wx.html2.WebView.New(frame)
browser.LoadURL("http://www.google.com")
frame.Show()
app.MainLoop()




tried loading local html file with some javascript.
worked so far. tested with jquery. ok too.

import os
browser.LoadURL(os.path.realpath("test.html"))


Tuesday, July 24, 2012

Panda3D & maya


Maya (+x, +y, +z) <=> Panda3D (+x, +z, -y)
Panda3D (+x, +y, +z) <=> Maya (+x, -z, +y)

Panda3D: camera face +Y by default; Maya: Model face +Z as Front

Sample code to add keyboard input:
        self.accept('arrow_up-up', self.moveForward ) # up cursor key released
def moveForward(self):
        self.pos = self.camera.getPos()
        self.pos.y = self.pos.y + 1
        self.camera.setPos(self.pos)
        print self.pos

Sample for mouse input:
self.accept('mouse1-up', self.click)
    
    def click(self):
        if self.mouseWatcherNode.hasMouse():
             print str(self.mouseWatcherNode.getMouseX()) + ", " + str(self.mouseWatcherNode.getMouseY()) # x and y = [-1,1], top left (-1,1), bottom right (1, -1)

Tuesday, May 22, 2012

Panda3D: Maya exporter

used maya2egg****.exe 
kept having error about "procedure entry point not located in some libmmd.dll", etc.

realised that have to copy the exe from panda/bin folder to maya/bin folder

maya2egg -a model -o "output.egg" "input.mb"


m = loader.loadModel("cube.egg")
m.reparentTo(base.render)
m.setPos(0,20,0)

EGG model loaded with texture.

couldn't get the COLLADA model to display textures.


Supported in Panda3d
Currently known scene file types are:
  Bam                             .bam
  Egg                             .egg
  MultiGen                        .flt
  Lightwave                       .lwo
  DXF                             .dxf
  VRML                            .wrl
  DirectX                         .x
  COLLADA                         .dae
  Also available: .ma .mb



Tuesday, May 15, 2012

Python & XML

how to parse XML file
using built-in xml.parsers.expat
steps:
  1. create handlers. eg.: def start_element(name, attrs):
  2. create parser. eg.: p = ParserCreate('utf-8')
  3. link handlers. eg.: p.StartElementHandler = start_element
  4. open file eg.: f = open(filename)
  5. ParseFile(file)
Python IDE summary: Netbeans 6.x looks like better choice than Eclipse in terms of code completion. however, netbeans 7 does not support python plugin. currently using netbeans 6.9.1
no problem in using Netbeans with Panda3D
discover a bug. cannot debug properly in Netbeans 6.9.1. cannot step into a method for multiple PY files. breakpoints do not work in multiple files. can be quite troublesome for debugging.
No issue with Eclipse.

converting from String to int or float using int() or float()
attributes in StartElementHandler is stored in Dictionary. eg.: to access an attribute called x , use attrs['x']

thing to note when using classes and methods, have to keep using 'self' keyword in methods when accessing object properties or methods. same as "this" in java but if you omit it in python, it will default to global variable. 

interesting note: cannot use ( ) parenthesis in "for" statement. eg.: for (x in a): 
instead use "for x in a:"

another interesting note: cannot use the same instance to re-parse another file or string. has to create a new instance of parser to do so. ie. Step 2

Sunday, May 13, 2012

Saturday, April 21, 2012

javascript: String to XML

a quick utility function to convert from string to xml object.
Reference:
http://www.w3schools.com/xml/xml_dom.asp

function stringToXML(text)
{
var xmldoc;
if (window.DOMParser)
{
 var parser=new DOMParser();
 xmldoc=parser.parseFromString(text,"text/xml");
}
else // Internet Explorer
{
 xmldoc=new ActiveXObject("Microsoft.XMLDOM");
 xmldoc.async=false;
 xmldoc.loadXML(text);
}
return xmldoc;
}

Useful properties/methods for XML Object:

  • getElementsByTagName(tagName)
  • childNodes[index]
  • nodeValue
  • getAttribute(atttributeName)
  • setAttribute(name, value)
  • createElement(name)
  • createTextNode(text)
  • appendChild(element)
  • removeChild(element)

Friday, April 13, 2012

WPF Controls in XNA

http://www.c-sharpcorner.com/uploadfile/iersoy/windows-controls-and-wpf-usercontrols-inside-an-xna-game-project/
http://stackoverflow.com/questions/835878/wpf-textbox-not-accepting-input-when-in-elementhost-in-window-forms

But the textbox is still not receiving input.

Alternative is to render a separate window
Window window = new Window();
window.Content = control;
WindowInteropHelper helper = new WindowInteropHelper(window);
 helper.Owner = Window.Handle;
ElementHost.EnableModelessKeyboardInterop(window);
window.Show();


Have to Add Reference:
System.Xaml
WindowsFormsIntegration
System.Windows.Forms
PresentationCore
PresentationFramework

import

using System.Windows;
using System.Windows.Interop;
using System.Windows.Forms.Integration;


Run the program and you will get an error about STAThread
so add "[STAThread]" in eg.: 
Program.cs
just before "static void Main(String[] args)" 

Sunday, April 01, 2012

HTML5 WebSocket server using c#

Use Socket.Listen(10) as per normal.
on Socket.Accept(): the HTML5 client from the browser will initiate a handshake.
grab the request using Socket.Receive(byte[])
C#:

bytes = new byte[1024];
 int bytesRec = client.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

Example:

"--- Request ---
GET /echo HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1:9998
Origin: null
Sec-WebSocket-Key: NBX4xUnlu1QWVPtGE2RFyw==
Sec-WebSocket-Version: 13"

To generate a response back, need a few steps.
Reference: http://en.wikipedia.org/wiki/WebSocket#WebSocket_protocol_handshake

Get the key, eg.: "NBX4xUnlu1QWVPtGE2RFyw=="
append the magic string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" to the key.
Use SHA1 to hash the combined string.
Convert this string to base64

Reference: http://www.gamedev.net/topic/611744-websocket-c-handshake-client-does-not-response-on-handshake/
C#:

string combined = key + magicString;
 SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hash = sha.ComputeHash(Encoding.ASCII.GetBytes(combined));
string acceptKey = Convert.ToBase64String(hash);

so in this case, accept key is "YOBURURfF9giWA8womjw1NpT9fk="

Then form the response.
Example:

"--- Response ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: YOBURURfF9giWA8womjw1NpT9fk="

use "\r\n" to end each line. and add an additional "\r\n" to the last line, ie., two "\r\n"

send this thru the socket.
example:

byte[] outputBytes = Encoding.ASCII.GetBytes(output);
 int result = client.Send(outputBytes);

To decode any message from client. using the WebSocket.send(message) method
Reference: http://stackoverflow.com/questions/8125507/how-can-i-send-and-receive-websocket-messages-on-the-server-side

sequence: "one byte which contains the type of data
one byte which contains the length
either two or eight additional bytes if the length did not fit in the second byte
four bytes which are the masks (= decoding keys)
the actual data"

to decode: "decodedByte = encodedByte XOR masks[encodedByteIndex MOD 4]"
C#:

                    bytes = new byte[1024];
                    int bytesRec = client.Receive(bytes);


                    int second = bytes[1] & 127; // AND 0111 1111
                    int maskIndex = 2;
                    if (second < 126)
                    {
                        // length fit in second byte
                        maskIndex = 2;
                    }
                    else if (second == 126)
                    {
                        // next 2 bytes contain length
                        maskIndex = 4;
                    }
                    else if (second == 127)
                    {
                        // next 8 bytes contain length
                        maskIndex = 10;
                    }
                    // get mask
                    byte[] mask = { bytes[maskIndex], 
                                  bytes[maskIndex+1], 
                                  bytes[maskIndex+2], 
                                  bytes[maskIndex+3]};
                    int contentIndex = maskIndex + 4;


                    // decode
                    byte[] decoded = new byte[bytesRec - contentIndex];
                    for (int i = contentIndex, k = 0; i < bytesRec; i++, k++ )
                    {
                        // decoded = byte XOR mask
                        decoded[k] = (byte)(bytes[i] ^ mask[k % 4]);
                    }
                    data = Encoding.UTF8.GetString(decoded, 0, decoded.Length);
                    Console.WriteLine(data);

Wednesday, March 28, 2012

WP7: Isolated Storage

To store app data so that it can be restored when app is tombstoned/deactivated and then restored. stored in key/value pairs


IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
 if (!setting.Contains("rounds")) // check if key exists
 {
     setting.Add("rounds", rounds); // if not, create new key
}
 else
{
      setting["rounds"] = rounds; // if exists, just change the value
}

Reference: http://create.msdn.com/en-US/education/quickstarts/Isolated_Storage

Tuesday, March 27, 2012

WP7: Canvas, Random, 2D Array & Timer



// create a rectangle and fill it with color
Rectangle r = new Rectangle();
 r.Width = r.Height = 50;
r.Fill = new SolidColorBrush(Colors.Orange);
 r.Stroke = new SolidColorBrush(Colors.Black);
 r.StrokeThickness = 3;
// add to canvas
canvas1.Children.Add(r);
// set position

Canvas.SetLeft(r, x);
 Canvas.SetTop(r, y);


// random generator
Random rand = new Random();
int n = rand.Next(maxNumber); // integer :0 to less than maxNumber


// 2D Array
int[,] containers = new int[w, h];

for (int i = 0; i < w; i++ )
 {
       for (int k = 0; k < h; k++)
      {
           containers[i, k] = -1;
       }
 }


// Timer
using System.Windows.Threading;
DispatcherTimer timer = new DispatcherTimer();

timer.Interval = TimeSpan.FromSeconds(5); 
timer.Tick += new EventHandler(timer_Tick);


void timer_Tick(object sender, EventArgs e)
{
     // do something 
 }

Monday, March 26, 2012

WP7: Button MouseDown and Rotate

Interesting that the Button control in silverlight does not support mousedown event.
however, to capture touch down event on the button, has to change the ClickMode of the Button control to "Press" instead of "Release"
and then capture the mousedown event using the "Click" event

Reference: http://www.silverlightshow.net/items/Tip-How-to-handle-the-MouseLeftButtonDown-and-MouseLeftButtonUp-events-of-the-Button-control.aspx

Rotation done using the following:
<Button.RenderTransform>
   <RotateTransform Angle="180" CenterX="100" CenterY="25"/>
</Button.RenderTransform>