Shiki

I'm so bad with words that I can't even make a cool tagline

Why I don’t code in Ruby

Well, not yet anyway. Perhaps when those hosting prices go down I’d go and take a shot at building something useful. I did start reading a few books on Ruby and Rails. It’s an incredibly awesome and fun language. I’ve never been very excited when learning a new language. I drool when I see Ruby code. It’s easy to learn but I’ve already forgotten most about it since I don’t use it fulltime.

If it were just me, I’d have built PicLyf using Ruby to make it more exciting. But there’s the city talent pool we had to think of. Currently, it’s hard to find good PHP developers. I reckon it’ll be more hard to find those who know Ruby.

Creating PID files for beanstalkd on CentOS

Yep, managing servers is hard >.< I’ve been trying to set beanstalkd to be managed by monit on CentOS. Unfortunately beanstalkd doesn’t seem to create pid files on CentOS (it creates one in Ubuntu though). Pid files are needed by monit so it can check if the process is still running or not. Many grueling hours later, I settled with modifying /etc/init.d/beanstalkd and adding this to the start() function (after daemon $exec…):

echo `ps auxf | grep -v grep | grep "$exec -d $options" | awk '{print $2}'` > /var/run/beanstalkd.pid

I have no idea what all those grep and awk exactly mean. ^_^x But the effect is it creates the pid file in /var/run/beanstalkd.pid containing the correct process id of beanstalkd. You could then have monit watch that pid file.

Here’s the whole modified script. And this is my main reference: http://gist.github.com/508889. A huge thanks to him (Sam X).

The undefined curl function in console (WampServer)

Stupid stupid me. On Windows/WampServer, I’ve always had this problem when working with PHP code that can run in the console and using cURL methods..

PHP Fatal error:  Call to undefined function curl_init() in D:\Shiki\github\yii-clockwerk\test-app\CurlHelper.php on line 90
Fatal error: Call to undefined function curl_init() in D:\Shiki\github\yii-clockwerk\test-app\CurlHelper.php on line 90

It (cURL) works in the browser but not when in console. I didn’t think that it was this simple to fix. The PHP CLI uses a different config file (php.ini) compared to the one used by WampServer/Apache. You can see the location of the config file being used by typing:

php --ini

Result:

Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\wamp\bin\php\php5.3.0\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

You can then fix the curl problem by enabling it in the php.ini file being used. Make sure this is not commented out:

extension=php_curl.dll

FirePHP Logger for Yii Framework

I made this a few weeks ago. It is a Yii Framework extension which routes log messages to FirePHP.

Requirements

Installation

  1. Download and extract the “shiki” folder to your extensions directory. This is usually /protected/extensions.
  2. Download the FirePHP core class and put it somewhere in your /protected directory. I usually put these files in /protected/vendors.
  3. Modify your config file to include this LogRoute class and set the fbPath property to the path of fb.php. Use a Yii alias (e.g. application.vendors.FirePHPCore031.lib.FirePHPCore.fb):

config file code (e.g. /protected/config/main.php)

'log'=>array(
    'class'=>'CLogRouter',
    'routes'=>array(
        // the default (file logger)
        array(
            'class'=>'CFileLogRoute',
            'levels'=>'error, warning',
        ),
        // the FirePHP LogRoute
        array(
            'class' => 'ext.shiki.firePHPLogRoute.ShikiFirePHPLogRoute', // "ext" alias points to /protected/extensions
            'fbPath' => 'application.vendors.FirePHPCore031.lib.FirePHPCore.fb', // set path to fb.php
        ),
    ),
),

Usage

Once you’ve got the extension setup in the config, you can use Yii’s logging methods to log messages to FirePHP.

// logging an INFO message (arrays will work and looks awesome in FirePHP)
Yii::log(array('username' => 'Shiki', 'profiles' => array('twidl', 'twitter', 'facebook')), CLogger::LEVEL_INFO);

// logging a WARNING message
Yii::log("You didn't setup a profile, are you really a person?", CLogger::LEVEL_WARNING);

// logging with a CATEGORY (categories are displayed as "labels" in FirePHP -- just an additional info text)
Yii::log('Profile successfully created', CLogger::LEVEL_INFO, 'application.user.profiles');

// tracing simple text
Yii::trace('Loading application.user.profiles.ninja', 'application.user.profiles');

// logging an ERROR
Yii::log('We have successfully determined that you are not a person', CLogger::LEVEL_ERROR, 'Any category/label will work');

Installing Memcached for PHP 5.3 on Windows 7

Updated:

First off, all credits go to this guy. I’m just listing the steps on how I did it in Windows 7 with PHP 5.3. Also, I tested this using WampServer but I believe it should work on any PHP install.

Install memcached

  1. Download the Memcached Win32 library here: http://code.jellycan.com/memcached. Just get the Win32 binary (direct link). Extract the downloaded archive file in a directory (e.g. c:\memcached). There should be a memcached.exe in there.
  2. Run a command prompt as an administrator. Some info on how to do that here.
  3. Install memcached as a service. Go to the memcached directory, type and run:

    memcached -d install
    

    If you get an error saying “MSVCP71.dll is missing”, see this page for a solution.

  4. Start the memcached service by running:

    memcached -d start
    
  5. You can verify if memcached is running by executing this in the command line:

    wmic process get description, executablepath | findstr memcached.exe
    

    You should see a result list showing memcached.exe and its full path.

Install PHP Memcache extension (php_memcache.dll)

  1. Chances are you don’t have php_memcache.dll in your PHP extensions yet. You can download a build of it here. Basu has noted in the comments that VC6 builds are no longer available from that link. You can download the correct build here.
  2. The archive should contain php_memcache.dll. Extract the archive to your php extensions directory. On my system (WampServer), this was C:\wamp\bin\php\php5.3.0\ext.
  3. Edit php.ini, add this line to enable the extension:

    extension=php_memcache.dll
    

    Or if you’re using WampServer, restart it and enable the extension through the WampServer system tray menu.

Test

Test the installation using the sample PHP code here: http://www.php.net/manual/en/memcache.examples-overview.php.

“Ignoring funny ref” error on Git + Dropbox

At Twidl HQ, we use a combination of Git and Dropbox for managing our source code. It’s a simple but awesome setup. Sometimes, we get this really cryptic error when fetching from our main repo (our shared Dropbox folder):

Ignoring funny ref 'refs/remotes/origin/master (Shiki's conflicted copy 2010-01-14)' locally

It seems to happen when 2 people push to origin/master at almost the same time. This makes Dropbox update the same file and seems to be the cause of the error. When this happens, you can bet that one of the people who did the push will lose his changes to origin/master. So you’ll have to fix it accordingly.

The “funny ref” error does not have any critical effect on the repo and Git seems to work perfectly. It will just annoy you every time you try to fetch. It turns out that this "master (Shiki's conflicted copy 2010-01-14)" is a branch in the main repo. Simply deleting it will remove the error. In terminal, go to your main repo’s (Dropbox) root folder:

git branch -d "master (Shiki's conflicted copy 2010-01-14)"

If you’re not sure of the name of the conflicting branch, you can execute git branch to show all branches. There should at least be a “master” branch and your conflicting branch.

Creating custom Box2D shape components in PushButton Engine

If you ever need to use other ways of creating Box2D shapes that are not currently available in PushButton Engine, you can simply make one yourself. You’ll just need to create a subclass of CollisionShape and use it just like the PBE shape classes.

Here’s a sample class we use to create an oriented box shape:

package cavalcade.box2D
{
    import Box2D.Collision.Shapes.b2PolygonDef;
    import Box2D.Collision.Shapes.b2ShapeDef;
    import Box2D.Common.Math.b2Vec2;

    import com.pblabs.box2D.CollisionShape;

    import flash.geom.Point;

    public class OrientedBoxCollisionShape extends CollisionShape
    {
        public var halfWidth:Number = 0.5;
        public var halfHeight:Number = 0.5;
        public var center:Point = new Point();
        public var angle:Number = 0;

        public function OrientedBoxCollisionShape()
        {
            super();
        }

        override protected function doCreateShape():b2ShapeDef
        {
            var scale:Number = _parent.manager.inverseScale;            

            var shape:b2PolygonDef = new b2PolygonDef();
            shape.SetAsOrientedBox(halfWidth * scale * _parent.size.x, halfHeight * scale * _parent.size.y, b2Vec2.Make(center.x, center.y), angle);            
            return shape;
        }
    }
}

As you can see, the class inherits from CollisionShape and overrides the doCreateShape method in order to create the actual Box2D oriented box shape from there. Use it in the level files like this:

<component type="com.pblabs.box2D.Box2DSpatialComponent" name="Cart">
    <collidesWithTypes childType="String">
        <_0>Platform</_0>
    </collidesWithTypes>

    <collisionShapes childType="com.pblabs.box2D.CollisionShape">
        <_0 type="cavalcade.box2D.OrientedBoxCollisionShape">
            <halfWidth>0.42</halfWidth>
            <halfHeight>0.12</halfHeight>
            <density>50</density> <!-- you can still use the same properties in CollisionShape -->
            <friction>2</friction>
            <restitution>0</restitution>
            <angle>3</angle> <!-- specify an angle of rotation -->
            <center> <!-- you can override the location of the box so it won't be positioned somewhere other than the center of the entity -->
                <x>1</x>
                <y>-0.5</y> 
            </center>
        </_0>                
    </collisionShapes>
    <collisionType childType="String">
        <_0>Renderable</_0>
    </collisionType>
    <manager componentReference="SpatialDB" />
        <position type="">
            <x>0</x>
            <y>110</y>
        </position>
        <size type="">
            <x>60</x>
            <y>45</y>
        </size>
</component>

Experiment: Using SWF MovieClips in PushButton Engine

Important: This tutorial is now deprecated due to the new and awesome, fully rewritten, rendering components. You can see some discussions about it here.

I’ve been working with PushButton Engine for a short while now but last night was actually the first time I tried integrating/using a MovieClip from a SWF into PBE. Unfortunately, there are no documentations on how do this at the moment. The examples mostly use images (pngs). I won’t btch about it because that is totally understandable. The PBE team are working their a*es off to get to 1.0 and the documentation is the least of their worries. I could at least thank them for doing such a good job — PBE’s a well thought-out framework, everything I learned from it made a lot of sense.

Anyway, what I wanted to do was simply to put my MovieClip in a SWF library into the stage. I am using FlexBuilder 3 + the latest PBE code from the SVN. I somehow got some ideas on how to do this when I was hanging out at the #pbengine IRC channel. And I did a lot of digging on the PBE code and did lots of experiments to try to understand how to use them. There are 2 different components we can use:

  • com.pblabs.rendering2D.SWFSpriteSheetComponent. This one actually had a class description: “A class that is similar to the SpriteSheetComponent except the frames are loaded by rasterizing a MovieClip rather than a single image”. Assuming you’ve gone through the PBE examples, I think this means that instead of creating the frames from a sprite sheet image and have it used by SpriteRenderComponent, you’ll be getting your frames from a loaded MovieClip instead. Nevertheless, this isn’t what I was aiming for.
  • com.pblabs.rendering2D.SWFRenderComponent. This component somehow works like SpriteRenderComponent, only it uses MovieClips. A little code investigation later, looks like this component will need to be subclassed in order for it to work. From that subclass, you can do what you want to do with your movieclip using a protected _clip variable.

Since I still wanted control over a movieclip, I used SWFRenderComponent. I’ll explain below how I did it. Please do note that I am still a novice with PBE (and Flex for that matter) so the method I used might not be good practice.

Requirements

  • Latest PBE code. You can get it from the SVN here or download here. As of this writing, I’m at revision 470 (Sep 10, 2009)
  • SWF. I have a compiled SWF containing exported assets (movieclip classes) that I want to use in PBE.
  • Flex compiler / IDE / or whatever your preferred tool is. I’m using FlexBuilder + Flex Compiler.
  • A PBE Project. Our team used the PBEngineDemo project as the base project.

Embed the SWF

In Resources.as, embed the SWF using the same method as the sample embedded resources in the PBEngineDemo project.

[Embed(source='../assets/gamemovieclips.swf', mimeType='application/octet-stream')]
public var _embeddedSWF:Class;

I thought that the above would be enough just like embedding images. However, I was getting this warning from the log:

WARN: Resources - ResourceBundle - No resource type specified for extension '.swf'.  In the ExtensionTypes parameter, expected to see something like: ResourceBundle.ExtensionTypes.mycustomext = "com.mydomain.customresource" where mycustomext is the (lower-case) extension, and "com.mydomain.customresource" is a string of the fully qualified resource class name.  Defaulting to generic DataResource.

This resulted to the gamemovieclips.swf not getting embedded in the final swf. I tried to look at the problem in ResourceBundle.as, and somehow, adding this to Resources.as fixed it:

public class Resources extends ResourceBundle
{
  ResourceBundle.ExtensionTypes.swf = "com.pblabs.engine.resource.SWFResource"; // added this line

  [Embed(source='../assets/gamemovieclips.swf', mimeType='application/octet-stream')]
  public var _embeddedSWF:Class; // our embedded swf

  // other embed files below
  ...

Subclass SWFRenderComponent

Next, I created a new class which inherits SWFRenderComponent and overrides the getClipInstance() method. For this example, let’s say in my embedded swf (gamemovieclips.swf in the example above) I have a car animation movieclip exported as CarMC. I will then need to have getClipInstance() return an instance of that movieclip. My class would then look like this:

package com.game.renders
{
    import com.pblabs.engine.resource.Resource;
    import com.pblabs.engine.resource.ResourceManager;
    import com.pblabs.engine.resource.SWFResource;
    import com.pblabs.rendering2D.SWFRenderComponent;

    import flash.display.MovieClip;

    public class CarRenderComponent extends SWFRenderComponent
    {
        public function CarRenderComponent()
        {
            super();
        }

        // override getClipInstance() and return a CarMC movieclip instance
        protected override function getClipInstance():MovieClip
        {
            // check if we are currently loading the movieclip or a CarMC instance was already loaded
            if (_clipInstance == null &amp;&amp; !_loading) {

                _loading = true;
                // load CarMC from gamemovieclips.swf using PBE's ResourceManager
                //I'm also passing an anonymous function which gets called if gamemovieclips.swf is loaded
                ResourceManager.instance.load("../assets/gamemovieclips.swf", SWFResource, function(resource:Resource):void {
                    // reaching this part of the code means that gamemovieclips.swf was loaded
                    // we will then get an instance of CarMC by calling getExportedAsset below
                    _clipInstance = (resource as SWFResource).getExportedAsset("CarMC") as MovieClip;

                    if (_clipInstance) { // check if the class was actually loaded
                        // if it was loaded, you can now do whatever you want with it

                        // for example, I have a child movieclip in CarMC with instance name "wheel" and I want it stopped initially
                        _wheel = _clipInstance.getChildByName("wheel") as MovieClip;
                        _wheel.stop();
                    }

                    _loading = false;
                });

            }

            // return our CarMC instance that will be rendered to the scene/stage
            return _clipInstance;
        }

        private var _loading:Boolean = false; // set to true if we are currently loading a movieclip
        private var _clipInstance:MovieClip = null; // will temporarily hold the loaded movieclip
        private var _wheel:MovieClip = null;
    }
}

A problem with this method is that I’m using ResourceManager to load the swf and then the movieclip. This means that loading the movieclip is not instantaneous. I did try a different method for this but somehow couldn’t get the movieclip loaded into PBE.

Add the component to the level file

Now that I have a render class (CarRenderComponent). I can add it to any entity with a spatial component. (Please see PBEngineDemo for more info on this)

<entity name="car">
    <component type="com.pblabs.box2D.Box2DSpatialComponent" name="CarSpatial">
        ....
    </component>
    <!-- our render component here -->
    <component type="com.game.renders.CarRenderComponent" name="SWFRender">
        <loop>true</loop> <!-- set to TRUE. The SWFRenderComponent will destroy the CarMC once it's done playing if this is FALSE -->
        <positionReference>@CarSpatial.position</positionReference> <!-- set the spatial's position as the movieclip's position when rendering -->
        <scaleFactor>0.3</scaleFactor> <!-- you can resize/scale your MC using this -->
        <screenOffset> <!-- or you can offset it's render position from the @CarSpatial.position -->
            <x>0</x>
            <y>20</y>
        </screenOffset>
    </component>
</entity>

One thing I noticed was the properties <sizeReference> and <rotationReference> didn’t seem to have any effect on the render. I’ll have look at that another time. Maybe I’m just missing something.

That’s it. I was happy enough to see the movieclip embedded, rendered and animated on the scene. Hopefully, this will be of help to someone.

Zend Studio (Eclipse) Remote Editing through a secure proxy

Remote Editing in Zend Studio for Eclipse has to be one of the biggest reasons why I use it in my current job. I work from home and our team’s development environment is securely setup on a Linux server with a firewall open only to specific IP addresses. This is a no biggie if my IP address never changes or if I work only in one place. Unfortunately, that’s not the case for my DSL setup — I get a different IP address everyday. And since I can’t bug the server admin every time I need to have my IP address added to the firewall, I connect through our proxy server first and then connect to the main development server. The setup’s kinda like this:

Local Machine to Proxy Server to Development Server setup

The problem now is Zend Studio doesn’t seem to support this kind of setup. At least, that’s what I concluded after so many hours of googling. Then I found this super awesome article. We can use Putty! Or just plain ol’ Terminal on a Mac (Linux should be the same I think). Continue reading →

Installing the missing Extract feature in Photoshop CS4

Extract Filter in Adobe Photoshop CS4

Yeah so I’m a little late on this. Primarily because I’m no designer and I don’t use Photoshop that much. But I just found out that the Extract filter has been removed from CS4. Or maybe CS3 too? I didn’t notice until I needed to use it at work today where I just had to take out some cats and dogs out of their backgrounds.

So, with some googling I found this article by John Nack. There he explains why they took Extract and other filters/plugins away. I still wish they retained Extract though, it’s kinda useful for us noob Photoshop users :p Thankfully you can still install the missing features. Just follow these steps:

  1. Download the plugins package. Download here for Mac, and here for Windows.
  2. In the package you should find 3 language folders. Open the one you need (ie English) and copy the child folder named Goodies and paste it somewhere safe like the Photoshop application folder. That’s /Applications/Adobe Photoshop CS4 for Mac and somewhere in C:/Program Files/ for Windows (sorry I can’t be too precise).
  3. Open Photoshop. Go to Preferences > Plug-Ins. Find a setting named Additional Plug-Ins Folder and set that to the Goodies folder.
  4. Restart Photoshop.

That should do it.