<commit_before>////////////////////////////////////////////////////////////////////////////////
// Name:      support.cpp
// Purpose:   Implementation of DecoratedFrame class
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
#include <wx/extension/report/listviewfile.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"

DecoratedFrame::DecoratedFrame()
  : wxExFrameWithHistory(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppDisplayName(), // title
      25,                            // maxFiles
      4)                             // maxProjects
{
  SetIcon(wxICON(app));

#if wxUSE_STATUSBAR
  std::vector<wxExStatusBarPane> panes;
  panes.push_back(wxExStatusBarPane());
  panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type")));
  panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines or items")));

  if (wxExLexers::Get()->GetCount() > 0)
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif

    panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer")));
    panes.push_back(wxExStatusBarPane("PaneTheme", lexer_size, _("Theme")));
  }

  if (wxExVCS::GetCount() > 0)
  {
    panes.push_back(wxExStatusBarPane("PaneVCS", 75, _("VCS")));
  }

  panes.push_back(wxExStatusBarPane("PaneMacro", 75));

  SetupStatusBar(panes);

  if (wxExVCS::GetCount() > 0)
  {
    wxExVCS vcs;
    vcs.GetDir();
    StatusText(vcs.GetName(), "PaneVCS");
  }
#endif

  wxExMenu *menuFile = new wxExMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE,
    _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu *menuEdit = new wxExMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_JUMP_TO);
  menuEdit->AppendSeparator();
  wxExMenu* menuFind = new wxExMenu();

  if (wxConfigBase::Get()->ReadBool(_("vi mode"), true))
  {
    // No accelerators for vi mode, Ctrl F is page down.
    menuFind->Append(wxID_FIND, wxGetStockLabel(wxID_FIND));
    menuFind->Append(wxID_REPLACE, wxGetStockLabel(wxID_REPLACE));
  }
  else
  {
    menuFind->Append(wxID_FIND);
    menuFind->Append(wxID_REPLACE);
  }

  menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &in Files")));
  menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace in File&s")));
  menuEdit->AppendSubMenu(menuFind, _("&Find and Replace"));
  menuEdit->AppendSeparator();
  menuEdit->Append(
    ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+K"));
  menuEdit->AppendSeparator();

  wxExMenu* menuMacro = new wxExMenu();
  menuMacro->Append(ID_EDIT_MACRO_START_RECORD, wxExEllipsed(_("Start Record")));
  menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuMacro->AppendSeparator();
  menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, wxExEllipsed(_("Playback"), "Ctrl+M"));

  if (wxExViMacros::GetFileName().FileExists())
  {
    menuMacro->AppendSeparator();
    menuMacro->Append(ID_EDIT_MACRO, wxGetStockLabel(wxID_EDIT));
  }

  menuEdit->AppendSubMenu(menuMacro, _("&Macro"));

  wxExMenu *menuView = new wxExMenu;
  menuView->AppendBars();
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
  menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
  menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
  menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
  menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(wxID_EXECUTE);
  menuProcess->Append(wxID_STOP);

  wxExMenu *menuProject = new wxExMenu();
  menuProject->Append(
    ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
  menuProject->Append(
    ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open as Text"));
  menuProject->Append(
    ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE);
  menuProject->AppendSeparator();
  menuProject->Append(
    ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
  menuProject->Append(
    ID_PROJECT_SAVEAS,
    wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();

  if (wxExVCS::GetCount() > 0)
  {
    menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS")));
    menuOptions->AppendSeparator();
  }

  menuOptions->Append(
    ID_OPTION_COMPARATOR, wxExEllipsed(_("Set &Comparator")));
  menuOptions->AppendSeparator();

  menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
  // text also used as caption
  menuOptions->Append(
    ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
  menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));

  wxExMenu *menuHelp = new wxExMenu(); // use wxExMenu for art with HELP
  menuHelp->Append(wxID_ABOUT);
  menuHelp->Append(wxID_HELP);

  wxMenuBar* menubar = new wxMenuBar();
  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  SetMenuBar(menubar);
}

bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  switch (id)
  {
  case NOTEBOOK_EDITORS:
    {
      wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile());

      if (dlg.ShowModalIfChanged() != wxID_OK)
      {
        return false;
      }
    }
  break;
  case NOTEBOOK_PROJECTS:
    {
      wxExFileDialog dlg(this, (wxExListViewFile*)page);

      if (dlg.ShowModalIfChanged() != wxID_OK)
      {
        return false;
      }
    }
  break;
  }

  return wxExFrameWithHistory::AllowClose(id, page);
}

void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  wxExFrameWithHistory::OnNotebook(id, page);

  switch (id)
  {
    case NOTEBOOK_EDITORS:
      ((wxExSTC*)page)->PropertiesMessage();
    break;
    case NOTEBOOK_LISTS:
    break;
    case NOTEBOOK_PROJECTS:
#if wxUSE_STATUSBAR
      wxExLogStatus(((wxExListViewFile*)page)->GetFileName());
      UpdateStatusBar((wxExListViewFile*)page);
#endif
    break;
    default:
      wxFAIL;
  }
}
<commit_msg>only add statusbar macro pane if macro file exists<commit_after>////////////////////////////////////////////////////////////////////////////////
// Name:      support.cpp
// Purpose:   Implementation of DecoratedFrame class
// Author:    Anton van Wezenbeek
// Copyright: (c) 2012 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/config.h>
#include <wx/stockitem.h> // for wxGetStockLabel
#include <wx/extension/filedlg.h>
#include <wx/extension/lexers.h>
#include <wx/extension/stc.h>
#include <wx/extension/util.h>
#include <wx/extension/vcs.h>
#include <wx/extension/report/listviewfile.h>
#ifndef __WXMSW__
#include "app.xpm"
#endif
#include "support.h"
#include "defs.h"

DecoratedFrame::DecoratedFrame()
  : wxExFrameWithHistory(
      NULL,
      wxID_ANY,
      wxTheApp->GetAppDisplayName(), // title
      25,                            // maxFiles
      4)                             // maxProjects
{
  SetIcon(wxICON(app));

#if wxUSE_STATUSBAR
  std::vector<wxExStatusBarPane> panes;
  panes.push_back(wxExStatusBarPane());
  panes.push_back(wxExStatusBarPane("PaneFileType", 50, _("File type")));
  panes.push_back(wxExStatusBarPane("PaneInfo", 100, _("Lines or items")));

  if (wxExLexers::Get()->GetCount() > 0)
  {
#ifdef __WXMSW__
    const int lexer_size = 60;
#else
    const int lexer_size = 75;
#endif

    panes.push_back(wxExStatusBarPane("PaneLexer", lexer_size, _("Lexer")));
    panes.push_back(wxExStatusBarPane("PaneTheme", lexer_size, _("Theme")));
  }

  if (wxExVCS::GetCount() > 0)
  {
    panes.push_back(wxExStatusBarPane("PaneVCS", 75, _("VCS")));
  }

  if (wxExViMacros::GetFileName().FileExists())
  {
    panes.push_back(wxExStatusBarPane("PaneMacro", 75));
  }

  SetupStatusBar(panes);

  if (wxExVCS::GetCount() > 0)
  {
    wxExVCS vcs;
    vcs.GetDir();
    StatusText(vcs.GetName(), "PaneVCS");
  }
#endif

  wxExMenu *menuFile = new wxExMenu();
  menuFile->Append(wxID_NEW);
  menuFile->Append(wxID_OPEN);
  UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
  menuFile->AppendSeparator();
  menuFile->Append(wxID_CLOSE);
  menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
  menuFile->AppendSeparator();
  menuFile->Append(wxID_SAVE);
  menuFile->Append(wxID_SAVEAS);
  menuFile->Append(ID_ALL_STC_SAVE,
    _("Save A&ll"), wxEmptyString, wxART_FILE_SAVE);
  menuFile->AppendSeparator();
  menuFile->AppendPrint();
  menuFile->AppendSeparator();
  menuFile->Append(wxID_EXIT);

  wxExMenu *menuEdit = new wxExMenu();
  menuEdit->Append(wxID_UNDO);
  menuEdit->Append(wxID_REDO);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_CUT);
  menuEdit->Append(wxID_COPY);
  menuEdit->Append(wxID_PASTE);
  menuEdit->AppendSeparator();
  menuEdit->Append(wxID_JUMP_TO);
  menuEdit->AppendSeparator();
  wxExMenu* menuFind = new wxExMenu();

  if (wxConfigBase::Get()->ReadBool(_("vi mode"), true))
  {
    // No accelerators for vi mode, Ctrl F is page down.
    menuFind->Append(wxID_FIND, wxGetStockLabel(wxID_FIND));
    menuFind->Append(wxID_REPLACE, wxGetStockLabel(wxID_REPLACE));
  }
  else
  {
    menuFind->Append(wxID_FIND);
    menuFind->Append(wxID_REPLACE);
  }

  menuFind->Append(ID_FIND_IN_FILES, wxExEllipsed(_("Find &in Files")));
  menuFind->Append(ID_REPLACE_IN_FILES, wxExEllipsed(_("Replace in File&s")));
  menuEdit->AppendSubMenu(menuFind, _("&Find and Replace"));
  menuEdit->AppendSeparator();
  menuEdit->Append(
    ID_EDIT_CONTROL_CHAR, wxExEllipsed(_("&Control Char"), "Ctrl+K"));
  menuEdit->AppendSeparator();

  wxExMenu* menuMacro = new wxExMenu();
  menuMacro->Append(ID_EDIT_MACRO_START_RECORD, wxExEllipsed(_("Start Record")));
  menuMacro->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
  menuMacro->AppendSeparator();
  menuMacro->Append(ID_EDIT_MACRO_PLAYBACK, wxExEllipsed(_("Playback"), "Ctrl+M"));

  if (wxExViMacros::GetFileName().FileExists())
  {
    menuMacro->AppendSeparator();
    menuMacro->Append(ID_EDIT_MACRO, wxGetStockLabel(wxID_EDIT));
  }

  menuEdit->AppendSubMenu(menuMacro, _("&Macro"));

  wxExMenu *menuView = new wxExMenu;
  menuView->AppendBars();
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_FILES, _("&Files"));
  menuView->AppendCheckItem(ID_VIEW_PROJECTS, _("&Projects"));
  menuView->AppendCheckItem(ID_VIEW_DIRCTRL, _("&Explorer"));
  menuView->AppendCheckItem(ID_VIEW_HISTORY, _("&History"));
  menuView->AppendCheckItem(ID_VIEW_OUTPUT, _("&Output"));
  menuView->AppendSeparator();
  menuView->AppendCheckItem(ID_VIEW_ASCII_TABLE, _("&Ascii Table"));

  wxMenu *menuProcess = new wxMenu();
  menuProcess->Append(ID_PROCESS_SELECT, wxExEllipsed(_("&Select")));
  menuProcess->AppendSeparator();
  menuProcess->Append(wxID_EXECUTE);
  menuProcess->Append(wxID_STOP);

  wxExMenu *menuProject = new wxExMenu();
  menuProject->Append(
    ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxART_NEW);
  menuProject->Append(
    ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxART_FILE_OPEN);
  UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
  menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open as Text"));
  menuProject->Append(
    ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE), wxEmptyString, wxART_CLOSE);
  menuProject->AppendSeparator();
  menuProject->Append(
    ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxART_FILE_SAVE);
  menuProject->Append(
    ID_PROJECT_SAVEAS,
    wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxART_FILE_SAVE_AS);
  menuProject->AppendSeparator();
  menuProject->AppendCheckItem(ID_SORT_SYNC, _("&Auto Sort"));

  wxMenu *menuWindow = new wxMenu();
  menuWindow->Append(ID_SPLIT, _("Split"));

  wxMenu* menuOptions = new wxMenu();

  if (wxExVCS::GetCount() > 0)
  {
    menuOptions->Append(ID_OPTION_VCS, wxExEllipsed(_("Set &VCS")));
    menuOptions->AppendSeparator();
  }

  menuOptions->Append(
    ID_OPTION_COMPARATOR, wxExEllipsed(_("Set &Comparator")));
  menuOptions->AppendSeparator();

  menuOptions->Append(ID_OPTION_LIST_FONT, wxExEllipsed(_("Set &List Font")));
  // text also used as caption
  menuOptions->Append(
    ID_OPTION_LIST_READONLY_COLOUR, wxExEllipsed(_("Set List &Read Only Colour")));
  wxMenu *menuListSort = new wxMenu;
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"));
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"));
  menuListSort->AppendRadioItem(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"));
  menuOptions->AppendSubMenu(menuListSort, _("Set &List Sort Method"));
  menuOptions->AppendSeparator();
  menuOptions->Append(ID_OPTION_EDITOR, wxExEllipsed(_("Set &Editor Options")));

  wxExMenu *menuHelp = new wxExMenu(); // use wxExMenu for art with HELP
  menuHelp->Append(wxID_ABOUT);
  menuHelp->Append(wxID_HELP);

  wxMenuBar* menubar = new wxMenuBar();
  menubar->Append(menuFile, wxGetStockLabel(wxID_FILE));
  menubar->Append(menuEdit, wxGetStockLabel(wxID_EDIT));
  menubar->Append(menuView, _("&View"));
  menubar->Append(menuProcess, _("&Process"));
  menubar->Append(menuProject, _("&Project"));
  menubar->Append(menuWindow, _("&Window"));
  menubar->Append(menuOptions, _("&Options"));
  menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));

  SetMenuBar(menubar);
}

bool DecoratedFrame::AllowClose(wxWindowID id, wxWindow* page)
{
  switch (id)
  {
  case NOTEBOOK_EDITORS:
    {
      wxExFileDialog dlg(this, &((wxExSTC*)page)->GetFile());

      if (dlg.ShowModalIfChanged() != wxID_OK)
      {
        return false;
      }
    }
  break;
  case NOTEBOOK_PROJECTS:
    {
      wxExFileDialog dlg(this, (wxExListViewFile*)page);

      if (dlg.ShowModalIfChanged() != wxID_OK)
      {
        return false;
      }
    }
  break;
  }

  return wxExFrameWithHistory::AllowClose(id, page);
}

void DecoratedFrame::OnNotebook(wxWindowID id, wxWindow* page)
{
  wxExFrameWithHistory::OnNotebook(id, page);

  switch (id)
  {
    case NOTEBOOK_EDITORS:
      ((wxExSTC*)page)->PropertiesMessage();
    break;
    case NOTEBOOK_LISTS:
    break;
    case NOTEBOOK_PROJECTS:
#if wxUSE_STATUSBAR
      wxExLogStatus(((wxExListViewFile*)page)->GetFileName());
      UpdateStatusBar((wxExListViewFile*)page);
#endif
    break;
    default:
      wxFAIL;
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
//
//
// Constants
//
//

    //
    // Digits
    //
        // decimal
            1
            .1
            .239480
            .239480f
            0.
            0.f
            0.L
            0.LL
            4897430la
            32094.930123a
            4897430LL
            32094.930123F
            32094.930123f
            1'03'432'43
            123232'1231321
            3'20'94.93'01'23
            3'20'94.93'1'23
        // e
            0e1
            1e10f
            1.e10
            1.e10
            1.e-10
            1.79769e+308
            1.79'76'9e+3'0'8
        // octal
            01
            01001202
            010'0'120'2
            0'1'2'3'4
        // binary
            0b101010
            0b000001
            0b100001
            0b1'01'010
            0b1'00'001
        // hex
            0x01
            0xabcdef
            0xaBCDEf
            0xABCDEF
            0xAB.cdp5f
            0xAB.cdp5l
            0x20394afLL
            0x01
            0xabc'def
            0xa'BC'DEf
            0xABC'DEF
            0x20'394'a'fLL
        // hex floating point literal
            0x0.5p10F
            0x0.5p10f
            0x1ffp10
            0x0.23p10
            0x0.234985p10L
            0x139804.234985p10L
            0x0.53'84'92p10
            0x5.p10
            0x0.23p+10
            0x0.234985p+10L
            0x139804.234985p-10L
            0x0.53'84'92p-10
            0x5.p+10
            0x13'98'04.234985p10L
        // custom literals
            29042ms
            0xabcdefmm
            0xabc'defmm
            0xabcdefyards
            20ounces
            2000miles
            L"akdjfhald"

    //
    // chars
    //
        '1'
        'a'
        '\n'
        '\0'
    //
    // Strings
    //
        auto a = "things\n\b\v\t";
//
// Memory
//
    auto a = new int(5);
    delete a;
    int *array = new int[100];
    delete[] array;

//
//
// namespaces
//
//
using namespace std;
using namespace parent_namespace::std;

namespace {}
namespace scoped::console { }
namespace console {
    template <typename ANYTYPE> void __MAGIC__show(ANYTYPE input) {
            // by default use the stream operator with cout
            std::cout << input;
        }
}

//
//
// preprocessor
//
//
#define Infinite    numeric_limits<long double>::infinity()
#define DoubleMax   1.79769e+308
#define Pi          3.1415926535897932384626
#define show(argument) cout << #argument << "\n";
#ifndef CEKO_LIBRARY
#define CEKO_LIBRARY
#endif

//
// templates
//
template<int, typename Callable, typename Ret, typename... Args>
auto internalConversionToFuncPtr(Callable&& a_callable, Ret (*)(Args...))
    {
        static bool used = false;
        static storage<Callable> a_storage_of_callable;
        using type = decltype(a_storage_of_callable.callable);

        if(used) {
            a_storage_of_callable.callable.~type();
        }
        new (&a_storage_of_callable.callable) type(forward<Callable>(a_callable));
        used = true;
        // lambda
        return [](Args... args) -> Ret {
            return Ret(a_storage_of_callable.callable(forward<Args>(args)...));
        };
    }

//
// Classes
//
class Thing {
    public:
    public :
    private :
    private:
    protected:
        auto a = 1;
    Thing() {

    }
}
int main() {
    return 0;
}<commit_msg>add more test cases<commit_after>#include <iostream>
#include <sstream>
//
//
// Constants
//
//

    //
    // Digits
    //
        // decimal
            1
            .1
            .239480
            .239480f
            0.
            0.f
            0.L
            0.LL
            4897430la
            32094.930123a
            4897430LL
            32094.930123F
            32094.930123f
            1'03'432'43
            123232'1231321
            3'20'94.93'01'23
            3'20'94.93'1'23
        // e
            0e1
            1e10f
            1.e10
            1.e10
            1.e-10
            1.79769e+308
            1.79'76'9e+3'0'8
        // octal
            01
            01001202
            010'0'120'2
            0'1'2'3'4
        // binary
            0b101010
            0b000001
            0b100001
            0b1'01'010
            0b1'00'001
        // hex
            0x01
            0xabcdef
            0xaBCDEf
            0xABCDEF
            0xAB.cdp5f
            0xAB.cdp5l
            0x20394afLL
            0x01
            0xabc'def
            0xa'BC'DEf
            0xABC'DEF
            0x20'394'a'fLL
        // hex floating point literal
            0x0.5p10F
            0x0.5p10f
            0x1ffp10
            0x0.23p10
            0x0.234985p10L
            0x139804.234985p10L
            0x0.53'84'92p10
            0x5.p10
            0x0.23p+10
            0x0.234985p+10L
            0x139804.234985p-10L
            0x0.53'84'92p-10
            0x5.p+10
            0x13'98'04.234985p10L
        // custom literals
            29042ms
            0xabcdefmm
            0xabc'defmm
            0xabcdefyards
            20ounces
            2000miles
            L"akdjfhald"

    //
    // chars
    //
        '1'
        'a'
        '\n'
        '\0'
    //
    // Strings
    //
        auto a = "things\n\b\v\t";
//
// Memory
//
    auto a = new int(5);
    delete a;
    new (&a_storage_of_callable.callable) type(forward<Callable>(a_callable));
    int *array = new int[100];
    delete[] array;
    char should_always_be_a_newline;
    char deleter;

//
//
// namespaces
//
//
    using namespace std;
    using namespace parent_namespace::std;

    namespace {}
    namespace scoped::console { }
    namespace console {
        template <typename ANYTYPE> void __MAGIC__show(ANYTYPE input) {
                // by default use the stream operator with cout
                std::cout << input;
            }
    }

//
// Scope resolution
//
    std::cout << input;
    numeric_limits<long double>::infinity();
    char_traits<ANYTYPE>::eof();
    numeric_limits<streamsize>::max();
    Task<ANY_OUTPUT_TYPE, ANY_INPUT_TYPE>::links_to;
    &TEST_CLASS::name;
    Event<ANYTYPE>::   ListenersFor[input_event.name]

//
// Operator keyword
//
    ostream& operator<<(ostream& out, const Item& input_) {};
    Item  operator+( const string&  base        , const int&    repetitions ) {};
    Item  operator-( const int&     the_input   , const Item&   input_item  ) {};
    Item  operator/( const Item&    input_item  , const int&    the_input   ) {};
    Item  operator^( const Item&    input_item  , const int&    the_input   ) {};
    // implicit conversions
    operator string() const {};
    operator double() const {};
    // custom literal
    void operator "" _km(long double);

//
//
// preprocessor
//
//
    #define Infinite    numeric_limits<long double>::infinity()
    #define DoubleMax   1.79769e+308
    #define Pi          3.1415926535897932384626
    #define show(argument) cout << #argument << "\n";
    #ifndef CEKO_LIBRARY
    #define CEKO_LIBRARY
    #endif

//
// templates
//
    template<int, typename Callable, typename Ret, typename... Args>
    auto internalConversionToFuncPtr(Callable&& a_callable, Ret (*)(Args...))
        {
            static bool used = false;
            static storage<Callable> a_storage_of_callable;
            using type = decltype(a_storage_of_callable.callable);

            if(used) {
                a_storage_of_callable.callable.~type();
            }
            new (&a_storage_of_callable.callable) type(forward<Callable>(a_callable));
            used = true;
            // lambda
            return [](Args... args) -> Ret {
                return Ret(a_storage_of_callable.callable(forward<Args>(args)...));
            };
        }
        template<typename RETURN_TYPE, int N = 0, typename Callable>
        RETURN_TYPE* convertToFunctionPointer(Callable&& c)
            {
                return internalConversionToFuncPtr<N>(forward<Callable>(c), (RETURN_TYPE*)nullptr);
            }

//
// Classes
//
    class Thing {
        public:
        public :
        private :
        private:
        protected:
            auto a = 1;
            Thing() {

            }
    };
    struct Thing2 {
        public:
        public :
        private :
        private:
        protected:
            auto a = 1;
            Thing() {

            }
    };

//
// Functions
//
    template <class ANYTYPE>
    string ToBinary(ANYTYPE input)
        {
            // depends on #include <bitset>
            return bitset<8>(input).to_string();
        }

int main() {
    return 0;
}<|endoftext|>


<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// $Id$

/// \class AliMUONPolygon
///
/// A simple planar polygon, with a given orientation
///
/// \author Laurent Aphecetche, Subatech

#include "AliMUONPolygon.h"

#include "AliLog.h"
#include "Riostream.h"
#include "TMath.h"

///\cond CLASSIMP
ClassImp(AliMUONPolygon)
///\endcond

//_____________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(Int_t nvertices)
: TObject(),
fN(nvertices),
fX(new Double_t[fN]),
fY(new Double_t[fN])
{
  /// Ctor with a predefined number of vertices.
}

//_____________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(Double_t xpos, Double_t ypos, Double_t halfsizex, Double_t halfsizey)
: TObject(),
fN(5),
fX(new Double_t[fN]),
fY(new Double_t[fN])
{
  /// Ctor. Polygon will be a rectangle.

  double xmin(xpos-halfsizex);
  double xmax(xpos+halfsizex);
  double ymin(ypos-halfsizey);
  double ymax(ypos+halfsizey);

  SetVertex(0,xmin,ymin);
  SetVertex(1,xmax,ymin);
  SetVertex(2,xmax,ymax);
  SetVertex(3,xmin,ymax);

  Close();
}

//_____________________________________________________________________________
AliMUONPolygon::~AliMUONPolygon()
{
  /// dtor
  delete[] fX;
  delete[] fY;
}

//______________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(const AliMUONPolygon& rhs)
: TObject(rhs),
fN(0),
fX(0x0),
fY(0x0)
{
  /// Copy constructor.

  ((AliMUONPolygon&)rhs).Copy(*this);
}

//______________________________________________________________________________
AliMUONPolygon&
AliMUONPolygon::operator=(const AliMUONPolygon& rhs)
{
  /// Assignment operator
  if ( this != &rhs )
  {
    rhs.Copy(*this);
  }
  return *this;
}

//______________________________________________________________________________
Bool_t
AliMUONPolygon::Contains(Double_t x, Double_t y) const
{
  /// Whether the polygon contains point (x,y)

  // Note that the polygon must be a closed polygon (1st and last point
  // must be identical), which should be the case here.

  return TMath::IsInside(x,y,fN,fX,fY);
}

//______________________________________________________________________________
void AliMUONPolygon::Copy(TObject& obj) const
{
  /// Copy this to obj

  AliMUONPolygon& rhs = static_cast<AliMUONPolygon&>(obj);

  Double_t* x(0x0);
  Double_t* y(0x0);

  if ( fN > 0 )
  {
    x = new Double_t[fN];
    y = new Double_t[fN];

    for ( Int_t i = 0; i < fN; ++i )
    {
      x[i] = fX[i];
      y[i] = fY[i];
    }

  }

  delete [] rhs.fX;
  delete [] rhs.fY;

  rhs.fX = x;
  rhs.fY = y;
  rhs.fN = fN;
}

//_____________________________________________________________________________
void
AliMUONPolygon::Close()
{
  /// Make that last point = first point

  SetVertex(fN-1,X(0),Y(0));
}

//_____________________________________________________________________________
void AliMUONPolygon::Print(Option_t*) const
{
  /// Printout
  cout << Form("AliMUONPolygon : %3d vertices. Signed Area=%e",NumberOfVertices(),SignedArea()) << endl;
  for ( Int_t i = 0; i < NumberOfVertices(); ++i )
  {
    cout << Form("%10.5f,%10.5f",X(i),Y(i)) << endl;
  }
}

//_____________________________________________________________________________
Double_t
AliMUONPolygon::SignedArea() const
{
  /// Compute the signed area of this polygon
  /// Algorithm from F. Feito, J.C. Torres and A. Urena,
  /// Comput. & Graphics, Vol. 19, pp. 595-600, 1995

  Double_t area(0.0);

  for ( Int_t i = 0; i < NumberOfVertices()-1; ++i )
  {
    area += X(i)*Y(i+1) - X(i+1)*Y(i);
  }

  return area;
}

//_____________________________________________________________________________
void
AliMUONPolygon::ReverseOrientation()
{
  /// Reverse the orientation of this polygon
  Double_t* x = new Double_t[fN];
  Double_t* y = new Double_t[fN];

  for ( Int_t i = fN-1; i >= 0; --i )
  {
    x[i] = X(fN-i-1);
    y[i] = Y(fN-i-1);
  }

  delete[] fX;
  delete[] fY;

  fX = x;
  fY = y;
}

//_____________________________________________________________________________
void
AliMUONPolygon::SetVertex(Int_t i, Double_t x, Double_t y)
{
  /// Set one vertex
  if ( i >= fN )
  {
    AliFatal("Wrong index");
  }
  fX[i] = x;
  fY[i] = y;
}

<commit_msg>One more attempt to fix coverity MISSING_COPY<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// $Id$

/// \class AliMUONPolygon
///
/// A simple planar polygon, with a given orientation
///
/// \author Laurent Aphecetche, Subatech

#include "AliMUONPolygon.h"

#include "AliLog.h"
#include "Riostream.h"
#include "TMath.h"

///\cond CLASSIMP
ClassImp(AliMUONPolygon)
///\endcond

//_____________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(Int_t nvertices)
: TObject(),
fN(nvertices),
fX(new Double_t[fN]),
fY(new Double_t[fN])
{
  /// Ctor with a predefined number of vertices.
}

//_____________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(Double_t xpos, Double_t ypos, Double_t halfsizex, Double_t halfsizey)
: TObject(),
fN(5),
fX(new Double_t[fN]),
fY(new Double_t[fN])
{
  /// Ctor. Polygon will be a rectangle.

  double xmin(xpos-halfsizex);
  double xmax(xpos+halfsizex);
  double ymin(ypos-halfsizey);
  double ymax(ypos+halfsizey);

  SetVertex(0,xmin,ymin);
  SetVertex(1,xmax,ymin);
  SetVertex(2,xmax,ymax);
  SetVertex(3,xmin,ymax);

  Close();
}

//_____________________________________________________________________________
AliMUONPolygon::~AliMUONPolygon()
{
  /// dtor
  delete[] fX;
  delete[] fY;
}

//______________________________________________________________________________
AliMUONPolygon::AliMUONPolygon(const AliMUONPolygon& rhs)
: TObject(rhs),
fN(0),
fX(0x0),
fY(0x0)
{
  /// Copy constructor.

  ((AliMUONPolygon&)rhs).Copy(*this);
}

//______________________________________________________________________________
AliMUONPolygon&
AliMUONPolygon::operator=(const AliMUONPolygon& rhs)
{
  /// Assignment operator
  if ( this != &rhs )
  {
    rhs.Copy(*this);
  }
  return *this;
}

//______________________________________________________________________________
Bool_t
AliMUONPolygon::Contains(Double_t x, Double_t y) const
{
  /// Whether the polygon contains point (x,y)

  // Note that the polygon must be a closed polygon (1st and last point
  // must be identical), which should be the case here.

  return TMath::IsInside(x,y,fN,fX,fY);
}

//______________________________________________________________________________
void AliMUONPolygon::Copy(TObject& obj) const
{
  /// Copy this to obj

  TObject::Copy(obj);

  AliMUONPolygon& rhs = static_cast<AliMUONPolygon&>(obj);

  Double_t* x(0x0);
  Double_t* y(0x0);

  if ( fN > 0 )
  {
    x = new Double_t[fN];
    y = new Double_t[fN];

    for ( Int_t i = 0; i < fN; ++i )
    {
      x[i] = fX[i];
      y[i] = fY[i];
    }

  }

  delete [] rhs.fX;
  delete [] rhs.fY;

  rhs.fX = x;
  rhs.fY = y;
  rhs.fN = fN;
}

//_____________________________________________________________________________
void
AliMUONPolygon::Close()
{
  /// Make that last point = first point

  SetVertex(fN-1,X(0),Y(0));
}

//_____________________________________________________________________________
void AliMUONPolygon::Print(Option_t*) const
{
  /// Printout
  cout << Form("AliMUONPolygon : %3d vertices. Signed Area=%e",NumberOfVertices(),SignedArea()) << endl;
  for ( Int_t i = 0; i < NumberOfVertices(); ++i )
  {
    cout << Form("%10.5f,%10.5f",X(i),Y(i)) << endl;
  }
}

//_____________________________________________________________________________
Double_t
AliMUONPolygon::SignedArea() const
{
  /// Compute the signed area of this polygon
  /// Algorithm from F. Feito, J.C. Torres and A. Urena,
  /// Comput. & Graphics, Vol. 19, pp. 595-600, 1995

  Double_t area(0.0);

  for ( Int_t i = 0; i < NumberOfVertices()-1; ++i )
  {
    area += X(i)*Y(i+1) - X(i+1)*Y(i);
  }

  return area;
}

//_____________________________________________________________________________
void
AliMUONPolygon::ReverseOrientation()
{
  /// Reverse the orientation of this polygon
  Double_t* x = new Double_t[fN];
  Double_t* y = new Double_t[fN];

  for ( Int_t i = fN-1; i >= 0; --i )
  {
    x[i] = X(fN-i-1);
    y[i] = Y(fN-i-1);
  }

  delete[] fX;
  delete[] fY;

  fX = x;
  fY = y;
}

//_____________________________________________________________________________
void
AliMUONPolygon::SetVertex(Int_t i, Double_t x, Double_t y)
{
  /// Set one vertex
  if ( i >= fN )
  {
    AliFatal("Wrong index");
  }
  fX[i] = x;
  fY[i] = y;
}

<|endoftext|>


<commit_before>#include "drawings/cartesian.cpp"
#include "drawings/sphere.cpp"
#include "drawings/terrain.cpp"
#include "drawings/skeleton.cpp"

//#include "drawings/colorcube.cpp" //XXX
//#include "drawings/fractal.cpp" //XXX

void initFrame ( ) {
    static bool uninitialized = true;
    if (uninitialized) {

        initCartesian();
        initSphere();
        initTerrain();
        initSkeleton();

//        initColorcube(); //XXX
//        initSierpinski(); //XXX

        pEye   = glm::vec4(terrain.width/2,200,terrain.height/2,1);
        pFocus = AXIS_ORIGIN;
    }
    else {

//        initSierpinski(); //XXX
//        initColorcube(); //XXX

        initSkeleton();
        initTerrain();
        initSphere();
        initCartesian();
    }
    uninitialized = not uninitialized;
}

void drawTitle ( ) {
    sprintf(
        &title[0],
        "%dx%d (%d,%d) | %d FPS | %d%% | %d FOV | %s %s | %d",
        (int) windowW,   (int) windowH,
        (int) pCursor.x, (int) pCursor.y,
        (int) round(FPS),
        (int) round(zoom*100.0),
        (int) round(deg(lens)),
        (cull) ? "culled" : "unculled",
        (wire) ?   "wire" : "solid",
        selection
    );
    glfwSetWindowTitle(defaultWindow,&title[0]);
}

bool skeleton = false;

void drawFrame ( ) {

                  drawCartesian();
                  drawTerrain  ();
    if (lighting) drawSphere   (glm::translate(glm::mat4(),glm::vec3(pSelection[0])));
    if (skeleton) drawSkeleton (glm::translate(glm::mat4(),glm::vec3(pSelection[1])));

//    GLfloat s = 10;
//     drawColorcube(scale(mat4(),vec3(s,s,s))); //XXX
//    drawSierpinski(scale(mat4(),vec3(s,s,s))); //XXX
}
<commit_msg>Add a label to FOV in the title<commit_after>#include "drawings/cartesian.cpp"
#include "drawings/sphere.cpp"
#include "drawings/terrain.cpp"
#include "drawings/skeleton.cpp"

//#include "drawings/colorcube.cpp" //XXX
//#include "drawings/fractal.cpp" //XXX

void initFrame ( ) {
    static bool uninitialized = true;
    if (uninitialized) {

        initCartesian();
        initSphere();
        initTerrain();
        initSkeleton();

//        initColorcube(); //XXX
//        initSierpinski(); //XXX

        pEye   = glm::vec4(terrain.width/2,200,terrain.height/2,1);
        pFocus = AXIS_ORIGIN;
    }
    else {

//        initSierpinski(); //XXX
//        initColorcube(); //XXX

        initSkeleton();
        initTerrain();
        initSphere();
        initCartesian();
    }
    uninitialized = not uninitialized;
}

void drawTitle ( ) {
    sprintf(
        &title[0],
        "%dx%d (%d,%d) | %d FPS | %d%% | %d° FOV | %s %s | %d",
        (int) windowW,   (int) windowH,
        (int) pCursor.x, (int) pCursor.y,
        (int) round(FPS),
        (int) round(zoom*100.0),
        (int) round(deg(lens)),
        (cull) ? "culled" : "unculled",
        (wire) ?   "wire" : "solid",
        selection
    );
    glfwSetWindowTitle(defaultWindow,&title[0]);
}

bool skeleton = false;

void drawFrame ( ) {

                  drawCartesian();
                  drawTerrain  ();
    if (lighting) drawSphere   (glm::translate(glm::mat4(),glm::vec3(pSelection[0])));
    if (skeleton) drawSkeleton (glm::translate(glm::mat4(),glm::vec3(pSelection[1])));

//    GLfloat s = 10;
//     drawColorcube(scale(mat4(),vec3(s,s,s))); //XXX
//    drawSierpinski(scale(mat4(),vec3(s,s,s))); //XXX
}
<|endoftext|>


<commit_before>#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <glm.hpp>
#include "SDL.h"
#define GL_GLEXT_PROTOTYPES
#include <glcorearb.h>
#include "Object.h"
#include "Mesh.h"
#include "Renderer.h"
#include "constants.h"

float zoom_rate = 20.0f;
float drag_rate = M_PI/2;
float R_min = 2.0f;
float R_max = 100.0f;
float R = R_min;
int time_warp = 0;
const double far = 300.0f;
const double near = 0.1f;
float theta = 0.0f;
float phi = M_PI/2;

std::vector<Object> objects;

/*
name   e   a     inc  LAN AP  trueAnomaly m   Cd  A
Object 0.4 2.0e6 1.57 1.4 4.3 2.1         1.0 1.0 1.0
*/

void frame_init()
{
	const char* objects_filename = "objects";
	std::ifstream obj_ifs(objects_filename);
	if(obj_ifs.is_open())
	{
		std::string line;
 		while(std::getline(obj_ifs, line))
		{
			std::istringstream iss(line);
			std::string name;
			KeplerianElements ke;
			float m, Cd, A;
			iss >> name >> ke.e >> ke.a >> ke.inc >> ke.LAN >> ke.AP;
			float trueAnomaly;
			iss >> trueAnomaly;
			float E = 2*atan(tan(trueAnomaly/2)/sqrt((1+ke.e)/(1-ke.e)));
			ke.M0 = E - ke.e * sin(E);
			ke.epoch = 0.0f;
			ke.t = 0.0f;
			iss >> m >> Cd >> A;
			objects.push_back(Object(name, ke, m, Cd, A));
		}
	}
}

const float delay = 0.1f;
float timer = 0.0f;

int frame
	(float dt,
	SDL_Event evt,
	const Uint8* kbd,
	float dx, float dy, Uint32 mouseb)
{
	float real_tw = pow(10.0, time_warp);
	for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
	{
		i->tick(dt*real_tw);
	}

	if(mouseb & SDL_BUTTON(SDL_BUTTON_LEFT))
	{
		theta -= dx * drag_rate;
		phi += dy * drag_rate;
		if(phi < 0.0f)
		{
			phi = 0.001f;
		}
		if(phi > M_PI)
		{
			phi = M_PI - 0.001f;
		}
	}

	if(kbd[SDL_SCANCODE_PERIOD] && timer > delay && time_warp < 3)
	{
		time_warp += 1;
		timer = 0.0f;
	}
	if(kbd[SDL_SCANCODE_COMMA] && timer > delay && time_warp > 0)
	{
		time_warp -= 1;
		timer = 0.0f;
	}

	timer += dt;

	if(kbd[SDL_SCANCODE_UP] && R > R_min)
	{
		R -= zoom_rate * dt;
	}
	if(kbd[SDL_SCANCODE_DOWN] && R < R_max)
	{
		R += zoom_rate * dt;
	}

	if(kbd[SDL_SCANCODE_A])
	{
		for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
		{
			i->activate();
		}
	}
	if(kbd[SDL_SCANCODE_D])
	{
		for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
		{
			i->deactivate();
		}
	}

	if(kbd[SDL_SCANCODE_ESCAPE])
	{
		return 1;
	}

	return 0;
}

void frame_shutdown()
{
}

Renderer *renderer;
const char * vertex_shader_filename = "vertex_shader.vert";
const char * fragment_shader_filename = "fragment_shader.frag";

void render_init(int wnd_w, int wnd_h)
{
	float aspect = (float)wnd_w / (float)wnd_h;
	renderer = new Renderer
			(std::string(vertex_shader_filename),
			std::string(fragment_shader_filename),
			std::string("object.obj"),
			std::string("sphere.obj"),
			M_PI/4, aspect,
			near, far);
}

void render()
{
	renderer->frameTick(theta, phi, R);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
	{
		renderer->render(*i);
	}
	renderer->renderEarth();
}

void render_shutdown()
{
	delete renderer;
}
<commit_msg>Init LOP when reading objects file.<commit_after>#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <glm.hpp>
#include "SDL.h"
#define GL_GLEXT_PROTOTYPES
#include <glcorearb.h>
#include "Object.h"
#include "Mesh.h"
#include "Renderer.h"
#include "constants.h"

float zoom_rate = 20.0f;
float drag_rate = M_PI/2;
float R_min = 2.0f;
float R_max = 100.0f;
float R = R_min;
int time_warp = 0;
const double far = 300.0f;
const double near = 0.1f;
float theta = 0.0f;
float phi = M_PI/2;

std::vector<Object> objects;

/*
name   e   a     inc  LAN AP  trueAnomaly m   Cd  A
Object 0.4 2.0e6 1.57 1.4 4.3 2.1         1.0 1.0 1.0
*/

void frame_init()
{
	const char* objects_filename = "objects";
	std::ifstream obj_ifs(objects_filename);
	if(obj_ifs.is_open())
	{
		std::string line;
 		while(std::getline(obj_ifs, line))
		{
			std::istringstream iss(line);
			std::string name;
			KeplerianElements ke;
			float m, Cd, A;
			iss >> name >> ke.e >> ke.a >> ke.inc >> ke.LAN >> ke.AP;
			ke.LOP = ke.LAN + ke.AP;
			float trueAnomaly;
			iss >> trueAnomaly;
			float E = 2*atan(tan(trueAnomaly/2)/sqrt((1+ke.e)/(1-ke.e)));
			ke.M0 = E - ke.e * sin(E);
			ke.epoch = 0.0f;
			ke.t = 0.0f;
			iss >> m >> Cd >> A;
			objects.push_back(Object(name, ke, m, Cd, A));
		}
	}
}

const float delay = 0.1f;
float timer = 0.0f;

int frame
	(float dt,
	SDL_Event evt,
	const Uint8* kbd,
	float dx, float dy, Uint32 mouseb)
{
	float real_tw = pow(10.0, time_warp);
	for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
	{
		i->tick(dt*real_tw);
	}

	if(mouseb & SDL_BUTTON(SDL_BUTTON_LEFT))
	{
		theta -= dx * drag_rate;
		phi += dy * drag_rate;
		if(phi < 0.0f)
		{
			phi = 0.001f;
		}
		if(phi > M_PI)
		{
			phi = M_PI - 0.001f;
		}
	}

	if(kbd[SDL_SCANCODE_PERIOD] && timer > delay && time_warp < 3)
	{
		time_warp += 1;
		timer = 0.0f;
	}
	if(kbd[SDL_SCANCODE_COMMA] && timer > delay && time_warp > 0)
	{
		time_warp -= 1;
		timer = 0.0f;
	}

	timer += dt;

	if(kbd[SDL_SCANCODE_UP] && R > R_min)
	{
		R -= zoom_rate * dt;
	}
	if(kbd[SDL_SCANCODE_DOWN] && R < R_max)
	{
		R += zoom_rate * dt;
	}

	if(kbd[SDL_SCANCODE_A])
	{
		for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
		{
			i->activate();
		}
	}
	if(kbd[SDL_SCANCODE_D])
	{
		for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
		{
			i->deactivate();
		}
	}

	if(kbd[SDL_SCANCODE_ESCAPE])
	{
		return 1;
	}

	return 0;
}

void frame_shutdown()
{
}

Renderer *renderer;
const char * vertex_shader_filename = "vertex_shader.vert";
const char * fragment_shader_filename = "fragment_shader.frag";

void render_init(int wnd_w, int wnd_h)
{
	float aspect = (float)wnd_w / (float)wnd_h;
	renderer = new Renderer
			(std::string(vertex_shader_filename),
			std::string(fragment_shader_filename),
			std::string("object.obj"),
			std::string("sphere.obj"),
			M_PI/4, aspect,
			near, far);
}

void render()
{
	renderer->frameTick(theta, phi, R);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	for(std::vector<Object>::iterator i = objects.begin(); i != objects.end(); ++i)
	{
		renderer->render(*i);
	}
	renderer->renderEarth();
}

void render_shutdown()
{
	delete renderer;
}
<|endoftext|>


<commit_before>/* *****************************************************************************
 * The MIT License
 *
 * Copyright (c) 2010 Perry Hung.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * ****************************************************************************/

/**
 *  @brief wirish usb class for easy goin communication, uses libmaple's
 *  virtual com port implementation
 */

#include <string.h>

#include "wirish.h"
#include "usb.h"

#define USB_TIMEOUT 50

USBSerial :: USBSerial(void) {
}

void USBSerial::begin(void) {
    setupUSB();
}

void USBSerial::end(void) {
    disableUSB();
}

void USBSerial::write(uint8 ch) {
    uint16 status = 0;
    uint32 start = millis();
    while(status == 0 && (millis() - start <= USB_TIMEOUT)) {
        status = usbSendBytes(&ch, 1);
    }
}

void USBSerial::write(const char *str) {
    uint32 len = strlen(str);
    uint16 status = 0;
    uint16 oldstatus = 0;
    uint32 start = millis();
    while(status < len && (millis() - start < USB_TIMEOUT)) {
        status += usbSendBytes((uint8*)str+status, len-status);
        if(oldstatus != status)
            start = millis();
        oldstatus = status;
    }
}

void USBSerial::write(void *buf, uint32 size) {
   if (!buf) {
      return;
   }
    uint16 status = 0;
    uint16 oldstatus = 0;
    uint32 start = millis();
    while(status < size && (millis() - start < USB_TIMEOUT)) {
        status += usbSendBytes((uint8*)buf+status, size-status);
        if(oldstatus != status)
            start = millis();
        oldstatus = status;
    }
}

uint32 USBSerial::available(void) {
   return usbBytesAvailable();
}

uint32 USBSerial::read(void *buf, uint32 len) {
   if (!buf) {
      return 0;
   }

   return usbReceiveBytes((uint8*)buf, len);
}

uint8 USBSerial::read(void) {
   uint8 ch;
   usbReceiveBytes(&ch, 1);
   return ch;
}

uint8 USBSerial::pending(void) {
   return usbGetPending();
}

uint8 USBSerial::getDTR(void) {
   return usbGetDTR();
}

uint8 USBSerial::getRTS(void) {
   return usbGetRTS();
}

uint8 USBSerial::isConnected(void) {
   return (usbIsConnected() && usbIsConfigured());
}

USBSerial SerialUSB;

<commit_msg>0.0.6 release candidate 2<commit_after>/* *****************************************************************************
 * The MIT License
 *
 * Copyright (c) 2010 Perry Hung.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 * ****************************************************************************/

/**
 *  @brief wirish usb class for easy goin communication, uses libmaple's
 *  virtual com port implementation
 */

#include <string.h>

#include "wirish.h"
#include "usb.h"

#define USB_TIMEOUT 50

USBSerial :: USBSerial(void) {
}

void USBSerial::begin(void) {
    setupUSB();
}

void USBSerial::end(void) {
    disableUSB();
}

void USBSerial::write(uint8 ch) {
    if(!(usbIsConnected() && usbIsConfigured())) {
        return;
    }
    uint16 status = 0;
    uint32 start = millis();
    while(status == 0 && (millis() - start <= USB_TIMEOUT)) {
        status = usbSendBytes(&ch, 1);
    }
}

void USBSerial::write(const char *str) {
    if(!(usbIsConnected() && usbIsConfigured())) {
        return;
    }
    uint32 len = strlen(str);
    uint16 status = 0;
    uint16 oldstatus = 0;
    uint32 start = millis();
    while(status < len && (millis() - start < USB_TIMEOUT)) {
        status += usbSendBytes((uint8*)str+status, len-status);
        if(oldstatus != status)
            start = millis();
        oldstatus = status;
    }
}

void USBSerial::write(void *buf, uint32 size) {
    if(!(usbIsConnected() && usbIsConfigured())) {
        return;
    }
    if (!buf) {
        return;
    }
    uint16 status = 0;
    uint16 oldstatus = 0;
    uint32 start = millis();
    while(status < size && (millis() - start < USB_TIMEOUT)) {
        status += usbSendBytes((uint8*)buf+status, size-status);
        if(oldstatus != status)
            start = millis();
        oldstatus = status;
    }
}

uint32 USBSerial::available(void) {
   return usbBytesAvailable();
}

uint32 USBSerial::read(void *buf, uint32 len) {
   if (!buf) {
      return 0;
   }

   return usbReceiveBytes((uint8*)buf, len);
}

uint8 USBSerial::read(void) {
   uint8 ch;
   usbReceiveBytes(&ch, 1);
   return ch;
}

uint8 USBSerial::pending(void) {
   return usbGetPending();
}

uint8 USBSerial::getDTR(void) {
   return usbGetDTR();
}

uint8 USBSerial::getRTS(void) {
   return usbGetRTS();
}

uint8 USBSerial::isConnected(void) {
   return (usbIsConnected() && usbIsConfigured());
}

USBSerial SerialUSB;

<|endoftext|>


<commit_before>#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <mixerr.h>
#include "TRANS.h"
#include <rt.h>

#define DEBUG

extern "C" {
#include <ugens.h>
}

static float interp(float, float, float, float);

extern int resetval;
extern int lineset;

TRANS::TRANS() : Instrument()
{
	incount = 2.0f;
	counter = 0;
}

//  p0 = outskp  p1 = inskp  p2 = dur (tmnd)  p3 = intrvl of trnsp. p4 = amp
//  we're stashing the setline info in gen table 1

int
TRANS::init(float p[], short n_args)
{
	if (n_args != 5) {
             cerr << "Wrong number of args for TRANS!" << endl;
             return -1;
	}
	if (p[2] < 0.0) p[2] = -p[2] - p[1];
	nsamps = rtsetoutput(p[0], p[2], this);
	rtsetinput(p[1], this);
	float interval = octpch(p[3]);  /* convert interval to lin octave */
	increment = cpsoct(10.0+interval)/cpsoct(10.0);  /* the samp incr. */
	amp = p[4];

	printf("increment: %g\n", increment);

	amptable = floc(1);
	if (amptable) {
		int amplen = fsize(1);
		tableset(p[2], amplen, tabs);
	}
	else
		printf("Setting phrase curve to all 1's\n");

	skip = (int)(SR/(float)resetval);        // how often to update amp curve

	// clear sample history

	for(int n=0; n < NCHANS; n++) {
		vold[n] = 0;
		old[n] = 0;
	}

	return(nsamps);
}

inline int min(int x, int y) { if (x < y) return x; else return y; }

int
TRANS::run()
{
	const int nchans = NCHANS;
	const int sampsout = 0, outsamps = chunksamps;
	int insamp = 0, sampsread = 0;
	float in[MAXCHANS*(MAXBUF+2)], out[MAXCHANS*MAXBUF], aamp;
	int branch = 0;
	float *inp = &in[0], *outp = &out[0];

	aamp = amp;       /* in case amptable == NULL */

	// read initial block of input at offset +2 frames

	int totalinleft = 0.5 + (outsamps * increment);
	int toRead = min(totalinleft, MAXBUF);
	printf("READ %d samples\n", toRead);
	rtgetin(&in[2 * nchans], this, toRead * inputchans);
	sampsread += toRead;

	// retrieve history and store into first two frames of input array

	for (int n = 0; n < nchans; n++) {
		in[n] = vold[n];
		in[n + nchans] = old[n];
	}

	for (int i = 0; i < outsamps; i++) {
		if (insamp > sampsread) {
			totalinleft = 0.5 + ((outsamps - i) * increment);
			toRead = min(totalinleft, MAXBUF);
			printf("READ %d samples\n", toRead);
			rtgetin(&in[0], this, toRead * inputchans);
			inp = &in[0];	// reset
			sampsread += toRead;
		}
		if (--branch < 0) {
			if (amptable)
				aamp = table(cursamp, amptable, tabs) * amp;
			branch = skip;
		}
		float frac = (counter - incount) + 2.0f;
#ifdef DEBUG
		printf("i: %d counter: %g incount: %d frac: %g insamp: %d cursamp: %d\n",
					i, counter, incount, frac, insamp, cursamp);
#endif
		for (n = 0; n < nchans; n++) {
#ifdef DEBUG
			printf("interping %g, %g, %g\n", inp[0], inp[1], inp[2]);
#endif
			outp[n] = interp(inp[0], inp[1], inp[2], frac) * aamp;
		}
		outp += nchans;
		cursamp++;
		counter += increment;	// keeps track of interp pointer

		// increment input
		while ((counter - (float)incount) >= -0.5f) {
			inp += nchans;
			incount++;
			insamp++;
		}
	}
	// save history for next time
	printf("saving samps %g, %g\n", in[insamp+1], in[insamp+2]);
	for (n = 0; n < nchans; n++) {
		vold[n] = in[(nchans * (insamp + 1)) + n];
		old[n] = in[(nchans * (insamp + 2)) + n];
	}
	rtbaddout(out, outsamps * nchans);
	printf("OUT %d samples\n\n", i);
	return (i);
}

Instrument *
makeTRANS()
{
	return new TRANS();
}

void
rtprofile()
{
	RT_INTRO("TRANS",makeTRANS);
}

static float
interp(float y0, float y1, float y2, float t)
{
    float hy2, hy0, a, b, c;

    a = y0;
    hy0 = y0/2.0f;
    hy2 =  y2/2.0f;
    b = (-3.0f * hy0) + (2.0f * y1) - hy2;
    c = hy0 - y1 + hy2;

    return(a + b*t + c*t*t);
}
<commit_msg>removed unused lineset declaration<commit_after>#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <mixerr.h>
#include "TRANS.h"
#include <rt.h>

#define DEBUG

extern "C" {
#include <ugens.h>
}

static float interp(float, float, float, float);

extern int resetval;

TRANS::TRANS() : Instrument()
{
	incount = 2.0f;
	counter = 0;
}

//  p0 = outskp  p1 = inskp  p2 = dur (tmnd)  p3 = intrvl of trnsp. p4 = amp
//  we're stashing the setline info in gen table 1

int
TRANS::init(float p[], short n_args)
{
	if (n_args != 5) {
             cerr << "Wrong number of args for TRANS!" << endl;
             return -1;
	}
	if (p[2] < 0.0) p[2] = -p[2] - p[1];
	nsamps = rtsetoutput(p[0], p[2], this);
	rtsetinput(p[1], this);
	float interval = octpch(p[3]);  /* convert interval to lin octave */
	increment = cpsoct(10.0+interval)/cpsoct(10.0);  /* the samp incr. */
	amp = p[4];

	printf("increment: %g\n", increment);

	amptable = floc(1);
	if (amptable) {
		int amplen = fsize(1);
		tableset(p[2], amplen, tabs);
	}
	else
		printf("Setting phrase curve to all 1's\n");

	skip = (int)(SR/(float)resetval);        // how often to update amp curve

	// clear sample history

	for(int n=0; n < NCHANS; n++) {
		vold[n] = 0;
		old[n] = 0;
	}

	return(nsamps);
}

inline int min(int x, int y) { if (x < y) return x; else return y; }

int
TRANS::run()
{
	const int nchans = NCHANS;
	const int sampsout = 0, outsamps = chunksamps;
	int insamp = 0, sampsread = 0;
	float in[MAXCHANS*(MAXBUF+2)], out[MAXCHANS*MAXBUF], aamp;
	int branch = 0;
	float *inp = &in[0], *outp = &out[0];

	aamp = amp;       /* in case amptable == NULL */

	// read initial block of input at offset +2 frames

	int totalinleft = 0.5 + (outsamps * increment);
	int toRead = min(totalinleft, MAXBUF);
	printf("READ %d samples\n", toRead);
	rtgetin(&in[2 * nchans], this, toRead * inputchans);
	sampsread += toRead;

	// retrieve history and store into first two frames of input array

	for (int n = 0; n < nchans; n++) {
		in[n] = vold[n];
		in[n + nchans] = old[n];
	}

	for (int i = 0; i < outsamps; i++) {
		if (insamp > sampsread) {
			totalinleft = 0.5 + ((outsamps - i) * increment);
			toRead = min(totalinleft, MAXBUF);
			printf("READ %d samples\n", toRead);
			rtgetin(&in[0], this, toRead * inputchans);
			inp = &in[0];	// reset
			sampsread += toRead;
		}
		if (--branch < 0) {
			if (amptable)
				aamp = table(cursamp, amptable, tabs) * amp;
			branch = skip;
		}
		float frac = (counter - incount) + 2.0f;
#ifdef DEBUG
		printf("i: %d counter: %g incount: %d frac: %g insamp: %d cursamp: %d\n",
					i, counter, incount, frac, insamp, cursamp);
#endif
		for (n = 0; n < nchans; n++) {
#ifdef DEBUG
			printf("interping %g, %g, %g\n", inp[0], inp[1], inp[2]);
#endif
			outp[n] = interp(inp[0], inp[1], inp[2], frac) * aamp;
		}
		outp += nchans;
		cursamp++;
		counter += increment;	// keeps track of interp pointer

		// increment input
		while ((counter - (float)incount) >= -0.5f) {
			inp += nchans;
			incount++;
			insamp++;
		}
	}
	// save history for next time
	printf("saving samps %g, %g\n", in[insamp+1], in[insamp+2]);
	for (n = 0; n < nchans; n++) {
		vold[n] = in[(nchans * (insamp + 1)) + n];
		old[n] = in[(nchans * (insamp + 2)) + n];
	}
	rtbaddout(out, outsamps * nchans);
	printf("OUT %d samples\n\n", i);
	return (i);
}

Instrument *
makeTRANS()
{
	return new TRANS();
}

void
rtprofile()
{
	RT_INTRO("TRANS",makeTRANS);
}

static float
interp(float y0, float y1, float y2, float t)
{
    float hy2, hy0, a, b, c;

    a = y0;
    hy0 = y0/2.0f;
    hy2 =  y2/2.0f;
    b = (-3.0f * hy0) + (2.0f * y1) - hy2;
    c = hy0 - y1 + hy2;

    return(a + b*t + c*t*t);
}
<|endoftext|>


<commit_before>// Copyright 2014 BVLC and contributors.
//
// matcaffe.cpp provides a wrapper of the caffe::Net class as well as some
// caffe::Caffe functions so that one could easily call it from matlab.
// Note that for matlab, we will simply use float as the data type.

#include <string>
#include <vector>

#include "mex.h"
#include "caffe/caffe.hpp"

#define MEX_ARGS int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs

using namespace caffe;  // NOLINT(build/namespaces)

// The pointer to the internal caffe::Net instance
static shared_ptr<Net<float> > net_;
static int init_key = -2;

// Five things to be aware of:
//   caffe uses row-major order
//   matlab uses column-major order
//   caffe uses BGR color channel order
//   matlab uses RGB color channel order
//   images need to have the data mean subtracted
//
// Data coming in from matlab needs to be in the order
//   [width, height, channels, images]
// where width is the fastest dimension.
// Here is the rough matlab for putting image data into the correct
// format:
//   % convert from uint8 to single
//   im = single(im);
//   % reshape to a fixed size (e.g., 227x227)
//   im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
//   % permute from RGB to BGR and subtract the data mean (already in BGR)
//   im = im(:,:,[3 2 1]) - data_mean;
//   % flip width and height to make width the fastest dimension
//   im = permute(im, [2 1 3]);
//
// If you have multiple images, cat them with cat(4, ...)
//
// The actual forward function. It takes in a cell array of 4-D arrays as

// input and outputs a cell array.

static mxArray* do_forward(const mxArray* const bottom) {
  vector<Blob<float>*>& input_blobs = net_->input_blobs();
  CHECK_EQ(static_cast<unsigned int>(mxGetDimensions(bottom)[0]),
      input_blobs.size());
  for (unsigned int i = 0; i < input_blobs.size(); ++i) {
    const mxArray* const elem = mxGetCell(bottom, i);
    const float* const data_ptr =
        reinterpret_cast<const float* const>(mxGetPr(elem));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(input_blobs[i]->mutable_cpu_data(), data_ptr,
          sizeof(float) * input_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(input_blobs[i]->mutable_gpu_data(), data_ptr,
          sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }
  const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled();
  mxArray* mx_out = mxCreateCellMatrix(output_blobs.size(), 1);
  for (unsigned int i = 0; i < output_blobs.size(); ++i) {
    // internally data is stored as (width, height, channels, num)
    // where width is the fastest dimension
    mwSize dims[4] = {output_blobs[i]->width(), output_blobs[i]->height(),
      output_blobs[i]->channels(), output_blobs[i]->num()};
    mxArray* mx_blob =  mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
    mxSetCell(mx_out, i, mx_blob);
    float* data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(data_ptr, output_blobs[i]->cpu_data(),
          sizeof(float) * output_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(data_ptr, output_blobs[i]->gpu_data(),
          sizeof(float) * output_blobs[i]->count(), cudaMemcpyDeviceToHost);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }

  return mx_out;
}

static mxArray* do_backward(const mxArray* const top_diff) {
  vector<Blob<float>*>& output_blobs = net_->output_blobs();
  vector<Blob<float>*>& input_blobs = net_->input_blobs();
  CHECK_EQ(static_cast<unsigned int>(mxGetDimensions(top_diff)[0]),
      output_blobs.size());
  // First, copy the output diff
  for (unsigned int i = 0; i < output_blobs.size(); ++i) {
    const mxArray* const elem = mxGetCell(top_diff, i);
    const float* const data_ptr =
        reinterpret_cast<const float* const>(mxGetPr(elem));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(output_blobs[i]->mutable_cpu_diff(), data_ptr,
        sizeof(float) * output_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(output_blobs[i]->mutable_gpu_diff(), data_ptr,
        sizeof(float) * output_blobs[i]->count(), cudaMemcpyHostToDevice);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }
  //LOG(INFO) << "Start";
  net_->Backward();
  //LOG(INFO) << "End";
  mxArray* mx_out = mxCreateCellMatrix(input_blobs.size(), 1);
  for (unsigned int i = 0; i < input_blobs.size(); ++i) {
    // internally data is stored as (width, height, channels, num)
    // where width is the fastest dimension
    mwSize dims[4] = {input_blobs[i]->width(), input_blobs[i]->height(),
      input_blobs[i]->channels(), input_blobs[i]->num()};
    mxArray* mx_blob =  mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
    mxSetCell(mx_out, i, mx_blob);
    float* data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(data_ptr, input_blobs[i]->cpu_diff(),
          sizeof(float) * input_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(data_ptr, input_blobs[i]->gpu_diff(),
          sizeof(float) * input_blobs[i]->count(), cudaMemcpyDeviceToHost);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }

  return mx_out;
}

static mxArray* do_get_weights() {
  const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
  const vector<string>& layer_names = net_->layer_names();

  // Step 1: count the number of layers with weights
  int num_layers = 0;
  {
    string prev_layer_name = "";
    for (unsigned int i = 0; i < layers.size(); ++i) {
      vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
      if (layer_blobs.size() == 0) {
        continue;
      }
      if (layer_names[i] != prev_layer_name) {
        prev_layer_name = layer_names[i];
        num_layers++;
      }
    }
  }

  // Step 2: prepare output array of structures
  mxArray* mx_layers;
  {
    const mwSize dims[2] = {num_layers, 1};
    const char* fnames[2] = {"weights", "layer_names"};
    mx_layers = mxCreateStructArray(2, dims, 2, fnames);
  }

  // Step 3: copy weights into output
  {
    string prev_layer_name = "";
    int mx_layer_index = 0;
    for (unsigned int i = 0; i < layers.size(); ++i) {
      vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
      if (layer_blobs.size() == 0) {
        continue;
      }

      mxArray* mx_layer_cells = NULL;
      if (layer_names[i] != prev_layer_name) {
        prev_layer_name = layer_names[i];
        const mwSize dims[2] = {layer_blobs.size(), 1};
        mx_layer_cells = mxCreateCellArray(2, dims);
        mxSetField(mx_layers, mx_layer_index, "weights", mx_layer_cells);
        mxSetField(mx_layers, mx_layer_index, "layer_names",
            mxCreateString(layer_names[i].c_str()));
        mx_layer_index++;
      }

      for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
        // internally data is stored as (width, height, channels, num)
        // where width is the fastest dimension
        mwSize dims[4] = {layer_blobs[j]->width(), layer_blobs[j]->height(),
            layer_blobs[j]->channels(), layer_blobs[j]->num()};
        mxArray* mx_weights = mxCreateNumericArray(4, dims, mxSINGLE_CLASS,
                                                   mxREAL);
        mxSetCell(mx_layer_cells, j, mx_weights);
        float* weights_ptr = reinterpret_cast<float*>(mxGetPr(mx_weights));

        //  mexPrintf("layer: %s (%d) blob: %d  %d: (%d, %d, %d) %d\n",
        //  layer_names[i].c_str(), i, j, layer_blobs[j]->num(),
        //  layer_blobs[j]->height(), layer_blobs[j]->width(),
        //  layer_blobs[j]->channels(), layer_blobs[j]->count());

        switch (Caffe::mode()) {
        case Caffe::CPU:
          memcpy(weights_ptr, layer_blobs[j]->cpu_data(),
              sizeof(float) * layer_blobs[j]->count());
          break;
        case Caffe::GPU:
          CUDA_CHECK(cudaMemcpy(weights_ptr, layer_blobs[j]->gpu_data(),
              sizeof(float) * layer_blobs[j]->count(), cudaMemcpyDeviceToHost));
          break;
        default:
          LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
        }
      }
    }
  }

  return mx_layers;
}

static void get_weights(MEX_ARGS) {
  plhs[0] = do_get_weights();
}

static void set_mode_cpu(MEX_ARGS) {
  Caffe::set_mode(Caffe::CPU);
}

static void set_mode_gpu(MEX_ARGS) {
  Caffe::set_mode(Caffe::GPU);
}

static void set_phase_train(MEX_ARGS) {
  Caffe::set_phase(Caffe::TRAIN);
}

static void set_phase_test(MEX_ARGS) {
  Caffe::set_phase(Caffe::TEST);
}

static void set_device(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  int device_id = static_cast<int>(mxGetScalar(prhs[0]));
  Caffe::SetDevice(device_id);
}

static void get_init_key(MEX_ARGS) {
  plhs[0] = mxCreateDoubleScalar(init_key);
}

static void init(MEX_ARGS) {
  if (nrhs != 2) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  char* param_file = mxArrayToString(prhs[0]);
  char* model_file = mxArrayToString(prhs[1]);

  net_.reset(new Net<float>(string(param_file)));
  net_->CopyTrainedLayersFrom(string(model_file));

  mxFree(param_file);
  mxFree(model_file);

  // NOLINT_NEXT_LINE(runtime/threadsafe_fn)
  init_key = rand();
  if (nlhs == 1) {
    plhs[0] = mxCreateDoubleScalar(init_key);
  }
}

static void end(MEX_ARGS){
  if (net_) {
    net_.reset();
    init_key = -2;
    LOG(INFO) << "Network reset, now it needs to init before used again";
  }
}

static void forward(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  plhs[0] = do_forward(prhs[0]);
}

static void backward(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  plhs[0] = do_backward(prhs[0]);
}

static void is_initialized(MEX_ARGS) {
  if (!net_) {
    plhs[0] = mxCreateDoubleScalar(0);
  } else {
    plhs[0] = mxCreateDoubleScalar(1);
  }
}

/** -----------------------------------------------------------------
 ** Available commands.
 **/
struct handler_registry {
  string cmd;
  void (*func)(MEX_ARGS);
};

static handler_registry handlers[] = {
  // Public API functions
  { "forward",            forward         },
  { "backward",           backward        },
  { "init",               init            },
  { "is_initialized",     is_initialized  },
  { "set_mode_cpu",       set_mode_cpu    },
  { "set_mode_gpu",       set_mode_gpu    },
  { "set_phase_train",    set_phase_train },
  { "set_phase_test",     set_phase_test  },
  { "set_device",         set_device      },
  { "get_weights",        get_weights     },
  { "get_init_key",       get_init_key    },
  // The end.
  { "END",                end             },
};

/** -----------------------------------------------------------------
 ** matlab entry point: caffe(api_command, arg1, arg2, ...)
 **/
void mexFunction(MEX_ARGS) {
  if (nrhs == 0) {
    LOG(ERROR) << "No API command given";
    mexErrMsgTxt("An API command is requires");
    return;
  }

  { // Handle input command
    char *cmd = mxArrayToString(prhs[0]);
    bool dispatched = false;
    // Dispatch to cmd handler
    for (int i = 0; handlers[i].func != NULL; i++) {
      if (handlers[i].cmd.compare(cmd) == 0) {
        handlers[i].func(nlhs, plhs, nrhs-1, prhs+1);
        dispatched = true;
        break;
      }
    }
    if (!dispatched) {
      LOG(ERROR) << "Unknown command `" << cmd << "'";
      mexErrMsgTxt("API command not recognized");
    }
    mxFree(cmd);
  }
}
<commit_msg>Cleaned matcaffe.cpp to pass lint<commit_after>// Copyright 2014 BVLC and contributors.
//
// matcaffe.cpp provides a wrapper of the caffe::Net class as well as some
// caffe::Caffe functions so that one could easily call it from matlab.
// Note that for matlab, we will simply use float as the data type.

#include <string>
#include <vector>

#include "mex.h"
#include "caffe/caffe.hpp"

#define MEX_ARGS int nlhs, mxArray **plhs, int nrhs, const mxArray **prhs

using namespace caffe;  // NOLINT(build/namespaces)

// The pointer to the internal caffe::Net instance
static shared_ptr<Net<float> > net_;
static int init_key = -2;

// Five things to be aware of:
//   caffe uses row-major order
//   matlab uses column-major order
//   caffe uses BGR color channel order
//   matlab uses RGB color channel order
//   images need to have the data mean subtracted
//
// Data coming in from matlab needs to be in the order
//   [width, height, channels, images]
// where width is the fastest dimension.
// Here is the rough matlab for putting image data into the correct
// format:
//   % convert from uint8 to single
//   im = single(im);
//   % reshape to a fixed size (e.g., 227x227)
//   im = imresize(im, [IMAGE_DIM IMAGE_DIM], 'bilinear');
//   % permute from RGB to BGR and subtract the data mean (already in BGR)
//   im = im(:,:,[3 2 1]) - data_mean;
//   % flip width and height to make width the fastest dimension
//   im = permute(im, [2 1 3]);
//
// If you have multiple images, cat them with cat(4, ...)
//
// The actual forward function. It takes in a cell array of 4-D arrays as
// input and outputs a cell array.

static mxArray* do_forward(const mxArray* const bottom) {
  vector<Blob<float>*>& input_blobs = net_->input_blobs();
  CHECK_EQ(static_cast<unsigned int>(mxGetDimensions(bottom)[0]),
      input_blobs.size());
  for (unsigned int i = 0; i < input_blobs.size(); ++i) {
    const mxArray* const elem = mxGetCell(bottom, i);
    const float* const data_ptr =
        reinterpret_cast<const float* const>(mxGetPr(elem));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(input_blobs[i]->mutable_cpu_data(), data_ptr,
          sizeof(float) * input_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(input_blobs[i]->mutable_gpu_data(), data_ptr,
          sizeof(float) * input_blobs[i]->count(), cudaMemcpyHostToDevice);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }
  const vector<Blob<float>*>& output_blobs = net_->ForwardPrefilled();
  mxArray* mx_out = mxCreateCellMatrix(output_blobs.size(), 1);
  for (unsigned int i = 0; i < output_blobs.size(); ++i) {
    // internally data is stored as (width, height, channels, num)
    // where width is the fastest dimension
    mwSize dims[4] = {output_blobs[i]->width(), output_blobs[i]->height(),
      output_blobs[i]->channels(), output_blobs[i]->num()};
    mxArray* mx_blob =  mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
    mxSetCell(mx_out, i, mx_blob);
    float* data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(data_ptr, output_blobs[i]->cpu_data(),
          sizeof(float) * output_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(data_ptr, output_blobs[i]->gpu_data(),
          sizeof(float) * output_blobs[i]->count(), cudaMemcpyDeviceToHost);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }

  return mx_out;
}

static mxArray* do_backward(const mxArray* const top_diff) {
  vector<Blob<float>*>& output_blobs = net_->output_blobs();
  vector<Blob<float>*>& input_blobs = net_->input_blobs();
  CHECK_EQ(static_cast<unsigned int>(mxGetDimensions(top_diff)[0]),
      output_blobs.size());
  // First, copy the output diff
  for (unsigned int i = 0; i < output_blobs.size(); ++i) {
    const mxArray* const elem = mxGetCell(top_diff, i);
    const float* const data_ptr =
        reinterpret_cast<const float* const>(mxGetPr(elem));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(output_blobs[i]->mutable_cpu_diff(), data_ptr,
        sizeof(float) * output_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(output_blobs[i]->mutable_gpu_diff(), data_ptr,
        sizeof(float) * output_blobs[i]->count(), cudaMemcpyHostToDevice);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }
  // LOG(INFO) << "Start";
  net_->Backward();
  // LOG(INFO) << "End";
  mxArray* mx_out = mxCreateCellMatrix(input_blobs.size(), 1);
  for (unsigned int i = 0; i < input_blobs.size(); ++i) {
    // internally data is stored as (width, height, channels, num)
    // where width is the fastest dimension
    mwSize dims[4] = {input_blobs[i]->width(), input_blobs[i]->height(),
      input_blobs[i]->channels(), input_blobs[i]->num()};
    mxArray* mx_blob =  mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
    mxSetCell(mx_out, i, mx_blob);
    float* data_ptr = reinterpret_cast<float*>(mxGetPr(mx_blob));
    switch (Caffe::mode()) {
    case Caffe::CPU:
      memcpy(data_ptr, input_blobs[i]->cpu_diff(),
          sizeof(float) * input_blobs[i]->count());
      break;
    case Caffe::GPU:
      cudaMemcpy(data_ptr, input_blobs[i]->gpu_diff(),
          sizeof(float) * input_blobs[i]->count(), cudaMemcpyDeviceToHost);
      break;
    default:
      LOG(FATAL) << "Unknown Caffe mode.";
    }  // switch (Caffe::mode())
  }

  return mx_out;
}

static mxArray* do_get_weights() {
  const vector<shared_ptr<Layer<float> > >& layers = net_->layers();
  const vector<string>& layer_names = net_->layer_names();

  // Step 1: count the number of layers with weights
  int num_layers = 0;
  {
    string prev_layer_name = "";
    for (unsigned int i = 0; i < layers.size(); ++i) {
      vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
      if (layer_blobs.size() == 0) {
        continue;
      }
      if (layer_names[i] != prev_layer_name) {
        prev_layer_name = layer_names[i];
        num_layers++;
      }
    }
  }

  // Step 2: prepare output array of structures
  mxArray* mx_layers;
  {
    const mwSize dims[2] = {num_layers, 1};
    const char* fnames[2] = {"weights", "layer_names"};
    mx_layers = mxCreateStructArray(2, dims, 2, fnames);
  }

  // Step 3: copy weights into output
  {
    string prev_layer_name = "";
    int mx_layer_index = 0;
    for (unsigned int i = 0; i < layers.size(); ++i) {
      vector<shared_ptr<Blob<float> > >& layer_blobs = layers[i]->blobs();
      if (layer_blobs.size() == 0) {
        continue;
      }

      mxArray* mx_layer_cells = NULL;
      if (layer_names[i] != prev_layer_name) {
        prev_layer_name = layer_names[i];
        const mwSize dims[2] = {layer_blobs.size(), 1};
        mx_layer_cells = mxCreateCellArray(2, dims);
        mxSetField(mx_layers, mx_layer_index, "weights", mx_layer_cells);
        mxSetField(mx_layers, mx_layer_index, "layer_names",
            mxCreateString(layer_names[i].c_str()));
        mx_layer_index++;
      }

      for (unsigned int j = 0; j < layer_blobs.size(); ++j) {
        // internally data is stored as (width, height, channels, num)
        // where width is the fastest dimension
        mwSize dims[4] = {layer_blobs[j]->width(), layer_blobs[j]->height(),
            layer_blobs[j]->channels(), layer_blobs[j]->num()};

        mxArray* mx_weights =
          mxCreateNumericArray(4, dims, mxSINGLE_CLASS, mxREAL);
        mxSetCell(mx_layer_cells, j, mx_weights);
        float* weights_ptr = reinterpret_cast<float*>(mxGetPr(mx_weights));

        switch (Caffe::mode()) {
        case Caffe::CPU:
          memcpy(weights_ptr, layer_blobs[j]->cpu_data(),
              sizeof(float) * layer_blobs[j]->count());
          break;
        case Caffe::GPU:
          CUDA_CHECK(cudaMemcpy(weights_ptr, layer_blobs[j]->gpu_data(),
              sizeof(float) * layer_blobs[j]->count(), cudaMemcpyDeviceToHost));
          break;
        default:
          LOG(FATAL) << "Unknown caffe mode: " << Caffe::mode();
        }
      }
    }
  }

  return mx_layers;
}

static void get_weights(MEX_ARGS) {
  plhs[0] = do_get_weights();
}

static void set_mode_cpu(MEX_ARGS) {
  Caffe::set_mode(Caffe::CPU);
}

static void set_mode_gpu(MEX_ARGS) {
  Caffe::set_mode(Caffe::GPU);
}

static void set_phase_train(MEX_ARGS) {
  Caffe::set_phase(Caffe::TRAIN);
}

static void set_phase_test(MEX_ARGS) {
  Caffe::set_phase(Caffe::TEST);
}

static void set_device(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  int device_id = static_cast<int>(mxGetScalar(prhs[0]));
  Caffe::SetDevice(device_id);
}

static void get_init_key(MEX_ARGS) {
  plhs[0] = mxCreateDoubleScalar(init_key);
}

static void init(MEX_ARGS) {
  if (nrhs != 2) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  char* param_file = mxArrayToString(prhs[0]);
  char* model_file = mxArrayToString(prhs[1]);

  net_.reset(new Net<float>(string(param_file)));
  net_->CopyTrainedLayersFrom(string(model_file));

  mxFree(param_file);
  mxFree(model_file);

  init_key = random();

  if (nlhs == 1) {
    plhs[0] = mxCreateDoubleScalar(init_key);
  }
}

static void end(MEX_ARGS) {
  if (net_) {
    net_.reset();
    init_key = -2;
    LOG(INFO) << "Network reset, now it needs to init before used again";
  }
}

static void forward(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  plhs[0] = do_forward(prhs[0]);
}

static void backward(MEX_ARGS) {
  if (nrhs != 1) {
    LOG(ERROR) << "Only given " << nrhs << " arguments";
    mexErrMsgTxt("Wrong number of arguments");
  }

  plhs[0] = do_backward(prhs[0]);
}

static void is_initialized(MEX_ARGS) {
  if (!net_) {
    plhs[0] = mxCreateDoubleScalar(0);
  } else {
    plhs[0] = mxCreateDoubleScalar(1);
  }
}

/** -----------------------------------------------------------------
 ** Available commands.
 **/
struct handler_registry {
  string cmd;
  void (*func)(MEX_ARGS);
};

static handler_registry handlers[] = {
  // Public API functions
  { "forward",            forward         },
  { "backward",           backward        },
  { "init",               init            },
  { "is_initialized",     is_initialized  },
  { "set_mode_cpu",       set_mode_cpu    },
  { "set_mode_gpu",       set_mode_gpu    },
  { "set_phase_train",    set_phase_train },
  { "set_phase_test",     set_phase_test  },
  { "set_device",         set_device      },
  { "get_weights",        get_weights     },
  { "get_init_key",       get_init_key    },
  // The end.
  { "END",                end             },
};

/** -----------------------------------------------------------------
 ** matlab entry point: caffe(api_command, arg1, arg2, ...)
 **/
void mexFunction(MEX_ARGS) {
  if (nrhs == 0) {
    LOG(ERROR) << "No API command given";
    mexErrMsgTxt("An API command is requires");
    return;
  }

  { // Handle input command
    char *cmd = mxArrayToString(prhs[0]);
    bool dispatched = false;
    // Dispatch to cmd handler
    for (int i = 0; handlers[i].func != NULL; i++) {
      if (handlers[i].cmd.compare(cmd) == 0) {
        handlers[i].func(nlhs, plhs, nrhs-1, prhs+1);
        dispatched = true;
        break;
      }
    }
    if (!dispatched) {
      LOG(ERROR) << "Unknown command `" << cmd << "'";
      mexErrMsgTxt("API command not recognized");
    }
    mxFree(cmd);
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: otherjre.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-08-18 08:21:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "osl/thread.h"
#include "otherjre.hxx"

using namespace rtl;
using namespace std;

namespace jfw_plugin
{

Reference<VendorBase> OtherInfo::createInstance()
{
    return new OtherInfo;
}

char const* const* OtherInfo::getJavaExePaths(int * size)
{
    static char const * ar[] = {
#ifdef WNT
        "bin/java.exe",
        "jre/bin/java.exe"
#elif UNX
        "bin/java",
        "jre/bin/java"
#endif
    };
        *size = sizeof (ar) / sizeof (char*);
    return ar;
}

char const* const* OtherInfo::getRuntimePaths(int * size)
{
    static char const* ar[]= {
#ifdef WNT
        "/bin/client/jvm.dll",
        "/bin/hotspot/jvm.dll",
        "/bin/classic/jvm.dll"
#elif UNX
#ifdef MACOSX
        "/../../../JavaVM"
#else
        "/bin/classic/libjvm.so", // for IBM Java
        "/jre/bin/classic/libjvm.so", // for IBM Java
        "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC
        "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so" // for Blackdown PPC
#endif
#endif

    };
    *size = sizeof(ar) / sizeof (char*);
    return ar;
}

char const* const* OtherInfo::getLibraryPaths(int* size)
{

#ifdef UNX
    static char const * ar[] = {
#ifdef MACOSX
        "/../Libraries",
        "/lib"
#else
        "/bin",
        "/jre/bin",
        "/bin/classic",
        "/jre/bin/classic",
        "/lib/" JFW_PLUGIN_ARCH "/client",
        "/lib/" JFW_PLUGIN_ARCH "/classic",
        "/lib/" JFW_PLUGIN_ARCH "/native_threads",
        "/lib/" JFW_PLUGIN_ARCH
#endif
    };

    *size = sizeof(ar) / sizeof (char*);
    return ar;
#endif
    size = 0;
    return NULL;
}

int OtherInfo::compareVersions(const rtl::OUString& sSecond) const
{
    //Need to provide an own algorithm for comparing version.
    //Because this function returns always 0, which means the version of
    //this JRE and the provided version "sSecond" are equal, one cannot put
    //any excludeVersion entries in the javavendors.xml file.
    return 0;
}

}
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.4); FILE MERGED 2005/09/05 17:12:22 rt 1.7.4.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: otherjre.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 19:30:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "osl/thread.h"
#include "otherjre.hxx"

using namespace rtl;
using namespace std;

namespace jfw_plugin
{

Reference<VendorBase> OtherInfo::createInstance()
{
    return new OtherInfo;
}

char const* const* OtherInfo::getJavaExePaths(int * size)
{
    static char const * ar[] = {
#ifdef WNT
        "bin/java.exe",
        "jre/bin/java.exe"
#elif UNX
        "bin/java",
        "jre/bin/java"
#endif
    };
        *size = sizeof (ar) / sizeof (char*);
    return ar;
}

char const* const* OtherInfo::getRuntimePaths(int * size)
{
    static char const* ar[]= {
#ifdef WNT
        "/bin/client/jvm.dll",
        "/bin/hotspot/jvm.dll",
        "/bin/classic/jvm.dll"
#elif UNX
#ifdef MACOSX
        "/../../../JavaVM"
#else
        "/bin/classic/libjvm.so", // for IBM Java
        "/jre/bin/classic/libjvm.so", // for IBM Java
        "/lib/" JFW_PLUGIN_ARCH "/client/libjvm.so", // for Blackdown PPC
        "/lib/" JFW_PLUGIN_ARCH "/classic/libjvm.so" // for Blackdown PPC
#endif
#endif

    };
    *size = sizeof(ar) / sizeof (char*);
    return ar;
}

char const* const* OtherInfo::getLibraryPaths(int* size)
{

#ifdef UNX
    static char const * ar[] = {
#ifdef MACOSX
        "/../Libraries",
        "/lib"
#else
        "/bin",
        "/jre/bin",
        "/bin/classic",
        "/jre/bin/classic",
        "/lib/" JFW_PLUGIN_ARCH "/client",
        "/lib/" JFW_PLUGIN_ARCH "/classic",
        "/lib/" JFW_PLUGIN_ARCH "/native_threads",
        "/lib/" JFW_PLUGIN_ARCH
#endif
    };

    *size = sizeof(ar) / sizeof (char*);
    return ar;
#endif
    size = 0;
    return NULL;
}

int OtherInfo::compareVersions(const rtl::OUString& sSecond) const
{
    //Need to provide an own algorithm for comparing version.
    //Because this function returns always 0, which means the version of
    //this JRE and the provided version "sSecond" are equal, one cannot put
    //any excludeVersion entries in the javavendors.xml file.
    return 0;
}

}
<|endoftext|>


<commit_before>#include <QDebug>
#include <QtGui/QOpenGLVertexArrayObject>
#include <QtGui/QOpenGLBuffer>
#include <assimp/scene.h>
#include <limits>
#include "glpointcloud.h"
#include "dynamics.h"
#include "fluid.h"

// GLPointCloud stuff
template<typename REAL, typename SIZE>
GLPointCloudRS<REAL,SIZE>::GLPointCloudRS(
    PointCloudPtrRS<REAL,SIZE> pc,
    MaterialConstPtr mat,
    UniformBuffer &ubo,
    ShaderManager &shaderman)
  : GLPrimitiveS<SIZE>(mat, ubo, shaderman)
  , m_pc(pc)
  , m_vertices(3, get_num_vertices())
  , m_radius(pc->get_radius())
  , m_halo_radius(pc->get_halo_radius())
  , m_insync(true)
  , m_halos(false)
  , m_isdynamic(pc->is_dynamic())
{
  m_vertices = m_pc->get_pos().template cast<float>(); // copy position data

  this->m_vao.create();
  this->m_vao.bind();

  this->m_pos.create();
  this->m_pos.setUsagePattern(
      is_dynamic() ? QOpenGLBuffer::StreamDraw : QOpenGLBuffer::StaticDraw );
  this->m_pos.bind();
  this->m_pos.allocate( m_vertices.data(), sizeof( GLfloat ) * m_vertices.size() );

  this->m_vao.release();

  if (is_dynamic())
  {
    FluidRS<REAL,SIZE> &fl = static_cast<FluidRS<REAL,SIZE> &>(*pc);
    fl.init(this);
  }

  update_shader(ShaderManager::ADDITIVE_PARTICLE);
}

template<typename REAL, typename SIZE>
GLPointCloudRS<REAL,SIZE>::~GLPointCloudRS()
{ }

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_data()
{
  std::lock_guard<std::mutex> guard(this->m_lock);

  if (!m_insync)
    return;

  m_vertices = m_pc->get_pos().template cast<float>();

  m_insync = false;
}

template<typename REAL, typename SIZE>
inline void GLPointCloudRS<REAL,SIZE>::clear_cache()
{
  std::lock_guard<std::mutex> guard(this->m_lock);
  if (is_dynamic())
  {
    FluidRS<REAL,SIZE> &fl = static_cast<FluidRS<REAL,SIZE> &>(*m_pc);
    fl.clear_cache();
  }
}

template<typename REAL, typename SIZE>
Vector3f GLPointCloudRS<REAL,SIZE>::get_closest_pt() const
{
  return Vector3f(m_vertices.col(get_num_vertices()-1));
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::sort_by_depth(const AffineCompact3f &mvtrans)
{
  std::lock_guard<std::mutex> guard(this->m_lock); // prevent others from reading buffers

  // Sort all vertices by the z value
  Matrix3XR<GLfloat> mvpos = mvtrans * m_vertices; // TODO: mem alloc expensive?
  SIZE num_verts = get_num_vertices();
  VectorXT<SIZE> perm_vec(num_verts);
  for (SIZE i = 0; i < num_verts; ++i)
    perm_vec[i] = i;

  SIZE *perm_data = perm_vec.data();

  std::sort(perm_data, perm_data + num_verts,
      [mvpos](SIZE i, SIZE j) { return mvpos.col(i)[2] < mvpos.col(j)[2]; });

  m_vertices = m_vertices * PermutationMatrix<Dynamic, Dynamic, SIZE>(perm_vec);

  m_insync = false;
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_glbuf()
{
  // even though this routine doesn't access m_pc, another thread may be
  // writing to m_vertices so we still need to lock it
  std::lock_guard<std::mutex> guard(this->m_lock);

  if (m_insync)
    return;

  // write to gl buffer object
  this->m_pos.bind();
  this->m_pos.write( 0, m_vertices.data(), sizeof( GLfloat ) * m_vertices.size() );
  this->m_pos.release();

  m_insync = true;
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_shader(ShaderManager::ShaderType type)
{
  if (this->m_prog)
  {
    this->m_prog->disableAttributeArray( "pos" );
  }

  if (type == ShaderManager::PARTICLE)
    this->m_prog = this->m_shaderman.get_particle_shader();
  else
    this->m_prog = this->m_shaderman.get_additive_particle_shader();

  this->m_vao.bind();

  this->m_pos.bind();
  this->m_prog->enableAttributeArray( "pos" );
  this->m_prog->setAttributeBuffer( "pos", GL_FLOAT, 0, 3 );

  this->m_vao.release();

  this->m_ubo.bindToProg(this->m_prog->programId(), "Globals");
}

template class GLPointCloudRS<double, unsigned int>;
<commit_msg>measure sort time<commit_after>#include <QDebug>
#include <QtGui/QOpenGLVertexArrayObject>
#include <QtGui/QOpenGLBuffer>
#include <assimp/scene.h>
#include <limits>
#include "glpointcloud.h"
#include "dynamics.h"
#include "fluid.h"

// GLPointCloud stuff
template<typename REAL, typename SIZE>
GLPointCloudRS<REAL,SIZE>::GLPointCloudRS(
    PointCloudPtrRS<REAL,SIZE> pc,
    MaterialConstPtr mat,
    UniformBuffer &ubo,
    ShaderManager &shaderman)
  : GLPrimitiveS<SIZE>(mat, ubo, shaderman)
  , m_pc(pc)
  , m_vertices(3, get_num_vertices())
  , m_radius(pc->get_radius())
  , m_halo_radius(pc->get_halo_radius())
  , m_insync(true)
  , m_halos(false)
  , m_isdynamic(pc->is_dynamic())
{
  m_vertices = m_pc->get_pos().template cast<float>(); // copy position data

  this->m_vao.create();
  this->m_vao.bind();

  this->m_pos.create();
  this->m_pos.setUsagePattern(
      is_dynamic() ? QOpenGLBuffer::StreamDraw : QOpenGLBuffer::StaticDraw );
  this->m_pos.bind();
  this->m_pos.allocate( m_vertices.data(), sizeof( GLfloat ) * m_vertices.size() );

  this->m_vao.release();

  if (is_dynamic())
  {
    FluidRS<REAL,SIZE> &fl = static_cast<FluidRS<REAL,SIZE> &>(*pc);
    fl.init(this);
  }

  update_shader(ShaderManager::ADDITIVE_PARTICLE);
}

template<typename REAL, typename SIZE>
GLPointCloudRS<REAL,SIZE>::~GLPointCloudRS()
{ }

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_data()
{
  std::lock_guard<std::mutex> guard(this->m_lock);

  if (!m_insync)
    return;

  m_vertices = m_pc->get_pos().template cast<float>();

  m_insync = false;
}

template<typename REAL, typename SIZE>
inline void GLPointCloudRS<REAL,SIZE>::clear_cache()
{
  std::lock_guard<std::mutex> guard(this->m_lock);
  if (is_dynamic())
  {
    FluidRS<REAL,SIZE> &fl = static_cast<FluidRS<REAL,SIZE> &>(*m_pc);
    fl.clear_cache();
  }
}

template<typename REAL, typename SIZE>
Vector3f GLPointCloudRS<REAL,SIZE>::get_closest_pt() const
{
  return Vector3f(m_vertices.col(get_num_vertices()-1));
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::sort_by_depth(const AffineCompact3f &mvtrans)
{
  std::lock_guard<std::mutex> guard(this->m_lock); // prevent others from reading buffers

  // Sort all vertices by the z value
  clock_t s = clock();
  Matrix3XR<GLfloat> mvpos = mvtrans * m_vertices; // TODO: mem alloc expensive?
  SIZE num_verts = get_num_vertices();
  VectorXT<SIZE> perm_vec(num_verts);
  for (SIZE i = 0; i < num_verts; ++i)
    perm_vec[i] = i;

  SIZE *perm_data = perm_vec.data();

  std::sort(perm_data, perm_data + num_verts,
      [mvpos](SIZE i, SIZE j) { return mvpos.col(i)[2] < mvpos.col(j)[2]; });
  clock_t sort_t = clock();

  m_vertices = m_vertices * PermutationMatrix<Dynamic, Dynamic, SIZE>(perm_vec);

  clock_t mult_t = clock();
  fprintf(stderr, "\rsort: %05.2e  mult: %05.2e", float(sort_t - s), float(mult_t - sort_t));

  m_insync = false;
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_glbuf()
{
  // even though this routine doesn't access m_pc, another thread may be
  // writing to m_vertices so we still need to lock it
  std::lock_guard<std::mutex> guard(this->m_lock);

  if (m_insync)
    return;

  // write to gl buffer object
  this->m_pos.bind();
  this->m_pos.write( 0, m_vertices.data(), sizeof( GLfloat ) * m_vertices.size() );
  this->m_pos.release();

  m_insync = true;
}

template<typename REAL, typename SIZE>
void GLPointCloudRS<REAL,SIZE>::update_shader(ShaderManager::ShaderType type)
{
  if (this->m_prog)
  {
    this->m_prog->disableAttributeArray( "pos" );
  }

  if (type == ShaderManager::PARTICLE)
    this->m_prog = this->m_shaderman.get_particle_shader();
  else
    this->m_prog = this->m_shaderman.get_additive_particle_shader();

  this->m_vao.bind();

  this->m_pos.bind();
  this->m_prog->enableAttributeArray( "pos" );
  this->m_prog->setAttributeBuffer( "pos", GL_FLOAT, 0, 3 );

  this->m_vao.release();

  this->m_ubo.bindToProg(this->m_prog->programId(), "Globals");
}

template class GLPointCloudRS<double, unsigned int>;
<|endoftext|>