install (TARGETS eglretrace RUNTIME DESTINATION bin) 
 endif ()
 
+if (WIN32 AND DirectX_D3DX9_INCLUDE_DIR)
+    add_custom_command (
+        OUTPUT d3dretrace_d3d9.cpp
+        COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/d3dretrace.py > ${CMAKE_CURRENT_BINARY_DIR}/d3dretrace_d3d9.cpp
+        DEPENDS d3dretrace.py retrace.py specs/d3d9.py specs/d3d9types.py specs/d3d9caps.py specs/winapi.py specs/stdapi.py
+    )
+
+    include_directories (SYSTEM ${DirectX_D3DX9_INCLUDE_DIR})
+    add_executable (d3dretrace
+        retrace.cpp
+        d3dretrace_main.cpp
+        d3dretrace_d3d9.cpp
+    )
+endif ()
+
 ##############################################################################
 # CLI
 
 
--- /dev/null
+/**************************************************************************
+ *
+ * Copyright 2012 Jose Fonseca
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ **************************************************************************/
+
+#ifndef _D3DRETRACE_HPP_
+#define _D3DRETRACE_HPP_
+
+#include "retrace.hpp"
+
+
+namespace d3dretrace {
+
+
+extern const retrace::Entry d3d9_callbacks[];
+
+
+} /* namespace d3dretrace */
+
+
+#endif /* _D3DRETRACE_HPP_ */
 
--- /dev/null
+##########################################################################
+#
+# Copyright 2011 Jose Fonseca
+# All Rights Reserved.
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+# THE SOFTWARE.
+#
+##########################################################################/
+
+
+"""GL retracer generator."""
+
+
+import specs.stdapi as stdapi
+from specs.d3d9 import d3d9
+from retrace import Retracer
+
+
+class D3DRetracer(Retracer):
+
+    table_name = 'd3dretrace::d3d9_callbacks'
+
+
+if __name__ == '__main__':
+    print r'''
+#include <string.h>
+
+#include <iostream>
+
+#include "d3d9imports.hpp"
+#include "d3dretrace.hpp"
+
+
+'''
+    retracer = D3DRetracer()
+    retracer.retraceApi(d3d9)
 
--- /dev/null
+/**************************************************************************
+ *
+ * Copyright 2011 Jose Fonseca
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ **************************************************************************/
+
+
+#include <string.h>
+
+#include "os_string.hpp"
+#include "retrace.hpp"
+#include "d3dretrace.hpp"
+
+
+namespace d3dretrace {
+
+static void display(void) {
+    retrace::Retracer retracer;
+
+    retracer.addCallbacks(d3d9_callbacks);
+
+    trace::Call *call;
+
+    while ((call = retrace::parser.parse_call())) {
+        retracer.retrace(*call);
+
+        delete call;
+    }
+
+    exit(0);
+}
+
+
+static void usage(void) {
+    std::cout << 
+        "Usage: d3dretrace [OPTION] TRACE\n"
+        "Replay TRACE.\n"
+        "\n"
+        "  -v           increase output verbosity\n"
+    ;
+}
+
+
+extern "C"
+int main(int argc, char **argv)
+{
+
+    int i;
+    for (i = 1; i < argc; ++i) {
+        const char *arg = argv[i];
+
+        if (arg[0] != '-') {
+            break;
+        }
+
+        if (!strcmp(arg, "--")) {
+            break;
+        } else if (!strcmp(arg, "--help")) {
+            usage();
+            return 0;
+        } else if (!strcmp(arg, "-v")) {
+            ++retrace::verbosity;
+        } else {
+            std::cerr << "error: unknown option " << arg << "\n";
+            usage();
+            return 1;
+        }
+    }
+
+    for ( ; i < argc; ++i) {
+        if (!retrace::parser.open(argv[i])) {
+            std::cerr << "error: failed to open " << argv[i] << "\n";
+            return 1;
+        }
+
+        display();
+
+        retrace::parser.close();
+    }
+
+    return 0;
+}
+
+} /* namespace glretrace */
 
 #ifndef _GLRETRACE_HPP_
 #define _GLRETRACE_HPP_
 
-#include "trace_parser.hpp"
 #include "glws.hpp"
 #include "retrace.hpp"
 
 
 extern bool double_buffer;
 extern bool insideGlBeginEnd;
-extern trace::Parser parser;
 extern glws::Profile defaultProfile;
 extern glws::Visual *visual[glws::PROFILE_MAX];
 extern glws::Drawable *drawable;
 
 
 bool double_buffer = true;
 bool insideGlBeginEnd = false;
-trace::Parser parser;
 glws::Profile defaultProfile = glws::PROFILE_COMPAT;
 glws::Visual *visual[glws::PROFILE_MAX];
 glws::Drawable *drawable = NULL;
 
 namespace retrace {
 
 
+trace::Parser parser;
+
+
 int verbosity = 0;
 
 
 
 #include <ostream>
 
 #include "trace_model.hpp"
+#include "trace_parser.hpp"
 
 
 namespace retrace {
 
 
+extern trace::Parser parser;
+
+
 /**
  * Handle map.
  *
 
         print '}'
         print
 
+    def retraceInterfaceMethod(self, interface, method):
+        print 'static void retrace_%s__%s(trace::Call &call) {' % (interface.name, method.name)
+        self.retraceInterfaceMethodBody(interface, method)
+        print '}'
+        print
+
     def retraceFunctionBody(self, function):
         if not function.sideeffects:
             print '    (void)call;'
             return
 
+        self.deserializeArgs(function)
+        
+        self.invokeFunction(function)
+
+        self.swizzleValues(function)
+
+    def retraceInterfaceMethodBody(self, interface, method):
+        if not method.sideeffects:
+            print '    (void)call;'
+            return
+
+        self.deserializeThisPointer(interface)
+
+        self.deserializeArgs(method)
+        
+        self.invokeInterfaceMethod(interface, method)
+
+        self.swizzleValues(method)
+
+    def deserializeThisPointer(self, interface):
+        print '    %s *_this;' % (interface.name,)
+        # FIXME
+
+    def deserializeArgs(self, function):
         success = True
         for arg in function.args:
             arg_type = ConstRemover().visit(arg.type)
             try:
                 self.extractArg(function, arg, arg_type, lvalue, rvalue)
             except NotImplementedError:
-                success = False
+                success =  False
                 print '    %s = 0; // FIXME' % arg.name
+
         if not success:
             print '    if (1) {'
             self.failFunction(function)
+            if function.name[-1].islower():
+                sys.stderr.write('warning: unsupported %s call\n' % function.name)
             print '    }'
-        self.invokeFunction(function)
+
+    def swizzleValues(self, function):
         for arg in function.args:
             if arg.output:
                 arg_type = ConstRemover().visit(arg.type)
                 self.regiterSwizzledValue(function.type, lvalue, rvalue)
             except NotImplementedError:
                 print '    // XXX: result'
-        if not success:
-            if function.name[-1].islower():
-                sys.stderr.write('warning: unsupported %s call\n' % function.name)
 
     def failFunction(self, function):
         print '    if (retrace::verbosity >= 0) {'
         else:
             print '    %s(%s);' % (function.name, arg_names)
 
+    def invokeInterfaceMethod(self, interface, method):
+        arg_names = ", ".join(method.argNames())
+        if method.type is not stdapi.Void:
+            print '    %s __result;' % (method.type)
+            print '    __result = _this->%s(%s);' % (method.name, arg_names)
+            print '    (void)__result;'
+        else:
+            print '    _this->%s(%s);' % (method.name, arg_names)
+
     def filterFunction(self, function):
         return True
 
     table_name = 'retrace::callbacks'
 
-    def retraceFunctions(self, functions):
-        functions = filter(self.filterFunction, functions)
-
-        for function in functions:
-            self.retraceFunction(function)
-
-        print 'const retrace::Entry %s[] = {' % self.table_name
-        for function in functions:
-            print '    {"%s", &retrace_%s},' % (function.name, function.name)
-        print '    {NULL, NULL}'
-        print '};'
-        print
-
-
     def retraceApi(self, api):
 
         print '#include "trace_parser.hpp"'
         print '#include "retrace.hpp"'
         print
 
-        types = api.all_types()
+        types = api.getAllTypes()
         handles = [type for type in types if isinstance(type, stdapi.Handle)]
         handle_names = set()
         for handle in handles:
                 handle_names.add(handle.name)
         print
 
-        self.retraceFunctions(api.functions)
+        functions = filter(self.filterFunction, api.functions)
+        for function in functions:
+            self.retraceFunction(function)
+        interfaces = api.getAllInterfaces()
+        for interface in interfaces:
+            for method in interface.iterMethods():
+                self.retraceInterfaceMethod(interface, method)
+
+        print 'const retrace::Entry %s[] = {' % self.table_name
+        for function in functions:
+            print '    {"%s", &retrace_%s},' % (function.name, function.name)
+        for interface in interfaces:
+            for method in interface.iterMethods():
+                print '    {"%s::%s", &retrace_%s__%s},' % (interface.name, method.name, interface.name, method.name)
+        print '    {NULL, NULL}'
+        print '};'
+        print
 
 
     def visitOpaque(self, opaque):
         return opaque
 
+    def visitInterface(self, interface, *args, **kwargs):
+        return interface
+
     def visitPolymorphic(self, polymorphic):
         defaultType = self.visit(polymorphic.defaultType)
         switchExpr = polymorphic.switchExpr
         self.functions = []
         self.interfaces = []
 
-    def all_types(self):
+    def getAllTypes(self):
         collector = Collector()
         for function in self.functions:
             for arg in function.args:
                 collector.visit(method.type)
         return collector.types
 
+    def getAllInterfaces(self):
+        types = self.getAllTypes()
+        interfaces = [type for type in types if isinstance(type, Interface)]
+        for interface in self.interfaces:
+            if interface not in interfaces:
+                interfaces.append(interface)
+        return interfaces
+
     def addFunction(self, function):
         self.functions.append(function)
 
 
         print
 
         # Generate the serializer functions
-        types = api.all_types()
+        types = api.getAllTypes()
         visitor = ComplexValueSerializer(self.serializerFactory())
         map(visitor.visit, types)
         print
 
         # Interfaces wrapers
-        interfaces = [type for type in types if isinstance(type, stdapi.Interface)]
+        interfaces = api.getAllInterfaces()
         map(self.declareWrapperInterface, interfaces)
         map(self.implementWrapperInterface, interfaces)
         print