Wednesday, 17 April 2013

TouchPad class for AS3+Starling.

When I started developing games for Android I had to work pretty hard to invent a good controller, It has been created to meet the needs of my shooter game Beekyr. But Im sure it will work in other kinds of games.

I couldn't find anything that was good enough so I made one that works very well...

UPDATE, VER2: Allows two fingers and works better than this version. VIEW UPDATE HERE!

At the moment only allows one finger, if you want to extend this class feel free to do so!

package beekyr.controllers
{
    import flash.geom.Point;
    import starling.display.Quad;
    import starling.events.Touch;
    import starling.events.TouchEvent;
    import starling.events.TouchPhase;
    public class TouchPad extends Quad
    {
    /**
     * ...
     * @author Jaime Dominguez for Beekyr : 2013
     * http://www.jaimedominguez.com
     */
       
        private var _moveVector:Point = new Point();
        private var _latestVector:Object = new Object();
        private var _sensitivity:Number;
        private var _touching:Boolean;
       
        public function TouchPad(width:int, height:int, sensitivity:Number = 1) {
            super(width,height,0xff0000);

            _moveVector = new Point();
            _sensitivity = sensitivity;
            _touching = false;
            alpha = 0;
            addEventListener(TouchEvent.TOUCH , _handleTouch);
        }
       
        public function getLatestMovement():Object     {
            _latestVector._vX = _moveVector.x * _sensitivity;
            _latestVector._vY = _moveVector.y * _sensitivity;
            _latestVector.touching = _touching;
            _moveVector.x = 0 ;
            _moveVector.y = 0 ;
            return _latestVector;
   
        }
       
        public function setWidth(w:Number):void {
            width = w;
        }
       
        public function setHeight(h:Number):void {
            height = h;
        }
       
        public function updateSensitivity(s:Number):void {
            _sensitivity = s;
        }
       
        private function _handleTouch(e:TouchEvent):void {
            e.stopImmediatePropagation()
            var touchArray:Vector. = e.getTouches(this);
           
            if (touchArray.length>0){
           
                var touch:Touch = touchArray[0];

                    switch (touch.phase)
                    {
                        case TouchPhase.BEGAN:
                            storeThisPos(touch);
                        break;
                       
                        case TouchPhase.ENDED:
                            stopMovement();
                        break;
                       
                        case TouchPhase.MOVED:
                            getMovementVector(touch);
                        break;
                       
                    }
               
            };
           
        }
       
        private function stopMovement():void
        {
             _moveVector = new Point();
             _moveVector.x = 0;
             _moveVector.y = 0;
             _touching = false;
        }
       
        private function stopMovementVector():void {
            _moveVector = new Point(0, 0);
        }
               
        private function getMovementVector(touch:Touch):void
        {
            _moveVector = touch.getMovement(this);
        }
       
        private function storeThisPos(touch:Touch):void
        {
            _touching = true;
        }
   
    }

}

With this class initialized at start of the game. Then you need to collect the values in each loop of the game with:


_speed = _game._touchPad.getLatestMovement();

IT will return a vector of the lastest movement.

You can adjust the sensitivity too with:


public function updateSensitivity(s:Number):void {
            _sensitivity = s;
        }



 

Monday, 8 April 2013

PHP security.


I recently discovered a blog post that I had written back in 2008 but it is still relevant today So I have decided to release it now in 2013.

This was the original post:


I have been recently reading a book about security. And I thought it was good to share all this new knowledge with the rest of the world.

There may be lots of practices that I'll miss but this text intends to be tips to be considered while programming any PHP app. :


Filter all the data you manage:

Golden rule:
All data you receive on your PHP scripts is invalid until is filtered and validated.



Use SSL every time you send sensitive data. Such login details or credit card data.


Differentiate your variables between verified and unverified. Create an empty array where you can copy all clean variables. This way will be a good thing to do verify that you are using the correct valid variables:
$cleanVars = array();

//if a variable is validated successfully you copy the value into the new array:

switch ($_POST['colorEyes']){

case 'brown':
case 'blue':
case 'green':

$cleanVar['colorEyes'] = $_POST['colorEyes']

}


Once you have filtered all the data:

Use htmlentities() to escape HTML code and html_entity_decode() to decode it.

To send strings into SQL queries use: mysql_real_escape_string().

Ask for re-login some times for specially delicate movements such password reset or contact details among others.

To check if a string is alphanumeric use: ctype_alnum()

When receiving a file name link as string you don't want the hackers to be using relative or full paths, you want just file names and deal with the directories on the script. Erase all possibility of path edition on the variables using the function basename()



Include files:
Set the includes outside root directory.
They can be anywhere and make sure that only the server and only your internal user is able to access them no one else need them. Use .htacess for this matter.

Credentials such password and username for databases should be stored in a file named db.inc
Make sure that inc is treated like a php file and if u want to deny all access to INC files u can configure Apache htaccess to deny all requests to that file extension by normal users:

<Files ~ "\.inc(.php)?$">
Order allow,deny
Deny from all
Satisfy All
</Files>


Dangerous functions:

Try to avoid using the next functions:
eval , exec, shell exec, passthru, system, popen, preg_replace, proc_open, file_get_contents, readfile, file, ini_restore, symlink, fsockopen, escapeshellcmd

Then disable them on Apache with disable_functions. If some of the functions above has to be used then be very careful how you use them...


Apache security:

Have a look at the php.ini and have a look at these apache directives:

allow_url_fopen
disable_functions
display_errors
enable_dl
error_reporting
file_uploads
log_errors
magic_quotes_gpc
memory_limit
open_basedir
register_globals
safe_mode (not used anymore?)

They are all gathered in this php.net page, (you have to scroll down, it is not very well structured)...

Wednesday, 3 April 2013

Some Apache security.

I recently discovered a blog post that I had written back in 2008 but it is still relevant today. So I have decided to release it now in 2013.

Apache Security

I have been receiving attacks from someone using zombie computers and banning IPs on Apache.
That didn't stop the attacker as he was able to use different IPS for the same attack. So I decided to fix the problem from the root problem.

I checked apache.log and I saw that the attacker was trying to erase some internal Windows files using a PHP file he uploaded by him self using some kind of vulnerability of the XAMPP default settings.

The biggest problem was that I didn't have a password set for phpMyAdmin software so it was like a big hole in the security.

Now I know what to do:
Go to myphpadmin folder and in config.ini
find the next line and set it to authenticate using http and not automatic!

$cfg['Servers'][$i]['auth_type'] = 'http';

Another good thing for security is to disable directory listings. So when a user tries to open a folder, Apache doesn't show the files on the folder...

on .htacess add the following line:

Options -Indexes


Monday, 1 April 2013

Improving JSFL performance



I'm currently working with JSFL.

What is JSFL? JavaScript for FLash . It's a scripting language that allows to automatize some tasks interacting with Flash GUI to store or edit data.... like here: It stores the keyframe's properties of specific Movieclips.

I have made a levels editor for my game where I can edit the path of enemies too.


I made it using MovieClips where I would detect key frames and store the coordinates in that frame.

I have all Movieclips stored in the library, and the script I generated checks all objects in library to export the relevant data to JSON, but it was taking too long. How long? About 2 mins to process ~10 paths in a 6 core 3.4GHz machine. This is far too long and would make sense the need to optmize code.

I was processing many things but I isolated the problem:  the bottle neck was the keyframes detector function.

function getKeyframes (layer){
   var keyframes = [];
    for(var f in layer.frames){
      if (f==layer.frames[f].startFrame){
            keyframes.push({
            frame:layer.frames[f],
            index:f
         });
      }
   }
    return keyframes;
};

It was taking very long time per MC. I played with code and I finally improved it by changing it to:


function getKeyframes (layer){
   var keyframes = [];
   var layerFrames = layer.frames;
     for(var f in layerFrames){
      if (f==layerFrames[f].startFrame){
            keyframes.push({
           frame:layerFrames[f],
            index:f
         });
      }
   }
    
    return keyframes;
};

After this, the script takes about 2-3 seconds instead of 2 mins.

A note for the reader: I usually optimize all my code but since this JSFL script is only executed every now and then I didn't think it was necessary to optimize it.

I hope it helps to someone!

Thanks for reading!