Monday, December 21, 2009
Flash: Webcam motion detection
Using edge detection, thresholding, k-means clustering
http://psalmhundred.net/experiment/webcam/motion/
http://psalmhundred.net/experiment/webcam/motion/
Friday, December 18, 2009
Sunday, December 13, 2009
Plumbing experience - changing fill valve of toilet bowl
It all started with water leak from the back of the toilet bowl. then further investigation proved that the bottom inlet valve where the water enters to fill the toilet bowl after a flush is not functioning after 6 yrs of usage. somehow the water will seep in and water level will go beyond the drainage hole at the back hence the wet toilet floor at the back of the toilet bowl.
so gotta go spend $12 on the new valve to replace the original Fluidmaster. then realise need a bigger plier so spend another $18 to get the big big pliers to unscrew that white plastic nut at the bottom of the valve.
so the procedure can be found on youtube:
now to wait til next day to see if new valve is working fine
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
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.
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
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.
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();
}
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:
AS:
<?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.
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' ) ;
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();
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' )
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
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
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/
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
Subscribe to:
Posts (Atom)