Monday, November 02, 2009

Flex: K-means algorithm in AS3

Move mouse within white canvas to collect mouse (x, y) data.
Enter the number of clusters to group the data.
Click "Cluster" to cluster mouse data
Click "Reset" to clear all previous data



url: http://psalmhundred.net/experiment/gesture/GestureApp.html

Sunday, November 01, 2009

Flash, AIR, ActionScript: File & FileStream

Cannot write to filesystem at File.applicationDirectory
But yet you can write using File.applicationDirectory.nativePath

To serialise an object of a custom class,
1) use flash.net.registerClassAlias( aliasName:String, classObject:Class)
to register the class before writing or reading
2) implement IExternalizable to your custom class
- readExternal(input:IDataInput):void
- writeExternal(output:IDataOutput):void
- Alternatively, you can use public fields in the custom class. But that is not entirely recommended for real world application.


import flash.filesystem.*;
import flash.net.*;

var a:A = new A();
...
...

function write():void{
registerClassAlias("A", A);
fileStream.open(file, FileMode.UPDATE);
fileStream.writeObject(a);
fileStream.close();
}
function read():void{
fileStream.open(file, FileMode.READ);
var o:A = fileStream.readObject() as A;
o.c();
fileStream.close();
}

/********************
class A
********************/
import flash.utils.*;

public class A implements IExternalizable
{
var b:int = 10;
public function c():void{
trace(b);
}
public function readExternal(input:IDataInput):void
{
b = input.readInt();
}
public function writeExternal(output:IDataOutput):void
{
output.writeInt(b);
}
}

Thursday, October 29, 2009

Wii remote libraries

Wiigee - A Java-based gesture recognition library for the Wii remote
Background Tech Info:
http://www.wiigee.org/development/background/background.html

wiiremotej
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/
http://www.world-of-cha0s.hostrocket.com/WiiRemoteJ/docs.zip.gz
http://www.wiili.com/forum/wiiremotej-f68.html

Managed library for wii remote
http://www.codeplex.com/WiimoteLib
http://blogs.msdn.com/coding4fun/archive/2007/03/14/1879033.aspx

Monday, October 12, 2009

Flash SWF in Flex

Interestingly, got stuck at an application domain issue.
Did a Flex SWC library using Flex builder.
Used the SWC in Flash CS4. no issue. SWF created.
Loaded SWF into a flex mxml app using Loader. the app domain of the loader is different from the app domain of the flex app. had used Application.currentDomain to format the LoaderContext. http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e07.html
it just doesn't work.

However, the LoaderContext works in Flash CS4. seems that the context is dependent on how the SWF is created. looks like that's the only way, and have to endure without code hinting in flash CS4.

Tried using Flex component library for CS4. still doesn't work.

Sunday, September 13, 2009

WPF: rendering & timer

strange that there's a 24fps limit even on DispatcherTimer

have to use a thread to force a fast refresh rate

partial code:

bool running = true;
public delegate void updateDelegate();


public Window1(){
Thread t = new Thread(new ThreadStart(Run));
t.Start();
}

void Run()
{
while (running)
{

this.Dispatcher.Invoke(new updateDelegate(update), DispatcherPriority.Normal);
Thread.Sleep(5);
}
Console.WriteLine("ended thread");
}

void Window1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
running = false;
}
void update()
{
this.InvalidateVisual();
}

Tuesday, September 08, 2009

maya + python: UI


cubeHt = 2
rgb = [0.5, 0.5, 0.5]

# functions
def updateSlider(*args):
intSlider(slider, value = int(args[0]), e=True);
def updateTxt(*args):
intField(txt, value = int(args[0]), e=True);
def buttonPush(*args):
print(str(args))
n = intField(txt, q=True, value=True)
createCubes(n)
def createCubes(n):
i=0
while(i<n):
names = polyCube();
move((i-n/2)*2, cubeHt, 0, names[0]);
#apply material
sets( names[0], e=True, forceElement=shadingGroup[0] )
i= i+1
def newFile(*args):
init()
def colorUpdate(*args):
rgb = colorSliderGrp(color, q=True, rgb=True)
print(shadingGroup[1])
setAttr(shadingGroup[1]+".diffuse" , rgb[0], rgb[1], rgb[2], type='double3' ) ;

def createMaterials():
# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );

# set up shading group, connect material to this group and apply group to cube object
group = sets( renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;
result = [group, material, texture]
return result
def createPlane():
names = polyPlane( w=20, h=20)
white = createMaterials()
sets( names[0], e=True, forceElement=white[0] )
def init():
# new file
file(new=True, force=True)
# create a plane
createPlane()
shadingGroup = createMaterials()

init()
result = promptDialog(
title='Welcome',
message='Enter Name:',
button=['OK', 'Cancel'],
defaultButton='OK',
cancelButton='Cancel',
dismissString='Cancel')

if (result == 'OK'):
name = promptDialog(query=True, text=True)
confirmDialog( title='Welcome', message='Welcome, ' + name, button=['OK'] )


# create a window
w = 400
h = 240
win = window( title="Boon's UI", iconName='TBY', widthHeight=(w, h) )
c1 = columnLayout( columnAttach=('both', 5), rowSpacing=5, adjustableColumn=True )
r1 = rowLayout( numberOfColumns=3, parent=c1)
text( label='Number of cubes')
txt = intField(value=1, changeCommand=updateSlider)
slider = intSlider(min=0, max=10, value=1, step=1, changeCommand=updateTxt)
color = colorSliderGrp( parent=c1, label='Color of cube', rgb=(1, 1, 1) ,changeCommand=colorUpdate)
button(parent=c1, label='Create cubes', command=buttonPush )
button(parent=c1, label='New File', command=newFile )
showWindow(win)


Monday, September 07, 2009

Flex: charting

MXML:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script source="chart.as" />
<mx:LineChart x="62" y="78" id="linechart1" dataProvider="{expenses}">
<mx:horizontalAxis>
<mx:CategoryAxis
dataProvider="{expenses}"
categoryField="Month"
/>
</mx:horizontalAxis>
<mx:series>
<mx:LineSeries displayName="Series 1" yField="Expenses" xField="Month" sortOnXField="true"/>
</mx:series>
</mx:LineChart>
<mx:Legend dataProvider="{linechart1}"/>

</mx:WindowedApplication>


AS:

import mx.collections.*;
[Bindable]
private var expenses:ArrayCollection = new ArrayCollection([
{Month:"January", Profit:2000, Expenses:1500, Amount:450},
{Month:"February", Profit:1000, Expenses:200, Amount:600},
{Month:"March", Profit:1500, Expenses:500, Amount:300},
{Month:"April", Profit:500, Expenses:300, Amount:500},
{Month:"May", Profit:1000, Expenses:450, Amount:250},
{Month:"June", Profit:2000, Expenses:500, Amount:700}
]);

Blogger: CSS not loaded & image upload not working

been getting the following errors:
Message: 'Textbar' is undefined
Line: 202
Char: 5
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815


Message: Object doesn't support this property or method
Line: 385
Char: 7
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815


Message: Object expected
Line: 233
Char: 1
Code: 0
URI: http://www.blogger.com/post-create.g?blogID=8001423862883592815

Error: Detect is not defined

Source File: http://www.blogger.com/static/v1/v-app/scripts/2280349093-post.images.js

Line: 214

sigh. search the internet.
strange solution: clear all cache in browser, and add the proxy server setting in the browser.

Sunday, September 06, 2009

maya + python: mental ray nodes

# set up ambient occlusion for mental ray
material = shadingNode('mib_illum_lambert', asShader=True)
texture = shadingNode('mib_amb_occlusion', asShader=True)
connectAttr(texture + '.outValue', material + '.ambient', f=True );

# set up shading group, connect material to this group and apply group to cube object
group = 'mibMaterialGroup'
sets( name=group, renderable=True, empty=True )
connectAttr( material+".outValue", group+".miMaterialShader", force=True)
sets( cube, e=True, forceElement=group )
setAttr(material+".ambience", 0.5, 0.5, 0.5, type='double3' ) ;
setAttr(material+".diffuse" , 0.5, 0.5, 0.5, type='double3' ) ;

Friday, September 04, 2009

python+maya: animation

from maya.cmds import *
import random
import math

# Delete any existing scene
file(newFile=True, force=True)

names = sphere(r=10)
s = names[0] # object name
# call python script procedure haha() in anim.py module
expression(o=s, s='python("anim.haha()")', ae=True)
playbackOptions( minTime='0sec', maxTime='10sec', loop='continuous')
play( state=True )
viewFit()

# create a function to run every frame
def haha():
x = getAttr(s + ".translateX")
#print(x)
t = currentTime(query=True)
#print(t)
x = 50* math.cos(math.pi * t / 120)
# setAttr(s + ".translateX", x);
setAttr(s + ".translate", x, 0, 0);


Apparently, must Bake Simulation before rendering. no dynamic content when rendering
Edit > Keys > Bake Simulation

Strange. some bug. in Render option > Common > End Frame. if i key in 240, it will reset to 10. but if i key in 100 first, it will accept. and then 240, it will accept. ???

python + maya: lighting

# create ambient light
light = ambientLight(intensity=0.4, softShadow=True, useRayTraceShadows=True)
# Create a directional light
#lightDir = directionalLight(rotation=(45, 30, 15))
lightDir = directionalLight(intensity=0.9, softShadow=True, useRayTraceShadows=True)

rotate(-60, 45, 0, lightDir);

# fit scene in active camera
viewFit();

python + maya: shading

can also use the following commands:
cmds.sets( name='redMaterialGroup', renderable=True, empty=True )
cmds.shadingNode( 'phong', name='redShader', asShader=True )
cmds.setAttr( 'redShader.color', 1, 0, 0, type='double3' )
cmds.surfaceShaderList( 'redShader', add='redMaterialGroup' )
cmds.sets( 'plane1', e=True, forceElement='redMaterialGroup' )



i=0
n = 50
limit = 20
lamb = []
lambSG = []
while i< n:
size = random.uniform(0.1, 5)
names = polyCube(o=True, w=size, h=size, d=size)
k=0
for name in names:
print(str(k) + ": " + name)
k = k + 1
cube = names[0] # object name
node = names[1] # node name

lamb=lamb + [createNode('lambert', n=('lamb' + str(i)))]; # create lambert shader node
lambSG= lambSG + [sets(n='lambSG'+str(i), empty=True, r=True, nss=True )] # create an empty shading group
connectAttr( lamb[i]+".outColor", lambSG[i]+".surfaceShader", force=True) # connect attribute

r = random.uniform(0, 1)
g = random.uniform(0, 1)
b = random.uniform(0, 1)

setAttr(lamb[i]+".color", r, g, b, type='double3' ); # set to random colour
sets(cube, fe=lambSG[i]) # set cube to have the above shading group

move(random.uniform(-limit, limit),
random.uniform(-limit, limit),
random.uniform(-limit, limit), cube, r=True)
i = i+1


Thursday, September 03, 2009

randomise cubes


file(f=True, new=True); # new file
i=0
n = 10
while i< n:
size = random.uniform(0.1, 5)
names = polyCube(o=True, w=size, h=size, d=size)
cube = names[0]
move(random.uniform(-5, 5),
random.uniform(-5, 5),
random.uniform(-5, 5), cube, r=True)
i = i+1


Wednesday, September 02, 2009

Maya and Python - 1st try

C:\Documents and Settings\{username}\My Documents\maya\{version}\Maya.env
PYTHONPATH="C:\Documents and Settings\{username}\My Documents\maya\scripts"
* for Mac OS, DON'T use double quotes "..."
instead eg.: PYTHONPATH = /Users/username/Documents/maya/scripts

default for Mac OSX: ~/Library/Preferences/Autodesk/maya//scripts

start new hello.py file
put into the "scripts" folder

start maya. open Script Editor window
import hello
(to reload, use reload(hello))

.pyc compiled python also works in the scripts folder

sample py code:
print("hello world");
from maya.cmds import *
file(f=True, new=True); # new file
#select(all=True) # select all objects
#delete(all=True) # delete all objects. not supported anymore. Use "file -f -new;" instead.
# create a polygon cube
# store all names
names = polyCube(ch=True, o=True,w=5.038671,h=3.648038,d=3.788829,cuv=4)
# use for loop to print out the object and node name
#for s in names:
# print(s);
cube = names[0]
print(cube)
move(10, 0, 0, cube, r=True) # move (10, 0, 0), note that the order of arguments is different from MEL

just realised from the maya help doc:
"Objects and arguments are passed to commands as they would be in MEL, but they must be passed in the following order:

command arguments object flags/named arguments

This is different from MEL where the ordering requires that objects appear at the end of the argument list. However, Python requires that named arguments come after all other arguments."
eg.: move(10, 0, 0, cube, r=True) # python
MEL: move -r 10 0 0 cube

&

"Maya Python implementation requires you to assign a boolean argument to those flags that do not normally take any arguments."
eg.: file(f=True, new=True); # python
MEL: file -f -new

save the following python script on shelf:
import hello
reload(hello)

Script Editor > File > Save Script to Shelf...
this will facilitate easier execution of the hello.py script

Recertified Flash and Dreamweaver CS4 ACE

Yay! passed the recertification exam for Flash and Dreamweaver CS4 ACE

Tuesday, August 25, 2009

1st try at Python

# for comments
variables. easy.
concatenating strings a bit more troublesome.
eg.:
i = 1.23
s = "hello"
a = s + i
will give error
have to convert to string
a = s + str(i)

b = True
b = not b #store False. same as b = !b

if-else conditions
>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
...


while loop still ok. but must get used to the : at the back
eg.:
i = 0
while i<= 10: # : is equivalent of starting a curly brace {
   print i   # identation used to indicate within while loop
   i = i + 1 # what happened to ++, --?!

for loop v different.
>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)

OR
for i in range(10):
    print i # print 0, 1, 2,..., 9


functions
eg.:
def functionName():
  print "running in function"


classes and objects
class MyClass:
   property = 1 # static variable
   self.myVar = "hello" # instance variable
   def __init__(self, p): # contructor, self = this
         self.property = p

   def method1(self): # note the need for self, even with no arguments/parameters
      print "running method"
   @staticmethod
   def staticMethod2(args, arg2):
      print "call me by classname, eg.: MyClass.staticMethod2(1,2)"

x = MyClass() # instantiate
print x.property
x.method1()

class DerivedClass(MyClass): # inheritance
  newProperty = 2

class SubSubClass(Class1, Class2, Class3): # multiple inheritance supported
  # fields & methods


modules
save into separate .py files
and then import
using import hello (if module is hello.py)
or use from hello import *

Thursday, August 06, 2009

Flash 10: Matrix3D

rawData is set as column major order

hence, gotta transpose to row major

var v:Vector.<Number> = Vector.<Number>(
[1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16]);
var m:Matrix3D = new Matrix3D();
m.rawData = v;
/*
matrix is stored as
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
*/
m.transpose();
/*
matrix is stored as
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]
*/

Monday, June 08, 2009

TBY appears on ST paper


ha. found this newspaper clipping while clearing my old office.
ST, Tech & Sci, H9, 28 Aug 2003

Thursday, June 04, 2009

Using Flex Library SWC with Flash CS3 FLA

Useful link: http://www.timwalling.com/2007/10/22/compiling-flash-cs3-compatible-swcs-with-flex/

It works.
1) manifest.xml
eg.:
<?xml version="1.0" encoding="utf-8"?>
<componentPackage>
<component id="OOPMLibrary" class="com.boon.OOPM" />
</componentPackage>

1b) Flex Library Compiler > Fill in Namespace URL and Manifest File

2) Compiler arguments: -compute-digest=false

3) put in the folder (WinXP): C:\Documents and Settings\{username}\Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Components

4) Flash CS3 > Components Panel > Reload (Menu)

Wednesday, May 20, 2009

Fireworks effect

Created a fireworks effect component.
FLA: fireworks_cs3.fla


Drag the fireworks component from the library to the Stage.
Modify the component parameters from the Component Inspector Panel. play around with different values for different effect.

parameters:
- burstVelMin/Max : min and max speed of the particles when fireworks explode. randomise. higher, faster
- colour: colour of fireworks
- drag: how fast the particles will slow down. lower number, slow down faster
- gravity: how fast the particle will fall downward. higher number, faster the drop
- numFramesToBurst: number of frames before the fireworks explode
- numParticles: number of particles when the the fireworks explode
- particleLifeSpan: number of frames before particles will disappear
- particleSizeGrowth: how fast the size of the particle will grow. higher number, bigger the growth
- trailDecay: how fast the trail will disappear. higher number, faster
- vx / vy: starting speed in x and y direction