Thursday, 27 October 2011
The following video shows one of the Road Safety training exercises available in the Simax Road Safety simulator. It allows to practice emergency braking and obstacle avoidance on wet surfaces. The driver learns how to react depending on the presence of an ABS system or not.
Today, we have released a new video about emergency situations practice in Simax:
Description: This exercise allows the driver to practice reactions at emergency situations like water ponds on the road, accidents, trucks dropping their load, or even rocks falling. The simulator can even analyze reaction times, traveling direction progress, etc.
Hope you like it…
Thursday, 20 October 2011
Sunday, 9 October 2011
Cada vez me llama más la atención esto del Longboard… Será que me estoy haciendo abuelo.
El caso es que, cuando estuve en Nueva York este verano, me llamó mucho la atención encontrarme con esto:
Gente practicando Longboarding por medio de la quinta avenida, entre el tráfico, como si no tuviera el más mínimo peligro. Pero no uno, ni dos, ni tres… Mucha peña, como podéis apreciar en estas fotos que saqué.
Pues bien, ahora me entero que es una afición muy en auge pro allí, e incluso se reúnen todos, una vez al año, para descender toda la avenida Broadway, hasta el Battery. Es la carrera conocida como “Broadway Bomb”: un evento organizado por internet, que no cuenta con permisos de ningún tipo.
Cada año son más, y este han participado casi 1000. Realmente se juegan el pellejo, pero como en NYC no está prohibido patinar por la calle, nadie les dice gran cosa.
En la web de la organización, se solicitaba a los participantes que no se detuvieran a celebrarlo (como es tradicional) frente al toro que hay al sur de Broadway, ya que había protestas por todo Wall St. y temían que los policías se rebotaran al ver llegar a 1000 skaters por la calle.
Me parece flipante el nivel de tolerancia que hay en esta ciudad… Y para que flipéis un poco, algunos vídeos alucinantes sobre Longboarding:
1.- A más de 100 Kmh en un monopatín, adelantando a camiones por la autovía. Y para mayor alucine, al final se junta con otro pavo, que va a la misma velodidad, per…. ¡¡¡¡¡descalzo!!!!
2.- Extreme downhill championship
3.- Y como estoy abuelo, pero no tanto, otro de esos vídeos que me hacen desear tener 18 años otra vez…
Thursday, 6 October 2011
In this previous post, we already showed how to use T4 templates for several use cases, with a special focus on Resource Files (ResX). Now we are going to complete that post with another one, focused specifically on Content management.
What we want to achieve is an elegant, cross-platform, and strongly-typed way of accessing contents in our projects.
The XNA approach to contentsXNA identifies contents with Asset Names, in the form of strings, but it doesn’t offer any form of strong-typed access, what is very bug-prone, because if you misspell the name of an asset, you won’t notice until runtime, or you won’t notice ever…
The Android approach to contentsAndroid already offers strongly-typed access to contents that are placed below the “Resources” special folder. Unfortunately, there are a lot of limitations for the contents inside that folder. One of the most evident (and stupid), is that contents cannot be re-arranged into subfolders, what makes it almost un-usable for medium-big projects. Besides that, the kind of access Android gives to that folder is through INT identifiers, what conflicts with the XNA way of doing this (which uses Asset names).
One of the possible solutions is to move our contents to the “Assets” folder, where things can be arranged arbitrarily, and where assets are identified with a string, very much like in XNA. Too bad that Android doesn’t offer strongly-typed access to that folder…
What we want to achieve1.- We want to be able to arrange our contents in sub-folders, so in Android, we will have to go to the Assets approach, instead of the Resources one.
2.- That solves also the unification of types when identifying assets. In both cases (XNA and Android), we will be using Asset Names as strings.
3.- In both sides we will need to provide a strongly-typed way of accessing contents.
4.- We want the exact same interface that is finally published outwards, so that every piece of code that uses our strongly-typed classes, write the exact same code no matter which platform we are coding on.
An implementation using again T4 templatesAgain, we will write down two different T4 templates, one for XNA and one for Android. Both of them will have to do merely the same, but with some minor differences. Let’s see them:
Example: XNA T4 Template to give strongly-typed access to contentsThis template will be placed wherever we want to use it. It can be in the main XNA Game project, or in a library project shared all around. Basically, it will search inside the Visual Studio solution for the Game’s Content Project. Once found, it will iterate recursively through the file and folder structure of the project, generating classes that give strong-typed access to each Asset.
Imagine we have the following structure in our contents project:
We want to get an output like the following:
As you can see, we will use namespaces to represent the tree-structure of folders in the content project. Once we find a folder with one or more content files, we will create a class named “Keys” that will hold properties to access asset names. We will also create an enumeration with all the assets found at that level. This way, we also allow to navigate through the contents tree, if needed.
The codeThe XNA template that generates that, is the following:
UsageOne the T4 template is included on your solution, the way of accessing Assets in XNA is like the following:
Android versionOnce you have that as a start point, developing the Android version is pretty straight-forward. You just need to change a couple of things:
- Instead of searching for the Contents Project inside your solution, you will need to search for the main project, and look for the “Assets” subfolder.
- Asset names do include file extensions in Android, so be sure to not remove them (like in XNA)
- Also, asset names will need to replace ‘\’ for ‘/’, so you can correctly invoke:
stream = mContext.Assets.Open(pAssetName);
Strongly typed code rocks. Easy as that. Reduces bugs, and makes your developments more productive and efficient. We all know that.
One example of strong-typing inside Visual Studio: resource files are parsed by default with the ResXFileCodeGenerator tool, which generates automatic properties in C# files, that give us strongly-typed access to strings.
That’s cool, by I there’s a lot of customization capabilities there missing. For instance, ResXFileCodeGenerator generates internal classes by default, and this is not always desirable. Many people struggled around this in the past, so in Visual Studio 2008 a new custom tool was introduced: PublicResXFileCodeGenerator: the same one than before, but building public classes. Cool again, but still missing many things…
So, how to customize the code generation process?
Option 1: Write your own toolYou can write a tool that mimics the behavior of ResXFileCodeGenerator, and you can install it within the Visual Studio (so you can select your ResX files to be parsed with it). It´s not too complicated, but you need to develop a separate installation project, to be able to install it within VStudio. You can find an example here.
To be honest, I don´t like the idea of having to write the extension in a different project, needing to go there for every change, recompiling, re-installing, etc. Besides that, this approach means having one single tool for every resX files you want to parse, and therefor, the tool needs to be generic enough to give support for every use case you have.
One last inconvenient, is that as far as I know, a tool like this cannot act in several files at a time. That means that it will generate a code file for each resource file. It’s impossible to generate ONE code file for SEVERAL resource files.
Seems that I´m too lazy today for all of that, so I searched for other solutions, and found one that I really like: T4 templates
Option 2: Write a T4 Text TemplateA T4 Text Template is “a mixture of text blocks and control logic that generate a text file”. In other words, it’s a piece of code that will generate a text file and will include it in your Solution (below the .tt file itself). This text file, pretty well can be a source code file, so this way we can automatically generate code for the solution, with all the power to customize it.
I have been studying them for a while, and I can tell you that they are really powerful. Some relevant aspects around them:
- They are text files (with .tt extension), that are included INSIDE your solution, so no need to keep them in a separate project, and no need to build a setup project to install them.
- This .tt files are, by default, parsed by the custom tool: TextTemplatingFileGenerator
- They can operate on several project files at a time, not only one, generating if you want ONE code file, for SEVERAL resource files.
- They don´t need to be installed or distributed in any form. Simply add them to your solution
- Changes in the Template don’t mean to go to a different solution, rebuilding and re-installing
- They can be written in both C# or VisualBasic.
- When they are parsed, the generate a code file below the Template (see below), with the same name as the template itself:
- They are usually parsed as soon as they are modified and re-saved.
- Because the modification and installation process is so simple, and because you can have if you want a different T4 Template for each resX file, you can have as many versions of the templates as you wish. Each one covering different needs. And that is cool !
Any disadvantages? Visual Studio integrationBy now, Visual Studio offers no integration for T4 files. That means that by default you get no syntax highlighting, no intellisense, etc.
But this can be fixed by using one of the T4 integration extensions for VStudio out there. I have tested three of them:
- Tangible T4 Editor: Honestly, I couldn’t get it to work. I installed it, apparently with no error, but it didn’t work. And I already started this post by saying I´m too lazy today, so I tested other solutions that installed fine at first try:
- Clarius Visual T4: It installed just fine and added syntax highlighting and intellisense to T4 files. Unfortunately, it made my Visual Studio 2010 Ultimate freeze for about 10 seconds from time to time. So I decided to try a different option.
- Deviart T4: It installed fine, and works pretty well. The syntax highlighting gets messed from time to time, but nothing serious. Just re-opening the file fixes it. It’s fast, and I like it. It’s the clear winner. And it’s free!
Some basic concepts about developing T4 templatesDeveloping a T4 template is pretty straightforward, if you have some experience with .Net. We are not going to explain here all the coding aspects about T4 templates, as it is extremely clearly explained here and here.
However, it’s a bit meesy the first time you see one, how code blocks are mixed with plain text blocks, especially if you don´t have an extension installed that gives you syntax highlighting.
So, first thing you should understand is that T4 templates mix parts of text that will simply be copied to the generated file (Text Blocks), and others that are code blocks to control the logic of the generation (Code Blocks). In Deviart T4, you will see the following highlighting:
- Text blocks, copied directly to the destination file (grayed out):
As I mentioned, whatever you write here will be directly copied to the destination file. No matter what it is. It won´t be validated by the tool, just copied. You are responsible of writing something that makes sense, and that won’t generate compiling errors.
- Code blocks (surrounded by <# … #> and similar):
These code blocks are parsed by the tool and executed. They are validated by the compiler, just like any other piece of code you write (that means that will generate compiling errors as usually). In the previous example, the code block is writing a “}” symbol to the output file, using the WriteLine method (se next chapter for more info).
Different ways to output text to the destination fileWe already seen some of them, but basically, you have three different ways of outputting text:
1.- Put a Text Block in your template (like in the previous chapter).
2.- Invoke the WriteLine method inside a Code Block. Like in the example of previous chapter, anywhere you call WriteLine(“…”) from within a code block, will write that text line to the destination file.
3.- Mixing both Code Blocks and Text Blocks, like in the following example:
In this example, the header Text Block (grayed out) will only be copied if insertWarningHeader == true. This means that flow control of code blocks affect the output of plain text blocks too.
Please note that you need to “end” the Code Block by using the “#>”, and therefor the text inside the braces will be identified as a Text Block. Then, re-open a code block, just to put the final brace “}” of the IF statement. Separating it into two different Code Blocks doesn’t prevent the IF from doing its job…
Other useful kinds of Code BlocksAs you can see, the <# … #> labels define the start and end of code blocks that should be parsed and evaluated. Anything outside those labels is considered text blocks. There are other kinds of code blocks, as explained here:
- Expression code blocks (<#= … #>): They evaluate an expression, and convert the result to string. Some examples:
- <#= 2 + 3 #> … will output a “5”
- <#= numberOfEntries * 2#> … Where numberOfEntries is a valid variable on that scope, will output the result of the addition.
- Class feature code blocks (<#+ … #>): Allow to define properties or helper methods. They can be defined in separate files. The following example defines the property RootNamespace and the helper method EmitEnum, available in all the template.
- Importing namespaces is also very easy, you just need to put in the top of the file statements like the following:
Example: Custom strong-typed access to resources with a T4 template
What we needIn this example, we will used the mentioned T4 templates to give a full-featured, strong-typed access to strings in resource files. I did it to meet my own needs, but using it as a starting point, it will very easy for you to adapt it to your own.
The goal is to be able to customize the following aspects directly from the resX file:
- Access modifier of the class: public, private, internal
- Namespace where the class is defined
- Generate (if wanted), an enumeration with all the keys of the entries
- Modify the return type of the properties. Does this make any sense? Yes (read below).
- Allow ResX files to use Conditional Compilation:
- It would be fantastic if we could specify different values for strings, depending on conditional compilation symbols
- And it would be even greater, if we could specify different return types, depending on the same conditional compilation symbols.
Does it make any sense to modify return types?In my scenario, it does. I’ll explain it, so you can see one example. Then it’s up to you to decide if that’s useful also in other situations…
I was writing a piece of code, related to 3D graphics, that I wanted to run in both Windows Phone and Android. That code has contents (bitmaps, etc), which are identified differently in Windows Phone (XNA) projects, and Android.
In the first one, contents are identified with Asset Names, which are strings. In the second one, contents are identified with Integer IDs. In fact, Android automatically generates a class like the ones we are creating here to give strong-type access to those integers.
Well, I wanted to centralize the loading of contents, so it was obvious that I would need to unify content identification with my own IDs. I simply didn’t want to have #if #endif blocks all around my code.
Question is, that I can write two versions of methods like LoadTexture(), one for each platform, and keeping the specifics inside the Content Repository, but the problem is that Android identifies contents with a different type (ints instead of strings), and that makes my code end up with a different interface for each version. Something like this:
Why? Because then, every single point in my code where I use this method will need a #if #endif code block too. And I hate that. I want this contents repository to expose a single interface. How do we achieve that?
If both platforms used strings to identify contents, I could create a table to map my own resource identifiers to that ones. But Android uses ints. And what is worse, they are automatically generated. I can see what IDs Android gave to a content, but I cannot guarantee that the ID will be consistent over time, as it’s generated by an automatic tool. In addition to that, I would need to maintain that table by hand, what is horrible and very bug prone.
Seems that the only solution is writing code, with methods or properties that map my own resource IDs to: string assets in the case of XNA, and resource IDs in the case of Android. Something like:
If we are compiling to ANDROID, Button1 will return an int and LoadTextures() will expect an int, so no problem. If we are compiling to Windows Phone, both will give and expect a string. Everything fine again.
The problem with that is that a single project can have hundreds, or thousands of resources, an maintaining the file manually can be a nightmare. If only it could be done automatically…
That’s where the variable return type of my template kicks in. It will give us precisely that, with the particularity that when on ANDROID (being the return type an int), the template will not insert string, but a call to the Android Repository.
This way, I get rid of having to deal manually with Android int IDs, and just work with their strong-typed names.
See below for more…
The implementationThe behavior of the template we have developed, to achieve all of this is:
- It is designed to be placed inside your projects, just by the file it will process. It has to be in the same folder and needs to have the same name. So, if you want to process the file Textures.resx, you will end up with something like this in your solution:
- It will generate strong-typed properties to access all the strings it finds in the resX file
- It can be instructed to generate an enumerate with all the keys in the file too
- It will automatically generate the well formatted XML comments for the properties
- It supports some special keywords (entries starting by “#C#_”), to allow customizing the generation process:
- CT4_ACCESS_MODIFIERS (public, private, internal): By default, the generated class will be public, but you can include this entry to modify this behavior. You can set the following values: public, private or internal.
- CT4_OVERRIDE_NAMESPACE (namespace name): By default, the class will be in the default namespace of the project, but you can include this entry to override that behavior, setting the desired namespace in the value of the entry:
- CT4_GENERATE_ENUM (enum name): If this entry is included, the template will create an Enumeration with all the key names of the ResX file, and also an special version of the GetResourceString() method, accepting as parameter one of those enumerations. You can specify the name of the enumeration in the Value field.
- CT4_DEFAULT_RETURNTYPE (string, int, etc): Allows to specify the default return type for all properties. The default return type if string.
- CT4_CONDITIONAL_COMPILATION_SYMBOLXX (Symbol Name): Allows to use conditional compilation inside the resource files. To do so, you must first identify what conditional compilation symbols are used in your project. In this example, we will have two of them: WINDOWS_PHONE, and ANDROID. So, we will create two entries to let the generator know about them, like the following:
- CT4_CONDITIONAL_RETURNTYPE: If conditional compilation is being used, it allows to specify a different return type for each conditional symbol, with following syntax:
Once we have configured the generation process with the control entries, it’s time to put some data there. A normal string entry is entered as usual, with unique name, a value, and a comment if you want to. How to include conditional compilation entries?
Using conditional compilation in string entriesThe name and the comment of the entry are the same as in normal ones. It’s in the Value where we put the information needed, very much like when defining specific return types for each conditional compilation. The syntax is:
Will generate the following code:
The template codeThe template is based on this other one, but with a modified behavior to meet my own needs. The code is:
Et voilà ! An input and output exampleThe above template, applied to the following input:
Produces the following output class:
Other use casesThe possibilities are almost endless. You don´t need to stick to Resource Files (ResX) only. You can do this operations with almost anything. For example:
- You can write a T4 Template for a “Contents” projects, that searches for Textures or Bitmaps in the project, and generates a Class that strong-types the names and/or paths of those textures. Creating your own Content Manager.
- You can generate your own classes to give strong-type access to your Data-Sets, in a totally customized way.
- Or you can generate a class that bases it’s strong type access in an enumeration, instead properties, something like the following:
So use your imagination !!