<commit_before>/*
 * GStreamer
 * Copyright (C) 2016 Freescale Semiconductor, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstqtglutility.h"
#include <QtGui/QGuiApplication>

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
#include <QX11Info>
#include <gst/gl/x11/gstgldisplay_x11.h>
#if GST_GL_HAVE_PLATFORM_GLX
#include <gst/gl/x11/gstglcontext_glx.h>
#elif GST_GL_HAVE_PLATFORM_EGL
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#endif

#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/wayland/gstgldisplay_wayland.h>
#endif

#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/viv-fb/gstgldisplay_viv_fb.h>
#else
#include <gst/gl/egl/gstgldisplay_egl.h>
#endif
#include <gst/gl/egl/gstglcontext_egl.h>
#endif

#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
#include <gst/gl/coaoa/gstgldisplay_cocoa.h>
#endif

#define GST_CAT_DEFAULT qt_gl_utils_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

GstGLDisplay *
gst_qt_get_gl_display ()
{
  GstGLDisplay *display = NULL;
  QGuiApplication *app = static_cast<QGuiApplication *> (QCoreApplication::instance ());
  static volatile gsize _debug;

  g_assert (app != NULL);

  if (g_once_init_enter (&_debug)) {
    GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "qtglutility", 0,
        "Qt gl utility functions");
    g_once_init_leave (&_debug, 1);
  }
  GST_INFO ("QGuiApplication::instance()->platformName() %s", app->platformName().toUtf8().data());

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
  if (QString::fromUtf8 ("xcb") == app->platformName())
    display = (GstGLDisplay *)
        gst_gl_display_x11_new_with_display (QX11Info::display ());
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
  if (QString::fromUtf8 ("wayland") == app->platformName()
        || QString::fromUtf8 ("wayland-egl") == app->platformName()){
    struct wl_display * wayland_display;
    QPlatformNativeInterface *native =
        QGuiApplication::platformNativeInterface();
    wayland_display = (struct wl_display *)
        native->nativeResourceForWindow("display", NULL);
    display = (GstGLDisplay *)
        gst_gl_display_wayland_new_with_display (wayland_display);
  }
#endif
#if GST_GL_HAVE_PLATFORM_EGL && GST_GL_HAVE_WINDOW_ANDROID
  if (QString::fromUtf8 ("android") == app->platformName())
    display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#elif GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
  if (QString::fromUtf8("eglfs") == app->platformName()) {
#if GST_GL_HAVE_WINDOW_VIV_FB
    /* FIXME: Could get the display directly from Qt like this
      QPlatformNativeInterface *native =
          QGuiApplication::platformNativeInterface();
      EGLDisplay egl_display = (EGLDisplay)
          native->nativeResourceForWindow("egldisplay", NULL);

      However we seem to have no way for getting the EGLNativeDisplayType, aka
      native_display, via public API. As such we have to assume that display 0
      is always used. Only way around that is parsing the index the same way as
      Qt does in QEGLDeviceIntegration::fbDeviceName(), so let's do that.
    */
    const gchar *fb_dev;
    gint disp_idx = 0;

    fb_dev = g_getenv ("QT_QPA_EGLFS_FB");
    if (fb_dev) {
      if (sscanf (fb_dev, "/dev/fb%d", &disp_idx) != 1)
        disp_idx = 0;
    }

    display = (GstGLDisplay *) gst_gl_display_viv_fb_new (disp_idx);
#else
    display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#endif
  }
#endif

#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
  if (QString::fromUtf8 ("cocoa") == app->platformName())
    display = (GstGLDisplay *) gst_gl_display_cocoa_new ();
#endif
#if GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
  if (QString::fromUtf8 ("ios") == app->platformName())
    display = gst_gl_display_new ();
#endif
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
  if (QString::fromUtf8 ("windows") == app->platformName())
    display = gst_gl_display_new ();
#endif

  if (!display)
    display = gst_gl_display_new ();

  return display;
}

gboolean
gst_qt_get_gl_wrapcontext (GstGLDisplay * display,
    GstGLContext **wrap_glcontext, GstGLContext **context)
{
  GstGLPlatform platform = (GstGLPlatform) 0;
  GstGLAPI gl_api;
  guintptr gl_handle;
  GError *error = NULL;

  g_return_val_if_fail (display != NULL && wrap_glcontext != NULL, FALSE);

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
  if (GST_IS_GL_DISPLAY_X11 (display)) {
#if GST_GL_HAVE_PLATFORM_GLX
    platform = GST_GL_PLATFORM_GLX;
#elif GST_GL_HAVE_PLATFORM_EGL
    platform = GST_GL_PLATFORM_EGL;
#endif
  }
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && defined (HAVE_QT_WAYLAND)
  if (GST_IS_GL_DISPLAY_WAYLAND (display)) {
    platform = GST_GL_PLATFORM_EGL;
  }
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
  if (GST_IS_GL_DISPLAY_VIV_FB (display)) {
#else
  if (GST_IS_GL_DISPLAY_EGL (display)) {
#endif
    platform = GST_GL_PLATFORM_EGL;
  }
#endif
  if (platform == 0) {
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_COCOA && defined (HAVE_QT_MAC)
    platform = GST_GL_PLATFORM_CGL;
#elif GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
    platform = GST_GL_PLATFORM_EAGL;
#elif GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
    platform = GST_GL_PLATFORM_WGL;
#else
    GST_ERROR ("Unknown platform");
    return FALSE;
#endif
  }

  gl_api = gst_gl_context_get_current_gl_api (platform, NULL, NULL);
  gl_handle = gst_gl_context_get_current_gl_context (platform);
  if (gl_handle)
    *wrap_glcontext =
        gst_gl_context_new_wrapped (display, gl_handle,
        platform, gl_api);

  if (!*wrap_glcontext) {
    GST_ERROR ("cannot wrap qt OpenGL context");
    return FALSE;
  }

  (void) platform;
  (void) gl_api;
  (void) gl_handle;

  gst_gl_context_activate (*wrap_glcontext, TRUE);
  if (!gst_gl_context_fill_info (*wrap_glcontext, &error)) {
    GST_ERROR ("failed to retrieve qt context info: %s", error->message);
    g_object_unref (*wrap_glcontext);
    *wrap_glcontext = NULL;
    return FALSE;
  } else {
    gst_gl_display_filter_gl_api (display, gst_gl_context_get_gl_api (*wrap_glcontext));
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
    g_return_val_if_fail (context != NULL, FALSE);

    G_STMT_START {
      GstGLWindow *window;
      HDC device;

      /* If there's no wglCreateContextAttribsARB() support, then we would fallback to
       * wglShareLists() which will fail with ERROR_BUSY (0xaa) if either of the GL
       * contexts are current in any other thread.
       *
       * The workaround here is to temporarily disable Qt's GL context while we
       * set up our own.
       *
       * Sometimes wglCreateContextAttribsARB()
       * exists, but isn't functional (some Intel drivers), so it's easiest to do this
       * unconditionally.
       */
      *context = gst_gl_context_new (display);
      window = gst_gl_context_get_window (*context);
      device = (HDC) gst_gl_window_get_display (window);

      wglMakeCurrent (device, 0);
      gst_object_unref (window);
      if (!gst_gl_context_create (*context, *wrap_glcontext, &error)) {
        GST_ERROR ("%p failed to create shared GL context: %s", this, error->message);
        g_object_unref (*context);
        *context = NULL;
        g_object_unref (*wrap_glcontext);
        *wrap_glcontext = NULL;
        wglMakeCurrent (device, (HGLRC) gl_handle);
        return FALSE;
      }
      wglMakeCurrent (device, (HGLRC) gl_handle);
    }
#endif
    gst_gl_context_activate (*wrap_glcontext, FALSE);
  } G_STMT_END;

  return TRUE;
}
<commit_msg>qt: Use GST_GL_HAVE_PLATFORM_CGL instead of GST_GL_HAVE_PLATFORM_COCOA<commit_after>/*
 * GStreamer
 * Copyright (C) 2016 Freescale Semiconductor, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "gstqtglutility.h"
#include <QtGui/QGuiApplication>

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
#include <QX11Info>
#include <gst/gl/x11/gstgldisplay_x11.h>
#if GST_GL_HAVE_PLATFORM_GLX
#include <gst/gl/x11/gstglcontext_glx.h>
#elif GST_GL_HAVE_PLATFORM_EGL
#include <gst/gl/egl/gstglcontext_egl.h>
#endif
#endif

#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/wayland/gstgldisplay_wayland.h>
#endif

#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
#include <qpa/qplatformnativeinterface.h>
#include <gst/gl/viv-fb/gstgldisplay_viv_fb.h>
#else
#include <gst/gl/egl/gstgldisplay_egl.h>
#endif
#include <gst/gl/egl/gstglcontext_egl.h>
#endif

#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
#include <gst/gl/cocoa/gstgldisplay_cocoa.h>
#endif

#define GST_CAT_DEFAULT qt_gl_utils_debug
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

GstGLDisplay *
gst_qt_get_gl_display ()
{
  GstGLDisplay *display = NULL;
  QGuiApplication *app = static_cast<QGuiApplication *> (QCoreApplication::instance ());
  static volatile gsize _debug;

  g_assert (app != NULL);

  if (g_once_init_enter (&_debug)) {
    GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, "qtglutility", 0,
        "Qt gl utility functions");
    g_once_init_leave (&_debug, 1);
  }
  GST_INFO ("QGuiApplication::instance()->platformName() %s", app->platformName().toUtf8().data());

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
  if (QString::fromUtf8 ("xcb") == app->platformName())
    display = (GstGLDisplay *)
        gst_gl_display_x11_new_with_display (QX11Info::display ());
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_WAYLAND)
  if (QString::fromUtf8 ("wayland") == app->platformName()
        || QString::fromUtf8 ("wayland-egl") == app->platformName()){
    struct wl_display * wayland_display;
    QPlatformNativeInterface *native =
        QGuiApplication::platformNativeInterface();
    wayland_display = (struct wl_display *)
        native->nativeResourceForWindow("display", NULL);
    display = (GstGLDisplay *)
        gst_gl_display_wayland_new_with_display (wayland_display);
  }
#endif
#if GST_GL_HAVE_PLATFORM_EGL && GST_GL_HAVE_WINDOW_ANDROID
  if (QString::fromUtf8 ("android") == app->platformName())
    display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#elif GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
  if (QString::fromUtf8("eglfs") == app->platformName()) {
#if GST_GL_HAVE_WINDOW_VIV_FB
    /* FIXME: Could get the display directly from Qt like this
      QPlatformNativeInterface *native =
          QGuiApplication::platformNativeInterface();
      EGLDisplay egl_display = (EGLDisplay)
          native->nativeResourceForWindow("egldisplay", NULL);

      However we seem to have no way for getting the EGLNativeDisplayType, aka
      native_display, via public API. As such we have to assume that display 0
      is always used. Only way around that is parsing the index the same way as
      Qt does in QEGLDeviceIntegration::fbDeviceName(), so let's do that.
    */
    const gchar *fb_dev;
    gint disp_idx = 0;

    fb_dev = g_getenv ("QT_QPA_EGLFS_FB");
    if (fb_dev) {
      if (sscanf (fb_dev, "/dev/fb%d", &disp_idx) != 1)
        disp_idx = 0;
    }

    display = (GstGLDisplay *) gst_gl_display_viv_fb_new (disp_idx);
#else
    display = (GstGLDisplay *) gst_gl_display_egl_new_with_egl_display (eglGetDisplay(EGL_DEFAULT_DISPLAY));
#endif
  }
#endif

#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
  if (QString::fromUtf8 ("cocoa") == app->platformName())
    display = (GstGLDisplay *) gst_gl_display_cocoa_new ();
#endif
#if GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
  if (QString::fromUtf8 ("ios") == app->platformName())
    display = gst_gl_display_new ();
#endif
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
  if (QString::fromUtf8 ("windows") == app->platformName())
    display = gst_gl_display_new ();
#endif

  if (!display)
    display = gst_gl_display_new ();

  return display;
}

gboolean
gst_qt_get_gl_wrapcontext (GstGLDisplay * display,
    GstGLContext **wrap_glcontext, GstGLContext **context)
{
  GstGLPlatform platform = (GstGLPlatform) 0;
  GstGLAPI gl_api;
  guintptr gl_handle;
  GError *error = NULL;

  g_return_val_if_fail (display != NULL && wrap_glcontext != NULL, FALSE);

#if GST_GL_HAVE_WINDOW_X11 && defined (HAVE_QT_X11)
  if (GST_IS_GL_DISPLAY_X11 (display)) {
#if GST_GL_HAVE_PLATFORM_GLX
    platform = GST_GL_PLATFORM_GLX;
#elif GST_GL_HAVE_PLATFORM_EGL
    platform = GST_GL_PLATFORM_EGL;
#endif
  }
#endif
#if GST_GL_HAVE_WINDOW_WAYLAND && defined (HAVE_QT_WAYLAND)
  if (GST_IS_GL_DISPLAY_WAYLAND (display)) {
    platform = GST_GL_PLATFORM_EGL;
  }
#endif
#if GST_GL_HAVE_PLATFORM_EGL && defined (HAVE_QT_EGLFS)
#if GST_GL_HAVE_WINDOW_VIV_FB
  if (GST_IS_GL_DISPLAY_VIV_FB (display)) {
#else
  if (GST_IS_GL_DISPLAY_EGL (display)) {
#endif
    platform = GST_GL_PLATFORM_EGL;
  }
#endif
  if (platform == 0) {
#if GST_GL_HAVE_WINDOW_COCOA && GST_GL_HAVE_PLATFORM_CGL && defined (HAVE_QT_MAC)
    platform = GST_GL_PLATFORM_CGL;
#elif GST_GL_HAVE_WINDOW_EAGL && GST_GL_HAVE_PLATFORM_EAGL && defined (HAVE_QT_IOS)
    platform = GST_GL_PLATFORM_EAGL;
#elif GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
    platform = GST_GL_PLATFORM_WGL;
#else
    GST_ERROR ("Unknown platform");
    return FALSE;
#endif
  }

  gl_api = gst_gl_context_get_current_gl_api (platform, NULL, NULL);
  gl_handle = gst_gl_context_get_current_gl_context (platform);
  if (gl_handle)
    *wrap_glcontext =
        gst_gl_context_new_wrapped (display, gl_handle,
        platform, gl_api);

  if (!*wrap_glcontext) {
    GST_ERROR ("cannot wrap qt OpenGL context");
    return FALSE;
  }

  (void) platform;
  (void) gl_api;
  (void) gl_handle;

  gst_gl_context_activate (*wrap_glcontext, TRUE);
  if (!gst_gl_context_fill_info (*wrap_glcontext, &error)) {
    GST_ERROR ("failed to retrieve qt context info: %s", error->message);
    g_object_unref (*wrap_glcontext);
    *wrap_glcontext = NULL;
    return FALSE;
  } else {
    gst_gl_display_filter_gl_api (display, gst_gl_context_get_gl_api (*wrap_glcontext));
#if GST_GL_HAVE_WINDOW_WIN32 && GST_GL_HAVE_PLATFORM_WGL && defined (HAVE_QT_WIN32)
    g_return_val_if_fail (context != NULL, FALSE);

    G_STMT_START {
      GstGLWindow *window;
      HDC device;

      /* If there's no wglCreateContextAttribsARB() support, then we would fallback to
       * wglShareLists() which will fail with ERROR_BUSY (0xaa) if either of the GL
       * contexts are current in any other thread.
       *
       * The workaround here is to temporarily disable Qt's GL context while we
       * set up our own.
       *
       * Sometimes wglCreateContextAttribsARB()
       * exists, but isn't functional (some Intel drivers), so it's easiest to do this
       * unconditionally.
       */
      *context = gst_gl_context_new (display);
      window = gst_gl_context_get_window (*context);
      device = (HDC) gst_gl_window_get_display (window);

      wglMakeCurrent (device, 0);
      gst_object_unref (window);
      if (!gst_gl_context_create (*context, *wrap_glcontext, &error)) {
        GST_ERROR ("%p failed to create shared GL context: %s", this, error->message);
        g_object_unref (*context);
        *context = NULL;
        g_object_unref (*wrap_glcontext);
        *wrap_glcontext = NULL;
        wglMakeCurrent (device, (HGLRC) gl_handle);
        return FALSE;
      }
      wglMakeCurrent (device, (HGLRC) gl_handle);
    }
#endif
    gst_gl_context_activate (*wrap_glcontext, FALSE);
  } G_STMT_END;

  return TRUE;
}
<|endoftext|>


<commit_before>// phan_client.C - simplest example: generates a flat horizontal plane

#include <stdio.h>    // for printf, NULL
#include <time.h>     // for nanosleep
#include <algorithm>  // for std::min_element
#include <iostream>   // for std::cout
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <chrono>

#include <boost/math/common_factor.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#include "liblager_connect.h"
#include "liblager_convert.h"

#include "spherical_coordinates.h"
#include "coordinates_letter.h"
#include "string_tokenizer.h"

#define RECOGNIZER_ERROR -1
#define RECOGNIZER_NO_ERROR 0

#define MAIN_SLEEP_INTERVAL_MICROSECONDS 1000 // 1ms
#define MAIN_SLEEP_INTERVAL_MILLISECONDS MAIN_SLEEP_INTERVAL_MICROSECONDS/1000
#define GESTURE_PAUSE_TIME_MILLISECONDS 500
#define GESTURE_GROUPING_TIME_MILLISECONDS 200
#define SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 20
#define DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 30

using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::stringstream;
using std::vector;

using std::chrono::duration;
using std::chrono::system_clock;
using std::chrono::time_point;

using namespace boost::interprocess;

/* Globals */

struct SubscribedGesture {
  string name;
  string lager;
  string expanded_lager;
  pid_t pid;
  int dl_distance;
  float dl_distance_pct;
};

string g_gesture_string;

vector<SubscribedGesture> g_subscribed_gestures;

#define d(i,j) dd[(i) * (m+2) + (j) ]
#define min(x,y) ((x) < (y) ? (x) : (y))
#define min3(a,b,c) ((a)< (b) ? min((a),(c)) : min((b),(c)))
#define min4(a,b,c,d) ((a)< (b) ? min3((a),(c),(d)) : min3((b),(c),(d)))

int DPrint(int* dd, int n, int m) {
  int i, j;
  for (i = 0; i < n + 2; i++) {
    for (j = 0; j < m + 2; j++) {
      printf("%02d ", d(i, j));
    }
    printf("\n");
  }
  printf("\n");
  return 0;
}

int DlDist2(const char *s, const char* t, int n, int m) {
  int *dd, *DA;
  int i, j, cost, k, i1, j1, DB;
  int infinity = n + m;

  DA = (int*) malloc(256 * sizeof(int));
  dd = (int*) malloc((n + 2) * (m + 2) * sizeof(int));

  d(0,0)= infinity;
  for (i = 0; i < n + 1; i++) {
    d(i+1,1)= i;
    d(i+1,0) = infinity;
  }
  for (j = 0; j < m + 1; j++) {
    d(1,j+1)= j;
    d(0,j+1) = infinity;
  }
  //DPrint(dd,n,m);
  for (k = 0; k < 256; k++)
    DA[k] = 0;
  for (i = 1; i < n + 1; i++) {
    DB = 0;
    for (j = 1; j < m + 1; j++) {
      i1 = DA[t[j - 1]];
      j1 = DB;
      cost = ((s[i - 1] == t[j - 1]) ? 0 : 1);
      if (cost == 0)
        DB = j;
      d(i+1,j+1)=
      min4(d(i,j)+cost,
          d(i+1,j) + 1,
          d(i,j+1)+1,
          d(i1,j1) + (i-i1-1) + 1 + (j-j1-1));
    }
    DA[s[i - 1]] = i;
    //dprint(dd,n,m);
  }
  cost = d(n + 1, m + 1);
  free(dd);
  return cost;
}

/* New size must be a multiple of the original string size */
string ExpandString(const string& input_string, int new_size) {
  stringstream output_string;
  int length_multiplier = new_size / input_string.length();

  vector<string> movement_pairs;
  TokenizeString(input_string, movement_pairs, ".");

  for (vector<string>::iterator it = movement_pairs.begin();
      it < movement_pairs.end(); ++it) {
    for (int i = 0; i < length_multiplier; i++) {
      output_string << *it << ".";
    }
  }

  return output_string.str();
}

bool GestureEntryLessThan(SubscribedGesture i, SubscribedGesture j) {
  return (i.dl_distance_pct < j.dl_distance_pct);
}

void UpdateSubscribedGestureDistance(
    struct SubscribedGesture& subscribed_gesture) {
  const string input_gesture = g_gesture_string;

  int gesture_length_least_common_multiple = boost::math::lcm(
      input_gesture.length(), subscribed_gesture.lager.length());

  string expanded_input_string = ExpandString(
      input_gesture, gesture_length_least_common_multiple);
  subscribed_gesture.expanded_lager = ExpandString(
      subscribed_gesture.lager, gesture_length_least_common_multiple);

  subscribed_gesture.dl_distance = DlDist2(
      expanded_input_string.c_str(), subscribed_gesture.expanded_lager.c_str(),
      expanded_input_string.length(),
      subscribed_gesture.expanded_lager.length());

  subscribed_gesture.dl_distance_pct = (subscribed_gesture.dl_distance * 100.0f)
      / subscribed_gesture.expanded_lager.length();

  cout << subscribed_gesture.name << endl << "\t" << subscribed_gesture.lager
       << endl;
  cout << "Distance: " << subscribed_gesture.dl_distance_pct << "% ("
       << subscribed_gesture.dl_distance << " D-L ops)" << endl;
  cout << endl;
}

void UpdateSubscribedGestureDistances() {
  for (vector<SubscribedGesture>::iterator it = g_subscribed_gestures.begin();
      it < g_subscribed_gestures.end(); ++it) {
    UpdateSubscribedGestureDistance(*it);
  }
}

void DrawMatchingGestures(const SubscribedGesture& closest_gesture) {
  stringstream viewer_command;
  string viewer_command_prefix =
      "cd ~/lager/viewer/src/ && ../build/lager_viewer --gesture ";
  string hide_output_suffix = " > /dev/null";

  cout << "Drawing input gesture..." << endl;

  viewer_command << viewer_command_prefix << g_gesture_string
                 << hide_output_suffix;
  system(viewer_command.str().c_str());

  cout << "Drawing gesture match..." << endl;

  viewer_command.str("");
  viewer_command << viewer_command_prefix << closest_gesture.lager
                 << hide_output_suffix;
  system(viewer_command.str().c_str());
}

bool IsSingleSensorGesture() {
  vector<string> movement_pairs;
  TokenizeString(g_gesture_string, movement_pairs, ".");
  bool sensor_0_moved = false;
  bool sensor_1_moved = false;

  for (vector<string>::iterator it = movement_pairs.begin();
      it < movement_pairs.end(); ++it) {
    // Check if sensor 0 movement is present
    if ((*it).c_str()[0] != '_') {
      sensor_0_moved = true;
    }

    // Check if sensor 0 movement is present
    if ((*it).c_str()[0] != '_') {
      sensor_1_moved = true;
    }

    // If we already found movement on both sensors, there is no need to keep checking
    if (sensor_0_moved && sensor_1_moved) {
      break;
    }
  }

  return (!sensor_0_moved || !sensor_1_moved);
}

int GetMillisecondsUntilNow(const time_point<system_clock> &last_time) {
  time_point<system_clock> now = system_clock::now();
  return duration<double, std::milli>(now - last_time).count();
}

void RecognizeGesture(bool use_gestures_file, bool draw_gestures) {
  if (g_subscribed_gestures.size() == 0) {
    cout << "No gesture subscriptions." << endl;
    return;
  }

  int lowestDistance;
  bool match_found = false;
  unsigned int num_milliseconds_since_recognition_start = 0;
  time_point<system_clock> recognition_start_time = system_clock::now();
  int gesture_distance_threshold_pct =
      IsSingleSensorGesture() ?
      SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT :
                                DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT;

  cout << " ________________________________ " << endl;
  cout << "|                                |" << endl;
  cout << "|         RECOGNIZING...         |" << endl;
  cout << "|________________________________|" << endl;
  cout << "                                  " << endl;

  UpdateSubscribedGestureDistances();

  SubscribedGesture closest_gesture = *min_element(
      g_subscribed_gestures.begin(), g_subscribed_gestures.end(),
      GestureEntryLessThan);
  match_found = closest_gesture.dl_distance_pct
      <= gesture_distance_threshold_pct;
  num_milliseconds_since_recognition_start = GetMillisecondsUntilNow(
      recognition_start_time);

  if (match_found) {
    cout << " ________________________________ " << endl;
    cout << "|                                |" << endl;
    cout << "|          MATCH FOUND!          |" << endl;
    cout << "|________________________________|" << endl;
    cout << "                                  " << endl;
  } else {
    cout << endl;
    cout << "NO MATCH." << endl;
  }

  cout << endl;
  cout << "Closest gesture:\t" << closest_gesture.name << endl;
  cout << endl;
  cout << "Distance:\t\t" << closest_gesture.dl_distance_pct << "% ("
       << closest_gesture.dl_distance << " D-L ops)" << endl;
  cout << "Threshold:\t\t" << gesture_distance_threshold_pct << "%" << endl;
  cout << endl;
  cout << "Recognition time: \t" << num_milliseconds_since_recognition_start
       << "ms" << endl;
  cout << endl;

  if (match_found) {
    if (draw_gestures) {
      DrawMatchingGestures(closest_gesture);
    }
    if (!use_gestures_file && closest_gesture.pid != 0) {
      SendDetectedGestureMessage(closest_gesture.name, closest_gesture.pid);
    }
  }

  cout << endl << endl;
  ;
}

/*****************************************************************************
 *
 Callback handler
 *
 *****************************************************************************/

bool DetermineButtonUse(const int argc, const char** argv) {
  bool use_buttons;

  if ((argc > 1)
      && (std::string(argv[1]).find("--use_buttons") != std::string::npos)) {
    cout << "Gesture detection will be active while pressing a button." << endl;
    use_buttons = true;
  } else {
    cout << "Gesture detection will be active at all times." << endl;
    use_buttons = false;
  }

  return use_buttons;
}

bool DetermineGesturesFileUse(const int argc, const char** argv) {
  bool use_gestures_file;

  if ((argc > 1)
      && (std::string(argv[1]).find("--use_gestures_file") != std::string::npos)) {
    cout << "Comparing input to gestures in a file." << endl;
    use_gestures_file = true;
  } else {
    cout << "Comparing input to subscribed gestures." << endl;
    use_gestures_file = false;
  }

  return use_gestures_file;
}

bool DetermineGestureDrawing(const int argc, const char** argv) {
  bool draw_gestures;

  if ((argc > 1)
      && (std::string(argv[1]).find("--draw_gestures") != std::string::npos)) {
    cout << "Using lager_viewer to draw input and subscribed gestures." << endl;
    draw_gestures = true;
  } else {
    cout << "Will not draw gestures." << endl;
    draw_gestures = false;
  }

  return draw_gestures;
}

void AddSubscribedGestures() {
  while (true) {
    GestureSubscriptionMessage message = GetGestureSubscriptionMessage();

    cout << "Adding subscription..." << endl;
    cout << endl;
    cout << "Name: \"" << message.gesture_name() << "\"" << endl;
    cout << "Lager: \"" << message.gesture_lager() << endl;
    cout << endl;

    SubscribedGesture subscription;
    subscription.name = message.gesture_name();
    subscription.lager = message.gesture_lager();
    subscription.pid = message.pid();
    g_subscribed_gestures.push_back(subscription);
  }
}

int GetSubscribedGesturesFromFile() {
  ifstream gestures_file;
  string current_line;

  cout << "Current gesture" << endl << "\t" << g_gesture_string << endl
       << endl;

  gestures_file.open("gestures.dat");
  if (!gestures_file.is_open()) {
    return RECOGNIZER_ERROR;
  }

  while (getline(gestures_file, current_line)) {
    string name, lager;
    stringstream ss(current_line);
    ss >> name >> lager;

    SubscribedGesture new_gesture;
    ss >> new_gesture.name >> new_gesture.lager;
    new_gesture.pid = 0;
    g_subscribed_gestures.push_back(new_gesture);
  }

  return RECOGNIZER_NO_ERROR;
}

int main(int argc, const char *argv[]) {
  //printf("Generates strings for movement of tracker %s\n\n", TRACKER_SERVER);

  struct timespec sleep_interval = { 0, MAIN_SLEEP_INTERVAL_MICROSECONDS };
  bool use_buttons = DetermineButtonUse(argc, argv);
  bool use_gestures_file = DetermineGesturesFileUse(argc, argv);
  bool draw_gestures = DetermineGestureDrawing(argc, argv);
  LagerConverter* lager_converter = LagerConverter::Instance();

  if (use_gestures_file) {
    GetSubscribedGesturesFromFile();
  } else {
    CreateGestureSubscriptionQueue();
    boost::thread subscription_updater(AddSubscribedGestures);
  }

  cout << " ________________________________ " << endl;
  cout << "|                                |" << endl;
  cout << "|       COLLECTING DATA...       |" << endl;
  cout << "|________________________________|" << endl;
  cout << "                                  " << endl;

  lager_converter->SetUseButtons(use_buttons);
  lager_converter->Start();

  while(true) {
    g_gesture_string = lager_converter->BlockingGetLagerString();
    RecognizeGesture(use_gestures_file, draw_gestures);
  }
} /* main */
<commit_msg>Recognizer: Use non-absolute path to lager_viewer<commit_after>// phan_client.C - simplest example: generates a flat horizontal plane

#include <stdio.h>    // for printf, NULL
#include <time.h>     // for nanosleep
#include <algorithm>  // for std::min_element
#include <iostream>   // for std::cout
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <chrono>

#include <boost/math/common_factor.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

#include "liblager_connect.h"
#include "liblager_convert.h"

#include "spherical_coordinates.h"
#include "coordinates_letter.h"
#include "string_tokenizer.h"

#define RECOGNIZER_ERROR -1
#define RECOGNIZER_NO_ERROR 0

#define MAIN_SLEEP_INTERVAL_MICROSECONDS 1000 // 1ms
#define MAIN_SLEEP_INTERVAL_MILLISECONDS MAIN_SLEEP_INTERVAL_MICROSECONDS/1000
#define GESTURE_PAUSE_TIME_MILLISECONDS 500
#define GESTURE_GROUPING_TIME_MILLISECONDS 200
#define SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 20
#define DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT 30

using std::cout;
using std::endl;
using std::ifstream;
using std::string;
using std::stringstream;
using std::vector;

using std::chrono::duration;
using std::chrono::system_clock;
using std::chrono::time_point;

using namespace boost::interprocess;

/* Globals */

struct SubscribedGesture {
  string name;
  string lager;
  string expanded_lager;
  pid_t pid;
  int dl_distance;
  float dl_distance_pct;
};

string g_gesture_string;

vector<SubscribedGesture> g_subscribed_gestures;

#define d(i,j) dd[(i) * (m+2) + (j) ]
#define min(x,y) ((x) < (y) ? (x) : (y))
#define min3(a,b,c) ((a)< (b) ? min((a),(c)) : min((b),(c)))
#define min4(a,b,c,d) ((a)< (b) ? min3((a),(c),(d)) : min3((b),(c),(d)))

int DPrint(int* dd, int n, int m) {
  int i, j;
  for (i = 0; i < n + 2; i++) {
    for (j = 0; j < m + 2; j++) {
      printf("%02d ", d(i, j));
    }
    printf("\n");
  }
  printf("\n");
  return 0;
}

int DlDist2(const char *s, const char* t, int n, int m) {
  int *dd, *DA;
  int i, j, cost, k, i1, j1, DB;
  int infinity = n + m;

  DA = (int*) malloc(256 * sizeof(int));
  dd = (int*) malloc((n + 2) * (m + 2) * sizeof(int));

  d(0,0)= infinity;
  for (i = 0; i < n + 1; i++) {
    d(i+1,1)= i;
    d(i+1,0) = infinity;
  }
  for (j = 0; j < m + 1; j++) {
    d(1,j+1)= j;
    d(0,j+1) = infinity;
  }
  //DPrint(dd,n,m);
  for (k = 0; k < 256; k++)
    DA[k] = 0;
  for (i = 1; i < n + 1; i++) {
    DB = 0;
    for (j = 1; j < m + 1; j++) {
      i1 = DA[t[j - 1]];
      j1 = DB;
      cost = ((s[i - 1] == t[j - 1]) ? 0 : 1);
      if (cost == 0)
        DB = j;
      d(i+1,j+1)=
      min4(d(i,j)+cost,
          d(i+1,j) + 1,
          d(i,j+1)+1,
          d(i1,j1) + (i-i1-1) + 1 + (j-j1-1));
    }
    DA[s[i - 1]] = i;
    //dprint(dd,n,m);
  }
  cost = d(n + 1, m + 1);
  free(dd);
  return cost;
}

/* New size must be a multiple of the original string size */
string ExpandString(const string& input_string, int new_size) {
  stringstream output_string;
  int length_multiplier = new_size / input_string.length();

  vector<string> movement_pairs;
  TokenizeString(input_string, movement_pairs, ".");

  for (vector<string>::iterator it = movement_pairs.begin();
      it < movement_pairs.end(); ++it) {
    for (int i = 0; i < length_multiplier; i++) {
      output_string << *it << ".";
    }
  }

  return output_string.str();
}

bool GestureEntryLessThan(SubscribedGesture i, SubscribedGesture j) {
  return (i.dl_distance_pct < j.dl_distance_pct);
}

void UpdateSubscribedGestureDistance(
    struct SubscribedGesture& subscribed_gesture) {
  const string input_gesture = g_gesture_string;

  int gesture_length_least_common_multiple = boost::math::lcm(
      input_gesture.length(), subscribed_gesture.lager.length());

  string expanded_input_string = ExpandString(
      input_gesture, gesture_length_least_common_multiple);
  subscribed_gesture.expanded_lager = ExpandString(
      subscribed_gesture.lager, gesture_length_least_common_multiple);

  subscribed_gesture.dl_distance = DlDist2(
      expanded_input_string.c_str(), subscribed_gesture.expanded_lager.c_str(),
      expanded_input_string.length(),
      subscribed_gesture.expanded_lager.length());

  subscribed_gesture.dl_distance_pct = (subscribed_gesture.dl_distance * 100.0f)
      / subscribed_gesture.expanded_lager.length();

  cout << subscribed_gesture.name << endl << "\t" << subscribed_gesture.lager
       << endl;
  cout << "Distance: " << subscribed_gesture.dl_distance_pct << "% ("
       << subscribed_gesture.dl_distance << " D-L ops)" << endl;
  cout << endl;
}

void UpdateSubscribedGestureDistances() {
  for (vector<SubscribedGesture>::iterator it = g_subscribed_gestures.begin();
      it < g_subscribed_gestures.end(); ++it) {
    UpdateSubscribedGestureDistance(*it);
  }
}

void DrawMatchingGestures(const SubscribedGesture& closest_gesture) {
  stringstream viewer_command;
  string viewer_command_prefix =
      "lager_viewer --gesture ";
  string hide_output_suffix = " > /dev/null";

  cout << "Drawing input gesture..." << endl;

  viewer_command << viewer_command_prefix << g_gesture_string
                 << hide_output_suffix;
  system(viewer_command.str().c_str());

  cout << "Drawing gesture match..." << endl;

  viewer_command.str("");
  viewer_command << viewer_command_prefix << closest_gesture.lager
                 << hide_output_suffix;
  system(viewer_command.str().c_str());
}

bool IsSingleSensorGesture() {
  vector<string> movement_pairs;
  TokenizeString(g_gesture_string, movement_pairs, ".");
  bool sensor_0_moved = false;
  bool sensor_1_moved = false;

  for (vector<string>::iterator it = movement_pairs.begin();
      it < movement_pairs.end(); ++it) {
    // Check if sensor 0 movement is present
    if ((*it).c_str()[0] != '_') {
      sensor_0_moved = true;
    }

    // Check if sensor 0 movement is present
    if ((*it).c_str()[0] != '_') {
      sensor_1_moved = true;
    }

    // If we already found movement on both sensors, there is no need to keep checking
    if (sensor_0_moved && sensor_1_moved) {
      break;
    }
  }

  return (!sensor_0_moved || !sensor_1_moved);
}

int GetMillisecondsUntilNow(const time_point<system_clock> &last_time) {
  time_point<system_clock> now = system_clock::now();
  return duration<double, std::milli>(now - last_time).count();
}

void RecognizeGesture(bool use_gestures_file, bool draw_gestures) {
  if (g_subscribed_gestures.size() == 0) {
    cout << "No gesture subscriptions." << endl;
    return;
  }

  int lowestDistance;
  bool match_found = false;
  unsigned int num_milliseconds_since_recognition_start = 0;
  time_point<system_clock> recognition_start_time = system_clock::now();
  int gesture_distance_threshold_pct =
      IsSingleSensorGesture() ?
      SINGLE_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT :
                                DUAL_SENSOR_GESTURE_DISTANCE_THRESHOLD_PCT;

  cout << " ________________________________ " << endl;
  cout << "|                                |" << endl;
  cout << "|         RECOGNIZING...         |" << endl;
  cout << "|________________________________|" << endl;
  cout << "                                  " << endl;

  UpdateSubscribedGestureDistances();

  SubscribedGesture closest_gesture = *min_element(
      g_subscribed_gestures.begin(), g_subscribed_gestures.end(),
      GestureEntryLessThan);
  match_found = closest_gesture.dl_distance_pct
      <= gesture_distance_threshold_pct;
  num_milliseconds_since_recognition_start = GetMillisecondsUntilNow(
      recognition_start_time);

  if (match_found) {
    cout << " ________________________________ " << endl;
    cout << "|                                |" << endl;
    cout << "|          MATCH FOUND!          |" << endl;
    cout << "|________________________________|" << endl;
    cout << "                                  " << endl;
  } else {
    cout << endl;
    cout << "NO MATCH." << endl;
  }

  cout << endl;
  cout << "Closest gesture:\t" << closest_gesture.name << endl;
  cout << endl;
  cout << "Distance:\t\t" << closest_gesture.dl_distance_pct << "% ("
       << closest_gesture.dl_distance << " D-L ops)" << endl;
  cout << "Threshold:\t\t" << gesture_distance_threshold_pct << "%" << endl;
  cout << endl;
  cout << "Recognition time: \t" << num_milliseconds_since_recognition_start
       << "ms" << endl;
  cout << endl;

  if (match_found) {
    if (draw_gestures) {
      DrawMatchingGestures(closest_gesture);
    }
    if (!use_gestures_file && closest_gesture.pid != 0) {
      SendDetectedGestureMessage(closest_gesture.name, closest_gesture.pid);
    }
  }

  cout << endl << endl;
  ;
}

/*****************************************************************************
 *
 Callback handler
 *
 *****************************************************************************/

bool DetermineButtonUse(const int argc, const char** argv) {
  bool use_buttons;

  if ((argc > 1)
      && (std::string(argv[1]).find("--use_buttons") != std::string::npos)) {
    cout << "Gesture detection will be active while pressing a button." << endl;
    use_buttons = true;
  } else {
    cout << "Gesture detection will be active at all times." << endl;
    use_buttons = false;
  }

  return use_buttons;
}

bool DetermineGesturesFileUse(const int argc, const char** argv) {
  bool use_gestures_file;

  if ((argc > 1)
      && (std::string(argv[1]).find("--use_gestures_file") != std::string::npos)) {
    cout << "Comparing input to gestures in a file." << endl;
    use_gestures_file = true;
  } else {
    cout << "Comparing input to subscribed gestures." << endl;
    use_gestures_file = false;
  }

  return use_gestures_file;
}

bool DetermineGestureDrawing(const int argc, const char** argv) {
  bool draw_gestures;

  if ((argc > 1)
      && (std::string(argv[1]).find("--draw_gestures") != std::string::npos)) {
    cout << "Using lager_viewer to draw input and subscribed gestures." << endl;
    draw_gestures = true;
  } else {
    cout << "Will not draw gestures." << endl;
    draw_gestures = false;
  }

  return draw_gestures;
}

void AddSubscribedGestures() {
  while (true) {
    GestureSubscriptionMessage message = GetGestureSubscriptionMessage();

    cout << "Adding subscription..." << endl;
    cout << endl;
    cout << "Name: \"" << message.gesture_name() << "\"" << endl;
    cout << "Lager: \"" << message.gesture_lager() << endl;
    cout << endl;

    SubscribedGesture subscription;
    subscription.name = message.gesture_name();
    subscription.lager = message.gesture_lager();
    subscription.pid = message.pid();
    g_subscribed_gestures.push_back(subscription);
  }
}

int GetSubscribedGesturesFromFile() {
  ifstream gestures_file;
  string current_line;

  cout << "Current gesture" << endl << "\t" << g_gesture_string << endl
       << endl;

  gestures_file.open("gestures.dat");
  if (!gestures_file.is_open()) {
    return RECOGNIZER_ERROR;
  }

  while (getline(gestures_file, current_line)) {
    string name, lager;
    stringstream ss(current_line);
    ss >> name >> lager;

    SubscribedGesture new_gesture;
    ss >> new_gesture.name >> new_gesture.lager;
    new_gesture.pid = 0;
    g_subscribed_gestures.push_back(new_gesture);
  }

  return RECOGNIZER_NO_ERROR;
}

int main(int argc, const char *argv[]) {
  //printf("Generates strings for movement of tracker %s\n\n", TRACKER_SERVER);

  struct timespec sleep_interval = { 0, MAIN_SLEEP_INTERVAL_MICROSECONDS };
  bool use_buttons = DetermineButtonUse(argc, argv);
  bool use_gestures_file = DetermineGesturesFileUse(argc, argv);
  bool draw_gestures = DetermineGestureDrawing(argc, argv);
  LagerConverter* lager_converter = LagerConverter::Instance();

  if (use_gestures_file) {
    GetSubscribedGesturesFromFile();
  } else {
    CreateGestureSubscriptionQueue();
    boost::thread subscription_updater(AddSubscribedGestures);
  }

  cout << " ________________________________ " << endl;
  cout << "|                                |" << endl;
  cout << "|       COLLECTING DATA...       |" << endl;
  cout << "|________________________________|" << endl;
  cout << "                                  " << endl;

  lager_converter->SetUseButtons(use_buttons);
  lager_converter->Start();

  while(true) {
    g_gesture_string = lager_converter->BlockingGetLagerString();
    RecognizeGesture(use_gestures_file, draw_gestures);
  }
} /* main */
<|endoftext|>


<commit_before>// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests

#include "itkTestMain.h"

void RegisterTests()
{
REGISTER_TEST(itkAntiAliasBinaryImageFilterTest  );
REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest  );
REGISTER_TEST(itkBinaryMask3DMeshSourceTest  );
REGISTER_TEST(itkBallonForce3DFilterTest );
REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkCurvatureFlowTest );
REGISTER_TEST(itkDemonsRegistrationFilterTest );
REGISTER_TEST(itkExtractMeshConnectedRegionsTest );
REGISTER_TEST(itkFastMarchingTest );
REGISTER_TEST(itkFastMarchingExtensionImageFilterTest );
//REGISTER_TEST(itkFEMRegistrationFilterTest );
REGISTER_TEST(itkGeodesicActiveContoursTest );
REGISTER_TEST(itkGradientVectorFlowImageFilterTest );
REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest );
REGISTER_TEST(itkHistogramMatchingImageFilterTest );
REGISTER_TEST(itkImageMomentsTest );
REGISTER_TEST(itkImageRegistrationMethodTest     );
REGISTER_TEST(itkImageRegistrationMethodTest_1 );
REGISTER_TEST(itkImageRegistrationMethodTest_2 );
REGISTER_TEST(itkImageRegistrationMethodTest_3 );
REGISTER_TEST(itkImageRegistrationMethodTest_4 );
REGISTER_TEST(itkImageRegistrationMethodTest_5 );
REGISTER_TEST(itkImageRegistrationMethodTest_6 );
REGISTER_TEST(itkImageRegistrationMethodTest_7 );
REGISTER_TEST(itkImageRegistrationMethodTest_8 );
REGISTER_TEST(itkImageRegistrationMethodTest_9 );
REGISTER_TEST(itkImageRegistrationMethodTest_10);
REGISTER_TEST(itkImageRegistrationMethodTest_11);
REGISTER_TEST(itkImageRegistrationMethodTest_12);
REGISTER_TEST(itkImageRegistrationMethodTest_13);
REGISTER_TEST(itkImageRegistrationMethodTest_14);
REGISTER_TEST(itkImageRegistrationMethodTest_15);
REGISTER_TEST(itkInterpolateTest );
REGISTER_TEST(itkKalmanLinearEstimatorTest );
REGISTER_TEST(itkKmeansModelEstimatorTest );
REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkLevelSetShapeDetectionTest );
REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest );
REGISTER_TEST(itkMeanSquaresImageMetricTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkMRFImageFilterTest );
REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest);
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 );
REGISTER_TEST(itkMutualInformationMetricTest );
REGISTER_TEST(itkNewTest );
REGISTER_TEST(itkNormalizedCorrelationImageMetricTest );
REGISTER_TEST(itkOtsuThresholdImageCalculatorTest );
REGISTER_TEST(itkPatternIntensityImageMetricTest  );
REGISTER_TEST(itkRegionGrow2DTest );
REGISTER_TEST(itkSupervisedImageClassifierTest);
REGISTER_TEST(itkGibbsTest );
REGISTER_TEST(itkDeformableTest );
REGISTER_TEST(itk2DDeformableTest );
REGISTER_TEST(itkSphereMeshSourceTest );
REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkVectorFuzzyConnectednessImageFilterTest );
REGISTER_TEST(itkVoronoiDiagram2DTest );
REGISTER_TEST(itkVoronoiSegmentationImageFilterTest );
REGISTER_TEST(itkWatershedImageFilterTest );
}

<commit_msg>ERR: removed BallonForce3DFilterTest.<commit_after>// this file defines the itkBasicFiltersTest for the test driver
// and all it expects is that you have a function called RegisterTests

#include "itkTestMain.h"

void RegisterTests()
{
REGISTER_TEST(itkAntiAliasBinaryImageFilterTest  );
REGISTER_TEST(itkBinaryMinMaxCurvatureFlowImageFilterTest  );
REGISTER_TEST(itkBinaryMask3DMeshSourceTest  );
REGISTER_TEST(itkCannySegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkCurvatureFlowTest );
REGISTER_TEST(itkDemonsRegistrationFilterTest );
REGISTER_TEST(itkExtractMeshConnectedRegionsTest );
REGISTER_TEST(itkFastMarchingTest );
REGISTER_TEST(itkFastMarchingExtensionImageFilterTest );
//REGISTER_TEST(itkFEMRegistrationFilterTest );
REGISTER_TEST(itkGeodesicActiveContoursTest );
REGISTER_TEST(itkGradientVectorFlowImageFilterTest );
REGISTER_TEST(itkSimpleFuzzyConnectednessScalarImageFilterTest );
REGISTER_TEST(itkHistogramMatchingImageFilterTest );
REGISTER_TEST(itkImageMomentsTest );
REGISTER_TEST(itkImageRegistrationMethodTest     );
REGISTER_TEST(itkImageRegistrationMethodTest_1 );
REGISTER_TEST(itkImageRegistrationMethodTest_2 );
REGISTER_TEST(itkImageRegistrationMethodTest_3 );
REGISTER_TEST(itkImageRegistrationMethodTest_4 );
REGISTER_TEST(itkImageRegistrationMethodTest_5 );
REGISTER_TEST(itkImageRegistrationMethodTest_6 );
REGISTER_TEST(itkImageRegistrationMethodTest_7 );
REGISTER_TEST(itkImageRegistrationMethodTest_8 );
REGISTER_TEST(itkImageRegistrationMethodTest_9 );
REGISTER_TEST(itkImageRegistrationMethodTest_10);
REGISTER_TEST(itkImageRegistrationMethodTest_11);
REGISTER_TEST(itkImageRegistrationMethodTest_12);
REGISTER_TEST(itkImageRegistrationMethodTest_13);
REGISTER_TEST(itkImageRegistrationMethodTest_14);
REGISTER_TEST(itkImageRegistrationMethodTest_15);
REGISTER_TEST(itkInterpolateTest );
REGISTER_TEST(itkKalmanLinearEstimatorTest );
REGISTER_TEST(itkKmeansModelEstimatorTest );
REGISTER_TEST(itkLaplacianSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkLevelSetShapeDetectionTest );
REGISTER_TEST(itkMattesMutualInformationImageToImageMetricTest );
REGISTER_TEST(itkMeanSquaresImageMetricTest );
REGISTER_TEST(itkMinimumMaximumImageCalculatorTest );
REGISTER_TEST(itkMinMaxCurvatureFlowImageFilterTest );
REGISTER_TEST(itkMRFImageFilterTest );
REGISTER_TEST(itkMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkRecursiveMultiResolutionPyramidImageFilterTest );
REGISTER_TEST(itkMultiResolutionPDEDeformableRegistrationTest );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest);
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_1 );
REGISTER_TEST(itkMultiResolutionImageRegistrationMethodTest_2 );
REGISTER_TEST(itkMutualInformationMetricTest );
REGISTER_TEST(itkNewTest );
REGISTER_TEST(itkNormalizedCorrelationImageMetricTest );
REGISTER_TEST(itkOtsuThresholdImageCalculatorTest );
REGISTER_TEST(itkPatternIntensityImageMetricTest  );
REGISTER_TEST(itkRegionGrow2DTest );
REGISTER_TEST(itkSupervisedImageClassifierTest);
REGISTER_TEST(itkGibbsTest );
REGISTER_TEST(itkDeformableTest );
REGISTER_TEST(itk2DDeformableTest );
REGISTER_TEST(itkSphereMeshSourceTest );
REGISTER_TEST(itkThresholdSegmentationLevelSetImageFilterTest );
REGISTER_TEST(itkVectorFuzzyConnectednessImageFilterTest );
REGISTER_TEST(itkVoronoiDiagram2DTest );
REGISTER_TEST(itkVoronoiSegmentationImageFilterTest );
REGISTER_TEST(itkWatershedImageFilterTest );
}

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLargeImageWriteReadTest.cxx
  Language:  C++
  Date:      $Date$xgoto-l

  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkTimeProbesCollectorBase.h"

int itkLargeImageWriteReadTest(int ac, char* av[])
{

  if (ac < 3)
    {
    std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl;
    return EXIT_FAILURE;
    }

  typedef unsigned short  PixelType;
  typedef itk::Image<PixelType,2> ImageType;

  typedef itk::ImageFileWriter< ImageType >   WriterType;
  typedef itk::ImageFileReader< ImageType >   ReaderType;

  ImageType::Pointer image = ImageType::New();
  ImageType::RegionType region;
  ImageType::IndexType index;
  ImageType::SizeType size;

  itk::TimeProbesCollectorBase chronometer;

  const unsigned long numberOfPixelsInOneDimension = atol( av[2] );

  size.Fill( numberOfPixelsInOneDimension );
  index.Fill(0);
  region.SetSize(size);
  region.SetIndex(index);

  image->SetRegions(region);

  const unsigned long sizeInMegaBytes =
    static_cast< unsigned long >(
      ( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) /
      ( 1024.0 * 1024.0 ) );

  std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl;

  chronometer.Start("Allocate");
  image->Allocate();
  chronometer.Stop("Allocate");

  std::cout << "Initializing pixel values " << std::endl;
  typedef itk::ImageRegionIterator< ImageType >  IteratorType;
  typedef itk::ImageRegionConstIterator< ImageType >  ConstIteratorType;

  IteratorType itr( image, region );
  itr.GoToBegin();

  PixelType pixelValue = itk::NumericTraits< PixelType >::Zero;

  chronometer.Start("Initializing");
  while( !itr.IsAtEnd() )
    {
    itr.Set( pixelValue );
    ++pixelValue;
    ++itr;
    }
  chronometer.Stop("Initializing");

  std::cout << "Trying to write the image to disk" << std::endl;
  try
    {
    WriterType::Pointer writer = WriterType::New();
    writer->SetInput(image);
    writer->SetFileName(av[1]);
    chronometer.Start("Write");
    writer->Update();
    chronometer.Stop("Write");
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Trying to read the image back from disk" << std::endl;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(av[1]);

  try
    {
    chronometer.Start("Read");
    reader->Update();
    chronometer.Stop("Read");
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex << std::endl;
    return EXIT_FAILURE;
    }

  ImageType::ConstPointer readImage = reader->GetOutput();

  ConstIteratorType ritr( readImage, region );
  IteratorType oitr( image, region );

  ritr.GoToBegin();
  oitr.GoToBegin();

  std::cout << "Comparing the pixel values.. :" << std::endl;

  chronometer.Start("Compare");
  while( !ritr.IsAtEnd() )
    {
    if( oitr.Get() != ritr.Get() )
      {
      std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl;
      return EXIT_FAILURE;
      }
    ++oitr;
    ++ritr;
    }
  chronometer.Stop("Compare");

  chronometer.Report( std::cout );

  std::cout << std::endl;
  std::cout << "Test PASSED !" << std::endl;

  return EXIT_SUCCESS;

}
<commit_msg>ENH: Now testing the values of the pixels in both the created image and      the read image. Before we were assuming that the values assigned to      pixels were correct. Now we check for them.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkLargeImageWriteReadTest.cxx
  Language:  C++
  Date:      $Date$xgoto-l

  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImage.h"
#include "itkImageFileWriter.h"
#include "itkImageFileReader.h"
#include "itkImageRegionIterator.h"
#include "itkTimeProbesCollectorBase.h"

int itkLargeImageWriteReadTest(int ac, char* av[])
{

  if (ac < 3)
    {
    std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl;
    return EXIT_FAILURE;
    }

  typedef unsigned short  PixelType;
  typedef itk::Image<PixelType,2> ImageType;

  typedef itk::ImageFileWriter< ImageType >   WriterType;
  typedef itk::ImageFileReader< ImageType >   ReaderType;

  ImageType::Pointer image = ImageType::New();
  ImageType::RegionType region;
  ImageType::IndexType index;
  ImageType::SizeType size;

  itk::TimeProbesCollectorBase chronometer;

  const unsigned long numberOfPixelsInOneDimension = atol( av[2] );

  size.Fill( numberOfPixelsInOneDimension );
  index.Fill(0);
  region.SetSize(size);
  region.SetIndex(index);

  image->SetRegions(region);

  const unsigned long sizeInMegaBytes =
    static_cast< unsigned long >(
      ( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) /
      ( 1024.0 * 1024.0 ) );

  std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl;

  chronometer.Start("Allocate");
  image->Allocate();
  chronometer.Stop("Allocate");

  std::cout << "Initializing pixel values " << std::endl;
  typedef itk::ImageRegionIterator< ImageType >  IteratorType;
  typedef itk::ImageRegionConstIterator< ImageType >  ConstIteratorType;

  IteratorType itr( image, region );
  itr.GoToBegin();

  PixelType pixelValue = itk::NumericTraits< PixelType >::Zero;

  chronometer.Start("Initializing");
  while( !itr.IsAtEnd() )
    {
    itr.Set( pixelValue );
    ++pixelValue;
    ++itr;
    }
  chronometer.Stop("Initializing");

  std::cout << "Trying to write the image to disk" << std::endl;
  try
    {
    WriterType::Pointer writer = WriterType::New();
    writer->SetInput(image);
    writer->SetFileName(av[1]);
    chronometer.Start("Write");
    writer->Update();
    chronometer.Stop("Write");
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Trying to read the image back from disk" << std::endl;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(av[1]);

  try
    {
    chronometer.Start("Read");
    reader->Update();
    chronometer.Stop("Read");
    }
  catch (itk::ExceptionObject &ex)
    {
    std::cout << ex << std::endl;
    return EXIT_FAILURE;
    }

  ImageType::ConstPointer readImage = reader->GetOutput();

  ConstIteratorType ritr( readImage, region );
  IteratorType oitr( image, region );

  ritr.GoToBegin();
  oitr.GoToBegin();

  std::cout << "Comparing the pixel values.. :" << std::endl;

  pixelValue = itk::NumericTraits< PixelType >::Zero;

  chronometer.Start("Compare");
  while( !ritr.IsAtEnd() )
    {
    if( ( oitr.Get() != ritr.Get() ) || ( oitr.Get() != pixelValue ) )
      {
      std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl;
      std::cerr << "Expected pixel value " << pixelValue << std::endl;
      std::cerr << "Original Image pixel value " << oitr.Get() << std::endl;
      std::cerr << "Read Image pixel value " << ritr.Get() << std::endl;
      return EXIT_FAILURE;
      }

    ++pixelValue;
    ++oitr;
    ++ritr;
    }
  chronometer.Stop("Compare");

  chronometer.Report( std::cout );

  std::cout << std::endl;
  std::cout << "Test PASSED !" << std::endl;

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: RptObject.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _REPORT_RPTUIOBJ_HXX
#define _REPORT_RPTUIOBJ_HXX

#include <svx/svdoole2.hxx>
#include <svx/svdouno.hxx>

#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/report/XReportComponent.hpp>
#include <com/sun/star/report/XSection.hpp>
#include <svx/svdocirc.hxx>
#include <svx/svdogrp.hxx>
#include <svx/svdoashp.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/implementationreference.hxx>
#include "dllapi.h"

namespace rptui
{
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
    enum DlgEdHintKind
    {
        RPTUI_HINT_UNKNOWN,
        RPTUI_HINT_WINDOWSCROLLED,
        RPTUI_HINT_LAYERCHANGED,
        RPTUI_HINT_OBJORDERCHANGED,
        RPTUI_HINT_SELECTIONCHANGED
    };

    class OUnoObject;
    class REPORTDESIGN_DLLPUBLIC DlgEdHint: public SfxHint
    {
    private:
        DlgEdHintKind   eHintKind;
        OUnoObject*     pDlgEdObj;

        DlgEdHint(DlgEdHint&);
        void operator =(DlgEdHint&);
    public:
        TYPEINFO();
        DlgEdHint( DlgEdHintKind eHint );
        virtual ~DlgEdHint();

        inline DlgEdHintKind    GetKind() const { return eHintKind; }
        inline OUnoObject*      GetObject() const { return pDlgEdObj; }
    };

class OReportPage;
class OPropertyMediator;

class REPORTDESIGN_DLLPUBLIC OObjectBase
{
public:
    typedef ::comphelper::ImplementationReference<OPropertyMediator,::com::sun::star::beans::XPropertyChangeListener> TMediator;

protected:
    mutable TMediator                                                                           m_xMediator;
    mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
    //mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>
    mutable ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>       m_xReportComponent;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener>          m_xContainerListener;
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>                       m_xSection;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >                       m_xKeepShapeAlive;
    ::rtl::OUString m_sComponentName;
    sal_Bool        m_bIsListening;

    OObjectBase(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    OObjectBase(const ::rtl::OUString& _sComponentName);

    virtual ~OObjectBase();

    inline sal_Bool isListening() const { return m_bIsListening; }

    void SetPropsFromRect(const Rectangle& _rRect);

    virtual void SetSnapRectImpl(const Rectangle& _rRect) = 0;
    virtual SdrPage* GetImplPage() const = 0;
    virtual void SetObjectItemHelper(const SfxPoolItem& rItem);
    sal_Bool IsInside(const Rectangle& _rRect,const Point& rPnt,USHORT nTol) const;

    /** called by instances of derived classes to implement their overloading of getUnoShape
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            getUnoShapeOf( SdrObject& _rSdrObject );

private:
    static void    ensureSdrObjectOwnership(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxShape );

public:
    void StartListening();
    void EndListening(sal_Bool bRemoveListener = sal_True);
    // PropertyChangeListener
    virtual void _propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);

    sal_Bool        supportsService( const ::rtl::OUString& _sServiceName ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> getReportComponent() const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
    inline void setOldParent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) { m_xSection = _xSection; }
    inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getOldParent() const { return m_xSection;}
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getSection() const;
    inline const ::rtl::OUString getServiceName() const { return m_sComponentName; }

    /** releases the reference to our UNO shape (m_xKeepShapeAlive)
    */
    void    releaseUnoShape() { m_xKeepShapeAlive.clear(); }

    static SdrObject* createObject(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    static sal_uInt16 getObjectType(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
};
//============================================================================
// OCustomShape
//============================================================================
class REPORTDESIGN_DLLPUBLIC OCustomShape: public SdrObjCustomShape , public OObjectBase
{
    friend class OReportPage;
    friend class DlgEdFactory;

public:
    static OCustomShape* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent )
    {
        return new OCustomShape( _xComponent );
    }

protected:
    OCustomShape(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    OCustomShape(const ::rtl::OUString& _sComponentName);

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;
    void SetObjectItemHelper(const SfxPoolItem& rItem);

public:
    TYPEINFO();

    virtual ~OCustomShape();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
};

//============================================================================
// OOle2Obj
//============================================================================
class REPORTDESIGN_DLLPUBLIC OOle2Obj: public SdrOle2Obj , public OObjectBase
{
    friend class OReportPage;
    friend class DlgEdFactory;

    UINT16 m_nType;
    void impl_createDataProvider_nothrow( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
public:
    static OOle2Obj* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType )
    {
        return new OOle2Obj( _xComponent,_nType );
    }
    OOle2Obj(const ::rtl::OUString& _sComponentName,const svt::EmbeddedObjectRef& rNewObjRef, const String& rNewObjName, const Rectangle& rNewRect,UINT16 _nType, FASTBOOL bFrame_=FALSE);

protected:
    OOle2Obj(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType);
    OOle2Obj(const ::rtl::OUString& _sComponentName,UINT16 _nType);

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;

public:
    TYPEINFO();

    virtual ~OOle2Obj();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
    // Clone() soll eine komplette Kopie des Objektes erzeugen.
    virtual SdrObject* Clone() const;

    void initializeChart( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
};

//============================================================================
// OUnoObject
//============================================================================
class REPORTDESIGN_DLLPUBLIC OUnoObject: public SdrUnoObj , public OObjectBase
{
    friend class OReportPage;
    friend class OObjectBase;
    friend class DlgEdFactory;

    sal_uInt16   m_nObjectType;
protected:
    OUnoObject(const ::rtl::OUString& _sComponentName
                ,const ::rtl::OUString& rModelName
                ,sal_uInt16   _nObjectType);
    OUnoObject(  const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent
                ,const ::rtl::OUString& rModelName
                ,sal_uInt16   _nObjectType);

    virtual ~OUnoObject();

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;

public:
    TYPEINFO();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual void _propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);

    /** creates the m_xMediator when it doesn't already exist.
        @param  _bReverse   when set to <TRUE/> then the properties from the uno control will be copied into report control
    */
    void CreateMediator(sal_Bool _bReverse = sal_False);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    static ::rtl::OUString GetDefaultName(const OUnoObject* _pObj);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
    virtual SdrObject* Clone() const;
};

//============================================================================
} // rptui
//============================================================================
#endif // _REPORT_RPTUIOBJ_HXX

<commit_msg>INTEGRATION: CWS dba31a (1.7.12); FILE MERGED 2008/07/15 08:38:54 fs 1.7.12.1: remove unused code Issue number:  #i91592# Submitted by:  cmc@openoffice.org Reviewed by:   frank.schoenheit@sun.com<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: RptObject.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _REPORT_RPTUIOBJ_HXX
#define _REPORT_RPTUIOBJ_HXX

#include <svx/svdoole2.hxx>
#include <svx/svdouno.hxx>

#include <comphelper/processfactory.hxx>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/report/XReportComponent.hpp>
#include <com/sun/star/report/XSection.hpp>
#include <svx/svdocirc.hxx>
#include <svx/svdogrp.hxx>
#include <svx/svdoashp.hxx>
#include <comphelper/stl_types.hxx>
#include <comphelper/implementationreference.hxx>
#include "dllapi.h"

namespace rptui
{
typedef ::std::multimap< sal_Int16, ::rtl::OUString, ::std::less< sal_Int16 > > IndexToNameMap;
    enum DlgEdHintKind
    {
        RPTUI_HINT_UNKNOWN,
        RPTUI_HINT_WINDOWSCROLLED,
        RPTUI_HINT_LAYERCHANGED,
        RPTUI_HINT_OBJORDERCHANGED,
        RPTUI_HINT_SELECTIONCHANGED
    };

    class OUnoObject;
    class REPORTDESIGN_DLLPUBLIC DlgEdHint: public SfxHint
    {
    private:
        DlgEdHintKind   eHintKind;
        OUnoObject*     pDlgEdObj;

        DlgEdHint(DlgEdHint&);
        void operator =(DlgEdHint&);
    public:
        TYPEINFO();
        DlgEdHint( DlgEdHintKind eHint );
        virtual ~DlgEdHint();

        inline DlgEdHintKind    GetKind() const { return eHintKind; }
        inline OUnoObject*      GetObject() const { return pDlgEdObj; }
    };

class OReportPage;
class OPropertyMediator;

class REPORTDESIGN_DLLPUBLIC OObjectBase
{
public:
    typedef ::comphelper::ImplementationReference<OPropertyMediator,::com::sun::star::beans::XPropertyChangeListener> TMediator;

protected:
    mutable TMediator                                                                           m_xMediator;
    mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener> m_xPropertyChangeListener;
    //mutable ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener>
    mutable ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>       m_xReportComponent;
    ::com::sun::star::uno::Reference< ::com::sun::star::container::XContainerListener>          m_xContainerListener;
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>                       m_xSection;
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >                       m_xKeepShapeAlive;
    ::rtl::OUString m_sComponentName;
    sal_Bool        m_bIsListening;

    OObjectBase(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    OObjectBase(const ::rtl::OUString& _sComponentName);

    virtual ~OObjectBase();

    inline sal_Bool isListening() const { return m_bIsListening; }

    void SetPropsFromRect(const Rectangle& _rRect);

    virtual void SetSnapRectImpl(const Rectangle& _rRect) = 0;
    virtual SdrPage* GetImplPage() const = 0;
    virtual void SetObjectItemHelper(const SfxPoolItem& rItem);
    sal_Bool IsInside(const Rectangle& _rRect,const Point& rPnt,USHORT nTol) const;

    /** called by instances of derived classes to implement their overloading of getUnoShape
    */
    ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
            getUnoShapeOf( SdrObject& _rSdrObject );

private:
    static void    ensureSdrObjectOwnership(
                    const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxShape );

public:
    void StartListening();
    void EndListening(sal_Bool bRemoveListener = sal_True);
    // PropertyChangeListener
    virtual void _propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);

    sal_Bool        supportsService( const ::rtl::OUString& _sServiceName ) const;

    ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> getReportComponent() const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();
    inline void setOldParent(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection) { m_xSection = _xSection; }
    inline ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getOldParent() const { return m_xSection;}
    ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection> getSection() const;
    inline const ::rtl::OUString getServiceName() const { return m_sComponentName; }

    /** releases the reference to our UNO shape (m_xKeepShapeAlive)
    */
    void    releaseUnoShape() { m_xKeepShapeAlive.clear(); }

    static SdrObject* createObject(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    static sal_uInt16 getObjectType(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
};
//============================================================================
// OCustomShape
//============================================================================
class REPORTDESIGN_DLLPUBLIC OCustomShape: public SdrObjCustomShape , public OObjectBase
{
    friend class OReportPage;
    friend class DlgEdFactory;

public:
    static OCustomShape* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent )
    {
        return new OCustomShape( _xComponent );
    }

protected:
    OCustomShape(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent);
    OCustomShape(const ::rtl::OUString& _sComponentName);

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;
    void SetObjectItemHelper(const SfxPoolItem& rItem);

public:
    TYPEINFO();

    virtual ~OCustomShape();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
};

//============================================================================
// OOle2Obj
//============================================================================
class REPORTDESIGN_DLLPUBLIC OOle2Obj: public SdrOle2Obj , public OObjectBase
{
    friend class OReportPage;
    friend class DlgEdFactory;

    UINT16 m_nType;
    void impl_createDataProvider_nothrow( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
public:
    static OOle2Obj* Create( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType )
    {
        return new OOle2Obj( _xComponent,_nType );
    }
protected:
    OOle2Obj(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent,UINT16 _nType);
    OOle2Obj(const ::rtl::OUString& _sComponentName,UINT16 _nType);

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;

public:
    TYPEINFO();

    virtual ~OOle2Obj();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
    // Clone() soll eine komplette Kopie des Objektes erzeugen.
    virtual SdrObject* Clone() const;

    void initializeChart( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel>& _xModel);
};

//============================================================================
// OUnoObject
//============================================================================
class REPORTDESIGN_DLLPUBLIC OUnoObject: public SdrUnoObj , public OObjectBase
{
    friend class OReportPage;
    friend class OObjectBase;
    friend class DlgEdFactory;

    sal_uInt16   m_nObjectType;
protected:
    OUnoObject(const ::rtl::OUString& _sComponentName
                ,const ::rtl::OUString& rModelName
                ,sal_uInt16   _nObjectType);
    OUnoObject(  const ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent>& _xComponent
                ,const ::rtl::OUString& rModelName
                ,sal_uInt16   _nObjectType);

    virtual ~OUnoObject();

    virtual void NbcMove( const Size& rSize );
    virtual void NbcResize(const Point& rRef, const Fraction& xFact, const Fraction& yFact);
    virtual void NbcSetLogicRect(const Rectangle& rRect);
    virtual FASTBOOL EndCreate(SdrDragStat& rStat, SdrCreateCmd eCmd);

    virtual void SetSnapRectImpl(const Rectangle& _rRect);
    virtual SdrPage* GetImplPage() const;

public:
    TYPEINFO();

    virtual sal_Int32   GetStep() const;

    virtual SdrObject* CheckHit(const Point& rPnt,USHORT nTol,const SetOfByte*) const;
    virtual void _propertyChange( const  ::com::sun::star::beans::PropertyChangeEvent& evt ) throw(::com::sun::star::uno::RuntimeException);

    /** creates the m_xMediator when it doesn't already exist.
        @param  _bReverse   when set to <TRUE/> then the properties from the uno control will be copied into report control
    */
    void CreateMediator(sal_Bool _bReverse = sal_False);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> getAwtComponent();

    static ::rtl::OUString GetDefaultName(const OUnoObject* _pObj);

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > getUnoShape();
    virtual UINT16 GetObjIdentifier() const;
    virtual UINT32 GetObjInventor() const;
    virtual SdrObject* Clone() const;
};

//============================================================================
} // rptui
//============================================================================
#endif // _REPORT_RPTUIOBJ_HXX

<|endoftext|>


<commit_before>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/tensor.h"
#include "math/random.hpp"
#include "tensor/random.hpp"
#include "tensor/conv2d_cpp.hpp"
#include "tensor/conv2d_dyn.hpp"
#include "tensor/conv2d_eig.hpp"
#include "tensor/corr2d_cpp.hpp"
#include "tensor/corr2d_dyn.hpp"
#include "tensor/corr2d_egb.hpp"
#include "tensor/corr2d_egr.hpp"
#include "text/table_row_mark.h"
#include "cortex/util/measure.hpp"
#include <iostream>

namespace
{
        using namespace cortex;

        std::string make_header(const int isize, const int ksize)
        {
                const int osize = isize - ksize + 1;

                return  "(" +
                        text::to_string(isize) + "x" +
                        text::to_string(isize) + " @ " +
                        text::to_string(ksize) + "x" +
                        text::to_string(ksize) + " -> " +
                        text::to_string(osize) + "x" +
                        text::to_string(osize) +
                        ")";
        }

        template
        <
                typename tmatrix
        >
        void make_matrices(const int isize, const int ksize,
                tmatrix& idata, tmatrix& kdata, tmatrix& odata)
        {
                const int osize = isize - ksize + 1;

                math::random_t<typename tmatrix::Scalar> rng(-1.0 / isize, 1.0 / isize);

                idata.resize(isize, isize);
                kdata.resize(ksize, ksize);
                odata.resize(osize, osize);

                tensor::set_random(idata, rng);
                tensor::set_random(kdata, rng);
                tensor::set_random(odata, rng);
        }

        template
        <
                typename top,
                typename tmatrixi,
                typename tmatrixk,
                typename tmatrixo
        >
        auto measure_op(const top& op,
                const tmatrixi& idata, const tmatrixk& kdata, tmatrixo&& odata, const size_t trials = 16)
        {
                return cortex::measure_robustly_nsec([&] ()
                {
                        op(idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename tmatrix
        >
        void test_config_conv(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
        {
                tmatrix idata, kdata, odata;
                make_matrices(isize, ksize, idata, kdata, odata);

                tmatrix odata_ret = odata;

                row << measure_op(tensor::conv2d_eig_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_cpp_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dot_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dot_dyn_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_mad_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_mad_dyn_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dyn_t(), idata, kdata, odata_ret, trials).count();
        }

        template
        <
                typename tmatrix
        >
        void test_config_corr(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
        {
                tmatrix idata, kdata, odata;
                make_matrices(isize, ksize, idata, kdata, odata);

                tmatrix idata_ret = idata;

                row << measure_op(tensor::corr2d_egb_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_egr_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_cpp_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdk_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdk_dyn_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdo_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdo_dyn_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_dyn_t(), odata, kdata, idata_ret, trials).count();
        }
}

int main(int argc, char* argv[])
{
        using namespace cortex;

        const int min_isize = 4;
        const int max_isize = 48;

        const int min_ksize = 3;
        const int max_ksize = 15;

        // parse the command line
        text::cmdline_t cmdline("benchmark 2D convolutions & correlations");
        cmdline.add("", "conv", "benchmark convolutions");
        cmdline.add("", "corr", "benchmark correlations");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto has_conv = cmdline.has("conv");
        const auto has_corr = cmdline.has("corr");

        if (!has_conv && !has_corr)
        {
                cmdline.usage();
        }

        // convolutions
        if (has_conv)
        {
                text::table_t table("size\\convolution [ns]");
                table.header()
                        << "eig"
                        << "cpp"
                        << "dot"
                        << "dot-dyn"
                        << "mad"
                        << "mad-dyn"
                        << "dyn";

                for (int isize = min_isize; isize <= max_isize; ++ isize)
                {
                        for (int ksize = min_ksize; ksize <= isize; ++ ksize)
                        {
                                const auto header = make_header(isize, ksize);
                                test_config_conv<matrix_t>(isize, ksize, table.append(header));
                        }
                }

                table.mark(text::make_table_mark_minimum_col<size_t>());
                table.print(std::cout);
        }

        // correlations
        if (has_corr)
        {
                text::table_t table("size\\correlation [ns]");
                table.header()
                        << "egb"
                        << "egr"
                        << "cpp"
                        << "mdk"
                        << "mdk-dyn"
                        << "mdo"
                        << "mdo-dyn"
                        << "dyn";

                for (int isize = min_isize; isize <= max_isize; ++ isize)
                {
                        for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
                        {
                                const auto header = make_header(isize, ksize);
                                test_config_corr<matrix_t>(isize, ksize, table.append(header));
                        }
                }

                table.mark(text::make_table_mark_minimum_col<size_t>());
                table.print(std::cout);
        }

        return EXIT_SUCCESS;
}

<commit_msg>benchmark convolutions similarly to the ones used in convnets<commit_after>#include "text/table.h"
#include "text/cmdline.h"
#include "cortex/tensor.h"
#include "math/random.hpp"
#include "tensor/random.hpp"
#include "tensor/conv2d_cpp.hpp"
#include "tensor/conv2d_dyn.hpp"
#include "tensor/conv2d_eig.hpp"
#include "tensor/corr2d_cpp.hpp"
#include "tensor/corr2d_dyn.hpp"
#include "tensor/corr2d_egb.hpp"
#include "tensor/corr2d_egr.hpp"
#include "text/table_row_mark.h"
#include "cortex/util/measure.hpp"
#include <set>
#include <iostream>

namespace
{
        using namespace cortex;

        std::string make_header(const int isize, const int ksize)
        {
                const int osize = isize - ksize + 1;

                return  "(" +
                        text::to_string(isize) + "x" +
                        text::to_string(isize) + " @ " +
                        text::to_string(ksize) + "x" +
                        text::to_string(ksize) + " -> " +
                        text::to_string(osize) + "x" +
                        text::to_string(osize) +
                        ")";
        }

        template
        <
                typename tmatrix
        >
        void make_matrices(const int isize, const int ksize,
                tmatrix& idata, tmatrix& kdata, tmatrix& odata)
        {
                const int osize = isize - ksize + 1;

                math::random_t<typename tmatrix::Scalar> rng(-1.0 / isize, 1.0 / isize);

                idata.resize(isize, isize);
                kdata.resize(ksize, ksize);
                odata.resize(osize, osize);

                tensor::set_random(idata, rng);
                tensor::set_random(kdata, rng);
                tensor::set_random(odata, rng);
        }

        template
        <
                typename top,
                typename tmatrixi,
                typename tmatrixk,
                typename tmatrixo
        >
        auto measure_op(const top& op,
                const tmatrixi& idata, const tmatrixk& kdata, tmatrixo&& odata, const size_t trials = 16)
        {
                return cortex::measure_robustly_nsec([&] ()
                {
                        op(idata, kdata, odata);
                }, trials);
        }

        template
        <
                typename tmatrix
        >
        void test_config_conv(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
        {
                tmatrix idata, kdata, odata;
                make_matrices(isize, ksize, idata, kdata, odata);

                tmatrix odata_ret = odata;

                row << measure_op(tensor::conv2d_eig_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_cpp_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dot_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dot_dyn_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_mad_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_mad_dyn_t(), idata, kdata, odata_ret, trials).count();
                row << measure_op(tensor::conv2d_dyn_t(), idata, kdata, odata_ret, trials).count();
        }

        template
        <
                typename tmatrix
        >
        void test_config_corr(const int isize, const int ksize, text::table_row_t& row, const size_t trials = 16)
        {
                tmatrix idata, kdata, odata;
                make_matrices(isize, ksize, idata, kdata, odata);

                tmatrix idata_ret = idata;

                row << measure_op(tensor::corr2d_egb_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_egr_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_cpp_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdk_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdk_dyn_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdo_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_mdo_dyn_t(), odata, kdata, idata_ret, trials).count();
                row << measure_op(tensor::corr2d_dyn_t(), odata, kdata, idata_ret, trials).count();
        }
}

int main(int argc, char* argv[])
{
        using namespace cortex;

        const int min_isize = 4;
        const int max_isize = 48;

        const int min_ksize = 3;
        const int max_ksize = 15;

        // parse the command line
        text::cmdline_t cmdline("benchmark 2D convolutions & correlations");
        cmdline.add("", "conv", "benchmark convolutions");
        cmdline.add("", "corr", "benchmark correlations");

        cmdline.process(argc, argv);

        // check arguments and options
        const auto has_conv = cmdline.has("conv");
        const auto has_corr = cmdline.has("corr");

        if (!has_conv && !has_corr)
        {
                cmdline.usage();
        }

        // convolutions
        if (has_conv)
        {
                text::table_t table("size\\convolution [ns]");
                table.header()
                        << "eig"
                        << "cpp"
                        << "dot"
                        << "dot-dyn"
                        << "mad"
                        << "mad-dyn"
                        << "dyn";

                for (int isize = min_isize; isize <= max_isize; ++ isize)
                {
                        std::set<int> ksizes;
                        for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
                        {
                                ksizes.insert(ksize);
                                ksizes.insert(isize - ksize + 1);
                        }

                        for (auto ksize : ksizes)
                        {
                                const auto header = make_header(isize, ksize);
                                test_config_conv<matrix_t>(isize, ksize, table.append(header));
                        }
                }

                table.mark(text::make_table_mark_minimum_col<size_t>());
                table.print(std::cout);
        }

        // correlations
        if (has_corr)
        {
                text::table_t table("size\\correlation [ns]");
                table.header()
                        << "egb"
                        << "egr"
                        << "cpp"
                        << "mdk"
                        << "mdk-dyn"
                        << "mdo"
                        << "mdo-dyn"
                        << "dyn";

                for (int isize = min_isize; isize <= max_isize; ++ isize)
                {
                        for (int ksize = min_ksize; ksize <= std::min(isize, max_ksize); ksize += 2)
                        {
                                const auto header = make_header(isize, ksize);
                                test_config_corr<matrix_t>(isize, ksize, table.append(header));
                        }
                }

                table.mark(text::make_table_mark_minimum_col<size_t>());
                table.print(std::cout);
        }

        return EXIT_SUCCESS;
}

<|endoftext|>