Taking Advantage of Scala 2.8: Replacing the Builder

In Scala 2.8, using the builder pattern is no longer necessary (or the most optimal solution) in many cases, as Scala 2.8 adds support for named and default parameters.

I’ll give an example of this based on ScalaBox2D. In the Box2D object model, physics Bodies are defined mostly by a set of Fixtures, which in turn are defined by a Shape, density, friction, restitution and some other parameters.

In the Scala 2.7 version of ScalaBox2D, there were mutable fixture definitions, which were used by the engine to create the actual fixtures. The user code only worked with definitions, through an internal DSL that looked something like this (note: all code examples are simplified for clarity):

body {
  box(halfWidth, halfHeight) density 1 friction 0.3f restitution 0
  computeMassFromShapes
}

For the DSL implementation, I used simple builders which left values to defaults if not specified:

def box(halfW: Float, halfH: Float) = new FixtureBuilder(FixtureDef(PolygonDef.box(halfW, halfH)))

class FixtureBuilder(defn: FixtureDef) {
  def userData(userData: AnyRef) = { defn.userData = userData; this }
  def material(material: Material) = { defn.apply(material); this }
  def friction(friction: Float) = { defn.friction = friction; this }
  def restitution(restitution: Float) = { defn.restitution = restitution; this }
  def density(density: Float) = { defn.density = density; this }
  def filter(filter: FilterData) = { defn.filter = filter; this }
  def sensor(isSensor: Boolean) = { defn.isSensor = isSensor; this }
  def define = defn
}

The FixtureDefs are mutable mostly to simplify the builder. In Scala 2.8, I can use named and default parameters, and drop some more lines of code by not having builders at all. As a bonus, I can easily make the definitions immutable.

def fixtures(fd: FixtureDef*) {...}
val fixture = FixtureDef // a shorthand to the companion object of FixtureDef
val box = BoxDef // a shorthand to a BoxDef object that creates PolygonDefs

case class FixtureDef(
  shapeDef: ShapeDef,
  /** The friction coefficient, usually in the range [0,1]. */
  friction: Float = 0.2f,
  /** The restitution (elasticity) usually in the range [0,1]. */
  restitution: Float = 0f,
  /** The density, usually in kg/m^2. */
  density: Float = 0f,
  /** A sensor collects contact information but never generates a collision response. */
  isSensor: Boolean = false,
  /** Contact filtering data. */
  filter: FilterData = FilterData.Default,
  /** Use this to store application specific fixture data. */
  userData: AnyRef = null
)

As you can see, the FixtureDef is now a case class with immutable parameters that have default values. Previously it looked very similar, but had only one parameter (ShapeDef) and all fields were mutable. The usage of the “DSL” now becomes a little bit more verbose (maybe I shouldn’t even call it a DSL any more) but I think it also becomes easier to understand for someone who knows the language but not the library, due to less moving parts and using built-in features instead of more code:

body {
  fixtures(
    fixture(box(halfWidth, halfHeight), density = 1, friction = 0.3f, restitution = 0)
  )
  computeMassFromShapes
}

Deleting code while maintaining functionality always makes me glad and this is one of those cases. I guess there may be some more complex cases where builders may still work better, but for simple things like the above example, I really like the named and default arguments feature.

Note: moving ScalaBox2D to Scala 2.8 is still a work in progress for me and there may be some further changes to this “DSL” as well.

A Simple Permission Based Security Library in Scala

I started writing a simple security library in Scala that supports permission checks similar to the java.security package, but is a lot simpler to extend or use and meant for securing application code and model objects based on user roles and permissions, not for protecting malicious code from executing. I personally like the basic concept of how the java.security.Permissions work, but that implementation is not suitable for handling user permissions for several reasons. The programming model with PAW (current code name for the library, it may change) is simple:

Extend the Permission trait in objects or case classes to define your own permissions. The Permission trait defines only one method:

def implies(that: Permission): Boolean

This is very similar to how java.security works: permissions can imply other permissions. Testing if a permission is implied is the same as testing if a user has a permission. For your own permission classes you only have to implement the implies method. But if you have simple permissions that don’t imply each other, but only themselves, you can just do this:

object MyPermission extends SimplePermission // A SimplePermission only implies itself and nothing else

Coming versions of the library may provide convenience classes or traits for hierarchically named permissions, CRUD permissions etc.

Permissions are grouped into PermissionSets, and they can be nested because PermissionSets are Permissions as well. There are two special Permission sets: AllPermissions and NoPermissions. The former can be used for “superadmin” users or during development; the latter can be used for guest users for example.

When you have defined your permissions, you need to set up a SecurityContext. JAAS integration, which gets the user Principal from JAAS, but stores permissions in a ThreadLocal, is provided with the library, but other implementations (such as Spring Security) can be plugged in. To set up the JAAS Context, you need to make sure that JAASSecurityContext is loaded, by making your code refer to it somewhere during initial setup:

init {
// You could also skip this and just use JAASSecurityContext everywhere instead of SecurityContext
JAASSecurityContext
}

You can ask SecurityContext for the current user Principal (this is still java.security.Principal) and it’s permissions. But most of the time you should need just two methods:

SecurityContext has MyPermission // SecurityContext.has(MyPermission) if you prefer

will tell you if the user has the permission or not. However, this still requires you to write an if-else statement if you want to throw an exception in case the user doesn’t have the required permissions. You can also do this:

SecurityContext mustHave MyPermission // will throw AccessControlException() if the permission is not implied

SecurityContext mustHave List(MyPermission, YourPermission) // must have both of them

Mostly, that’s it. You can write one-liners to check for user permissions and IMHO, this is in most cases superior to using Java EE annotations like @RolesAllowed("storeManager", "truckDriver", "cleaner"). You can go into details as much as required and you can put the permission checks anywhere in your code, including unmanaged objects.

I personally strongly prefer this security programming model. When I’ve had to use the Java EE role-based stuff I’ve usually had to “hack in” permissions by representing them as roles, which seems conceptually wrong. I haven’t taken a look at Spring Security for a while, but it seemed to follow a model similar to Java EE when I last tried it (years ago).

Of course, my library currently doesn’t cover roles or authentication. These can be handled by Spring Security, JAAS or something else, and may require custom integration work. But some of these features may also make into the PAW library in the future.

Feedback about the library would be greatly appreciated. Go a head and take a look at the sources at GitHub, it’s only about 250 lines of code currently, half of which are ScalaDoc comments. The sources and binaries are also available in my Maven repo.

PS. One thing to consider is this: the implication of Permissions is not transitive by default. i.e. A implies B, B implies C does not mean A implies C. When you test: SecurityContext has C, but the user has only A, an instance of B may not even exist. A.implies(that) is coded so that if the argument is B, it will return true, but there is no way to ask A for a list of all permissions it implies and if it does not directly imply C, then C is simply not implied. Can you think of a good solution for this?

Baseline Eclipse for Java Game Development?

The Eclipse IDE as it is offered for download at eclipse.org has become quite large. Size in bytes is probably not the biggest issue, but I think some of the functionality showing up in the UI is unnecessary clutter for many purposes that Eclipse could be used for. One such purpose I’m personally interested in is game development on the Java Platform (using Scala, Java, or another JVM language).

Some Java game development tools are already being built as Eclipse plug-ins and most likely more will be in the future. But right now they must provide them as a plug-in for an existing Eclipse installation that has all the clutter or build a completely custom Eclipse-based application, possibly an RCP app that doesn’t even include the Java Tools. I think this shouldn’t have to be the case: users of Java game dev tools should be able to download a version of Eclipse that is freed (as much as possible) from the cruft that they will not need, and be able to install specific tools and engine specific libraries into that baseline game development environment.

So I’m thinking of creating a lighter distribution of Eclipse JDT + XML tools that removes rarely used features from the Eclipse for Java Developers distribution and is specifically geared towards game development rather than enterprise Java or application development. Perhaps this should also extend to C/C++, but I am not familiar with the CDT so I’m not considering that aspect right now.

This distribution shouldn’t come from eclipse.org of course, but rather from the open source game engine and tools developers. I am willing to work on such a project, as long as it provides actual value to game developers and doesn’t eat up too much of my time. The first version of it could be fairly basic, just a lighter distro of Eclipse. Later versions can start incorporating game dev specific tools and UI concepts. Is there anyone interested in contributing to such a project? Or using such a build of Eclipse? Please let me know.

The first step of the project should be to create a reduced version of Eclipse JDT + XML tools that is still updateable, so that game development plug-ins and plug-ins such as Scala IDE, M2Eclipse, Subclipse, EGit can be installed. I have done some initial experiments and found an approximate list of features that can be easily removed from Eclipse JDT. If you would be interested in using such a distribution, please comment what you would like to be kept:

  • APT or Annotation Processing Tool support — I think this is very rarely used and just clutters the UI in some screens.
  • Ant support — I think a lot of people would be against this, so it should probably stay
  • CVS support — CVS should not be used by anyone for other than legacy reasons, now that we have Git, Mercurial, SVN etc. And I expect that games development will not involve much poking around in legacy repositories. I think most open source game tools use SVN (correct me if I’m wrong).
  • Help — this is debatable, but I would remove it from the first version and decide later what to do with it
  • Welcome screen — same as help, can be added back later if it’s found to have some use
  • JUnit3 support — JUnit4 should be enough, I think
  • Various internal tools and plug-ins, backwards compatibility stuff

I’m estimating that the size of this distro would be somewhere between 50-70 MB. The P2 update manager included in Eclipse will increase the size on disk though, because it may create a lot of meta data and caches. But disk space is relatively cheap, and I don’t think there’s a better update manager available. My main concern is removing UI clutter so that game dev tools that plug into it will have more UI space and better visibility. Compared to the Eclipse IDE for Java Developers distribution, which lists the following “features” (feature in Eclipse terms is a collection of plug-ins):

  • org.eclipse.cvs
  • org.eclipse.epp.usagedata.feature
  • org.eclipse.equinox.p2.user.ui
  • org.eclipse.help
  • org.eclipse.jdt
  • org.eclipse.mylyn.bugzilla_feature
  • org.eclipse.mylyn.context_feature
  • org.eclipse.mylyn.ide_feature
  • org.eclipse.mylyn.java_feature
  • org.eclipse.mylyn.wikitext_feature
  • org.eclipse.mylyn_feature
  • org.eclipse.platform
  • org.eclipse.rcp
  • org.eclipse.wst.xml_ui.feature

Only these would remain (and even those not in complete form):

  • org.eclipse.equinox.p2.user.ui (this is the update manager)
  • org.eclipse.jdt (custom lite version with APT and maybe a couple of more small things removed)
  • org.eclipse.platform (custom, with various plug-ins removed)
  • org.eclipse.rcp
  • org.eclipse.wst.xml_ui.feature (possibly custom with a couple of plug-ins removed)

Later versions could add optional updates that bundle engine-specific tools and libraries, Scala, SVN, Mercurial, Git or Maven support etc.

What do you think? Is there need for such an Eclipse distribution? I’m especially interested of the opinion of Eclipse based game tool developers, if any of you happen to read this post. Would you contribute if someone does the initial work? Has someone already done something like this (not engine specific)?

Call to JVM library developers: upload sources to Maven repos

I wish all developers that release libraries for the JVM platform (Java, Scala and other libraries) and put their libraries on Maven repos would also put the sources there. It makes it so much easier to get sources automatically attached in an IDE without going digging for them. Maven doesn’t do this by default, but building (and deploying) the sources Jar along with the binary Jar should be a matter of adding these settings to your library’s POM (or better yet, to a parent POM if you use a parent which defines commons settings).

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-source-plugin</artifactId>
  <executions>
    <execution>
      <id>attach-sources</id>
      <goals>
         <goal>jar</goal>
      </goals>
    </execution>
  </executions>
</plugin>

P2 Still Not Awesome

P2 has surely seen a lot of improvement in Eclipse 3.5, but some functionality that was actually somewhat acceptable in the old Update Manager is still lacking awesomeness. I’m trying to install VE into Galileo (Eclipse for Java + M2Eclipse + Subclipse + Scala IDE).

There are two usability issues with this. The first is that after selecting the “Visual Editor” feature from the site, I don’t have a “select dependencies” option. But from past usage of VE I remember that it requires Java EMF Model. So I select that too. A new user would not know to select this. I’ll have to navigate to the next page to find out if there are unresolved dependencies. And then we come to the second problem, which is this screen:

P2 unresolved dependencies

Am I really supposed to decipher this text and take action based on that? No thanks, I’ll just skip installing VE this time, I don’t have actual need for it right now.

ScalaBox2D is getting SVG support

ScalaBox2D is going to get an SVG scene importer soon. This will let you draw a scene in Inkscape and load it as a Box2D world in ScalaBox2D. I already pushed a very basic version of this to GitHub. It uses Slick‘s SVG parser and has many limitations as of now, but you can already draw a Scene like this:

SVG Drawing

Inkscape SVG drawing

And bring it to life in a ScalaBox2D application:

ScalaBox2D Scene

ScalaBox2D scene

Currently every circle, box or polygon that has a red (#ff0000) fill will be turned into a dynamic body, the rest will be static bodies. There are also some limitations to the shapes, including: polygons must be convex, and have at most 8 vertices (or they’ll become static edges). Ellipses/arcs are not supported, only circles. You may get exceptions when loading some shapes.

The goal right now is to make this as robust as possible, so you can run the ScalaBox2D testbed and load (almost) any SVG file saved by Inkscape into it. After that, I’ll add support for loading scenes from game code and tying the physical bodies to game objects.

The code for the app looks like this:

import org.villane.box2d.svg._
import org.villane.box2d.draw.DrawFlags._
import org.villane.box2d.testbed.slick._

object SVGApp {
  val scale = 15

  def main(args: Array[String]) {
    val loader = new SlickSVGSceneLoader("C:/drawing-1.svg", scale)
    val world = loader.create
    val flags = Shapes
    SlickDisplayWorld.runWithSimulation(world, false, flags)
  }

}