Test driving Push notification in Bluemix

This post is a continuation of my earlier post ‘Getting started with mobile cloud in Bluemix‘. Here I take a test drive of the push service that Bluemix offers based on the article “Extend an Android app using the Push cloud service” from developerWorks.

This post assumes that you have already completed the changes from my earlier post for the mobile cloud. If you haven’t,  you could clone the code from “mobile data” which is the official IBM version of this app and includes all the changes needed for persisting data in the cloud through their Android.

The Mobile Cloud App I created on Bluemix is “mobtvg“. The main steps to have Push notification service using Bluemix are

  1. GCM services : Get Google API Project number  & GCM API Key
  2. Include the Google Play services library project
  3. Add the jar files to enable Push service
  4. Modify the server side Node.js file to send push notifications to all registered devices
  5. Make necessary code changes
  6. Run the application and test for notification

Here are more details on the above steps

a) GCM services : Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users’ Android-powered device, and also to receive messages from devices on the same connection. The 1st thing to do is get the Google API Project number & GCM API key.

– Click on Google Developer Console

– Click Create Project. Enter Project name & click Create.

– Note the Project Number on top of the page.

– Click API & Auth on left panel. Click API.

– Scroll down and turn-on Google Messaging for Android

–  Click credentials and click “Create new key”. Click server key. Click create

-Copy API key in the Public API access

Now go the Bluemix dashboard and click your application. Click the Push module. In the Configuration tab, scroll down to Google Cloud Messaging and  click ‘Edit’

Enter the Google API Project Number & GCM API key for both the Sandbox & Production configuration and click Save.

4
b) In Eclipse click Windows->Android SDK manager. Scroll down to the bottom and under Extras select Google Play services. Click install. Once the installation is successful import the project as follows File-Import->Android->Existing Android  code into Workspace. Click Next. In the next screen Browse to the path where your ADT bundle is installed and choose the folder

<ADT-Bundle>\ sdk\extras\google\google_play_services

and Click Ok. Also  check ‘Copy project into workspace’. This will copy.

3

Now build the Google Play Services Project. To do this the project. Click Project->Properties->Android and make sure that you select ‘Is library project’ and then click build.

5

Add a reference to the Google Play services in the Androidmanifest.xml

<meta-data

android:name=”com.google.android.gms.version”

android:value=”@integer/google_play_services_version” />

c) Make all the code changes given in Step 4 of “Extend an Android app using the Push cloud service.

d) In MainActivity.java make sure you change the app_name to the name of your app for e.g

public static final String CLASS_NAME = “MainActivity”;

public static final String APP_NAME = “mobtvg“;

Also ensure that under assets folder you have populated the Application ID in the bluemix.properties file

applicationID=<Application ID from Bluemix>

d) Add ibmcloudcode.jar, ibmpush.jar, android-support-v4.jar (from <Android_SDK_Location>/extras/android/support/v4)

e) Now the Mobile Push project need to include this library project. To do this select your Mobile App project. Click Project->Properties->Android. Click Add and select google-play-services-lib. Note: Make sure “Is library project” is unchecked otherwise you are in for a lot of grief.

8

f) Now you need to make changes to the Node.js application to push any changes from the server to all registered devices.  The code for this is in bluelist-push-node. Note; Making changes through the GUI results in an error that “manifest.yml is not in root node”. So I suggest that you take the ‘cf’ route as follows.

– Clone the code using Git

git clone https://hub.jazz.net/git/mobilecloud/bluelist-push

Go to bluelist-push-node folder

i) Open the app.js with your favorite editor and enter the Application ID of your Bluemix application

//Data Values

var values = {

version:”0.3.1″,

//change this to the actual application id of your mobile backend starter

appID : “<APPLICATION ID>”,

host : “https://mobile.ng.bluemix.net&#8221;

}

ii) Open manifest.yml and change host name & name to the name of your application for e.g.

host: mobtvg

disk: 1024M

name: mobtvg

command: node app.js

path: .

domain: ng.bluemix.net

mem: 128M

instances: 1

iii) Once the changes are complete, open a command propmpt and  login into Bluemix using ‘cf’ as follows

– cd to the directory in which Node.js & manifest.yml exist, Do

cf login – a http://api.ng.bluemix.net

cf push mobtvg -p . -m 512M

(Note the changes are pushed to the mobile cloud app on Bluemix)

This will run through and finally give the status that the app is running successfully.

f) Now that all changes are complete the Mobile Cloud with Push can be tested..

g) Click Window->Android Virtual Device Manager. Click the Device definitions. You choose Google Nexus, Nexus 7. Click Create AVD.

Note: Make sure you choose Google API Level Y and not Android x.x.x API Y.

6

Let the AVD come up and display the current items in the grocery list.

h) Login to Bluemix. Click Push and select the Notifications tab and enter a test message for e.g. “This is a notification from Bluemix” and click send.

7

This will result in a Push Notification to be sent to the AVD. You should see this popup on you AVD as shown below

1

i) Add another AVD through Windows-Android Virtual Device manager. While one AVD is running go to Run->Run Configurations->Target Device and choose the newly created AVD.

j) This will start a second AVD which will refresh with the contents of the grocery list. Now adda new item in one of AVD devices. This will result in a Push notification to the other device that the Bluelist has been updated.

2

There you have it.

1) A mobile cloud applications in which changes persist in the cloud and are refreshed each time the Android device is restarted.

2) A Push notification that is sent to all registered devices whenever there is a change to the list.

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

Getting started with a Mobile Cloud app with Bluemix

This post gives the key steps to get going in building a Mobile Cloud application on IBM’s Bluemix. This post focuses on using the Android Platform for building the application. IBM Bluemix’es mobile cloud application includes under its hood mobile services like mobile application security, push and mobile data. A Node.js is also thrown in to provide server-side functions.

The Bluemix Mobile architecture is shown below

BuildingMobile

 

As in the previous post an existing Mobile cloud application IBM’s bluelist -base is cloned to get familiarity with the steps involved. The IBM’s bluelist-base app enables the user to maintain a grocery list that persists as mobile data in the cloud instance. To get started perform the following

1) Install ADT + Eclipse bundle from the aforementioned link

2) Unzip and install Eclipse and the ADT bundle

3) Make sure you have the Java JDK for Eclipse. If not install from the following site Java SE Development Kit 8 Downloads

4) Since we will be cloning an existing application and using Eclipse to make the changes we need to install EGit.

5) To do this open Eclipse and select Help-> Install New Software and type in http://download.eclipse.org/egit/updates in the Work with text field and hit enter. You should see the following

1

6) Once EGit is installed the IBM’s bluelist-base App can be cloned as follows

7) In Eclipse click File->Import->Git->Import from Git and click Next

8) Choose Clone URI and Click Next

9) Enter the URI for IBM’s bluelist-base. This shown below

2

10) This will download all the necessary source files and other Android related files and directories into the workspace.

11) After this perform the Steps 2 to Step 6 from the link given Build an Android app using the MobileData cloud service

12) After you make the necessary code changes you are good to go

13) Make sure you right-click and add all the necessary imports required (also Ctrl+Shift + O)

14) Build the Project and make sure that there are no errors

15) You are now ready to run the mobile cloud application. We need to run the mobile app on a Virtual simulator. This can be done as

a) In Eclipse click Window->Android Virtual Device Manager. Click the Device Definitions tab.

b) Choose Nexus 7 (Google) and Click Create AVD.
c) This will open a New Window. Set the following Skin->QVGA and Enter 100 MiB in SD Card size and click OK. This will add this as a AVD.

16) Now run the application.

17) This will bring up the AVD. This takes some time You should see the IBM bluelist showing up as one of the apps.

18) Click on IBM Bluelist. You can add grocery items. These items will persist even if you have to restart your application

3

19) The data is persisted in the IBM’s cloud. This can be checked by logging into BlueMix’es dashboard

4

20) Click the Mobile Data and the data entered in the AVD device will show up in Data Classes drop down.

5

21) The Analytics tab will give a graphical output of the API calls

6

So not the mobile app that is cloud enabled is ready.

Clearly the ability to build Android Apps with the data stored at a cloud opens up numerous possibilities for apps like Evernote, Pocket across several devices.

There you have your first Mobile Cloud App.

Watch this space!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

Get your feet wet with IBM Bluemix

This post provides the initial steps to get started on IBM’s Bluemix (currently in beta). Bluemix is open-standard, cloud based Platform-as-a-Service (PaaS) from IBM. Bluemix allows one to quickly put together mobile, web, Big Data, IoT applications. Bluemix is an implementation of IBM’s Open Cloud Architecture, Cloud Foundry which enables developers to rapidly build, deploy, and manage their cloud applications. The developers can tap into a growing ecosystem of available services and runtime frameworks.

Bluemix uses the Softlayer infrastructure to host the user applications. Clients/developers interact with Bluemix either with HTTP or REST as shown below
8

Here are the steps to get going on Bluemix

First things first

I would suggest that you get all the registrations and installations right away.

Bluemix dashboard– Get started by creating an account on Bluemix. This will provide you access to the Bluemix’s dashboard from which you can quickly create applications (mobile, Web, IoT, BigData) etc

Devops: Register for an account with Devops. Devops allows you to easily develop, deploy and track your code online. Devops also allows you to collaborate with others by forking code from their Git repositories

Cf Interface : Install the Command line interface ‘cf” to Bluemix. The ‘cf’ command interface is built with Google’s Go programming language. With ‘cf ‘you can login to Bluemix, create an application, add services and manage your application. You can also do this from the Bluemix’es dashboard.

Install Git: There are multiple ways to develop code for Bluemix. Git command line happens to be one of them, So it makes sense to have this installed. You can install this from this link https://hub.jazz.net/tutorials/clients#installing_git

Install Node.js:The application that this post discusses is based on a Node.js based application so it will help to have it installed. Node.js is a platform that enables building of fast, scalable network applications and created by Ryan Dahl.

Kicking off Bluemix : A good first application to get moving on in Bluemix is the already available Sentiment Analysis of Twitter. This application uses the Node.js ‘sentiment’ module to perform some basic sentiment analysis.

The quickest and most painless way to get started on Bluemix is to ‘fork’ the code for Sentiment Analysis from Devops.

1) Login to your Devops account. Click the following Sentiments link from Devops, in which I have created a slight modification to the sentiment analysis application. You can also clone the code from GitHub at sentiments.

2) Click the Edit Code button at the top. This will open the files and directories in this project (see picture below)

3) Next click the “Fork’ button on the panel on the left side. This will create a copy of the above code in your own repository (see picture below )

1

4) The Twitter sentiment analysis code is in app.js written in Node.js. You can make changes to the code as needed. I have made a few modifications to the code that I had forked. I added changes which adds a textual output of the Twitter sentiment

;

How to make code changes with Web IDE

5) To make code changes double click the app.js file. This will open up the code window. You can use the GUI based IDE to make the code changes and merge with the master branch, The steps are
a) Make the necessary changes and click the symbol shown

2

3. This will open a new window as shown below

3

4) Click the ‘Stage to change’ button.

5) This will move the changes to Staged. Click the ‘Commit’ button and enter the reason for the change and click the “Submit’

4

6) This will move the changes from ‘Staged’ to ‘Commits for master branch’

7) Now click ‘Push all’ and click ‘Ok’ in the Git Push popup window. This will merge the changes into the master branch.

8) Once this done click ‘Build & Deploy’ button

9) Your changes will transition from ‘Pending’ to ‘OK’. Now click the ‘Manage’ button. This will deploy the application with the latest changes on to Bluemix.

10) Do the following to populate the details for the parameters below  with a Twitter app that you create for your application

var tweeter = new twitter({
consumer_key:  <your API key>,
consumer_secret: <your API secret>,
access_token_key:<your access token >,
access_token_secret: <your access token secret>
});

11) To do this log into http://dev.twitter.com

12) Click My applications where your picture is displayed and then click Create application.

13) Enter the details for Name,Description & Website (can be any valid website) and then click Create Twitter application.. This will create the Twitter application.

1

14) Click the API tab. Scroll down to the bottom and click “Create my access token”.

15) This will generate the Access token & Access token secret. Enter all the details (API Key, API secret, Access Token, Access Token secret into app.js and push to the master branch before deploying on Bluemix

 

Code changes with Git command line

11) Incidentally the changes to code can also be made through the Git command shell as follows

a) git clone https://hub.jazz.net/git/tvganesh/sentiments

b) Modify the code using any editor and save the changes

c) Go the directory containing the files and do

git add *

d) git commit -m “Cosmetic” app.js

e) git push

This will push the changes to the git repository in the master branch

8) Click the ‘Build & deploy’ in the top right corner. You should see this

5

9) Click the ‘Manage’ button which will push the application onto the BlueMix

10) To test this application click the link next to ‘Routes’ . Enter a phrase that you would like to search and hit ‘Go’

6

You should see the application checking Twitter periodically for the tweets.

7

Thats it! You have built your first Bluemix application.

The ability to integrate Node.js into your cloud application allows one to easily create powerful applications.

Hasta la vista! I’ll be back!

Disclaimer: This article represents the author’s viewpoint only and doesn’t necessarily represent IBM’s positions, strategies or opinions

Find me on Google+

A method to crowd source pothole marking on (Indian) roads

In, India, roads and potholes are 2 sides of the same coin! You cannot think of one in exclusion of another. This post of mine looks at a novel technique of rapidly identifying & marking potholes in (Indian) roads. This approach can be used for any city in the world but is very pertinent to Indian roads.

This idea of mine provides a technique of quickly marking pothole in roads through the method of crowd sourcing

 

Introduction: It is a well known fact that Indian roads are riddled with potholes. Some may even say that there are potholes with patches of road in between them. This disclosure looks at a novel technique of rapidly identifying & marking potholes in (Indian) roads. The approach can be used for any city in the world. However this disclosure will focus on Indian roads. This disclosure proposes a novel technique of crowd-sourcing the marking of potholes on roads rather than having any single government body (NHAI etc) travel on roads to make the markings.

Description: This post proposes a novel crowd-sourced method for pothole marking that will be easy to conduct and extremely rapid The crowd-sourced pothole marking application will be made of the following components namely Pot-hole marking app, Backend server, Map Matching utility, Pothole ranking utility.

Pothole marking App: A location based smartphone app will need to be created preferably both on Android and iOS. The app will display the map with buttons to mark the following

a)   Points in map of potholes

b)   Bad segments of roads with potholes

Backend Server: The backend server will collect all the data (marked potholes) and bad segments of roads and will update a database.  A map-matching utility will map the latitude, longitude of the marked point on to a map. When the geographical location of a pothole is received (latitude, longitude) the backend server will also store the time stamp.

Pothole ranker: This module will run on a periodical basis, say once every 3 minutes. This module will determine all the potholes that have been entered in the last 3 minutes and add to the accumulated count of marked potholes. Each marked pothole will hold the count of the marks and also the time stamp of the mark. It will also rank the criticality of the pothole based on the accumulated count of potholes over the period.

The pothole ranker will maintain the following metrics

  1. Pothole criticality = Total accumulated count/ Total time
  2. Pothole impact measure = Max rate of pothole marks (Pothole marks/hr)
  3. Bad stretches of roads with many potholes =

Number of adjacent potholes/ Distance in meters

cs

Description: This how the scheme will work in practice. The app will be uploaded into Google Play and Apple’s App store.  All users who would like to participate in the pothole marking exercise can download and install the app on their smart phones. These users when they are traveling on a road can mark potholes as they encounter them. It is assumed that the users are passengers in vehicles or pillion riders. The fact that users all over the city can simultaneously mark potholes as they encounter them will make the gathering of pothole data rapid and extremely accurate. A map of a city would need to be generated with the circles/points for locations of potholes, color-coded appropriately. We could use the color red for higher ranked potholes and yellow for lower ranked potholes with intermediate colors like purple, pink etc.  This data can then be used by Government bodies in addressing roads in fixing the roads.

There are three advantages of crowd sourcing the pothole marking

1)   The process of gathering data is rapid

2)   Roads where the traffic is heaviest will have potholes with a higher rank and can be addressed first

3)   The process will be very accurate

Crowd sourcing of pothole marking will have the following benefits

  1. The marking of potholes will be extremely rapid
  2. The potholes will be ranked based on accumulated count
  3. Ranking of potholes can be done on

– Total accumulated count/Total time

– Rate of pothole mark

– Critical segments with major potholes

4. It will be easy to segregate

– Critical potholes
– Max impactful potholes
– Bad road segment

  1. The process will be very accurate

Conclusion: The process of crowd sourcing pothole marking of Indian roads will be extremely efficient in marking potholes and bringing it to the attention of the Government.

A map of a city with the circles for locations of potholes, color-coded appropriately, to indicate higher marked potholes versus the lower ranked potholes could be generated. This map can be used to bring to the attention of the government the really bad roads and terrible road segments. Rather than having a couple of vehicles trying to ply roads and mark roads this will be very fast and extremely accurate.

Afterword: The concept of crowd sourcing for traffic is not new. Waze, which Google bought for close to $2bn does just that. It crowd sources traffic conditions and alerts users of the app. Also I did a Google search on using mobile apps for potholes marking and, not surprisingly, there were others who had also thought of a similar idea in Boston & Florida see the links below

  1. http://www.cityofboston.gov/doit/apps/citizensconnect.asp
  2. http://dailycrowdsource.com/20-resources/projects/421-crowdsourced-pothole-database-to-track-road-repair

However, I personally think that the situation in India is different, where there are ‘roads in between potholes’ ;-). While in the above 2 cases in US, only the location of the potholes is important, my idea ranks potholes based on the accumulated count and the rate of pothole marks. These metrics can be used by the government in addressing those sections of roads where the potholes have a higher rank i.e. where the traffic is highest.

Your thoughts are welcome.

Find me on Google+

Simulating a Web Joint in Android

a (1) I got interested in this demo after I saw the Java demo of Box2D physics in Jbox (look in Joints). Moreover my interest in this demo was heightened as the Disney game ‘Cut the rope’ possibly uses some elements of a web joint.

Take a look at the simulation Simulating a Web Joint in Android on Youtube
You can clone the entire project from GitHub at WebJoint

The first task was to create & place Animated Sprites(face) at the corners of a rectangle. I also added distance Joints between them.

Vector2 v1 = new Vector2(p1[0]/PIXEL_TO_METER_RATIO_DEFAULT,p1[1]/PIXEL_TO_METER_RATIO_DEFAULT);

Vector2 v2 = new Vector2(p2[0]/PIXEL_TO_METER_RATIO_DEFAULT,p2[1]/PIXEL_TO_METER_RATIO_DEFAULT);

distanceJoint.initialize(body1, body2, v1, v2);

distanceJoint.collideConnected = true;

distanceJoint.dampingRatio = 1.0f;

distanceJoint.frequencyHz = 10.0f;

this.mPhysicsWorld.createJoint(distanceJoint);

}

I also had to draw connecting lines to represent the joints between the faces The challenge is to update these lines in real time as the bodies oscillate about their mean based on the damping constant. Fortunately I had done this in of my earlier demos “Creating a blob with an attitude”. The key to this is to update the connecting line to the attached bodies through the onUpdate method

@Override

publicvoid onUpdate(finalfloat pSecondsElapsed) {

super.onUpdate(pSecondsElapsed);

if(connectionLine != null)

connectionLine.setPosition(faceA.getX(),faceA.getY(),faceB.getX(),faceB.getY());

}

}

While the Animated Sprites are dynamic bodies I also created 4 pegs (static bodies) that attach to these 4 animated sprites which are suspended in a rectangle formation.

I also added a onAreaTouch listener to enable me to remove bodies interactively. This is a deviation from the demo where the user has to press a key which will remove the bodies in a pre-determined fashin.

To remove the bodies using onAreaTouch was a challenge. So when I remove an Animated Sprite I have to

  1. Remove all connecting lines to the body

  2. Destroy all the joints between the body and other bodies

TO remove the connecting lines I first tried the following

private void removeFace(AnimatedSprite face) {

if(connectionLine1 != null && connectionLine1.collidesWith(face)){

this.mScene.detachChild(connectionLine1);

connectionLine1.dispose();

connectionLine1 = null;

}

if(connectionLine2 != null && connectionLine2.collidesWith(face)){

..

But this did not quite work and it would remove only some of the lines. Then I changed it as follows based on the animated sprite that is being removed in which I specifically remove the connecting lines

if(face.equals(face1)){

Log.d(“Yes”,“Yes”);

destroyLine(connectionLine1);

destroyLine(connectionLine4);

destroyLine(connectionLine5);

}

where destroyLine() is as follow

if(line.isDisposed() == true)

return;

this.mScene.detachChild(line);

final PhysicsConnector linePhysicsConnector= this.mPhysicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(line);

this.mPhysicsWorld.unregisterPhysicsConnector(linePhysicsConnector);

line.dispose();

line = null;

}

To destroy all the distance joints which the bodies has we have to iterate through all of the joints as follows

// Determine all joints connected to Animated Sprite & destroy

ArrayList<JointEdge> jointsEdge = facePhysicsConnector.getBody().getJointList();

for(int i=0; i < jointsEdge.size(); i++){

Joint j = jointsEdge.get(i).joint;

this.mPhysicsWorld.destroyJoint(j);

j=null;

}

Finally the face is removed as follows

this.mPhysicsWorld.unregisterPhysicsConnector(facePhysicsConnector);

this.mPhysicsWorld.destroyBody(facePhysicsConnector.getBody());

this.mScene.unregisterTouchArea(face);

this.mScene.detachChild(face);

Anyway occasionally I do get a SIGSEGV in update thread if I remove face as follows lower right, lower left, upper left. Some orders work well for e.g. Upper left, lower left, lower right etc.

If you figure out what I am missing do let me know.

Take a look at the simulation Simulating a Web Joint in Android

You can clone the entire project from GitHub at WebJoint

Find me on Google+

The making of Total Control Android game

tc-1This game of Total Control was one of those games I played when I was a kid when there were no Smartphone or iPods. It was a simple, circular toy with small balls which you had to slowly nudge to the innermost circle. I have been wanting to replicate this game on Android for some time.

The game can be  downloaded from Google Play at Total Control
The Total Control project can be cloned from Git Hub at Total Control

I had decided to use AndEngine & Box2D physics for this. I was under the assumption that creating those concentric circles would be a breeze with AndEngine and Box2D physics. However it took me some time to figure out how to create these circles. Eventually I realized that each circle could be created by computing the circumference of the concentric circle and placing tiny circle bodies. Each of these tiny circles are of type BodyType.StaticBody. So they have physical properties of a ring on which other bodies can roll. With this solved the rest of the implementation was quite straight forward.
– Small colored balls were placed in different spots in the concentric circles.
– Small gaps were created like the real game to move to an inner circle

Finally the whole game uses the Accelaration Sensor and uses Gravity for movement of the balls much like the real game.

tc-2

I also wanted to include AdMob into the game. Here is a good link at WikiHow with all the steps for adding AdMob to your app.

However the above link provides a method of placing the Ad in your desired layout’s XML file. Since my game was based on AndEngine the method to place an Ad in the game uses the FrameLayout. The complete code is given here the AndEngine Forum. To test the working of the Ads make sure you add the code

// REQUEST an ad (Test ad) //
AdRequest adRequest = new AdRequest();
adRequest.addTestDevice(“<Your device Id from the Console”); //Comment this line when publishing
adView.loadAd(adRequest);

You should get your device id when your run your application in Eclipse in the Console tab. When you run the app you should see the Ad. You may have to adjust your app to allow for teh Ad. I had to move and shrink my Game to allow for the Ad display at the bottom.

You can download the game from Google Play at Total Control
The Total Control project can be cloned from Git Hub at Total Control

Find me on Google+

Blob with an attitude in Android

DSC00044This post is an enhanced version of my earlier blob post Creating a blob in Android with Box2D physics engine and AndEngine.. To introduce tautness to the overall blob structure I used revoluteJoint between adjacent bodies as follows

}

// Create a revoluteJoint between adjacent bodies – Lacks stiffness

for( int i = 1; i < nBodies; i++ ) {

final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(circleBody[i], circleBody[i-1], circleBody[i].getWorldCenter());

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

}

// Create a revolute joint between first and last bodies

final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();

revoluteJointDef.initialize(circleBody[0], circleBody[19], circleBody[0].getWorldCenter());

revoluteJointDef.enableMotor = false;

revoluteJointDef.motorSpeed = 0;

revoluteJointDef.maxMotorTorque = 0;

this.mPhysicsWorld.createJoint(revoluteJointDef);

The motorSpeed, maxMotorTorque is set to 0 and the enableMotor is set to false. However I found that this joint still lacks stiffness.

So I replaced the revoluteJoint with the weldJoint which is probably more appropriate

// Create a weldJoint between adjacent bodies – Weld Joint has more stiffness

for( int i = 1; i < nBodies; i++ ) {

final WeldJointDef weldJointDef = new WeldJointDef();

weldJointDef.initialize(circleBody[i], circleBody[i-1], circleBody[i].getWorldCenter());

this.mPhysicsWorld.createJoint(weldJointDef);

}

// Create a weld joint between first and last bodies

final WeldJointDef weldJointDef = new WeldJointDef();

weldJointDef.initialize(circleBody[0], circleBody[19], circleBody[0].getWorldCenter());

this.mPhysicsWorld.createJoint(weldJointDef);

Here are clips of the the Blob with more attitude

Blob with attitude – Part 1

Blob with attitude – Part 2

You can clone the project from Github at Blob_v1

Find me on Google+

Bull in a china shop – Behind the scenes in Android

DSC00032Here are the details about how I constructed the “Bull in a china shop” demo. For this demo I used Box2D physics engine and AndEngine to make the demo. I decided to use sprites for the china shop and picked up images of glasses, wine glasses, bottles etc from www.openclipart.org.

Be extremely careful when creating the TextureRegion using BitmapTextureAtlas. If you don’t get the co-ordinates right the display can be weird.

Here are 2 clips of Bull in a China Shop demo
1.Bull in a china shop in Moon’s gravity
2.Bull in a china shop in Earth’s gravity
The code for this can be cloned  from Github from Bulldozed

Here is a snippet of this

this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.getTextureManager(), 556, 246, TextureOptions.BILINEAR);
this.mTumblerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "tumblr.png", 0, 0);
this.mBitmapTextureAtlas.load();
this.mBottleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "bottle.png",20, 29);
this.mBitmapTextureAtlas.load();
this.mGlassTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "glass.png",36, 69);
this.mBitmapTextureAtlas.load();
this.mVaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "vase.png",56, 89);
this.mBitmapTextureAtlas.load();
...
...

This is very important to get right otherwise you are setting yourself for a lot of grief.

Superficially the demo looks real easy. It appears that creating a pyramid stack should be a breeze as long as you get the coordinates right. Wrong! Building a pyramid using Box2D with the effect of gravity can be a real challenge as I found out. I would build two stacks and the stack would become unstable and collapse.

Anyway here are the findings

  1. Each row is not placed directly over the object below. I leave a gap of 2 px between them The reason is the object below exerts a force ‘F’ upward. The object above exerts a force ‘mg” below and the physics engine tries to resolve this difference in forces and causes instability in the structure. So the key is a to leave a small gap in between
  2. Now that there is a gap between 2 rows the coefficient of restitution ‘e’ is made 0. Even a value as small as 0.1f can make the objects jitter and cause instability.
  3. The friction between the platform and the objects or the objects themselves is made maximum equal to 1.0f to prevent sliding of the objects.

// Add tumblers
for(int i=0; i < 21; i++) {
tumbler = new Sprite(80 + i * 25, 450, this.mTumblerTextureRegion, this.getVertexBufferObjectManager());
FIXTURE_DEF = PhysicsFactory.createFixtureDef(1f, 0.0f, 1f);
tumblerBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, tumbler, BodyType.DynamicBody, FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(tumbler, tumblerBody, true, true));
this.mScene.attachChild(tumbler);
}

// Add glasses
for(int i=0; i < 14; i++) {
glass = new Sprite(130 + i * 25, 428, this.mGlassTextureRegion, this.getVertexBufferObjectManager());
FIXTURE_DEF = PhysicsFactory.createFixtureDef(1f, 0.0f, 1f);
glassBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, glass, BodyType.DynamicBody, FIXTURE_DEF);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(glass, glassBody, true, true));
this.mScene.attachChild(glass);
...
...

Hopefully if you get everything right you should have a stable structure. I had to do this through trial and error before I got it finally right. Whew!

Once you get a stable structure with the proper sprites in place most of the problem is solved. For the last part I add a bull sprite and set it off at a velocity from the point of touch.

bull = new Sprite(pX, pY, this.mBullTextureRegion, this.getVertexBufferObjectManager());
FIXTURE_DEF = PhysicsFactory.createFixtureDef(25f, 0.0f, 1f);
Log.d("here","here");
bullBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, bull, BodyType.DynamicBody, FIXTURE_DEF);
if(pX > 360)
bullBody.setLinearVelocity(-5,-5);
else
bullBody.setLinearVelocity(5,5);

DSC00031

Note: Since the sprites are not regular shapes I had to use a box shape. So the collisions are not pixel perfect.
Make sure you set up your project properly in Eclipse. The important settings are
Project->Properties->Android->Android4.2
Project->Properties->Java Compiler: Check the “Enable project specific setting” and also set compiler compliance level to 1.6
Finally click Project->Properties->Android: Under Library click ‘Add’ and add AndEngine and AndEnginePhysicsBox2DExtension
and you are good to go.

Here are 2 clips of Bull in a China Shop demo

1.Bull in a china shop in Earth’s gravity

2.Bull in a china shop in Moon’s gravity

You can clone the project from Github from Bulldozed

Have fun …

Other cool simulations using AndEngine & Box2D
1. Simulating the domino effect using Box2D and AndEngine
2. The making of Total Control Android game
3. Simulating a Web Joint in Android
4. Modeling a Car in Android
5. A closer look at “Robot horse on a Trot! in Android”

Find me on Google+

Simulating the domino effect in Android using Box2D and AndEngine

In this post I describe the steps to create a domino effect in Android. I have used Box 2D which is a physics game engine and AndEngine. The simulation is based on a demo in Java by Daniel Murphy in his site http://www.jbox2d.org/. There is a great tutorial on Box2D at http://www.iforce2d.net/b2dtut/introduction. Box2D is a really powerful 2D physics engine with collision detection, friction and restitution and all the good things of nature.

In this post I deal with some of the basic concepts of Box2D engine. At the most basic level is the ‘Body’. A body has linear,angular velocity,mass, location etc. It is then assigned a ‘shape’ which can be circle or polygon and finally we have assign the bodies to fixtures which carry properties of friction, restitution, density (density x area = mass), etc.

Finally all bodies are part of the ‘world’.
You can take a look at the domino effect in the video clip –  domino clip
The entire project can be cloned from GitHub at Dominoes

So for the domino effect I create floor,roof,left and right walls which are the shapes

//Create the floor

final VertexBufferObjectManager vertexBufferObjectManager = this.getVertexBufferObjectManager();

final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT – 2, CAMERA_WIDTH, 2, vertexBufferObjectManager);

final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager);

final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);

final Rectangle right = new Rectangle(CAMERA_WIDTH – 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager);

The body with the fixture is

final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);

PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);

PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);

PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);

PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);

Similarly I create 3 platforms on which I array vertical bricks.

The shape is created by creating a sprite.

platform1 = new Sprite(50, 100, this.mPlatformTextureRegion, this.getVertexBufferObjectManager());

The platform body is created as follows

platformBody1 = PhysicsFactory.createBoxBody(this.mPhysicsWorld, platform1, BodyType.StaticBody, FIXTURE_DEF);

The FIXTURE_DEF is the fixture which is defined as

privatestaticfinal FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(50f, 0.1f, 0.5f);

where the parameters 50f,0.1f,0,5f correspond to density, coefficient of restitution and friction.

The platform is then added to the scene

this.mScene.attachChild(platform1);

I stack 37 vertical bricks on the platform

// Create 37 bricks

for(int i=0; i < 37; i++) {

brick = new Sprite(50 + i * 15, 50, this.mBrickTextureRegion, this.getVertexBufferObjectManager());

brickBody = PhysicsFactory.createBoxBody(this.mPhysicsWorld, brick, BodyType.DynamicBody, FIXTURE_DEF);

this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(brick, brickBody, true, true));

this.mScene.attachChild(brick);

brick.setUserData(brickBody);

}

I tilt the first few bricks to create the domino effect as follows

float angle = brickBody.getAngle();

Log.d(“Angle”,“angle:”+ angle);

// Tilt first 4 bricks

if (i == 0 || i == 1 || i == 2 || i == 3 || i == 4) {

brickBody.setTransform(120/PIXEL_TO_METER_RATIO_DEFAULT,80/PIXEL_TO_METER_RATIO_DEFAULT,(65 – (i*10)) * DEGTORAD);

}

Note: The PIXEL_TO_METER_RATIO_DEFAULT which divides the units.

I tried to make the end of the domino effect in the 1st platform trigger the domino effect in the 2nd which would trigger in the 3rd. However I could not make it happen consistently. So I trigger the domino effect in each of the 3 platforms by tilting the first few bricks.

Anyway it was good fun.

You can take a look at the domino effect in the domino clip

The entire project can be cloned from Dominoes

Take a look at some cool simulations using AndEngine & Box2D
1. Bull in a china shop – Behind the scenes in android
2. Creating a blob in Android using  Box2D physics Engine & AndEngine
3. The making of Total Control Android game
4. Simulating an Edge Shape in Android
5. Simulating a Web Joint in Android
6. Modeling a Car in Android
7. Fun simulation of a Chain in Android
8. “Is it animal? Is it an insect?” in Android
Find me on Google+

A Github Primer

This post gives some of the basic commands to get started on Git Hub. GitHub is the Open source source code management system that enables anybody to share code, projects, and work on other open source projects. The beauty of GitHub lies in its simplicity. A very good tutorial is given at Git Reference

I found that the using Git Hub on Linux command line is extremely simple and straight forward. This article gives the steps to push your project on to the Git Hub repository hosted on the web.

1) To get started create a GitHub account at https://github.com. Sign up for an account with your details.

2) On the GitHub page create a repository. This will be the icon next to your user account with a ‘+” sign. Let’s say I create a repository called ‘unity’

3) On Fedora Linux you can install git using the following command as root

$yum install git-core

4) Once git is installed it is a good idea to set your name and your email with commands below

$ git config –global user.name ‘tvganesh’
$ git config –global user.email tvganesh.85@gmail.com

5) Change to the directory which contains your project files .
cd unity

6) Setup for git using
git init
Initialized empty Git repository in /home/tvganesh/git/unity/.git/

7) You can check that Git has been initialized as follows which will show up a .git file
ls -a
. .. .git unity

8) Check the status of the git uodate with
git status -s
?? unity/

9) Add all the files and folders in your project directory recursively to the staging area with

git add .

10) Check that all the files & folders are in the staging area by checking the status again
git status -s
A unity/.classpath
A unity/.project
A unity/.settings/org.eclipse.jdt.core.prefs
A unity/AndroidManifest.xml
A unity/bin/jarlist.cache
A unity/ic_launcher-web.png
A unity/libs/android-support-v4.jar

The A shows that the files have been added to the staging area

11) A more detailed status check is below

[tvganesh@localhost unity]$ git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
# (use “git rm –cached <file>…” to unstage)
#
# new file: unity/.classpath
# new file: unity/.project
# new file: unity/.settings/org.eclipse.jdt.core.prefs
# new file: unity/AndroidManifest.xml
# new file: unity/bin/jarlist.cache
# new file: unity/ic_launcher-web.png
# new file: unity/libs/android-support-v4.jar

12) Now commit the files to the local repository with the command below

git commit -m “Unity – Unit converter code”
[master (root-commit) aedab49] Unity – Unit converter code
39 files changed, 2068 insertions(+), 0 deletions(-)
create mode 100644 unity/.classpath
create mode 100644 unity/.project
create mode 100644 unity/.settings/org.eclipse.jdt.core.prefs
create mode 100644 unity/AndroidManifest.xml
create mode 100644 unity/bin/jarlist.cache

13) Check the status again which shows all files commmitted to the repository

git status
# On branch master
nothing to commit (working directory clean)

14) Create an alias for the remote GitHub repository
git remote add unity https://github.com/tvganesh/unity.git

15) Push your local repository to GitHub
git push unity master
Username:
Password:
Counting objects: 56, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (48/48), done.
Writing objects: 100% (56/56), 430.66 KiB, done.
Total 56 (delta 12), reused 0 (delta 0)
To https://github.com/tvganesh/unity.git
* [new branch] master -> master

Check github for update

16) If you have a README.md at Github while creating you may get the following error
To https://github.com/tvganesh/unity.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to ‘https://github.com/tvganesh/unity.git&#8217;
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes before pushing again. See the ‘Note about
fast-forwards’ section of ‘git push –help’ for details.

17) To fix this simply do

git pull unity master
git merge master

and then
git push unity master

16) Now check Git Hub you should see all your files in the repository you pushed to. You should see an exact replica

unity

17) You can clone an entire poject from GitHub using
git clone https://github.com/tvganesh/unity.git

<a href=”https://plus.google.com/103077316191161424665/?rel=author”>Find me on Google+</a>