Wednesday, July 24, 2013

Android: downloading text data from network url

reference: http://developer.android.com/training/basics/network-ops/connecting.html

1) create method to download string from url

String downloadURL(String strurl) throws IOException{
InputStream is = null;
   // Only display the first 500 characters of the retrieved
   // web page content.
   int len = 500;
   
   try{
    URL url = new URL(strurl);
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    conn.setReadTimeout(10000); // 10 sec
    conn.setConnectTimeout(15000); // 15 sec
    conn.setRequestMethod("GET");
    conn.setDoInput(true); // allows receiving data.
    // starts query
    conn.connect();
    int response = conn.getResponseCode();
    Log.d("connection", "response is " + response);
    is = conn.getInputStream();
   
    InputStreamReader reader = new InputStreamReader(is);
   
    char[] buff = new char[len];
    reader.read(buff);
   
    String result =  new String(buff);
    Log.d("connection", "message is " + result);
    return result;
   }
   finally{
    if(is!=null){
    is.close();
    }
   }
}

2) create class to handle download in background process
// class to handle download
// http://developer.android.com/reference/android/os/AsyncTask.html
// < Params, Progress, Result>
// Params - the type of the parameters sent to the task upon execution.
// Progress - the type of the progress units published during the background computation.
// Result - the type of the result of the background computation.
// so in this case, String is the data type of parameter sent to task, void for type of progress units, string for data type of result
class MyTask extends AsyncTask<String, Void, String>{

@Override
  // "String..." = optional parameter. can be nullable 
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
return downloadURL(params[0]);
}
catch (Exception ex){
Log.d("download", "Error is " + ex.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.d("post-execute", result);
et2.setText(result); // display in EditText
}
}

3) Get connection state and execute the background process

// need to have android.permission.ACCESS_NETWORK_STATE
ConnectivityManager mgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected()){
new MyTask().execute(url);
}

Monday, July 22, 2013

Android: video playback

summary:
  1. Add VideoView into the xml layout
  2. copy video into "res/raw" folder
  3. import android.widget.VideoView
  4. VideoView videoView;
  5. videoView = (VideoView)this.findViewById(R.id.videoView1);
  6. String path = "android.resource://" + this.getPackageName() + "/" + R.raw.render; // assume that the video is render.mp4
    • alternatively: can use - String path = "android.resource://" + this.getPackageName() + "/raw/render"; // assume video is render.mp4
    • can use http url to a video file online. but must add uses permission to Internet in Manifest.xml - <uses-permission android:name="android.permission.INTERNET"/>
  7. videoView.setVideoPath(path );
  8. videoView.start();

Sunday, July 21, 2013

Android: music play back

Summary:
  1. Copy the music file, eg: MP3, into the res\raw folder. if raw folder does not exist, create it. 
  2. Check R.*.java. a new id should be created. eg.: R.raw.music.
  3. import android.media.MediaPlayer;
  4. MediaPlayer player
  5. player = MediaPlayer.create(this.getApplicationContext(), R.raw.music);
  6. player.start();
  7. player.pause(); 
  8. player.seekTo(0); // seek to 0 millisec 
Alternatively, use SoundPool to manage a list of sound (eg.: sound effects for a game level): http://developer.android.com/reference/android/media/SoundPool.html
  1. import android.media.*
  2. SoundPool sndPool;
  3. sndPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); // max streams: 10; sample-rate converter quality. Currently has no effect. Use 0 for the default.
  4. int button01 = sndPool.load(this.getApplicationContext(), R.raw.button01, 1); // etc. can load more; priority of the sound. Currently has no effect. Use a value of 1 for future compatibility.
  5. (Activity) : this.setVolumeControlStream(AudioManager.STREAM_MUSIC); // to set Activity sound be controlled by hardware volume keys
  6. when it's time to play, sndPool.play(button01, 1, 1, 0, 0, 1);
    • left & right volume: 0 to 1.0
    • priority: 0 lowest
    • no loop: 0; -1 loop forever
    • play rate: 1.0

Thursday, July 18, 2013

Android: Timer thread

  1. import java.util.*;
  2. Timer timer = new Timer();
  3. create subclass of TimerTask, eg.: class MyTask extends TimerTask { ... }
  4. add "public void run()" method in subclass
  5. timer.schedule(new MyTask(), 0, 30); // assume no delay and 30 millisec interval 
  6. timer.cancel(); // for cleanup. to start timer again, need to instantiate:  new Timer(); then schedule(...)
  7. if using "protected void onPause()" or onResume(), ensure that super.onPause(), etc is called. 
  8. if need to refresh View UI, then use postInvalidate() instead of invalidate(). else will have exception
Activity life cycle (to understand when to stop Timer to prevent waste of resources):


Android: View + touch listener

  1. implements View.OnTouchListener
  2. add public boolean onTouch(View v, MotionEvent event) method
  3. view.setOnTouchListener(this);
  4. event.getX() or getY() to get position of touch
sample code:
public class SecondActivity extends Activity implements View.OnTouchListener{
MyCanvas c;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
c = (MyCanvas)this.findViewById(R.id.myCanvas1);
tv = (TextView)this.findViewById(R.id.textView1);
c.setOnTouchListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.second, menu);
return true;
}
public boolean onTouch(View v, MotionEvent event){
if(v ==c ){
tv.setText("touched: " + event.getX() + ", " + event.getY());
}
return false;
}
}

Wednesday, July 17, 2013

Android: custom View with draw + xml layout

create custom View class:
public class MyCanvas extends View {
int x = 0;
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

Paint paint = new Paint();
Rect rect = new Rect();
protected void onDraw(Canvas canvas){
paint.setColor(0xFF999999);
rect.set(x, 100, 200, 150);
canvas.drawRect(rect, paint);
}
public void move(){
x+=5;
this.invalidate(); // redraw
}
}

xml layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" android:id="@+id/layout1">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="21dp"
        android:text="Button" />

    <com.boon.MyCanvas
        android:id="@+id/myCanvas1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:background="#CCCCCC" />

</RelativeLayout>

MainActivity.java: 
public class MainActivity extends Activity implements View.OnClickListener{
Button b;
MyCanvas c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)this.findViewById(R.id.button1);
b.setOnClickListener(this);
c = (MyCanvas) this.findViewById(R.id.myCanvas1);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
c.move();
}

}

Wednesday, July 10, 2013

Android: Accelerometer + Gyroscope

summary:
  1. import android.hardware.*;
  2. SensorManager mSensorManager;
  3. Sensor accSensor, gyroSensor;
  4. mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
  5. accSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
  6. gyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
  7. implements SensorEventListener 
  8. public void onSensorChanged(SensorEvent event) { ... }
  9. mSensorManager.registerListener(this, accSensor, SensorManager.SENSOR_DELAY_UI);
  10. mSensorManager.registerListener(this, gyroSensor, SensorManager.SENSOR_DELAY_UI);
  11. get the x, y, z values using event.values[0], [1], [2] in the onSensorChanged method
  12. mSensorManager.unregisterListener(this, accSensor);
  13. mSensorManager.unregisterListener(this, gyroSensor);




Wednesday, April 24, 2013

Kinect + Java + Eclipse

Steps:

  1. Download SimpleOpenNI from https://code.google.com/p/simple-openni/
  2. Extract the zip file. 
  3. In the "OpenNI_NITE_Installer-win32-0.27" folder, install openni "openni-win32-1.5.4.0-dev.msi"
  4. install NITE "nite-win32-1.5.2.21-dev.msi"
  5. download latest kinect primesense driver from https://github.com/avin2/SensorKinect/tree/unstable/Bin
  6. install driver
  7. Connect Kinect camera.
  8. if Kinect SDK driver installed, go to Device Manager and "update driver" for Kinect Camera to Primesense driver. right click on device > Properties > Update Driver Software...> Browse my computer > "Let me pick ... " > "Kinect Camera Version: ...." (unsigned)
  9. Create new Eclipse java project
  10. Add sample source into project. eg.: "OpenNI\Samples\SimpleRead.java"
  11. Add "{installation path}\OpenNI\Bin\org.OpenNI.jar" into eclipse project library build path. Project > Properties > Java Build Path > Add external JAR... > "org.OpenNI.jar". Native library location: "{installation path}\OpenNI\Bin"
  12.  run java app. 

Wednesday, March 27, 2013

Adobe Edge Animate


Stage properties: Title, Composition ID (useful to refer to it using code from outside javascript). eg.: AdobeEdge.getComposition("EDGE-9496421")

Elements and Library panel. 
Elements: HTML elements in the symbol. mainly using jQuery $(...). eg.: sym.getSymbol("rect1").$("RoundRect")
Library: shows the symbols. DO NOT confuse the symbol ID with instance ID below. similar concept with Flash. but strangely the API uses getSymbol() instead of getInstance()

Instance properties: ID. useful for referring to instances in javascript. eg.: sym.getSymbol("rect1")...

Timeline: can add Label like Frame label in flash. for use in javascript: eg.: sym.play("over")

sample code: 

var count = 0; // my own variable
(function($, Edge, compId){
var Composition = Edge.Composition, Symbol = Edge.Symbol; // aliases for commonly used Edge classes

   //Edge symbol: 'stage'
   (function(symbolName) {
   
      Symbol.bindElementAction(compId, symbolName, "${_rect1}", "mouseenter", function(sym, e) {
         // insert code to be run when the mouse enters an element
         sym.getSymbol("rect1").play();
      });
      //Edge binding end

      Symbol.bindElementAction(compId, symbolName, "${_rect1}", "mouseleave", function(sym, e) {
         // insert code to be run when the mouse leaves an element
         sym.getSymbol("rect1").playReverse();
      });
      //Edge binding end

      Symbol.bindElementAction(compId, symbolName, "${_rect1}", "click", function(sym, e) {
         // insert code for mouse click here
         //console.log(sym);
         e.preventDefault();

         // using jquery text() function
         sym.getSymbol("text1").$("Text").text("button clicked: " + (count++));

      });
      //Edge binding end

   })("stage");
   //Edge symbol end:'stage'


})(jQuery, AdobeEdge, "EDGE-9496421");

// my own code
var id = setTimeout(myfn, 1000);
function myfn(){
//console.log("time out");
// run some code in Edge
var comp = AdobeEdge.getComposition("EDGE-9496421");
//console.log("EDGE composition: " + comp);
console.log("stage: " + comp.getStage());

var mytext = comp.getStage().getSymbol("text1").$("Text");

 // using jquery offset() function
var x = mytext.offset().left + 1;
//console.log(x);
mytext.offset({left: x});

id = setTimeout(myfn, 1000);
}

Thursday, March 14, 2013

Unity: instantiating GameObjects at runtime

Use Prefabs!
Assets > Create > Prefab
Drag the model, material, etc into the new prefab

in the JS script, declare a variable. eg.: var bullet:GameObject;
Assuming that this JS script is added to a GameObject, you can drag a prefab from Project View to the variable in the Inspector view.

instantiate using code: eg.:
var bulletClone = Instantiate(bullet, Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0), Quaternion.identity);


Wednesday, March 13, 2013

Unity: XML parsing


import System.Xml;
import System.IO;

var filename = "Assets/sample.xml";
function Start () {
print("processing xml");
var reader:XmlTextReader = new XmlTextReader(filename);
print (reader);

while (reader.Read()) {
       switch (reader.NodeType) {
         case XmlNodeType.Element:
           print("element: " + reader.Name); // print the name
           print("attribute: " + reader.GetAttribute("name"));
           break;
         case XmlNodeType.Text: // for text node
          print(reader.Value); // read the content of the text
          break;
       }
    }
}


Note: to parse float or int from String, use float.Parse(string), or int.Parse(...) etc

Monday, March 11, 2013

Unity - audio and video

Put WAV or MP3 in Assets folder.
Create an empty Game Object.
Drag the Audio file to the Game Object
If "Play on Awake", music will play automatically.
If not, using code:
use GameObject.Find . eg.: var obj:GameObject = GameObject.Find("music");
and then
obj.audio.Play(); // audio is built-in, if audio component exists. else null

Video: It is a PRO / Advanced feature. only for Unity Pro license.



Wednesday, March 06, 2013

Unity Engine: mouse and key input

Sample JS:
function Update () {
this.gameObject.transform.position.x = Input.mousePosition.x;
this.gameObject.transform.position.y = Input.mousePosition.y;
// only capture once. will not be true until key is released
if(Input.GetKeyDown(KeyCode.R)){
print("rotate");
this.gameObject.transform.Rotate(0, 0, 6);
}
// will not be true until button is released
if(Input.GetMouseButtonDown(0)){
        print("left mouse button down");
this.gameObject.transform.Rotate(0, 0, -6);
}
// auto fire mode. will return true as long as key is down
    if(Input.GetKey(KeyCode.R) && Input.GetKey(KeyCode.LeftShift)){

this.gameObject.transform.Rotate(0, 0, 10*Time.deltaTime);
}
}


Used a new coordinate system. origin of plane at bottom left. to match with mouse screen coordinate
switched the camera to its original orientation. no rotation. orthographic. x, y, z = (w/2, h/2, 0)

Sample of OBJ file:
# This file uses centimeters as units for non-parametric coordinates.

v 0.000000 1.000000 0.000000
v -1.000000 1.000000 0.000000
v 0.000000 0.000000 -0.000000
v -1.000000 0.000000 -0.000000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 1.000000 1.000000
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
vn 0.000000 0.000000 -1.000000
f 3/1/4 4/2/3 2/4/2 1/3/1


Tuesday, March 05, 2013

Unity Engine: Text

Tried using GUI Text and 3D Text. GameObject > Create Other > ...
preferred 3D Text. easier placement using (x, y, z). easier to preview in Scene view.
GUI Text uses the [0,1] for location. (0,0) for bottom left, (1,1) for top right?

To change font, copy the desired TTF font in the Assets view. select the text GameObject and change the Font in Inspector.



to access the text from the GameObject:
  1. use GameObject.Find()
  2. use GetComponent()
  3. use .text property

Unity engine: Scripting

Asset > Create > Javascript

A JS file will be created in Assets view. It is like a class. It can be dragged to be added into a GameObject in Hierarchy. but the variable will be available in the Inspector view. its value can be changed there. it will NOT be taken from the default value in the script file. The variable / property name will automatically starts with Uppercase letter.


print() is use to print to console.

to access other GameObject in scene, use GameObject.Find("game object tag")
to access component in GameObject, use GetComponent("component name")

Example:

#pragma strict
// a script file is like a class
// a member variable
var i = 1;
var speed = 0.1;
// start calls once
function Start () {
// testing while loop
while(i < 10){
// it's like trace in Flash and echo/print in PHP
// prints to console.
print("hello ");
i++;
}
// instantiate a object / component by adding to the GameObject
// gameObject is built-in as this script is added to a GameObject
// declare class type of variable using ":"
var obj:MyClass = gameObject.AddComponent("MyClass");
// call a method
obj.myMethod();
}

// updates every frame
function Update () {
// rotate around z-axis by speed x time(s) taken to complete last frame
transform.Rotate(0, 0, speed * Time.deltaTime);
// transform is built-in for GameObject
transform.position.y+=0.1;

// testing if statement
if(transform.position.y > 300){
transform.position.y = 0;
}

}

NOTE: there is no %= operator. so has to do something like: number = number % 10;

creating a class: create a JS file. put the class code in. sample below:

class MyCustomClass{
var myVar = 10;
var myName = "TBY";

function MyMethod(){
myVar++;
return myVar;
}

static function MyStaticMethod(num){
return num*num;
}
}


to create an instance, sample:

print(MyCustomClass.MyStaticMethod(10));
var obj:MyCustomClass = new MyCustomClass();
print(obj.MyMethod());

Monday, March 04, 2013

Unity Game engine: Transparent Texture

Works with PNG (8 or 24) with transparency enabled in Photoshop. File > Save for Web > PNG-8 or PNG-24 > Transparency checked

Material Shader changed to Transparent/Diffuse. Hierarchy view > object > default > Inspector > defaultmat > Shader > Transparent/Diffuse

Took some time troubleshooting a silly error. Accidentally change the material's Main Color to RGBA (255, 255, 255, 0) . Alpha zero! and so when material shader set to transparent, nothing is seen as the Main Color alpha is ZERO.


Sunday, March 03, 2013

Unity engine: creating a 2d game project

Camera > Projection > Orthographic

Change resolution: Edit > Project Settings > Player > Resolution

Orthographic size is half of the vertical size of the viewing volume. (defined in Unity Reference: http://docs.unity3d.com/Documentation/ScriptReference/Camera-orthographicSize.html)
so if the resolution is set as 640x480. then for a 1:1 mapping the size is 480 (height in pixels) / 2 = 240.

Camera Preview may show more in the window compared to set resolution. but when build and run. actual app displays fine.

rotated camera x-axis: 180 deg
change ambient lighting to #FFFFFF or RGB (255, 255, 255). Edit > Render Setting > #FFFFFF

using following OBJ plane format to create a simple 2D plane in the XY plane:
# vertices x, y, z
v 0.000000 1.000000 0.000000
v -1.000000 1.000000 0.000000
v 0.000000 0.000000 -0.000000
v -1.000000 0.000000 -0.000000
# texture coordinates in u,v. (0,0) is bottom left corner
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 0.000000 1.000000
vt 1.000000 1.000000
# normal: x, y, z
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
vn 0.000000 0.000000 1.000000
# faces  1st point: vertex/vtexture/vnormal, 2nd point, 3rd point, etc.
f 1/1/1 2/2/2 4/4/3 3/3/4

texture working properly.




Wednesday, January 23, 2013

WebSocket: Alchemy - C# <-> javascript

Reference: http://divyen.wordpress.com/2012/06/13/html5-developing-websocket-server-using-c-sharp-dot-net/ 

Downloaded src code. http://alchemywebsockets.net/
Open it in Visual C# 2010 express
Managed to compile and get the Alchemy.dll

Created a new Console app project. added DLL
added the codes. https://gist.github.com/2976928
Build and then error....

Warning 8 - The referenced assembly "Alchemy" could not be resolved because it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client". Please remove references to assemblies not in the targeted framework or consider retargeting your project.

Go to Project Properties > application > Target Framework > .NET Framework 4
Click Yes for message box.

Build and Run. no more error.

added HTML codes. https://gist.github.com/a9409a82d2379d52e9af
run in chrome. HTML connected with websocket. clock ticking. cool.