Thursday, June 30, 2011

Wall.Orientation Property for walls based on arcs in Autodesk Revit 2011

This is what the documentation for the Wall.Orientation property in Autodesk Revit 2011 says:

The normal vector projected from the exterior side of the wall.

While this is tried and tested, it is only half of the story. I don't know the whole story, but this post is about one exception i found: Walls based on an arc.

Repro steps:

  1. create a new Revit document
  2. in the ribbon, on the "Home" tab click "Wall"
  3. in the "Draw" panel, choose the icon "Start-End-Radius Arc"
  4. create a wall by specifying the start, the end... well, you get it.

So, we now have a wall that isn't planar:

http://dl.dropbox.com/u/8112069/20110630-start-end-radius-arc.png

What is its orientation? What do you think it should be? Let's ask Revit! I'm going to use the RevitPythonShell (RPS) to query this wall, so we can see interactivly what is going on:

>>>collector = FilteredElementCollector(doc)

>>>wall = collector.OfClass(Wall).ToElements()[0]

>>>wall.Orientation

<Autodesk.Revit.DB.XYZ object at 0x000000000000002F [(-0.858104216, 0.513475563, 0.000000000)]>

I was expecting the orientation to be due North: (0, 1, 0). That is where the orientation handle bars are shown. But that is not what we get. What we get is a vector from the curve center point to the start point of the arc:

>>>curve = wall.Location.Curve

>>>P0 = curve.get_EndPoint(0)

>>>M = curve.Center

>>>Vector(P0, M)

IronTextBoxControl error: name 'Vector' is not defined
>>>XYZ(P0.X - M.X, P0.Y - M.Y, P0.Z - M.Z)

<Autodesk.Revit.DB.XYZ object at 0x0000000000000030 [(-34.284776903, 20.515451146, 0.000000000)]>
>>>r = XYZ(P0.X - M.X, P0.Y - M.Y, P0.Z - M.Z)

>>>r.Normalize()

<Autodesk.Revit.DB.XYZ object at 0x0000000000000031 [(-0.858104216, 0.513475563, 0.000000000)]>
>>>

As you can see, the orientation has the same direction as a vector from the arc center to the start point of the arc. This is for walls that face away from the arc center. Let's flip the wall and see what happens:

>>>t.Start()

<Autodesk.Revit.DB.TransactionStatus object at 0x0000000000000032 [Started]>
>>>wall.flip()

>>>t.Commit()

<Autodesk.Revit.DB.TransactionStatus object at 0x0000000000000033 [Committed]>
>>>wall.Orientation

<Autodesk.Revit.DB.XYZ object at 0x0000000000000034 [(0.858104216, -0.513475563, 0.000000000)]>
>>>

As you see, the vector changed it's orientation too. So, for arcs with wall orientation facing the arc center, the Wall.Orientation property is the normalized vector from the arc start point to the arc center.

Friday, May 27, 2011

Which of the parameters on the ProjectInfo are built in?

Yesterday I needed to know which of the ProjectInfo parameters are actually built in and can be relied on to be found in any Autodesk Revit Architecture document. Of course I fired up RPS and had a go at finding a solution. Here is what I came up with:

import clr
clr.AddReference('RevitAPI')
clr.AddReference('mscorlib')
from Autodesk.Revit.DB import *
from System import Enum

doc = __revit__.ActiveUIDocument.Document
pi = doc.ProjectInformation
params = list(pi.Parameters)
builtInParameterIds = set([p.Id.IntegerValue for p in params if p.Id.IntegerValue < 0])
for id in builtInParameterIds:
    parameter = pi.get_Parameter(Enum.ToObject(BuiltInParameter, id))
    name = Enum.GetName(BuiltInParameter, id)
    if parameter:
        print name, ': ', parameter.AsString()
    else:
        print name, ': <NULL>'

There are some aspects of this script I'd like to point out, since they might help you writing your own scripts:

This gives you access to the System.Enum type. The BuiltInParameter enumeration has to be marshalled back and forth to IronPython integers using Enum:

  • Enum.ToObject(BuiltInParameter, id) returns the enum constant that has the integer value id
  • Enum.GetName(BuiltInParameter, id) returns the name of the enum constant (handy for printing to the user)

Also note that all the predefined parameters in Revit have negative ids - that is how we find them:

The output on a test project on my computer is:

PROJECT_ISSUE_DATE :  Projekt Datum
GBXML_EDIT_DATA_PARAM : <NULL>
PROJECT_STATUS :  Projekt  Status
CLIENT_NAME :  Bauherr
PROJECT_ADDRESS :  Projektadresse
PROJECT_NAME :  Projekt Name
PROJECT_NUMBER :  01212

Thursday, May 19, 2011

Adding both 32 and 64 bit versions of DLLs to a Visual Studio 2010 Setup project

I ran into a snag, when trying to create an installer using a Visual Studio 2010 Setup project that would install for 32 and 64 bit versions of Autodesk Revit Architecture. Since my program depends on a DLL (in this case System.Data.SQLite.dll) that ships in two different versions, I wanted to include both in the MSI and then copy the correct one to the installation folder with a CustomAction project. The snag consists of this pesky error message whenever you add a 64 bit dll to a Setup project that is targeting x86:

File 'System.Data.SQLite.dll' of project output 'Content Files from MYPROJECT (Active)' targeting 'AMD64' is not compatible with the project's target platform 'x86'

That was easy to fix! All I had to do was include the file with a different extension, right? So... I renamed System.Data.SQLite.dll to System.Data.SQLite.txt and added it to MYPROJECT as a new content file. Same error when building the setup project:

File 'System.Data.SQLite.txt' of project output 'Content Files from MYPROJECT (Active)' targeting 'AMD64' is not compatible with the project's target platform 'x86'

It seems, the setup project figures out that you have a DLL here, even if the extension doesn't is something totally different. I tried various extensions to no avail.

So, the next logical step would be to use the old email zip file trick, right? It is rather easy to zip a DLL. Any number of tools will do that for you. It turns out to be rather tricky to unzip a DLL in C# inside your CustomAction.

It is possible to use a 3rd party library for unzipping, but I didn't really want to add a dependency just for the installer. Instead, I opted to use the DEFLATE algorithm provided in .NET here: System.IO.Compression.DeflateStream.

Given a file compressed with this algorithm, the code to inflate it back to normal size is trivial:

using (var srcFile = File.OpenRead(@"C:\MYPATH\System.Data.SQLite.x64"))
{
    using (var dstFile = File.OpenWrite(@"C:\MYPATH\System.Data.SQLite.dll"))
    {
        using (var deflator = new DeflateStream(srcFile, CompressionMode.Decompress))
        {
            CopyStream(deflator, dstFile);
        }
    }
}

Just... how to get the original file into the deflated version? I couldn't find a tool that reliably did this for me, so I created my own: http://code.google.com/p/deflate/

To quote from the projects page:

This project provides two simple programs:

deflate.exe inflate.exe They are implented using the System.IO.Compression.DeflateStream provided in .NET.

Usage:

C:\> type MYFILE | deflate.exe > MYFILE.deflated
C:\> type MYFILE.deflated | inflate.exe > MYFILE

I now have the honour to present the steps to create a DLL targeted at a different architecture as your setup:

  1. deflate the file using deflate.exe, naming it with a different extension (e.g. .x64)
  2. add it to your main project as a content file
  3. add a custom action project to your solution
  4. add the custom action to the setup projects "Install" custom actions
  5. inflate the file inside the custom actions Install method using System.IO.Compression.DeflateStream (see code above)
  6. do a little dance around your desk, down the hall, and past as many coworkers as you care to annoy :)

Thursday, April 14, 2011

Listing Window Dimensions with RevitPythonShell

I wrote this quick script this morning and thought I should share:

import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *

doc = __revit__.ActiveUIDocument.Document

import revitutil

def main():
    windows = revitutil.listWindows(doc)

    for w in windows:
        instance_width = revitutil.meters(w.get_Parameter(BuiltInParameter.WINDOW_WIDTH).AsDouble())
        instance_height = revitutil.meters(w.get_Parameter(BuiltInParameter.WINDOW_HEIGHT).AsDouble())

        wt = doc.get_Element(w.GetTypeId())

        type_width = revitutil.meters(wt.get_Parameter(BuiltInParameter.WINDOW_WIDTH).AsDouble())
        type_height = revitutil.meters(wt.get_Parameter(BuiltInParameter.WINDOW_HEIGHT).AsDouble())

        rough_width = revitutil.meters(wt.get_Parameter(BuiltInParameter.FAMILY_ROUGH_WIDTH_PARAM).AsDouble())
        rough_height = revitutil.meters(wt.get_Parameter(BuiltInParameter.FAMILY_ROUGH_WIDTH_PARAM).AsDouble())

        wid = w.Id.IntegerValue
        wname = w.Name

        print "%(wid)d\t%(wname)s\t%(instance_width).2f\t%(instance_height).2f\t%(type_width)s\t%(type_height).2f\t%(rough_width).2f\t%(rough_height).2f" % locals()


if __name__ == '__main__':
    import traceback
    try:
        main()
    except:
        traceback.print_exc()

It doesn't do much more than you could do with a window schedule in the Revit GUI, except that I couldn't figure out how to distinguish instance width and type width in window schedules. As I was trying to debug some code that made that distinction, I needed some goggles! Out pops RPS to the rescue ;)

One thing I'd like to point out is the structure of the script. I tend to write my canned commands in RPS following this structure:

  • import stuff and create a doc variable (I normally just copy the contens of the InitScript for this)
  • define a main() function that handles the code
  • use the if __name__ == '__main__' idiom to wrap calling the main function in a try block

The reason for using the try block is traceback.print_exc() which prints a nice error message to the console that helps debugging!

Wednesday, April 6, 2011

List Parameters of Current Selection

This is another post about using the RevitPythonShell (RPS) for accessing the Revit API. I assume you are using a variation of the default InitScript, as that provides a handy selection variable.

The following session in the RPS shell assumes you have selected a wall in your Revit model. It then provides a list of the names of all parameters on the walls type:

>>>w

<Autodesk.Revit.DB.Wall object at 0x000000000000002B [Autodesk.Revit.DB.Wall]>
>>>wt = doc.get_Element(w.GetTypeId())

>>>plist = list(wt.Parameters)

>>>pnames = [p.Definition.Name for p in plist]

>>>pnames

['Description', 'DPV:DpvConstruction', 'Fire Rating', 'Structure', 'Assembly Description', 'Type Mark', 'Cost', 'Coarse Scale Fill Color', 'URL', 'Function', 'Width', 'Wrapping at Inserts', 'Assembly Code', 'Type Comments', 'Coarse Scale Fill Pattern', 'Keynote', 'Model', 'Wrapping at Ends', 'Manufacturer']
>>>

Thursday, March 31, 2011

Exporting Images with the Autodesk Revit API

I tried to find some sample code for using the Document.ExportImage method in Autodesk Revit 2011 but couldn't find any. So I wrote my own sample code and posted it on the RevitPythonShell wiki as a featured script. I'd like to share it here too:

'''
exportImage.py

Export the currently visible view as a PNG image to a location specified by the user.
'''
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *

doc = __revit__.ActiveUIDocument.Document

# collect file location from user
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import DialogResult, SaveFileDialog
dialog = SaveFileDialog()
dialog.Title = 'Export current view as PNG'
dialog.Filter = 'PNG files (*.PNG)|*.PNG'

if dialog.ShowDialog() == DialogResult.OK:
    # set up the export options
    options = ImageExportOptions()
    options.ExportRange = ExportRange.VisibleRegionOfCurrentView
    options.FilePath = dialog.FileName
    options.HLRandWFViewsFileType = ImageFileType.PNG
    options.ImageResolution = ImageResolution.DPI_72
    options.ZoomType = ZoomFitType.Zoom
    options.ShadowViewsFileType = ImageFileType.PNG

    doc.ExportImage(options)

__window__.Close()

The above code does some stuff necessary for any canned command in RPS: It adds references to the RevitAPI and imports the Autodesk.Revit.DB types. I also open a SaveFileDialog using code found here: http://www.ironpython.info/index.php/SaveFileDialog.

Wednesday, March 16, 2011

How to install Trac on a Synology DS209+II

These are some short notes on how I (successfully) installed Trac on a Synology DS209+II. The process should be similar for many other Synology servers. Please comment on any errors you find or snags you run into.

I modified my Synology server from the original Synology setup:

Configuration of Apache for Subversion

I appended following lines to /opt/etc/apache2/httpd.conf:

# Subversion
Include etc/apache2/conf.d/mod_dav_svn.conf

Also, I created a file /opt/etc/apache2/conf.d/mod_dav_svn.conf with following contents:

LoadModule dav_svn_module     libexec/mod_dav_svn.so
LoadModule authz_svn_module   libexec/mod_authz_svn.so

<Location /svn>
   DAV svn
   SVNParentPath /volume1/svn
   AuthType Basic
   AuthName "Subversion repository"
   AuthUserFile /volume1/svn/svn-auth-file
   Require valid-user
</Location>

# allow Apache to be used for authenticating Trac
<Directory /opt/share/www/trac>
   AuthType Basic
   AuthName "Subversion repository"
   AuthUserFile /volume1/svn/svn-auth-file
   Require valid-user
</Directory>

This expects a file /volume1/svn/svn-auth-file to be present. That file contains the passwords used for Subversion (and, via Apache, Trac authentication). This file is generated with apaches htpasswd -c command. I used the cm too, to force md5 hashing of the passwords. Also, I added the folder /opt/share/www/trac` - this is used later on for Trac authentication, as I instruct Apache to authenticate this URL and tell Trac to use it for authentication.

Trac configuration

I am running Trac version 0.11.7. The Trac environments can be found at /volume1/trac-env. They are called "MYTRAC1" and "MYTRAC2". Access to them is via the following URLs:

Trac is run using tracd. This is configured to start automatically on system start by creation of the following file: /opt/etc/init.d/S81trac:

#!/bin/sh
# run tracd
/opt/bin/tracd -d -p 8888 -auth=*,/volume1/svn/svn-auth-file,myserver.example.com -e /volume1/trac-env

The file must be set to executable for root (see documentation for chmod), so that it will be run at system start.

Trac configuration files can be found at

  • /volume1/trac-env/MYTRAC1/conf/trac.ini
  • /volume1/trac-env/MYTRAC2/conf/trac.ini

Authentication via Apache

Authentication is done with the AccountManager plugin for trac (http://trac-hacks.org/wiki/AccountManagerPlugin). The website has a good explanation on how that works. See the copies of the trac.ini files for reference. I'd like to point out the last section:

[account-manager]
password_store = HttpAuthStore
authentication_url = http://myserver.example.com:8000/trac

This is where we tell Trac to use our Apache Server for authentication.

Backup

Backing up Trac

Trac is backed up with the trac-admin hotcopy command. The configuration of the backup is in /etc/crontab. It is done by executing the script /volume1/trac-env/tracbackup:

#!/bin/sh

/opt/bin/trac-admin /v9olume1/trac-env/MYTRAC1 hotcopy `date +/volumeUSB1/usbshare/TracBackup/%Y%m%d_trac_hotcopy_MYTRAC1`
/opt/bin/trac-admin /v9olume1/trac-env/MYTRAC2 hotcopy `date +/volumeUSB1/usbshare/TracBackup/%Y%m%d_trac_hotcopy_MYTRAC2`

# make sure other computers connecting to the share
# can delete these files
chmod 777 /volumeUSB1/usbshare/TracBackup/*

FIXME: these still have to be deleted regularly. I do this from my PC, so as to keep the complexity on the server minimal.

Backing up Subversion

Subversion is backed up with the svnadmin dump command, since this can then be read in from other subversion versions. The configuration of the backup is in /etc/crontab. It is done by executing the script /volume1/svn/svnbackup:

#!/bin/sh

/opt/bin/svnadmin dump /volume1/svn/MYREPO1 > `date +/volumeUSB1/usbshare/SvnBackup/%Y%m%d_svn_dump_MYREPO1`
/opt/bin/svnadmin dump /volume1/svn/MYREPO2 > `date +/volumeUSB1/usbshare/SvnBackup/%Y%m%d_svn_dump_MYREPO2`

# make sure other computers connecting to the share
# can delete these files
chmod 777 /volumeUSB1/usbshare/SvnBackup/*

FIXME: these still have to be deleted regularly. I do this from my PC, so as to keep the complexity on the server minimal.