Thursday, February 25, 2010

How to create a 3D wireframe with X3D

All I wanted to do was display some lines in a 3D coordinate system to make sure everything was as it should be. That can't be hard, can it?

Well, it seems it is hard. At least, it's hard to figure out how to do it, because there aren't that many tools that will show you a 3D scene from a file you generate by hand/script.

I quickly found out about the VRML/X3D stuff. It looked ancient. Rotten. Neglected. All sad. A bunch of tutorials made me sure that I didn't want to go that route: None of the tutorials talked about how to display a line in a 3D scene. Instead, it seemed VRML was all about showing shapes: Boxes, cylinders, spheres and stuff like that.

Ugh! Ok. I guess I could just draw really thin boxes and call them lines. But it just gets worse: All shapes are defined in distinces from an origin - so your sphere has a radius. That's it. It is stuck at [0, 0, 0]. But you then translate your shape to where you want it to go. Move it around, rotate it. Etc.

Argh! I had all these nice 3D coordinates for my lines ready. But the docs said I would have to transform them all into this complicated scheme. Which, I am sure makes a lot of sense for 3D modelling. It's just for simple wireframe output that it seems a little bloated.

Well, It's not really that bad: X3D has an element called LineSet that lets you specify... lines! You just write a list of 3D points to the file and off you go!

So, if you are the next person to try creating a simple wireframe with X3D, you might want to have a look at this stub file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE X3D PUBLIC "ISO//Web3D//DTD X3D 3.0//EN"
  "http://www.web3d.org/specifications/x3d-3.0.dtd">
<X3D profile="Immersive" >
  <Scene>

    <Transform>
      <Shape>
        <LineSet vertexCount="5">
            <Coordinate point="1 0 0
                               1 1 0
                               0 1 0
                               0 0 0
                               1 0 0"
                               />
        </LineSet>
    </Shape>
    <Shape>
        <LineSet vertexCount="5">
            <Coordinate point="1 0 1
                               1 1 1
                               0 1 1
                               0 0 1
                               1 0 1"
                               />
        </LineSet>
    </Shape>
    <Shape>
        <LineSet vertexCount="5">
            <Coordinate point="0 0 1
                               1 0 1
                               1 0 0
                               0 0 0
                               0 0 1"
                               />
        </LineSet>
    </Shape>
    <Shape>
        <LineSet vertexCount="5">
            <Coordinate point="0 1 1
                               1 1 1
                               1 1 0
                               0 1 0
                               0 1 1"
                               />
        </LineSet>
      </Shape>
    </Transform>
  </Scene>
</X3D>


This will create a simple 1x1x1 cube. You can view this with an X3D browser. I used FreeWRL. It is supposed to be only for OSX and Linux, but they do have a windows binary that sort of works. At least for my purposes it is really enough. The other browsers out there (ones that also act as web browser plugins) seem scammy. They let you download a "test" version. What does that meen? Is this a trial version? Do I have to buy it? Where? How much?

So, here is a screenshot of FreeWRL rendering the X3D file above:
I rotated the cube a bit (this is the nice thing about having a dedicated browser - try writing your own!) to make it more recognizable.

Friday, February 5, 2010

Where are all the posts I promised?

Why oh why have I not delivered on my promise to post neat stuff you can do with RevitPythonShell? Well, what exactly would you want to do with it? I use this tool to scratch an itch - automate a plugin I am writing. I mainly use the Interactive button and type away at the prompt. I also have some canned scripts I like to use, but I'm not sure if posting them here would make a lot of sense: They are very specific to the plugin. But I'll show a little bit, just for the curious among you:

Python 2.5.0 () on cli
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> apps = [a for a in __revit__.LoadedApplications if 'DpvApplication' in str(a)]
>>> dpv = apps[0]
>>> dir(dpv)
['ActiveDocument', 'Calculators', 'GetHistory', 'OnShutdown', 'OnStartup', 'Result', 'TakeSnapshot', '__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__']
>>> dpv.TakeSnapshot()
>>> snapshot = dpv.GetHistory(dpv.ActiveDocument).CurrentSnapshot
>>> for room in snapshot.Rooms:
...    print room.Area, room.Name
... 
163.14989375 Raum 1
>>> 


Right after the banner, I create a reference to my plugin. This uses the LoadedApplications collection on Autodesk.Revit.Application. As you can see, I then proceed to exercise the plugin, calling its methods (TakeSnapshot, GetHistory, ActiveDocument) etc. You can call any public methods defined in your plugin this way!

But working in the interactive shell for some period has shown some of its weaknesses. I'm busy trying to fix that, but this might still take a while - the last couple of revisions have gone in that direction (but there is no new release yet).

Since this is a tool to make exploring your (C#) plugins easier, it makes sense to customize it a bit. I have configured RevitPythonShell.xml like this:

<?xml version="1.0" encoding="UTF-8"?>
<RevitPythonShell>
  <SearchPaths>
    <!-- a list of paths to add to the engines search path -->
    <SearchPath name="C:\Python25\Lib"/>
    <SearchPath name="C:\RevitPythonShell"/>
  </SearchPaths>
  <Commands>
    <!-- a list of preconfigured commands -->
    <Command name="dumpdpvfolder" src="C:\RevitPythonShell\Commands\dpvdumpfolder.py"/>
    <Command name="read model" src="C:\RevitPythonShell\Commands\readmodel.py"/>
    <Command name="Report" src="C:\RevitPythonShell\Commands\report.py"/>
    <Command name="Interactive" src="C:\RevitPythonShell\Commands\interactive.py"/>
  </Commands>
  <DefaultScript><![CDATA[
# type in a python script to run here and click "Execute"
# you can access the Autodesk.Revit.Application object with the variable __revit__
# the default script (shown below) opens up an interactive interpreter

import code
code.interact(None, None,
  {
    '__name__' : '__console__',
    '__doc__'  : None,
    '__revit__': __revit__
  })]]></DefaultScript>
</RevitPythonShell>


Notice the Commands section: These are shortcuts to stuff I execute often. Conserved scripts that use the technique explained above to exercise the DesignPerformanceViewer plugin.

Wednesday, January 27, 2010

Name your GUIDs

Here is a little idea that came to me while waiting for my computer to become responsive again (don't ask):

Wouldn't it be really cool, if there was a name generator for GUIDs? You could submit a GUID and claim a name. That way, people could talk about GUIDs on the phone:


  • Guy on phone: I'm having problems with foobaz
  • Supporter: Oh, you want to check the registry for the GUID "PurpleRain"
  • Guy on phone: (checks up GUID via webservice)
I'll have to think some more about this... You'd want to make sure the names are easy to pronounce, easy to type and hard to get wrong. I'm sure someone has done similar stuff before.

Wednesday, December 23, 2009

Adding your plugin to the [ExternalApplications] section of Revit.ini

For the installer for RevitPythonShell, I need to programmatically add the plugin to the [ExternalApplications] section of Revit.ini. Instead of writing a one-off solution, I decided to create a little commandline tool that can be reused for my next project or even your project: addrevitplugin.exe. You can look at the source too!
The tool is written using AutoIt v3, a BASIC derivative with lots of useful functions for automating windows tasks. Expect to see some more samples of such scripts on this blog...
The commandline options to addrevitplugin.exe are:
  • EAClassName: This corresponds to the key "EAClassName#" in the Revit.ini file
  • EAAssembly: (optional) This corresponds to the key "EAAssembly#" in the Revit.ini file and is the full path to the .NET assembly containing the plugin class.
Using addrevitplugin.exe, you can either add, update or delete a plugin entry in the "ExternalApplications" section. By specifying EAClassName without EAAssembly, the corresponding plugin is deleted from Revit.ini. If EAAssembly is provided, then the plugin is either added (if it was not yet installed) or updated with the assembly.

I also use this tool in conjunction with Launchy to quickly switch between environments when developing Revit plugins: Create a batch file for each location of your plugin (Debug, Release, Installed) with contents similar to:

addrevitplugin.exe RevitPythonShell.RevitPythonShellApplication "C:\Projects\revitpythonshell\RevitPythonShell\bin\Debug\RevitPythonShell.dll"

Make sure the second argument is enclosed in double quotes if it contains spaces. Create a separate file for each environment.

I named the files debug_RevitPythonShell.bat, release_RevitPythonShell.bat and installed_RevitPythonShell.bat. By saving these files in a directory scanned by Launchy, I can quickly switch between the environments before starting Autodesk Revit Architecture 2010.

Note:If you are not using Autodesk Revit Architecture 2010 on a 32bit system, you will want to change the GUID used to look up the install path in the script addrevitplugin.au3. You will then need to recompile the script using Aut2Exe.exe, which can be obtained from the Auto It website.

Update: I have renamed addrevitplugin.exe to rac32plugin.exe and rac64plugin.exe so that now a 32-bit and a 64-bit version comes precompiled. Also, the scripts have changed somewhat. Please check the project website.

Friday, December 18, 2009

Introducing RevitPythonShell

RevitPythonShell is a little tool I built to make life in RevitAPI-land a little easier.

When writing plugins for Autodesk Revit Architecture 2010, you have to restart Revit each time you create a new build and manually click your way to the plugins functionality. If you are not so sure about how a given method or property from the API works (or what values to expect when reading it), you will end up with a lot of these edit-compile-run cycles. I don't know how fast your machine is, but starting Revit on mine is not as snappy as I would like. Plus, you can't really experiment, can you?

So, with RevitPythonShell, you can. It embeds IronPython, a .NET port of the python language as a plugin. The main window provides a simple text editor that lets you write a script and execute it. The most useful script is probably this one:

import code
code.interact(None, None, 
        {
            '__name__': '__console__', 
            '__doc__':None, 
            '__revit__': __revit__
        })


This will open up an interactive interpreter loop (known as a REPL), that will let you explore the RevitAPI. And by explore, I mean type a statement, hit enter, see the results, carry on. It doesn't get easier as this!

The above script is actually saved as a "canned command" - an button (in this case named "Interactive") in the toolbar above the main window. Canned commands like these are an ideal place to save scripts you have developed and found useful - a sort of mini-plugin-in-a-plugin architecture.

The default script shown when you start the RevitPythonShell plugin is this one:


# type in a python script to run here...
try:
  # assumes the following file exists: C:\RevitPythonShell\current.py
  import current  
  reload(current)
  
  current.main(__revit__)
except:
  import traceback
  traceback.print_exc()

It imports the module current.py from the search path (normally C:\RevitPythonShell) which contains a script you are currently working on. Clicking the button Execute (or pressing CTRL+RETURN) will execute the contents of the main window, which will in turn import the module and run its main() method.

Loading a script from the file system instead of typing it into the simple editor provided by RevitPythonShell is probably a good idea, since most editors make life a lot easier compared to the TextBox control used here - even Notepad.exe would be preferable!

Note the parameter __revit__ passed into the main method: This is a reference to the Autodesk.Revit.Application API object used by plugins to gain access to Revit.

I will be showing off some of the things you can do with RevitPythonShell in later posts.

Wednesday, December 9, 2009

Using C# extension methods for Revit Element Parameters

One of the places using C# extension methods shines is writing getters and setters for element parameters in Autodesk Revit Architecture 2010. Parameters are user defined meta data bound to either an instance or a type in Revit. Accessing these is a bit cumbersome:

public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
    var document = commandData.Application.ActiveDocument;    
    
    Parameter parameter = document.ProjectInformation.get_Parameter("BuildingCategory");
    if (parameter != null)
    {                
        var buildingCategory = parameter.AsInteger();
        // do something with this information
    }        
}

Imagine typing all that code every time you want to access your parameter in code! Of course you will wrap it up in a method, but wrapping it in an extension method allows for neat syntax:

public static int GetBuildingCategory(this ProjectInfo self)
{
        
    Parameter parameter = self.get_Parameter("BuildingCategory");
    if (parameter != null)
    {
                
        return parameter.AsInteger();
    }        
    // you could also throw an exception here...
    return 0;
}


Now, you can access the property through the element itself, and it shows up in intellisense!

int buildingCategory = document.ProjectInformation.GetBuildingCategory();

In fact, I go a step further in my project, utilizing the t4 templating engine to generate the parameter accessors as well as routines to bind them to the document from an XML file. But that will have to wait for another blog post.

Thursday, December 3, 2009

Using C# extension methods to extend plugin architectures

I've spent a lot of time recently writing a plugin for Autodesk Revit Architecture 2010. Extending Revit involves writing managed code that implements a special interface (Autodesk.Revit.IExternalApplication) that gets called by the host application when special events occur - the application starts up, one of your toolbar buttons was clicked, a document was opened / closed / saved etc.
Access to the host is provided as a parameter to the methods defined in the interface. One of the main objects of interest for the work I'm doing is the Autodesk.Revit.Document class. This is my window into Revit documents, providing information about elements in the document.
The catch: You cannot change how these objects behave, since they are provided by the host. If Autodesk.Revit.Document is missing a Rooms property that lists all the rooms in the document, well, you are out of luck.
The traditional object oriented solution to this problem is inheritance. You subclass the lacking class in question and add the desired functionality. This will not work in a plugin situation. You have no control of how Revit instantiates its document object.
You could decorate the object with new functionality: Implement the Document interface (in this case you would have to extract the interface first) and delegate all invocations to a stashed away instance received via Revit. This can fly, but its pretty ugly to do by hand - you might want to generate this.
C# 3.0 comes with a new solution to this problem: Extension Methods. Lets look at some code.
/// <summary>
/// Provides some utility methods for working with Revit.Document objects.
/// </summary>
public static class RevitDocumentExtensions
{
    /// <summary>
    /// Returns a list of all room objects in a Revit document.
    /// This excludes room
    /// </summary>
    public static IEnumerable<Room> GetRooms(this Document document)
    {
        var roomElements = new List<Element>();
        var filterFactory = document.Application.Create.Filter;
        var filter = filterFactory.NewTypeFilter(typeof(Room));
            document.get_Elements(filter, roomElements);

        // filter the rooms so only the placed ones are returned.
        return roomElements.Cast<Room>().Where(r => r.Location != null);
    }
}
Given an Autodesk.Revit.Document object, GetRooms can be called like so:
var rooms = RevitDocumentExtensions.GetRooms(document);
This is nothing new, hardly exciting, but works.
Did you notice the magic keyword this in the functions signature?
public static IEnumerable<Room> GetRooms(this Document document)
That's new. We are still talking static methods here, and that is all the .NET runtime ever sees, but the C# compiler will allow you to use this method syntactically as if it were defined in the Document class! So our usage chages to this:
var rooms = document.GetRooms();
Neat, huh? It looks as if we have subclassed Autodesk.Revit.Document and added a new instance method. Using this technique, a plugin API can be extended to better suit the needs of the plugin.
I will post more examples on how I used extension methods to augment Revit in my next post.