<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "alloc.h"
#include "intrinsics.h"

////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////

#ifdef _WIN32

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <malloc.h>

namespace embree
{
  void* alignedMalloc(size_t size, size_t align)
  {
    assert((align & (align-1)) == 0);
    if (size == 0) return nullptr;
    void* ptr = _aligned_malloc(size,align);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void alignedFree(const void* ptr)
  {
    if (ptr == nullptr) return;
    _aligned_free((void*)ptr);
  }

  void* os_malloc(size_t bytes, const int additional_flags)
  {
    int flags = MEM_COMMIT|MEM_RESERVE|additional_flags;
    char* ptr = (char*) VirtualAlloc(nullptr,bytes,flags,PAGE_READWRITE);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void* os_reserve(size_t bytes)
  {
    char* ptr = (char*) VirtualAlloc(nullptr,bytes,MEM_RESERVE,PAGE_READWRITE);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void os_commit (void* ptr, size_t bytes) {
    VirtualAlloc(ptr,bytes,MEM_COMMIT,PAGE_READWRITE);
  }

  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld)
  {
    size_t pageSize = 4096;
    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);
    assert(bytesNew <= bytesOld);
    if (bytesNew < bytesOld)
      VirtualFree((char*)ptr+bytesNew,bytesOld-bytesNew,MEM_DECOMMIT);
    return bytesNew;
  }

  void os_free(void* ptr, size_t bytes) {
    if (bytes == 0) return;
    VirtualFree(ptr,0,MEM_RELEASE);
  }

  void* os_realloc (void* ptr, size_t bytesNew, size_t bytesOld) {
    NOT_IMPLEMENTED;
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__UNIX__)

#include <sys/mman.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#if defined(__MIC__)
#define USE_HUGE_PAGES 1
#else
#define USE_HUGE_PAGES 0
#endif

namespace embree
{
  void* alignedMalloc(size_t size, size_t align)
  {
    assert((align & (align-1)) == 0);
    void* ptr = NULL;
    align = std::max(align,sizeof(void*));
    size = (size+align-1)&~(align-1);
    if (posix_memalign(&ptr,align,size) != 0) throw std::bad_alloc();
    return ptr;
  }

  void alignedFree(const void* ptr) {
    free((void*)ptr);
  }

  void* os_malloc(size_t bytes, const int additional_flags)
  {
    int flags = MAP_PRIVATE | MAP_ANON | additional_flags;
#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      flags |= MAP_HUGETLB;
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
#if __MIC__
    flags |= MAP_POPULATE;
#endif
    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);
    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();
    return ptr;
  }

  void* os_reserve(size_t bytes)
  {
    int flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      flags |= MAP_HUGETLB;
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
#if __MIC__ // || 1
    flags |= MAP_POPULATE;
#endif

    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);
    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();
    return ptr;
  }

  void os_commit (void* ptr, size_t bytes) {
  }

  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld)
  {
    size_t pageSize = 4096;
#if USE_HUGE_PAGES
    if (bytesOld > 16*4096) pageSize = 2*1024*1024;
#endif
    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);
    assert(bytesNew <= bytesOld);
    if (bytesNew < bytesOld)
      if (munmap((char*)ptr+bytesNew,bytesOld-bytesNew) == -1)
        throw std::bad_alloc();

    return bytesNew;
  }

  void os_free(void* ptr, size_t bytes)
  {
    if (bytes == 0)
      return;

#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
    if (munmap(ptr,bytes) == -1)
      throw std::bad_alloc();
  }

  void* os_realloc (void* old_ptr, size_t bytesNew, size_t bytesOld)
  {
#if defined(__MIC__)
    if (bytesOld > 16*4096)
      bytesOld = (bytesOld+2*1024*1024-1)&ssize_t(-2*1024*1024);
    else
      bytesOld = (bytesOld+4095)&ssize_t(-4096);

    if (bytesNew > 16*4096)
      bytesNew = (bytesNew+2*1024*1024-1)&ssize_t(-2*1024*1024);
    else
      bytesNew = (bytesNew+4095)&ssize_t(-4096);

    char *ptr = (char*)mremap(old_ptr,bytesOld,bytesNew,MREMAP_MAYMOVE);

    if (ptr == nullptr || ptr == MAP_FAILED) {
      perror("os_realloc ");
      throw std::bad_alloc();
    }
    return ptr;
#else
    NOT_IMPLEMENTED;
    return nullptr;
#endif

  }
}

#endif
<commit_msg>removed dead code<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

#include "alloc.h"
#include "intrinsics.h"

////////////////////////////////////////////////////////////////////////////////
/// Windows Platform
////////////////////////////////////////////////////////////////////////////////

#ifdef _WIN32

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <malloc.h>

namespace embree
{
  void* alignedMalloc(size_t size, size_t align)
  {
    assert((align & (align-1)) == 0);
    if (size == 0) return nullptr;
    void* ptr = _aligned_malloc(size,align);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void alignedFree(const void* ptr)
  {
    if (ptr == nullptr) return;
    _aligned_free((void*)ptr);
  }

  void* os_malloc(size_t bytes, const int additional_flags)
  {
    int flags = MEM_COMMIT|MEM_RESERVE|additional_flags;
    char* ptr = (char*) VirtualAlloc(nullptr,bytes,flags,PAGE_READWRITE);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void* os_reserve(size_t bytes)
  {
    char* ptr = (char*) VirtualAlloc(nullptr,bytes,MEM_RESERVE,PAGE_READWRITE);
    if (ptr == nullptr) throw std::bad_alloc();
    return ptr;
  }

  void os_commit (void* ptr, size_t bytes) {
    VirtualAlloc(ptr,bytes,MEM_COMMIT,PAGE_READWRITE);
  }

  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld)
  {
    size_t pageSize = 4096;
    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);
    assert(bytesNew <= bytesOld);
    if (bytesNew < bytesOld)
      VirtualFree((char*)ptr+bytesNew,bytesOld-bytesNew,MEM_DECOMMIT);
    return bytesNew;
  }

  void os_free(void* ptr, size_t bytes) {
    if (bytes == 0) return;
    VirtualFree(ptr,0,MEM_RELEASE);
  }
}
#endif

////////////////////////////////////////////////////////////////////////////////
/// Unix Platform
////////////////////////////////////////////////////////////////////////////////

#if defined(__UNIX__)

#include <sys/mman.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>

#if defined(__MIC__)
#define USE_HUGE_PAGES 1
#else
#define USE_HUGE_PAGES 0
#endif

namespace embree
{
  void* alignedMalloc(size_t size, size_t align)
  {
    assert((align & (align-1)) == 0);
    void* ptr = NULL;
    align = std::max(align,sizeof(void*));
    size = (size+align-1)&~(align-1);
    if (posix_memalign(&ptr,align,size) != 0) throw std::bad_alloc();
    return ptr;
  }

  void alignedFree(const void* ptr) {
    free((void*)ptr);
  }

  void* os_malloc(size_t bytes, const int additional_flags)
  {
    int flags = MAP_PRIVATE | MAP_ANON | additional_flags;
#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      flags |= MAP_HUGETLB;
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
#if __MIC__
    flags |= MAP_POPULATE;
#endif
    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);
    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();
    return ptr;
  }

  void* os_reserve(size_t bytes)
  {
    int flags = MAP_PRIVATE | MAP_ANON | MAP_NORESERVE;
#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      flags |= MAP_HUGETLB;
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
#if __MIC__ // || 1
    flags |= MAP_POPULATE;
#endif

    char* ptr = (char*) mmap(0, bytes, PROT_READ | PROT_WRITE, flags, -1, 0);
    if (ptr == nullptr || ptr == MAP_FAILED) throw std::bad_alloc();
    return ptr;
  }

  void os_commit (void* ptr, size_t bytes) {
  }

  size_t os_shrink(void* ptr, size_t bytesNew, size_t bytesOld)
  {
    size_t pageSize = 4096;
#if USE_HUGE_PAGES
    if (bytesOld > 16*4096) pageSize = 2*1024*1024;
#endif
    bytesNew = (bytesNew+pageSize-1) & ~(pageSize-1);
    assert(bytesNew <= bytesOld);
    if (bytesNew < bytesOld)
      if (munmap((char*)ptr+bytesNew,bytesOld-bytesNew) == -1)
        throw std::bad_alloc();

    return bytesNew;
  }

  void os_free(void* ptr, size_t bytes)
  {
    if (bytes == 0)
      return;

#if USE_HUGE_PAGES
    if (bytes > 16*4096) {
      bytes = (bytes+2*1024*1024-1)&ssize_t(-2*1024*1024);
    } else {
      bytes = (bytes+4095)&ssize_t(-4096);
    }
#endif
    if (munmap(ptr,bytes) == -1)
      throw std::bad_alloc();
  }
}

#endif
<|endoftext|>


<commit_before><commit_msg>X64: Disable crankshaft if serializerion is enabled.<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS swautomatic01 (1.2.324); FILE MERGED 2006/07/07 19:57:11 fme 1.2.324.1: #i65476# Automatic styles<commit_after><|endoftext|>


<commit_before>#include "logviewer.h"
#include "ui_logviewer.h"
#include <QApplication>
#include <QClipboard>
#include <QDebug>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>

LogViewer::LogViewer(const QFont &font, QWidget *parent)
    : QWidget(parent), ui(new Ui::LogViewer), m_default_font(font) {
  qDebug() << "font: " << font.toString();
  ui->setupUi(this);
  auto lb = ui->listView;

  m_delegate.m_default_font = m_default_font;

  lb->setAlternatingRowColors(true);
  lb->setItemDelegate(&m_delegate);
  lb->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
  lb->installEventFilter(this);
  lb->setUniformItemSizes(true);
  lb->setLayoutMode(QListView::LayoutMode::Batched);
  lb->setSpacing(2);

  lb->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
  connect(lb, SIGNAL(customContextMenuRequested(const QPoint &)), this,
          SLOT(customContextMenu(const QPoint &)));
  connect(lb->verticalScrollBar(), &QScrollBar::rangeChanged, this,
          &LogViewer::onScrollRangeChanged);
  connect(ui->actioncopy, &QAction::triggered, this, &LogViewer::copySelectedSlot);
}

LogViewer::~LogViewer() {
  delete ui;
}

void LogViewer::setModel(Log *model_) {
  this->ui->listView->setModel(model_);
  model_->setListVoxObject(this->ui->listView);
  m_model = model_;
  connect(model_, SIGNAL(rowsInserted(QModelIndex, int, int)), this->ui->listView,
          SLOT(scrollToBottom()));
}

void LogViewer::setAutoScroll(bool value) {
  m_autoscroll = value;
  if (value) {
    ui->listView->scrollToBottom();
  }
}

void LogViewer::onScrollRangeChanged(int min, int max) {
  Q_UNUSED(min);
  Q_UNUSED(max);
  if (m_autoscroll) {
    ui->listView->scrollToBottom();
  }
}

void LogViewer::copySelectedSlot() {
  qDebug() << "copySelectedSlot";
  auto selectedIndexes = this->ui->listView->selectionModel()->selectedIndexes();
  QClipboard *clipboard = QApplication::clipboard();
  QStringList sl;
  for (auto &i : selectedIndexes) {
    auto plainText = m_model->plainText(i);
    plainText.remove("\u0000");
    plainText.remove("\0");
    plainText.remove('\r');
    plainText.remove('\n');
    sl.append(plainText);
  }
  auto cs = sl.join("\n");
  qDebug() << cs;
  clipboard->setText(cs);
}

void LogViewer::customContextMenu(const QPoint &) {
  qDebug() << "customContextMenu";
  QMenu menu;
  menu.addAction(this->ui->actioncopy);
  menu.exec(QCursor::pos());
}

bool LogViewer::eventFilter(QObject *object, QEvent *event) {
  if (object == ui->listView && event->type() == QEvent::KeyPress) {
    QKeyEvent *ke = static_cast<QKeyEvent *>(event);
    if (ke->key() == Qt::Key_C &&
        ke->modifiers() == Qt::KeyboardModifier::ControlModifier) {
      this->copySelectedSlot();
      return true;
    }
  }
  return false;
}

void LogViewer::selectRow(int row) {
  ui->listView->selectionModel()->clearSelection();

  auto index = m_model->index(row, 0);

  ui->listView->selectionModel()->select(index,
                                         QItemSelectionModel::SelectionFlag::Select);
  ui->listView->scrollTo(index);
}
<commit_msg>logview spacing.<commit_after>#include "logviewer.h"
#include "ui_logviewer.h"
#include <QApplication>
#include <QClipboard>
#include <QDebug>
#include <QKeyEvent>
#include <QMenu>
#include <QScrollBar>

LogViewer::LogViewer(const QFont &font, QWidget *parent)
    : QWidget(parent), ui(new Ui::LogViewer), m_default_font(font) {
  qDebug() << "font: " << font.toString();
  ui->setupUi(this);
  auto lb = ui->listView;

  m_delegate.m_default_font = m_default_font;

  lb->setAlternatingRowColors(true);
  lb->setItemDelegate(&m_delegate);
  lb->setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
  lb->installEventFilter(this);
  lb->setUniformItemSizes(true);
  lb->setLayoutMode(QListView::LayoutMode::Batched);
  lb->setSpacing(0);

  lb->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
  connect(lb, SIGNAL(customContextMenuRequested(const QPoint &)), this,
          SLOT(customContextMenu(const QPoint &)));
  connect(lb->verticalScrollBar(), &QScrollBar::rangeChanged, this,
          &LogViewer::onScrollRangeChanged);
  connect(ui->actioncopy, &QAction::triggered, this, &LogViewer::copySelectedSlot);
}

LogViewer::~LogViewer() {
  delete ui;
}

void LogViewer::setModel(Log *model_) {
  this->ui->listView->setModel(model_);
  model_->setListVoxObject(this->ui->listView);
  m_model = model_;
  connect(model_, SIGNAL(rowsInserted(QModelIndex, int, int)), this->ui->listView,
          SLOT(scrollToBottom()));
}

void LogViewer::setAutoScroll(bool value) {
  m_autoscroll = value;
  if (value) {
    ui->listView->scrollToBottom();
  }
}

void LogViewer::onScrollRangeChanged(int min, int max) {
  Q_UNUSED(min);
  Q_UNUSED(max);
  if (m_autoscroll) {
    ui->listView->scrollToBottom();
  }
}

void LogViewer::copySelectedSlot() {
  qDebug() << "copySelectedSlot";
  auto selectedIndexes = this->ui->listView->selectionModel()->selectedIndexes();
  QClipboard *clipboard = QApplication::clipboard();
  QStringList sl;
  for (auto &i : selectedIndexes) {
    auto plainText = m_model->plainText(i);
    plainText.remove("\u0000");
    plainText.remove("\0");
    plainText.remove('\r');
    plainText.remove('\n');
    sl.append(plainText);
  }
  auto cs = sl.join("\n");
  qDebug() << cs;
  clipboard->setText(cs);
}

void LogViewer::customContextMenu(const QPoint &) {
  qDebug() << "customContextMenu";
  QMenu menu;
  menu.addAction(this->ui->actioncopy);
  menu.exec(QCursor::pos());
}

bool LogViewer::eventFilter(QObject *object, QEvent *event) {
  if (object == ui->listView && event->type() == QEvent::KeyPress) {
    QKeyEvent *ke = static_cast<QKeyEvent *>(event);
    if (ke->key() == Qt::Key_C &&
        ke->modifiers() == Qt::KeyboardModifier::ControlModifier) {
      this->copySelectedSlot();
      return true;
    }
  }
  return false;
}

void LogViewer::selectRow(int row) {
  ui->listView->selectionModel()->clearSelection();

  auto index = m_model->index(row, 0);

  ui->listView->selectionModel()->select(index,
                                         QItemSelectionModel::SelectionFlag::Select);
  ui->listView->scrollTo(index);
}
<|endoftext|>


<commit_before><commit_msg>Made audio sources "bigger"<commit_after><|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferScene/StandardOptions.h"

using namespace Gaffer;
using namespace GafferScene;

IE_CORE_DEFINERUNTIMETYPED( StandardOptions );

StandardOptions::StandardOptions( const std::string &name )
	:	Options( name )
{
	CompoundDataPlug *options = optionsPlug();

	// camera

	options->addOptionalMember( "render:camera", new IECore::StringData(), "renderCamera", Plug::Default, false );
	options->addOptionalMember( "render:resolution", new IECore::V2iData( Imath::V2i( 1024, 778 ) ), "renderResolution", Plug::Default, false );
	options->addOptionalMember( "render:pixelAspectRatio", new IECore::FloatData( 1.0f ), "pixelAspectRatio", Plug::Default, false );
	options->addOptionalMember( "render:resolutionMultiplier", new IECore::FloatData( 1.0f ), "resolutionMultiplier", Plug::Default, false );
	options->addOptionalMember( "render:cropWindow", new IECore::Box2fData( Imath::Box2f( Imath::V2f( 0 ), Imath::V2f( 1 ) ) ), "renderCropWindow", Plug::Default, false );

	options->addOptionalMember( "render:overscan", new IECore::BoolData( false ), "overscan", Plug::Default, false );
	options->addOptionalMember( "render:overscanTop", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanTop", false );
	options->addOptionalMember( "render:overscanBottom", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanBottom", false );
	options->addOptionalMember( "render:overscanLeft", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanLeft", false );
	options->addOptionalMember( "render:overscanRight", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanRight", false );

	// motion blur

	options->addOptionalMember( "render:cameraBlur", new IECore::BoolData( false ), "cameraBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:transformBlur", new IECore::BoolData( false ), "transformBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:deformationBlur", new IECore::BoolData( false ), "deformationBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:shutter", new IECore::V2fData( Imath::V2f( -0.25, 0.25 ) ), "shutter", Gaffer::Plug::Default, false );

}

StandardOptions::~StandardOptions()
{
}
<commit_msg>Added min/max limits to StandardOptions crop window plug.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "GafferScene/StandardOptions.h"

using namespace Gaffer;
using namespace GafferScene;

IE_CORE_DEFINERUNTIMETYPED( StandardOptions );

StandardOptions::StandardOptions( const std::string &name )
	:	Options( name )
{
	CompoundDataPlug *options = optionsPlug();

	// camera

	options->addOptionalMember( "render:camera", new IECore::StringData(), "renderCamera", Plug::Default, false );
	options->addOptionalMember( "render:resolution", new IECore::V2iData( Imath::V2i( 1024, 778 ) ), "renderResolution", Plug::Default, false );
	options->addOptionalMember( "render:pixelAspectRatio", new IECore::FloatData( 1.0f ), "pixelAspectRatio", Plug::Default, false );
	options->addOptionalMember( "render:resolutionMultiplier", new IECore::FloatData( 1.0f ), "resolutionMultiplier", Plug::Default, false );
	options->addOptionalMember( "render:cropWindow", new Box2fPlug( "value", Plug::In, Imath::Box2f( Imath::V2f( 0 ), Imath::V2f( 1 ) ), Imath::V2f( 0 ), Imath::V2f( 1 ) ), "renderCropWindow", false );

	options->addOptionalMember( "render:overscan", new IECore::BoolData( false ), "overscan", Plug::Default, false );
	options->addOptionalMember( "render:overscanTop", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanTop", false );
	options->addOptionalMember( "render:overscanBottom", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanBottom", false );
	options->addOptionalMember( "render:overscanLeft", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanLeft", false );
	options->addOptionalMember( "render:overscanRight", new FloatPlug( "value", Plug::In, 0.1f, 0.0f, 1.0f ), "overscanRight", false );

	// motion blur

	options->addOptionalMember( "render:cameraBlur", new IECore::BoolData( false ), "cameraBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:transformBlur", new IECore::BoolData( false ), "transformBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:deformationBlur", new IECore::BoolData( false ), "deformationBlur", Gaffer::Plug::Default, false );
	options->addOptionalMember( "render:shutter", new IECore::V2fData( Imath::V2f( -0.25, 0.25 ) ), "shutter", Gaffer::Plug::Default, false );

}

StandardOptions::~StandardOptions()
{
}
<|endoftext|>


<commit_before>#include "Genes/Pawn_Advancement_Gene.h"

#include <string>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Genes/Piece_Strength_Gene.h"
#include "Utility.h"

Pawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) :
    Gene(0.0),
    piece_strength_source(piece_strength_source_in),
    promoted_pawn_bonus(0.0)
{
}

void Pawn_Advancement_Gene::reset_properties() const
{
    reset_base_properties();
    properties["Promoted Pawn Bonus"] = promoted_pawn_bonus;
}

void Pawn_Advancement_Gene::load_properties()
{
    load_base_properties();
    promoted_pawn_bonus = properties["Promoted Pawn Bonus"];
}

double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
    double score = 0.0;
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
            {
                // 1 point per pawn + 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    if(board.get_game_record().size() < 2)
    {
        return score;
    }

    auto last_move_index = board.get_game_record().size() - (color == board.whose_turn() ? 2 : 1);
    auto last_move = board.get_game_record()[last_move_index];
    if(last_move.find('=') != std::string::npos)
    {
        auto piece_symbol = String::split(last_move, "=")[1][0]; // char
        score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol);
    }

    return score/(8.*7.); // normalize to 8 pawns just before promotion
}

Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
    return new Pawn_Advancement_Gene(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}

void Pawn_Advancement_Gene::mutate()
{
    Gene::mutate();
    promoted_pawn_bonus += Random::random_normal(1.0);
    promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0);
}

void Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg)
{
    piece_strength_source = psg;
}
<commit_msg>Make sure index for last game move is valid<commit_after>#include "Genes/Pawn_Advancement_Gene.h"

#include <string>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Genes/Piece_Strength_Gene.h"
#include "Utility.h"

Pawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) :
    Gene(0.0),
    piece_strength_source(piece_strength_source_in),
    promoted_pawn_bonus(0.0)
{
}

void Pawn_Advancement_Gene::reset_properties() const
{
    reset_base_properties();
    properties["Promoted Pawn Bonus"] = promoted_pawn_bonus;
}

void Pawn_Advancement_Gene::load_properties()
{
    load_base_properties();
    promoted_pawn_bonus = properties["Promoted Pawn Bonus"];
}

double Pawn_Advancement_Gene::score_board(const Board& board, Color perspective) const
{
    double score = 0.0;
    int home_rank = (perspective == WHITE ? 2 : 7);

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            auto piece = board.piece_on_square(file, rank);
            if(piece && piece->color() == perspective && toupper(piece->fen_symbol()) == 'P')
            {
                // 1 point per pawn + 1 point per move towards promotion
                score += std::abs(home_rank - rank);
            }
        }
    }

    if(board.get_game_record().size() < 2)
    {
        return score;
    }

    auto last_move_index = int(board.get_game_record().size()) - (perspective == board.whose_turn() ? 2 : 1);
    auto last_move = (last_move_index >= 0 ? board.get_game_record()[last_move_index] : std::string());
    if(last_move.find('=') != std::string::npos)
    {
        auto piece_symbol = String::split(last_move, "=")[1][0]; // char
        score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol);
    }

    return score/(8.*7.); // normalize to 8 pawns just before promotion
}

Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const
{
    return new Pawn_Advancement_Gene(*this);
}

std::string Pawn_Advancement_Gene::name() const
{
    return "Pawn Advancement Gene";
}

void Pawn_Advancement_Gene::mutate()
{
    Gene::mutate();
    promoted_pawn_bonus += Random::random_normal(1.0);
    promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0);
}

void Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg)
{
    piece_strength_source = psg;
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#include <SDL/SDL_mixer.h>

#include "main_game.h"
#include "game_state.h"
#include "render_world.h"
#include "defs.h"
#include "audio.h"
#include "texture.h"

using namespace std;

/*Our maze*/ //creates new instance
//Maze maze;

Maze maze;

/* For move function */
int turning_left_global;
int turning_right_global;
int moving_fowards_global;

/*Our player data structure - Where we are in the world */
int x_position = 0;
int y_position = 0;
int orientation;

/*Where we start*/
int start_x = 0;
int start_y = 0;
int end_x = 0;
int end_y = 3;

/*Music*/
Mix_Music *world_music;

/*Modifies the players position/orientation based
  on input variables such as moving_fowards_global*/
void move(){
  if(moving_fowards_global){
    if(orientation == NORTH){
      if(maze.value_at(x_position, y_position, NORTH) != 0){
	printf("No");
      }
      else{
	if(y_position < 2){
	y_position++;
	}

      }
    }
    if(orientation == SOUTH){
      if(maze.value_at(x_position, y_position, SOUTH) != 0){
	printf("No");
      }
      else{
	if(y_position > 0){
	y_position--;
	}
      }
    }

    if(orientation == EAST){
      if(maze.value_at(x_position, y_position, WEST) != 0){
	printf("No");
      }
      else{
	if(x_position > 0){
	x_position--;
	}
      }
    }

    if(orientation == WEST){
    if(maze.value_at(x_position, y_position, EAST) != 0){
	printf("No");
      }
      else{
	if(x_position < 2){
	x_position++;
	}
      }
    }
  }

 else if(turning_right_global){
    if(orientation == WEST){
      orientation = NORTH;
    }
    else{
      orientation++;
    }
  }
 else if(turning_left_global){
    if(orientation == NORTH){
      orientation = WEST ;
    }
    else{
      orientation--;
    }
  }
  if(orientation == SOUTH){
  printf("%d %d SOUTH\n", x_position, y_position);
  }
if(orientation == NORTH){
  printf("%d %d NORTH\n", x_position, y_position);
  }
if(orientation == EAST){
  printf("%d %d EAST\n", x_position, y_position);
  }
if(orientation == WEST){
  printf("%d %d WEST\n", x_position, y_position);
  }

  /*If these aren't reset the player races off at the speed of light*/
  moving_fowards_global = 0;
  turning_left_global = 0;
  turning_right_global = 0;
}

/*Called when a key is released*/
void inGameKeyboardUp(SDLKey key)
{

  if (key == SDLK_LEFT){
    turning_left_global = false;
  }
  else if(key == SDLK_RIGHT){
    turning_right_global = false;
  }

  else if(key == SDLK_UP){
    moving_fowards_global = false;
  }

}

/*Called when a key is held down*/
void inGameKeyboardDown(SDLKey key){
  if(key == SDLK_LEFT){
    turning_left_global = true;
  }

  else if(key == SDLK_UP){
    moving_fowards_global = true;
  }

  else if(key == SDLK_RIGHT){
    turning_right_global = true;
  }
}

/*Our main game function.. checks for input, moves and redraws the screen.

  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu */
void idle(void){

  if(turning_left_global == true || turning_right_global == true
     || moving_fowards_global == true){
    move();
  }

  if(x_position == end_x && y_position == end_y){

    printf("You win!\n");
    exit(0);
  }
  //glutPostRedisplay(); don't think there is a SDL equivalent of this
  // so taking it out.
}

/*Leslies code*/
static void initTextures(){
  wall_texture = genTexture("data/images/textures/wall.bmp");
  floor_texture = genTexture("data/images/textures/floor.bmp");
}

static void freeTextures(){
  glDeleteTextures( 1, &wall_texture);
  glDeleteTextures(1, &floor_texture);
}

static void initMusic(){
  world_music = loadAudioFile("data/audio/music/test.ogg");
  //might as well start it playing
  //if(music_on)
  playAudio(world_music,-1);//-1 loops forever
}

static void freeMusic(){
  unloadAudioFile(world_music);
}
//This code will need to be moved to main_game later.
/*Initialization of the game*/
int gameInit(){
  x_position = 0;
  y_position = 0;
  orientation = WEST;
  end_x = 9;
  end_y = 9;

  initTextures();
  initMusic();
  reshape(SCREEN_WIDTH,SCREEN_HEIGHT);
  return 0;
}

int gameDeInit(){
  if(isAudioPlaying())
    stopAllAudio();
  freeTextures();
  freeMusic();
  return 0;
}

<commit_msg>Small change<commit_after>#include <cstdio>
#include <cstdlib>
#include <string>
#include <cmath>
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#include <SDL/SDL_mixer.h>

#include "main_game.h"
#include "game_state.h"
#include "render_world.h"
#include "defs.h"
#include "audio.h"
#include "texture.h"

using namespace std;

/*Our maze*/ //creates new instance
//Maze maze;

Maze maze;

/* For move function */
int turning_left_global;
int turning_right_global;
int moving_fowards_global;

/*Our player data structure - Where we are in the world */
int x_position = 0;
int y_position = 0;
int orientation;

/*Where we start*/
int start_x = 0;
int start_y = 0;
int end_x = 0;
int end_y = 3;

/*Music*/
Mix_Music *world_music;

/*Modifies the players position/orientation based
  on input variables such as moving_fowards_global*/
void move(){
  if(moving_fowards_global){
    if(orientation == NORTH){
      if(maze.value_at(x_position, y_position, NORTH) != 0){
	printf("No");
      }
      else{
	if(y_position < 2){
	y_position++;
	}

      }
    }
    if(orientation == SOUTH){
      if(maze.value_at(x_position, y_position, SOUTH) != 0){
	printf("No");
      }
      else{
	if(y_position > 0){
	y_position--;
	}
      }
    }

    if(orientation == EAST){
      if(maze.value_at(x_position, y_position, WEST) != 0){
	printf("No");
      }
      else{
	if(x_position > 0){
	x_position--;
	}
      }
    }

    if(orientation == WEST){
    if(maze.value_at(x_position, y_position, EAST) != 0){
	printf("No");
      }
      else{
	if(x_position < 2){
	x_position++;
	}
      }
    }
  }

 else if(turning_right_global){
    if(orientation == WEST){
      orientation = NORTH;
    }
    else{
      orientation++;
    }
  }
 else if(turning_left_global){
    if(orientation == NORTH){
      orientation = WEST ;
    }
    else{
      orientation--;
    }
  }
  if(orientation == SOUTH){
  printf("%d %d SOUTH\n", x_position, y_position);
  }
if(orientation == NORTH){
  printf("%d %d NORTH\n", x_position, y_position);
  }
if(orientation == EAST){
  printf("%d %d EAST\n", x_position, y_position);
  }
if(orientation == WEST){
  printf("%d %d WEST\n", x_position, y_position);
  }

  /*If these aren't reset the player races off at the speed of light*/
  moving_fowards_global = 0;
  turning_left_global = 0;
  turning_right_global = 0;
}

/*Called when a key is released*/
void inGameKeyboardUp(SDLKey key)
{

  if (key == SDLK_LEFT){
    turning_left_global = false;
  }
  else if(key == SDLK_RIGHT){
    turning_right_global = false;
  }

  else if(key == SDLK_UP){
    moving_fowards_global = false;
  }

}

/*Called when a key is held down*/
void inGameKeyboardDown(SDLKey key){
  if(key == SDLK_LEFT){
    turning_left_global = true;
  }

  else if(key == SDLK_UP){
    moving_fowards_global = true;
  }

  else if(key == SDLK_RIGHT){
    turning_right_global = true;
  }
}

/*Our main game function.. checks for input, moves and redraws the screen.

  TODO: Needs to be changed to a timer function later so it dosen't hog 100%cpu */
void idle(void){

  if(turning_left_global == true || turning_right_global == true
     || moving_fowards_global == true){
    move();
  }

  if(x_position == end_x && y_position == end_y){

    printf("You win!\n");
    exit(0);
  }
  //glutPostRedisplay(); don't think there is a SDL equivalent of this
  // so taking it out.
}

/*Leslies code*/
static void initTextures(){
  wall_texture = genTexture("data/images/textures/wall.bmp");
  floor_texture = genTexture("data/images/textures/floor.bmp");
}

static void freeTextures(){
  glDeleteTextures( 1, &wall_texture);
  glDeleteTextures(1, &floor_texture);
}

static void initMusic(){
  world_music = loadAudioFile("data/audio/music/test.ogg");
  //might as well start it playing
  //if(music_on)
  playAudio(world_music,-1);//-1 loops forever
}

static void freeMusic(){
  unloadAudioFile(world_music);
}
//This code will need to be moved to main_game later.
/*Initialization of the game*/
int gameInit(){
  x_position = 0;
  y_position = 0;
  orientation = WEST;
  end_x = 3;
  end_y = 3;

  initTextures();
  initMusic();
  reshape(SCREEN_WIDTH,SCREEN_HEIGHT);
  return 0;
}

int gameDeInit(){
  if(isAudioPlaying())
    stopAllAudio();
  freeTextures();
  freeMusic();
  return 0;
}

<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include <boost/python.hpp>

#include "IECore/Data.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"

using namespace boost::python;

namespace IECore
{

void bindData()
{
	typedef class_< Data, boost::noncopyable, DataPtr, bases<Object> > DataPyClass;
	DataPyClass ("Data", "An abstract base class for data storage.", no_init)
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( Data )
	;

	INTRUSIVE_PTR_PATCH( Data, DataPyClass );

	implicitly_convertible<DataPtr, ObjectPtr>();

	/// \todo:
	/// add the conversion between a ptr and the const ptr for child elements
	implicitly_convertible<DataPtr, ConstDataPtr>();
}
}
<commit_msg>Removed todo which noone understands.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include <boost/python.hpp>

#include "IECore/Data.h"
#include "IECore/bindings/DataBinding.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"

using namespace boost::python;

namespace IECore
{

void bindData()
{
	typedef class_< Data, boost::noncopyable, DataPtr, bases<Object> > DataPyClass;
	DataPyClass ("Data", "An abstract base class for data storage.", no_init)
		.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( Data )
	;

	INTRUSIVE_PTR_PATCH( Data, DataPyClass );

	implicitly_convertible<DataPtr, ObjectPtr>();
	implicitly_convertible<DataPtr, ConstDataPtr>();
}
}
<|endoftext|>


<commit_before>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#include "PELConfig.h"

#include <boost/program_options.hpp>
#include <boost/tuple/tuple.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include <cstdlib>
#include "pel.h"
#include "logic/el_syntax.h"
#include "logic/folparser.h"
#include "logic/domain.h"
#include "log.h"
#include "logic/moves.h"
#include "inference/maxwalksat.h"
#include "logic/unit_prop.h"

int main(int argc, char* argv[]) {
    try {
        // Declare the supported options.
        po::options_description desc("Allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("version,v", "print version and exit")
            ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
            ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
            ("evalModel,e", "simply print the model weight of the facts file")
            ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
            ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
            ("output,o", po::value<std::string>(), "output model file")
            ("unitProp,u", "perform unit propagation only and exit")
            ("datafile,d", po::value<std::string>(), "log scores from maxwalksat to this file (csv form)")
        ;

        po::options_description hidden("Hidden options");
        hidden.add_options()
            ("facts-file", po::value<std::string>(), "facts file")
            ("formula-file", po::value<std::string>(), "formula file")
        ;
        po::positional_options_description p;
        p.add("facts-file", 1);
        p.add("formula-file", 1);

        po::options_description cmdline_options;
        cmdline_options.add(desc).add(hidden);

        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version")) {
            std::cout << "pel version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl;
            return EXIT_SUCCESS;
        }

        if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
            std::cout << "Usage: pel [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
            std::cout << desc << std::endl;
            return EXIT_FAILURE;
        }

        // setup our logging facilities
        FILE* debugFile = fopen("debug.log", "w");
        if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
        else FilePolicy::stream() = debugFile;
        FileLog::globalLogLevel() = LOG_DEBUG;

        LOG(LOG_INFO) << "Opened log file for new session";

        // make sure we can open the output model file, if specified
        FILE* outputFile = NULL;
        if (vm.count("output")) {
            outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
            if (!outputFile) {
                std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
                return EXIT_FAILURE;
            }
        }

        Domain d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
        if (vm.count("max") || vm.count("min")) {
            Interval maxInt = d.maxInterval();
            if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
            if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
            d.setMaxInterval(maxInt);
        }

        Model model = d.defaultModel();

        LOG_PRINT(LOG_INFO) << "model size: " << model.size();

        if (vm.count("evalModel")) {
            LOG(LOG_INFO) << "evaluating model...";
            unsigned long sum = 0;
            // evaluate the weight of each formula in the domain
            for(Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {
                ELSentence formula = *it;
                //SISet satisfied = d->satisfied(*(formula.sentence()), model);
                SISet satisfied = formula.sentence()->dSatisfied(model, d);
                unsigned long weight = d.score(formula, model);
                sum += weight;
                LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
                LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
                LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
            }
            LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
        } else {
            if (vm.count("unitProp")) {
                LOG_PRINT(LOG_INFO) << "running unit propagation...";
                QUnitsFormulasPair reducedforms = performUnitPropagation(d);
                // TODO: enforce the unit props better.  for now we are just adding
                // them to the formula set.
                d.clearFormulas();
                std::stringstream newForms;
                newForms << "Unit Clauses:\n";
                for (QCNFLiteralList::iterator it = reducedforms.first.begin(); it != reducedforms.first.end(); it++) {
                    ELSentence newS = convertFromQCNFClause(*it);
                    if (newS.hasInfWeight()) newS.setWeight(100);   // high enough for now?
                    newForms << "\t" << newS << "\n";
                    d.addFormula(newS);
                }
                newForms << "formulas:\n";
                for (QCNFClauseList::const_iterator it = reducedforms.second.begin(); it != reducedforms.second.end(); it++) {
                    ELSentence newS = convertFromQCNFClause(*it);
                    if (newS.hasInfWeight()) newS.setWeight(100);   // high enough for now?
                    newForms << "\t" << newS << "\n";
                    d.addFormula(newS);
                }
                LOG(LOG_INFO) << "unit prop completed.\n" << newForms.str();

            }
            double p = vm["prob"].as<double>();
            unsigned int iterations = vm["iterations"].as<unsigned int>();

            LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
            Model defModel = d.defaultModel();

            std::fstream datastream;
            if(vm.count("datafile")) {
                datastream.open(vm["datafile"].as<std::string>().c_str(), std::fstream::out);
                if (datastream.fail()) {
                    LOG_PRINT(LOG_ERROR) << "unable to open file \"" << vm["datafile"].as<std::string>() << "\" for data file storage.";
                }
            }
            Model maxModel(d.maxInterval());
            if (datastream.is_open() && datastream.good()) {
                maxModel = maxWalkSat(d, iterations, p, &defModel, &datastream);
            } else {
                maxModel = maxWalkSat(d, iterations, p, &defModel, 0);
            }

            if (datastream.is_open()) datastream.close();

            LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
            LOG_PRINT(LOG_INFO) << maxModel.toString();
            if (vm.count("output")) {
                // log it to the output file as well
                fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
                        vm["facts-file"].as<std::string>().c_str(),
                        vm["formula-file"].as<std::string>().c_str());
                std::string timeStr;
                {
                    time_t rawtime;
                    struct tm * timeinfo;
                    time (&rawtime);
                    timeinfo = localtime (&rawtime);
                    timeStr = asctime(timeinfo);
                }
                fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
                fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
                         iterations,
                        p);
                fputs(maxModel.toString().c_str(), outputFile);
            }
        }

        // Should be good and close files?
        return EXIT_SUCCESS;
    } catch (std::exception& e) {
        std::cerr << "Exception : " << e.what() << std::endl;
        return EXIT_FAILURE;
    } catch (...) {
        std::cerr << "Unknown exception occurred" << std::endl;
        return EXIT_FAILURE;
    }
}
<commit_msg>updated code to work with infinitely-weighted formulas<commit_after>//============================================================================
// Name        : pel.cpp
// Author      : Joe Selman
// Version     :

//============================================================================

#include "PELConfig.h"

#include <boost/program_options.hpp>
#include <boost/tuple/tuple.hpp>
namespace po = boost::program_options;
#include <boost/foreach.hpp>
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <utility>
#include <ctime>
#include <map>
#include <cstdlib>
#include "pel.h"
#include "logic/el_syntax.h"
#include "logic/folparser.h"
#include "logic/domain.h"
#include "log.h"
#include "logic/moves.h"
#include "inference/maxwalksat.h"
#include "logic/unit_prop.h"

int main(int argc, char* argv[]) {
    try {
        // Declare the supported options.
        po::options_description desc("Allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("version,v", "print version and exit")
            ("max", po::value<unsigned int>(), "maximum value an interval endpoint can take")
            ("min", po::value<unsigned int>(), "minimum value an interval endpoint can take")
            ("evalModel,e", "simply print the model weight of the facts file")
            ("prob,p", po::value<double>()->default_value(0.25), "probability of taking a random move")
            ("iterations,i", po::value<unsigned int>()->default_value(1000), "number of iterations before returning a model")
            ("output,o", po::value<std::string>(), "output model file")
            ("unitProp,u", "perform unit propagation only and exit")
            ("datafile,d", po::value<std::string>(), "log scores from maxwalksat to this file (csv form)")
        ;

        po::options_description hidden("Hidden options");
        hidden.add_options()
            ("facts-file", po::value<std::string>(), "facts file")
            ("formula-file", po::value<std::string>(), "formula file")
        ;
        po::positional_options_description p;
        p.add("facts-file", 1);
        p.add("formula-file", 1);

        po::options_description cmdline_options;
        cmdline_options.add(desc).add(hidden);

        po::variables_map vm;
        po::store(po::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
        po::notify(vm);

        if (vm.count("version")) {
            std::cout << "pel version " << PEL_VERSION_MAJOR << "." << PEL_VERSION_MINOR << std::endl;
            return EXIT_SUCCESS;
        }

        if (vm.count("help") || !vm.count("facts-file") || !vm.count("formula-file")) {
            std::cout << "Usage: pel [OPTION]... FACT-FILE FORMULA-FILE" << std::endl;
            std::cout << desc << std::endl;
            return EXIT_FAILURE;
        }

        // setup our logging facilities
        FILE* debugFile = fopen("debug.log", "w");
        if (!debugFile) std::cerr << "unable to open debug.log for logging - logging to stderr";
        else FilePolicy::stream() = debugFile;
        FileLog::globalLogLevel() = LOG_DEBUG;

        LOG(LOG_INFO) << "Opened log file for new session";

        // make sure we can open the output model file, if specified
        FILE* outputFile = NULL;
        if (vm.count("output")) {
            outputFile = fopen(vm["output"].as<std::string>().c_str(), "w");
            if (!outputFile) {
                std::cerr << "unable to open output file \"" << vm["output"].as<std::string>() << "\" for writing." << std::endl;
                return EXIT_FAILURE;
            }
        }

        Domain d = FOLParse::loadDomainFromFiles(vm["facts-file"].as<std::string>(), vm["formula-file"].as<std::string>());
        if (vm.count("max") || vm.count("min")) {
            Interval maxInt = d.maxInterval();
            if (vm.count("max")) maxInt.setFinish(vm["max"].as<unsigned int>());
            if (vm.count("min")) maxInt.setStart(vm["min"].as<unsigned int>());
            d.setMaxInterval(maxInt);
        }

        Model model = d.defaultModel();

        LOG_PRINT(LOG_INFO) << "model size: " << model.size();

        if (vm.count("evalModel")) {
            LOG(LOG_INFO) << "evaluating model...";
            unsigned long sum = 0;
            // evaluate the weight of each formula in the domain
            for(Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {
                ELSentence formula = *it;
                //SISet satisfied = d->satisfied(*(formula.sentence()), model);
                SISet satisfied = formula.sentence()->dSatisfied(model, d);
                unsigned long weight = d.score(formula, model);
                sum += weight;
                LOG_PRINT(LOG_INFO) << "formula: (" << formula.sentence()->toString() << ")";
                LOG_PRINT(LOG_INFO) << "\tsatisfied @ " << satisfied.toString();
                LOG_PRINT(LOG_INFO) << "\tscore contributed: " << weight;
            }
            LOG_PRINT(LOG_INFO) << "total score of model: " << sum;
        } else {
            if (vm.count("unitProp")) {
                LOG_PRINT(LOG_INFO) << "running unit propagation...";
                QUnitsFormulasPair reducedforms = performUnitPropagation(d);
                // TODO: enforce the unit props better.  for now we are just adding
                // them to the formula set.
                Domain newD;

                std::stringstream newForms;
                newForms << "Unit Clauses:\n";
                for (QCNFLiteralList::iterator it = reducedforms.first.begin(); it != reducedforms.first.end(); it++) {
                    ELSentence newS = convertFromQCNFClause(*it);
                    newS.setHasInfWeight(true);
                    newForms << "\t" << newS << "\n";
                    newD.addFact(newS);
                }
                newForms << "formulas:\n";
                for (QCNFClauseList::const_iterator it = reducedforms.second.begin(); it != reducedforms.second.end(); it++) {
                    ELSentence newS = convertFromQCNFClause(*it);
                    // should have inf weight
                    newS.setHasInfWeight(true);
                    newForms << "\t" << newS << "\n";
                    newD.addFormula(newS);
                }
                LOG(LOG_INFO) << "unit prop completed.\n" << newForms.str();

                // copy in all the unweighted formulas from the original d
                for (Domain::formula_const_iterator it = d.formulas_begin(); it != d.formulas_end(); it++) {
                    if (!it->hasInfWeight()) newD.addFormula(*it);
                }
                // replace the old form
                d = newD;

            }
            double p = vm["prob"].as<double>();
            unsigned int iterations = vm["iterations"].as<unsigned int>();

            // rewrite all our infinite weighted sentences
            LOG(LOG_INFO) << "rewriting infinite weights as pseudo-weights using factor of " << Domain::hardFormulaFactor;
            d = d.replaceInfForms();
            LOG(LOG_INFO) << "searching for a maximum-weight model, with p=" << p << " and iterations=" << iterations;
            Model defModel = d.defaultModel();

            std::fstream datastream;
            if(vm.count("datafile")) {
                datastream.open(vm["datafile"].as<std::string>().c_str(), std::fstream::out);
                if (datastream.fail()) {
                    LOG_PRINT(LOG_ERROR) << "unable to open file \"" << vm["datafile"].as<std::string>() << "\" for data file storage.";
                }
            }
            Model maxModel(d.maxInterval());
            if (datastream.is_open() && datastream.good()) {
                maxModel = maxWalkSat(d, iterations, p, &defModel, &datastream);
            } else {
                maxModel = maxWalkSat(d, iterations, p, &defModel, 0);
            }

            if (datastream.is_open()) datastream.close();

            LOG_PRINT(LOG_INFO) << "Best model found: " << std::endl;
            LOG_PRINT(LOG_INFO) << maxModel.toString();
            if (vm.count("output")) {
                // log it to the output file as well
                fprintf(outputFile, "# generated from fact file \"%s\" and formula file \"%s\"\n",
                        vm["facts-file"].as<std::string>().c_str(),
                        vm["formula-file"].as<std::string>().c_str());
                std::string timeStr;
                {
                    time_t rawtime;
                    struct tm * timeinfo;
                    time (&rawtime);
                    timeinfo = localtime (&rawtime);
                    timeStr = asctime(timeinfo);
                }
                fprintf(outputFile, "# generated on %s\n", timeStr.c_str());
                fprintf(outputFile, "# run with %d iterations and %g chance of choosing a random move\n",
                         iterations,
                        p);
                fputs(maxModel.toString().c_str(), outputFile);
            }
        }

        // Should be good and close files?
        return EXIT_SUCCESS;
    } catch (std::exception& e) {
        std::cerr << "Exception : " << e.what() << std::endl;
        return EXIT_FAILURE;
    } catch (...) {
        std::cerr << "Unknown exception occurred" << std::endl;
        return EXIT_FAILURE;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include "ImageServer.h"
#include <boost/filesystem.hpp>

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

namespace bfs = boost::filesystem;

// PManandhar note: not preferred, used for demo
// or short files
using namespace LMFocusStack;
using namespace std;

int options(char ** argv) {
  // Task 1.1: exit after help. Insert a flag after help, if that
  // flag exists then exit the program in main; return 0.
  // (Try to do this in the main function)

  const std::string help = "--help";
  if (argv[1] == help) {
    #include STR(L10N_LANG)
    std::wcout << rstr_help << std::endl;
    return -1;
  }
  else {
    return 0;
  }
}

int main(int argc, char ** argv) {

  if (options(argv) == -1){
    std::cout << "Program closing" << std::endl;

    return -1;

  }
  else {
    ImageServer server(argc, argv);

    return 0;
  }

}
<commit_msg>moved help feature to main<commit_after>#include <iostream>
#include "ImageServer.h"

#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)

// PManandhar note: not preferred, used for demo
// or short files
using namespace LMFocusStack;
using namespace std;

int options(char ** argv) {
  // Task 1.1: exit after help. Insert a flag after help, if that
  // flag exists then exit the program in main; return 0.
  // (Try to do this in the main function)

  const std::string help = "--help";
  if (argv[1] == help) {
    #include STR(L10N_LANG)
    std::wcout << rstr_help << std::endl;
    return -1;
  }
  else {
    return 0;
  }
}

int main(int argc, char ** argv) {

  if (argc >= 2 && options(argv) == -1){
    std::cout << "Program closing" << std::endl;

    return -1;

  }
  else {
    ImageServer server(argc, argv);

    return 0;
  }

}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
	#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
	#define XALAN_CPP_NAMESPACE_END  }
	#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
	#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
	#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

	namespace XALAN_CPP_NAMESPACE { }
	namespace xalanc = XALAN_CPP_NAMESPACE;
#else
	#define XALAN_CPP_NAMESPACE_BEGIN
	#define XALAN_CPP_NAMESPACE_END
	#define XALAN_CPP_NAMESPACE_USE
	#define XALAN_CPP_NAMESPACE_QUALIFIER
	#define XALAN_USING(NAMESPACE,NAME)
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
	#if !defined(XALAN_NO_STD_NAMESPACE)
		#define XALAN_NO_STD_NAMESPACE
	#endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
	#define XALAN_USING_STD(NAME)
	#define XALAN_STD_QUALIFIER
#else
	#define XALAN_USING_STD(NAME) using std :: NAME;
	#define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)

// Yuck!!!! Have to include this here because there's no way to handle
// the new namespace macros without it!
#include "xercesc/util/XercesDefs.hpp"

#if _XERCES_VERSION < 20200
	#define XERCES_CPP_NAMESPACE_QUALIFIER
	#define XERCES_CPP_NAMESPACE_BEGIN
	#define XERCES_CPP_NAMESPACE_END
#endif

#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)

#endif // __cplusplus

#endif	// PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Fixed macro.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(PLATFORMDEFINITIONS_HEADER_GUARD_1357924680)
#define PLATFORMDEFINITIONS_HEADER_GUARD_1357924680

#if defined(_MSC_VER)
#include "VCPPDefinitions.hpp"
#elif defined(__GNUC__)
#include "GCCDefinitions.hpp"
#elif defined(_AIX)
#include "AIXDefinitions.hpp"
#elif defined(__hpux)
#include "HPUXDefinitions.hpp"
#elif defined(SOLARIS)
#include "SolarisDefinitions.hpp"
#elif defined(OS390)
#include "OS390Definitions.hpp"
#elif defined(__DECCXX)
#include "TRU64Definitions.hpp"
#elif defined(__INTEL_COMPILER)
#include "IntelDefinitions.hpp"
#else
#error Unknown compiler!
#endif

#include "XalanVersion.hpp"

#if defined(__cplusplus)

// ---------------------------------------------------------------------------
// Define namespace symbols if the compiler supports it.
// ---------------------------------------------------------------------------
#if defined(XALAN_HAS_CPP_NAMESPACE)
	#define XALAN_CPP_NAMESPACE_BEGIN namespace XALAN_CPP_NAMESPACE {
	#define XALAN_CPP_NAMESPACE_END  }
	#define XALAN_CPP_NAMESPACE_USE using namespace XALAN_CPP_NAMESPACE;
	#define XALAN_CPP_NAMESPACE_QUALIFIER XALAN_CPP_NAMESPACE::
	#define XALAN_USING(NAMESPACE,NAME) using NAMESPACE :: NAME;
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) namespace NAMESPACE { class NAME; }
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) namespace NAMESPACE { struct NAME; }

	namespace XALAN_CPP_NAMESPACE { }
	namespace xalanc = XALAN_CPP_NAMESPACE;
#else
	#define XALAN_CPP_NAMESPACE_BEGIN
	#define XALAN_CPP_NAMESPACE_END
	#define XALAN_CPP_NAMESPACE_USE
	#define XALAN_CPP_NAMESPACE_QUALIFIER
	#define XALAN_USING(NAMESPACE,NAME)
	#define XALAN_DECLARE_CLASS(NAMESPACE,NAME) class NAME;
	#define XALAN_DECLARE_STRUCT(NAMESPACE,NAME) struct NAME;
	#if !defined(XALAN_NO_STD_NAMESPACE)
		#define XALAN_NO_STD_NAMESPACE
	#endif
#endif

#if defined(XALAN_NO_STD_NAMESPACE)
	#define XALAN_USING_STD(NAME)
	#define XALAN_STD_QUALIFIER
#else
	#define XALAN_USING_STD(NAME) using std :: NAME;
	#define XALAN_STD_QUALIFIER  std ::
#endif

#define XALAN_DECLARE_XALAN_CLASS(NAME) XALAN_DECLARE_CLASS(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XALAN_STRUCT(NAME) XALAN_DECLARE_STRUCT(XALAN_CPP_NAMESPACE, NAME)
#define XALAN_USING_XALAN(NAME) XALAN_USING(XALAN_CPP_NAMESPACE, NAME)

// Yuck!!!! Have to include this here because there's no way to handle
// the new namespace macros without it!
#include "xercesc/util/XercesDefs.hpp"

#if _XERCES_VERSION < 20200
	#define XERCES_CPP_NAMESPACE_QUALIFIER
	#define XERCES_CPP_NAMESPACE_BEGIN
	#define XERCES_CPP_NAMESPACE_END
#endif

#define XALAN_USING_XERCES(NAME) XALAN_USING(XERCES_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XERCES_CLASS(NAME) XALAN_DECLARE_CLASS(XERCES_CPP_NAMESPACE, NAME)
#define XALAN_DECLARE_XERCES_STRUCT(NAME) XALAN_DECLARE_STRUCT(XERCES_CPP_NAMESPACE, NAME)

#endif // __cplusplus

#endif	// PLATFORMDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Konsulko Group
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 */

#include <opencv2/core/cuda.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudafilters.hpp>
#include <opencv2/cudaimgproc.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <tclap/CmdLine.h>
#include <libconfig.h++>
#include <iostream>
#include <string>

#include "config.h"
#include "fps.h"

using namespace std;
using namespace cv;
using namespace libconfig;

int main(int argc, char* argv[])
{
	string config_file;
	bool display_intermediate;
	bool enable_cuda;
	bool enable_opencl;
	bool enable_display;
	bool write_output;
	bool verbose;

	// Parse command line options
	try {
		TCLAP::CmdLine cmd_line("Lane Departure Warning System", ' ', LDWS_VERSION);
		// FIXME CUDA and OpenCL should be mutually exclusive switches
		TCLAP::SwitchArg enable_cuda_switch("u","enable-cuda","Enable CUDA support", cmd_line, false);
		TCLAP::SwitchArg enable_opencl_switch("o","enable-opencl","Enable OpenCL support", cmd_line, false);
		TCLAP::SwitchArg disable_display_switch("d","disable-display","Disable video display", cmd_line, false);
		TCLAP::SwitchArg display_intermediate_switch("i","display-intermediate","Display intermediate processing steps", cmd_line, false);
		TCLAP::SwitchArg write_output_switch("w","write-video","Write video to a file", cmd_line, false);
		TCLAP::SwitchArg verbose_switch("v","verbose","Verbose messages", cmd_line, false);
		TCLAP::ValueArg<string> config_file_string("c","config-file","Configuration file name", false, "ldws.conf", "filename");
		cmd_line.add(config_file_string);
		cmd_line.parse(argc, argv);

		display_intermediate = display_intermediate_switch.getValue();
		enable_cuda = enable_cuda_switch.getValue();
		enable_opencl = enable_opencl_switch.getValue();
		enable_display = !disable_display_switch.getValue();
		write_output = write_output_switch.getValue();
		verbose = verbose_switch.getValue();
		config_file = config_file_string.getValue();
	} catch (TCLAP::ArgException &e) {
		std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}

	// Parse config file
	Config cfg;
	cfg.readFile(config_file.c_str());
	string video_file = cfg.lookup("video_file");
	int rx = cfg.lookup("region_of_interest.x");
	int ry = cfg.lookup("region_of_interest.y");
	int rw = cfg.lookup("region_of_interest.w");
	int rh = cfg.lookup("region_of_interest.h");

	// Open video input file/device
	VideoCapture capture(video_file);
	// If file open fails, try finding a camera indicated by an integer argument
	if (!capture.isOpened())
	{capture.open(atoi(video_file.c_str()));}

	// Toggle OpenCL on/off
	if (!enable_cuda)
		cv::ocl::setUseOpenCL(enable_opencl);

	string mode = "CPU";
	if (enable_cuda)
		mode = "CUDA";
	else if (enable_opencl)
		mode = "OpenCL";
	cout << "Mode: " << mode << endl;

	// Report video specs
	double width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
	double height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
	int ex = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));
	char fourcc[] = {(char)(ex & 0XFF),(char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24),0};
	Size frame_size(static_cast<int>(width), static_cast<int>(height));
	cout << "Video: frame size " << width << "x" << height << ", codec " << fourcc << endl;
	// FIXME Error check ROI settings here

	// Create output window
	string window_name = "Full Video";
	if (enable_display) {
		namedWindow(window_name, CV_WINDOW_KEEPRATIO);
	}

	// FIXME this should be conditional
	VideoWriter output_writer("ldws-full.avi", CV_FOURCC('P','I','M','1'), 30, frame_size, true);

	Mat frame, edge;
	cv::cuda::GpuMat gpu_frame, gpu_gray, gpu_edge;
	UMat u_frame, u_gray, u_edge;
	cv::Ptr<cv::cuda::Filter> blur = cv::cuda::createGaussianFilter(CV_8UC1, CV_8UC1, Size(5, 5), 1.5);
	cv::Ptr<cv::cuda::CannyEdgeDetector> canny = cv::cuda::createCannyEdgeDetector(1, 100, 3, false);

	frame_avg_init();

	while (true)
	{
		capture >> frame;
		if (frame.empty())
			break;

		// Display original frame
		if (display_intermediate) {
			namedWindow("Original Video", WINDOW_AUTOSIZE);
			imshow("Original Video", frame);
		}

		frame_begin();

		if (enable_cuda) {
			// CUDA
			gpu_frame.upload(frame);
			cv::cuda::GpuMat gpu_roi(gpu_frame, Rect(rx, ry, rw, rh));
			cv::cuda::cvtColor(gpu_roi, gpu_gray, CV_BGR2GRAY);
			blur->apply(gpu_gray, gpu_gray);
			canny->detect(gpu_gray, gpu_edge);
		} else {
			// TAPI
			frame.copyTo(u_frame);
			UMat u_roi(u_frame, Rect(rx, ry, rw, rh));
			cvtColor(u_roi, u_gray, CV_BGR2GRAY);
			GaussianBlur(u_gray, u_gray, Size(5, 5), 1.5);
			Canny(u_gray, u_edge, 1, 100);
		}

		// TODO Add line detection

		frame_end();

		// Display Canny image
		if (display_intermediate) {
			namedWindow("Edges");
			if (enable_cuda) {
				gpu_edge.download(edge);
				imshow("Edges", edge);
			} else {
				imshow("Edges", u_edge);
			}
		}

		// Display FPS
		putText(frame, "FPS: " + frame_fps_str(), Point(5,25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);

		// Display full image
		if (enable_display)
			imshow(window_name, frame);

		// Write frame to output file
		if (write_output)
			output_writer << frame;

		if (waitKey(1) == 27) break;
	}

	cout << "Average FPS: " << frame_fps_avg_str() << endl;
}

<commit_msg>Add probabilistic hough line detection.<commit_after>/*
 * Copyright 2016 Konsulko Group
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *     Unless required by applicable law or agreed to in writing, software
 *     distributed under the License is distributed on an "AS IS" BASIS,
 *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *     See the License for the specific language governing permissions and
 *     limitations under the License.
 */

#include <opencv2/core/cuda.hpp>
#include <opencv2/core/ocl.hpp>
#include <opencv2/cudaarithm.hpp>
#include <opencv2/cudafilters.hpp>
#include <opencv2/cudaimgproc.hpp>
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <tclap/CmdLine.h>
#include <libconfig.h++>
#include <iostream>
#include <string>

#include "config.h"
#include "fps.h"

using namespace std;
using namespace cv;
using namespace libconfig;

int main(int argc, char* argv[])
{
	string config_file;
	bool display_intermediate;
	bool enable_cuda;
	bool enable_opencl;
	bool enable_display;
	bool write_output;
	bool verbose;

	// Parse command line options
	try {
		TCLAP::CmdLine cmd_line("Lane Departure Warning System", ' ', LDWS_VERSION);
		// FIXME CUDA and OpenCL should be mutually exclusive switches
		TCLAP::SwitchArg enable_cuda_switch("u","enable-cuda","Enable CUDA support", cmd_line, false);
		TCLAP::SwitchArg enable_opencl_switch("o","enable-opencl","Enable OpenCL support", cmd_line, false);
		TCLAP::SwitchArg disable_display_switch("d","disable-display","Disable video display", cmd_line, false);
		TCLAP::SwitchArg display_intermediate_switch("i","display-intermediate","Display intermediate processing steps", cmd_line, false);
		TCLAP::SwitchArg write_output_switch("w","write-video","Write video to a file", cmd_line, false);
		TCLAP::SwitchArg verbose_switch("v","verbose","Verbose messages", cmd_line, false);
		TCLAP::ValueArg<string> config_file_string("c","config-file","Configuration file name", false, "ldws.conf", "filename");
		cmd_line.add(config_file_string);
		cmd_line.parse(argc, argv);

		display_intermediate = display_intermediate_switch.getValue();
		enable_cuda = enable_cuda_switch.getValue();
		enable_opencl = enable_opencl_switch.getValue();
		enable_display = !disable_display_switch.getValue();
		write_output = write_output_switch.getValue();
		verbose = verbose_switch.getValue();
		config_file = config_file_string.getValue();
	} catch (TCLAP::ArgException &e) {
		std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
	}

	// Parse config file
	Config cfg;
	cfg.readFile(config_file.c_str());
	string video_file = cfg.lookup("video_file");
	int rx = cfg.lookup("region_of_interest.x");
	int ry = cfg.lookup("region_of_interest.y");
	int rw = cfg.lookup("region_of_interest.w");
	int rh = cfg.lookup("region_of_interest.h");

	// Open video input file/device
	VideoCapture capture(video_file);
	// If file open fails, try finding a camera indicated by an integer argument
	if (!capture.isOpened())
	{capture.open(atoi(video_file.c_str()));}

	// Toggle OpenCL on/off
	if (!enable_cuda)
		cv::ocl::setUseOpenCL(enable_opencl);

	string mode = "CPU";
	if (enable_cuda)
		mode = "CUDA";
	else if (enable_opencl)
		mode = "OpenCL";
	cout << "Mode: " << mode << endl;

	// Report video specs
	double width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
	double height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
	int ex = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));
	char fourcc[] = {(char)(ex & 0XFF),(char)((ex & 0XFF00) >> 8),(char)((ex & 0XFF0000) >> 16),(char)((ex & 0XFF000000) >> 24),0};
	Size frame_size(static_cast<int>(width), static_cast<int>(height));
	cout << "Video: frame size " << width << "x" << height << ", codec " << fourcc << endl;
	// FIXME Error check ROI settings here

	// Create output window
	string window_name = "Full Video";
	if (enable_display) {
		namedWindow(window_name, CV_WINDOW_KEEPRATIO);
	}

	// FIXME this should be conditional
	VideoWriter output_writer("ldws-full.avi", CV_FOURCC('P','I','M','1'), 30, frame_size, true);

	Mat frame, edge;
	cv::cuda::GpuMat gpu_frame, gpu_gray, gpu_edge, gpu_lines;
	UMat u_frame, u_gray, u_edge;
	cv::Ptr<cv::cuda::Filter> blur = cv::cuda::createGaussianFilter(CV_8UC1, CV_8UC1, Size(5, 5), 1.5);
	cv::Ptr<cv::cuda::CannyEdgeDetector> canny = cv::cuda::createCannyEdgeDetector(1, 100, 3, false);
	double rho = 1;
	double theta = CV_PI/180;
	vector<Vec4i> lines;
	cv::Ptr<cuda::HoughSegmentDetector> hough = cuda::createHoughSegmentDetector(rho, theta, 50, 100);

	frame_avg_init();

	while (true)
	{
		capture >> frame;
		if (frame.empty())
			break;

		// Display original frame
		if (display_intermediate) {
			namedWindow("Original Video", WINDOW_AUTOSIZE);
			imshow("Original Video", frame);
		}

		frame_begin();

		if (enable_cuda) {
			// CUDA implementation
			gpu_frame.upload(frame);

			// Set ROI to reduce workload
			cv::cuda::GpuMat gpu_roi(gpu_frame, Rect(rx, ry, rw, rh));

			// Convert to grayscale and blur
			cv::cuda::cvtColor(gpu_roi, gpu_gray, CV_BGR2GRAY);
			blur->apply(gpu_gray, gpu_gray);

			// Canny edge detection
			canny->detect(gpu_gray, gpu_edge);

			// Probabilistic Hough line detection
			hough->detect(gpu_edge, gpu_lines);
			lines.resize(gpu_lines.cols);
			Mat temp(1, gpu_lines.cols, CV_32SC4, &lines[0]);
			gpu_lines.download(temp);
		} else {
			// TAPI implementation
			frame.copyTo(u_frame);

			// Set ROI to reduce workload
			UMat u_roi(u_frame, Rect(rx, ry, rw, rh));

			// Convert to grayscale and blur
			cvtColor(u_roi, u_gray, CV_BGR2GRAY);
			GaussianBlur(u_gray, u_gray, Size(5, 5), 1.5);

			// Canny edge detection
			Canny(u_gray, u_edge, 1, 100);

			// Probabilistic Hough line detection
			HoughLinesP(u_edge, lines, rho, theta, 50, 50, 100);
		}

		// TODO Add line filtering

		frame_end();

		// Display Canny image
		if (display_intermediate) {
			namedWindow("Edges");
			if (enable_cuda) {
				gpu_edge.download(edge);
				imshow("Edges", edge);
			} else {
				imshow("Edges", u_edge);
			}
		}

		// Display FPS
		putText(frame, "FPS: " + frame_fps_str(), Point(5,25), FONT_HERSHEY_SIMPLEX, 1., Scalar(255, 100, 0), 2);

		// Display full image
		if (enable_display)
			imshow(window_name, frame);

		// Write frame to output file
		if (write_output)
			output_writer << frame;

		if (waitKey(1) == 27) break;
	}

	cout << "Average FPS: " << frame_fps_avg_str() << endl;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include "emulator.h"
#include "device/display.h"
#include "shell/shell.h"

using namespace std;

//Emulator *emu;
//Display  *disp;
//Shell    *sh;
//extern char hankaku[4096];

void errExit(Emulator *emu){
	if(emu == nullptr) exit(-1);
	emu->memory.Dump("memdump.bin", 0x00, 1 * MB);
	exit(-1);
}

int main(int argc, char **argv){
try{
	Emulator *emu = new Emulator();
	Shell    *sh;

	emu = new Emulator();
	emu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);
	sh = new Shell(emu);

	// default script
	ifstream ifs;
	ifs.open(".emurc");
	sh->Exec(ifs);

	sh->SetDefaultStream();
	sh->sh_proc();

	delete emu;

}catch(string str){
	cout<<"error: "<<str<<endl;
	return -1;
}catch(const char *str){
	cout<<"error: "<<str<<endl;
	return -1;
}catch(...){
	cout<<"exception"<<endl;
	return -1;
}
	return 0;
}

//int main(int argc, char **argv){
int emu_proc(Emulator *emu){
	try{
		if(emu == nullptr) throw "emu_proc: emulator is null";
//		for(int i=0;i<4096;i++)
//			cout<<hankaku[i];
		//TODO parse args
//		if(argc < 2) return -1;

//		emu = new Emulator();
//		emu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);

//		sh  = new Shell(emu);
//		ifstream ifs;
//		ifs.open(".emurc");
//		sh->Exec(ifs);
//		sh->ChangeStream(ifs);
//		sh->sh_proc();
//		sh->SetDefaultStream();
//		sh->Start();

//		disp = new Display();
//		disp->Init();

//		emu->memory.MapMemory(disp->vram, 0xa0000, 0xffff);

//		emu->LoadBinary(argv[1], 0x7c00, 512); // IPLの読み込み(本来BIOSがやるべき)

		while(true){
			int bit = emu->GetBitMode();
			uint8_t code = emu->GetCode8(0);

			if(emu->IsHalt()){
				cerr<<"halt."<<endl;
				continue;
			}

//			cerr<<"EIP = "<<hex<<showbase<<emu->EIP;
//			cerr<<", code = "<<hex<<showbase<<(int)code<<endl;

			switch(bit){
			case 16:
				emu->insn16.Exec(emu, code);
				break;
			case 32:
				emu->insn32.Exec(emu, code);
				break;
			case 64:
				cout<<"64bit is not implemtented."<<endl;
				break;
			default:
				cout<<"bit mode error."<<endl;
				break;
			};
		}

		emu->memory.Dump("memdump.bin", 0x00, 1 * MB);

	}catch(Interrupt *i){	// 割り込み処理
		cerr<<"interrupt."<<endl;
	}catch(string str){
		cerr<<"error: "<<str<<endl;
//		errExit();
		return -1;
	}catch(const char *str){
		cerr<<"error: "<<str<<endl;
//		errExit();
		return -1;
	}catch(...){
		cerr<<"exception."<<endl;
		return -1;
	}
	return 0;
}

<commit_msg>comment out old emulator proc<commit_after>#include <iostream>
#include <string>
#include "emulator.h"
#include "device/display.h"
#include "shell/shell.h"

using namespace std;

//Emulator *emu;
//Display  *disp;
//Shell    *sh;
//extern char hankaku[4096];

void errExit(Emulator *emu){
	if(emu == nullptr) exit(-1);
	emu->memory.Dump("memdump.bin", 0x00, 1 * MB);
	exit(-1);
}

int main(int argc, char **argv){
try{
	Emulator *emu = new Emulator();
	Shell    *sh;

	emu = new Emulator();
	emu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);
	sh = new Shell(emu);

	// default script
	ifstream ifs;
	ifs.open(".emurc");
	sh->Exec(ifs);

	sh->SetDefaultStream();
	sh->sh_proc();

	delete emu;

}catch(string str){
	cout<<"error: "<<str<<endl;
	return -1;
}catch(const char *str){
	cout<<"error: "<<str<<endl;
	return -1;
}catch(...){
	cout<<"exception"<<endl;
	return -1;
}
	return 0;
}

/*

old emulator proc

//int main(int argc, char **argv){
int emu_proc(Emulator *emu){
	try{
		if(emu == nullptr) throw "emu_proc: emulator is null";
//		for(int i=0;i<4096;i++)
//			cout<<hankaku[i];
		//TODO parse args
//		if(argc < 2) return -1;

//		emu = new Emulator();
//		emu->Init(DEFAULT_MEMORY_SIZE, 0x7c00, 0x7c00);

//		sh  = new Shell(emu);
//		ifstream ifs;
//		ifs.open(".emurc");
//		sh->Exec(ifs);
//		sh->ChangeStream(ifs);
//		sh->sh_proc();
//		sh->SetDefaultStream();
//		sh->Start();

//		disp = new Display();
//		disp->Init();

//		emu->memory.MapMemory(disp->vram, 0xa0000, 0xffff);

//		emu->LoadBinary(argv[1], 0x7c00, 512); // IPLの読み込み(本来BIOSがやるべき)

		while(true){
			int bit = emu->GetBitMode();
			uint8_t code = emu->GetCode8(0);

			if(emu->IsHalt()){
				cerr<<"halt."<<endl;
				continue;
			}

//			cerr<<"EIP = "<<hex<<showbase<<emu->EIP;
//			cerr<<", code = "<<hex<<showbase<<(int)code<<endl;

			switch(bit){
			case 16:
				emu->insn16.Exec(emu, code);
				break;
			case 32:
				emu->insn32.Exec(emu, code);
				break;
			case 64:
				cout<<"64bit is not implemtented."<<endl;
				break;
			default:
				cout<<"bit mode error."<<endl;
				break;
			};
		}

		emu->memory.Dump("memdump.bin", 0x00, 1 * MB);

	}catch(Interrupt *i){	// 割り込み処理
		cerr<<"interrupt."<<endl;
	}catch(string str){
		cerr<<"error: "<<str<<endl;
//		errExit();
		return -1;
	}catch(const char *str){
		cerr<<"error: "<<str<<endl;
//		errExit();
		return -1;
	}catch(...){
		cerr<<"exception."<<endl;
		return -1;
	}
	return 0;
}

*/
<|endoftext|>