<commit_before>/*
 * File:     main.cpp
 * Project:  LinWarrior 3D
 * Home:     hackcraft.de
 *
 * Created on March 28, 2008, 21:25 PM (1999)
 */

// Startup code: Dispatching sub program startups.

#include <cstdlib>
#include <cstdio>

using namespace std;

#include "de/hackcraft/game/GameMain.h"

#include <de/hackcraft/util/HashMap.h>
#include <de/hackcraft/util/String.h>

void testHM1() {
    HashMap<Object*,Object*>* h = new HashMap<Object*,Object*>();

    Object a;
    Object b;
    h->put(&a, &b);
}

void testHM2() {
    HashMap<String*,String*>* h = new HashMap<String*,String*>();

    for (int i = 0; i <= ('z'-'a'); i++) {
        //std::cout << i << "\n";
        char x[] = { char('a' + i), '\0' };
        char y[] = { char('A' + i), '\0' };
        h->put(new String(x), new String(y));
    }
    for (int i = 0; i <= ('z'-'a'); i++) {
        char x[] = { char('a' + i), '\0' };
        String* y = h->get(new String(x));
        std::cout << y->c_str();
    }
}

void testHM() {
    //testHM1();
    testHM2();
}

static int test(int argc, char **args) {
    cout << "Arguments for test module:\n";
    for (int i = 0; i < argc; i++) {
        cout << args[i] << "\n";
    }
    testHM();
    return 0;
}

//#ifdef wonly_WIN32
//extern "C" int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow) {
//    int argc = 2;
//    char *args[] = {"Nothing", "Nothing", "Nothing"};
//#else
//#endif

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

    try {
        string subprogram = (argc >= 2) ? string(args[1]) : string("");

        if (subprogram == "game") {
            return (new GameMain())->run(argc-1, &args[1]);

        } else if (subprogram == "test") {
            return test(argc-1, &args[1]);

        } else {
            cout << "Please specify module to run: <program> <module> [parameters]\n";
            cout << "  game   Run game module\n";
            cout << "  test   Run test module\n";
            return 0;
        }

    } catch (char* s) {
        cout << "Fatal exception caught:\n" << s << endl;

    } catch (const char* s) {
        cout << "Fatal exception caught:\n" << s << endl;
    }
    return 0;
}
<commit_msg>Refactoring: Cleaning framework classes.<commit_after>/*
 * File:     main.cpp
 * Project:  LinWarrior 3D
 * Home:     hackcraft.de
 *
 * Created on March 28, 2008, 21:25 PM (1999)
 */

// Startup code: Dispatching sub program startups.

#include <cstdlib>
#include <cstdio>

using namespace std;

#include "de/hackcraft/game/GameMain.h"

#include <de/hackcraft/util/HashMap.h>
#include <de/hackcraft/lang/String.h>

void testHM1() {
    HashMap<Object*,Object*>* h = new HashMap<Object*,Object*>();

    Object a;
    Object b;
    h->put(&a, &b);
}

void testHM2() {
    HashMap<String*,String*>* h = new HashMap<String*,String*>();

    for (int i = 0; i <= ('z'-'a'); i++) {
        //std::cout << i << "\n";
        char x[] = { char('a' + i), '\0' };
        char y[] = { char('A' + i), '\0' };
        h->put(new String(x), new String(y));
    }
    for (int i = 0; i <= ('z'-'a'); i++) {
        char x[] = { char('a' + i), '\0' };
        String* y = h->get(new String(x));
        std::cout << y->c_str();
    }
}

void testHM() {
    //testHM1();
    testHM2();
}

static int test(int argc, char **args) {
    cout << "Arguments for test module:\n";
    for (int i = 0; i < argc; i++) {
        cout << args[i] << "\n";
    }
    testHM();
    return 0;
}

//#ifdef wonly_WIN32
//extern "C" int __stdcall WinMain(void* hInstance, void* hPrevInstance, char* lpCmdLine, int nCmdShow) {
//    int argc = 2;
//    char *args[] = {"Nothing", "Nothing", "Nothing"};
//#else
//#endif

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

    try {
        string subprogram = (argc >= 2) ? string(args[1]) : string("");

        if (subprogram == "game") {
            return (new GameMain())->run(argc-1, &args[1]);

        } else if (subprogram == "test") {
            return test(argc-1, &args[1]);

        } else {
            cout << "Please specify module to run: <program> <module> [parameters]\n";
            cout << "  game   Run game module\n";
            cout << "  test   Run test module\n";
            return 0;
        }

    } catch (char* s) {
        cout << "Fatal exception caught:\n" << s << endl;

    } catch (const char* s) {
        cout << "Fatal exception caught:\n" << s << endl;
    }
    return 0;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkTextProperty.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkTextProperty, "1.6");
vtkStandardNewMacro(vtkTextProperty);

//----------------------------------------------------------------------------
// Control wheter to globally force text antialiasing (ALL),
// disable antialiasing (NONE), allow antialising (SOME) depending on
// the per-object AntiAliasing attribute.

static int vtkTextPropertyGlobalAntiAliasing = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;

void vtkTextProperty::SetGlobalAntiAliasing(int val)
{
  if (val == vtkTextPropertyGlobalAntiAliasing)
    {
    return;
    }
  if (val < VTK_TEXT_GLOBAL_ANTIALIASING_SOME)
    {
    val = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
    }
  else if (val > VTK_TEXT_GLOBAL_ANTIALIASING_ALL)
    {
    val = VTK_TEXT_GLOBAL_ANTIALIASING_ALL;
    }

  vtkTextPropertyGlobalAntiAliasing = val;
}

int vtkTextProperty::GetGlobalAntiAliasing()
{
  return vtkTextPropertyGlobalAntiAliasing;
}

//----------------------------------------------------------------------------
// Creates a new text property with Font size 12, bold off, italic off,
// and Arial font

vtkTextProperty::vtkTextProperty()
{
  // TOFIX: the default text prop color is set to a special (-1, -1, -1) value
  // to maintain backward compatibility for a while. Text mapper classes will
  // use the Actor2D color instead of the text prop color if this value is
  // found (i.e. if the text prop color has not been set).

  this->Color[0] = -1.0;
  this->Color[1] = -1.0;
  this->Color[2] = -1.0;

  // TOFIX: same goes for opacity

  this->Opacity  = -1.0;

  this->FontFamily = VTK_ARIAL;
  this->FontSize = 12;

  this->Bold = 0;
  this->Italic = 0;
  this->Shadow = 0;
  this->AntiAliasing = 1;

  this->Justification = VTK_TEXT_LEFT;
  this->VerticalJustification = VTK_TEXT_BOTTOM;

  this->LineOffset = 0.0;
  this->LineSpacing = 1.0;

  this->FaceFileName = NULL;
}

//----------------------------------------------------------------------------
// Shallow copy of a text property.

void vtkTextProperty::ShallowCopy(vtkTextProperty *tprop)
{
  if (!tprop)
    {
    return;
    }

  this->SetColor(tprop->GetColor());
  this->SetOpacity(tprop->GetOpacity());

  this->SetFontFamily(tprop->GetFontFamily());
  this->SetFontSize(tprop->GetFontSize());

  this->SetBold(tprop->GetBold());
  this->SetItalic(tprop->GetItalic());
  this->SetShadow(tprop->GetShadow());
  this->SetAntiAliasing(tprop->GetAntiAliasing());

  this->SetJustification(tprop->GetJustification());
  this->SetVerticalJustification(tprop->GetVerticalJustification());

  this->SetLineOffset(tprop->GetLineOffset());
  this->SetLineSpacing(tprop->GetLineSpacing());

  this->SetFaceFileName(tprop->GetFaceFileName());
}

//----------------------------------------------------------------------------
vtkTextProperty::~vtkTextProperty()
{
  if (this->FaceFileName)
    {
    delete [] this->FaceFileName;
    this->FaceFileName = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkTextProperty::SetFaceFileName(const char *name)
{
  // Same name

  if (this->FaceFileName && name && (!strcmp(this->FaceFileName, name)))
    {
    return;
    }

  // Both empty ?

  if (!name && !this->FaceFileName)
    {
    return;
    }

  // Release old name

  if (this->FaceFileName)
    {
    delete [] this->FaceFileName;
    }

  // Copy

  if (name)
    {
    this->FaceFileName = new char[strlen(name) + 1];
    strcpy(this->FaceFileName, name);
    }
  else
    {
    this->FaceFileName = NULL;
    }

  this->Modified();
}

//----------------------------------------------------------------------------
void vtkTextProperty::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Color: (" << this->Color[0] << ", "
     << this->Color[1] << ", " << this->Color[2] << ")\n";

  os << indent << "Opacity: " << this->Opacity << "\n";

  os << indent << "FontFamily: " << this->GetFontFamilyAsString() << "\n";
  os << indent << "FontSize: " << this->FontSize << "\n";

  os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
  os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
  os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");

  os << indent << "Justification: "
     << this->GetJustificationAsString() << "\n";

  os << indent << "Vertical justification: "
     << this->GetVerticalJustificationAsString() << "\n";

  os << indent << "Line Offset: " << this->LineOffset << "\n";
  os << indent << "Line Spacing: " << this->LineSpacing << "\n";
  os << indent << "AntiAliasing: " << this->AntiAliasing << "\n";
  os << indent << "FaceFileName: " << this->FaceFileName << "\n";
}
<commit_msg>FIX: purify NPR<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTextProperty.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"

vtkCxxRevisionMacro(vtkTextProperty, "1.7");
vtkStandardNewMacro(vtkTextProperty);

//----------------------------------------------------------------------------
// Control wheter to globally force text antialiasing (ALL),
// disable antialiasing (NONE), allow antialising (SOME) depending on
// the per-object AntiAliasing attribute.

static int vtkTextPropertyGlobalAntiAliasing = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;

void vtkTextProperty::SetGlobalAntiAliasing(int val)
{
  if (val == vtkTextPropertyGlobalAntiAliasing)
    {
    return;
    }
  if (val < VTK_TEXT_GLOBAL_ANTIALIASING_SOME)
    {
    val = VTK_TEXT_GLOBAL_ANTIALIASING_SOME;
    }
  else if (val > VTK_TEXT_GLOBAL_ANTIALIASING_ALL)
    {
    val = VTK_TEXT_GLOBAL_ANTIALIASING_ALL;
    }

  vtkTextPropertyGlobalAntiAliasing = val;
}

int vtkTextProperty::GetGlobalAntiAliasing()
{
  return vtkTextPropertyGlobalAntiAliasing;
}

//----------------------------------------------------------------------------
// Creates a new text property with Font size 12, bold off, italic off,
// and Arial font

vtkTextProperty::vtkTextProperty()
{
  // TOFIX: the default text prop color is set to a special (-1, -1, -1) value
  // to maintain backward compatibility for a while. Text mapper classes will
  // use the Actor2D color instead of the text prop color if this value is
  // found (i.e. if the text prop color has not been set).

  this->Color[0] = -1.0;
  this->Color[1] = -1.0;
  this->Color[2] = -1.0;

  // TOFIX: same goes for opacity

  this->Opacity  = -1.0;

  this->FontFamily = VTK_ARIAL;
  this->FontSize = 12;

  this->Bold = 0;
  this->Italic = 0;
  this->Shadow = 0;
  this->AntiAliasing = 1;

  this->Justification = VTK_TEXT_LEFT;
  this->VerticalJustification = VTK_TEXT_BOTTOM;

  this->LineOffset = 0.0;
  this->LineSpacing = 1.0;

  this->FaceFileName = NULL;
}

//----------------------------------------------------------------------------
// Shallow copy of a text property.

void vtkTextProperty::ShallowCopy(vtkTextProperty *tprop)
{
  if (!tprop)
    {
    return;
    }

  this->SetColor(tprop->GetColor());
  this->SetOpacity(tprop->GetOpacity());

  this->SetFontFamily(tprop->GetFontFamily());
  this->SetFontSize(tprop->GetFontSize());

  this->SetBold(tprop->GetBold());
  this->SetItalic(tprop->GetItalic());
  this->SetShadow(tprop->GetShadow());
  this->SetAntiAliasing(tprop->GetAntiAliasing());

  this->SetJustification(tprop->GetJustification());
  this->SetVerticalJustification(tprop->GetVerticalJustification());

  this->SetLineOffset(tprop->GetLineOffset());
  this->SetLineSpacing(tprop->GetLineSpacing());

  this->SetFaceFileName(tprop->GetFaceFileName());
}

//----------------------------------------------------------------------------
vtkTextProperty::~vtkTextProperty()
{
  if (this->FaceFileName)
    {
    delete [] this->FaceFileName;
    this->FaceFileName = NULL;
    }
}

//----------------------------------------------------------------------------
void vtkTextProperty::SetFaceFileName(const char *name)
{
  // Same name

  if (this->FaceFileName && name && (!strcmp(this->FaceFileName, name)))
    {
    return;
    }

  // Both empty ?

  if (!name && !this->FaceFileName)
    {
    return;
    }

  // Release old name

  if (this->FaceFileName)
    {
    delete [] this->FaceFileName;
    }

  // Copy

  if (name)
    {
    this->FaceFileName = new char[strlen(name) + 1];
    strcpy(this->FaceFileName, name);
    }
  else
    {
    this->FaceFileName = NULL;
    }

  this->Modified();
}

//----------------------------------------------------------------------------
void vtkTextProperty::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Color: (" << this->Color[0] << ", "
     << this->Color[1] << ", " << this->Color[2] << ")\n";

  os << indent << "Opacity: " << this->Opacity << "\n";

  os << indent << "FontFamily: " << this->GetFontFamilyAsString() << "\n";
  os << indent << "FontSize: " << this->FontSize << "\n";

  os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n");
  os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n");
  os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n");

  os << indent << "Justification: "
     << this->GetJustificationAsString() << "\n";

  os << indent << "Vertical justification: "
     << this->GetVerticalJustificationAsString() << "\n";

  os << indent << "Line Offset: " << this->LineOffset << "\n";
  os << indent << "Line Spacing: " << this->LineSpacing << "\n";
  os << indent << "AntiAliasing: " << this->AntiAliasing << "\n";
  if (this->FaceFileName)
    {
    os << indent << "FaceFileName: " << this->FaceFileName << "\n";
    }
  else
    {
    os << indent << "FaceFileName: (none)\n";
    }
}
<|endoftext|>


<commit_before><commit_msg>stitching: fix l_gains data type from Eigen solver (float / double)<commit_after><|endoftext|>


<commit_before>#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"

FglTFImportOptions::FglTFImportOptions()
    : FilePathInOS(TEXT(""))
    , FilePathInEngine(TEXT(""))
    , MeshScaleRatio(1.0f)
    , bInvertNormal(false)
    , bImportMaterial(true)
    , bRecomputeNormals(true)
    , bRecomputeTangents(true)
{
    //
}

const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
<commit_msg>Set the default scale to 100<commit_after>#include "glTFForUE4EdPrivatePCH.h"
#include "glTFImportOptions.h"

FglTFImportOptions::FglTFImportOptions()
    : FilePathInOS(TEXT(""))
    , FilePathInEngine(TEXT(""))
    , MeshScaleRatio(100.0f)
    , bInvertNormal(false)
    , bImportMaterial(true)
    , bRecomputeNormals(true)
    , bRecomputeTangents(true)
{
    //
}

const FglTFImportOptions FglTFImportOptions::Default;
FglTFImportOptions FglTFImportOptions::Current;
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

//!    File   : RenderWindow.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : July 2008
//
//!    Copyright (C) 2008 SCI Institute

#include "RenderWindow.h"
#include "ImageVis3D.h"

#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>

RenderWindow::RenderWindow(MasterController& masterController, QString dataset, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
  QGLWidget(parent, glShareWidget, flags),
  m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
  m_MasterController(masterController),
  m_iTimeSliceMSecsActive(500),
  m_iTimeSliceMSecsInActive(100),
  m_strDataset(dataset),
  m_vWinDim(0,0),
  m_MainWindow((MainWindow*)parent)
{
  m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
  setWindowTitle(m_strID);

  m_Renderer->LoadDataset(m_strDataset.toStdString());

  this->setFocusPolicy(Qt::StrongFocus);
}

RenderWindow::~RenderWindow()
{
  Cleanup();
}

QSize RenderWindow::minimumSizeHint() const
{
  return QSize(50, 50);
}

QSize RenderWindow::sizeHint() const
{
  return QSize(400, 400);
}

void RenderWindow::initializeGL()
{
  static bool bFirstTime = true;
  if (bFirstTime) {
    int err = glewInit();
    if (err != GLEW_OK) {
      m_MasterController.DebugOut()->Error("RenderWindow::initializeGL", "Error initializing GLEW: %s",glewGetErrorString(err));
    } else {
      const GLubyte *vendor=glGetString(GL_VENDOR);
      const GLubyte *renderer=glGetString(GL_RENDERER);
      const GLubyte *version=glGetString(GL_VERSION);
      m_MasterController.DebugOut()->Message("RenderWindow::initializeGL", "Starting up GL! Running on a %s %s with OpenGL version %s",vendor, renderer, version);
    }

    bFirstTime = false;
  }

  if (m_Renderer != NULL) m_Renderer->Initialize();
}

void RenderWindow::paintGL()
{
  if (m_Renderer != NULL) {
    m_Renderer->Paint();
    if (isActiveWindow()) {
        m_MainWindow->SetRenderProgress(m_Renderer->GetFrameProgress(), m_Renderer->GetSubFrameProgress());
    }
  }
}

void RenderWindow::resizeGL(int width, int height)
{
  m_vWinDim = UINTVECTOR2((unsigned int)width, (unsigned int)height);
  if (m_Renderer != NULL) m_Renderer->Resize(UINTVECTOR2(width, height));
}

void RenderWindow::mousePressEvent(QMouseEvent *event)
{
  if (event->button() == Qt::RightButton) {
     // nothing todo yet
  }
  if (event->button() == Qt::LeftButton) {
    m_Renderer->Click(UINTVECTOR2(event->pos().x(), event->pos().y()));
  }
}

void RenderWindow::mouseReleaseEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    m_Renderer->Release(UINTVECTOR2(event->pos().x(), event->pos().y()));
  }
}

float scale(int max, float w) {
	if (w < 0) {
		return w-(((int)w/max)-1)*max;
	} else {
		return w-((int)w/max)*max;
	}
}

void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
  if (event->buttons() & Qt::LeftButton) {
    m_Renderer->Drag(UINTVECTOR2(event->x(), event->y()));
    updateGL();
  }
}

void RenderWindow::wheelEvent(QWheelEvent *event) {
  m_Renderer->Zoom(event->delta());
}

void RenderWindow::keyPressEvent ( QKeyEvent * event ) {
  QGLWidget::keyPressEvent(event);

  if (event->key() == Qt::Key_Space) {
    AbstrRenderer::EViewMode eMode = AbstrRenderer::EViewMode((int(m_Renderer->GetViewmode()) + 1) % int(AbstrRenderer::VM_INVALID));
    m_Renderer->SetViewmode(eMode);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }

}

void RenderWindow::ToggleRenderWindowView2x2() {
  if (m_Renderer != NULL) {
    m_Renderer->SetViewmode(AbstrRenderer::VM_TWOBYTWO);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }
}

void RenderWindow::ToggleRenderWindowViewSingle() {
  if (m_Renderer != NULL) {
    m_Renderer->SetViewmode(AbstrRenderer::VM_SINGLE);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }
}

void RenderWindow::Cleanup() {
  if (m_Renderer == NULL) return;

  makeCurrent();
  m_Renderer->Cleanup();
  m_MasterController.ReleaseVolumerenderer(m_Renderer);
  m_Renderer = NULL;
}

void RenderWindow::closeEvent(QCloseEvent *event) {
  QGLWidget::closeEvent(event);

  emit WindowClosing(this);
}

void RenderWindow::focusInEvent ( QFocusEvent * event ) {
  // call superclass method
  QGLWidget::focusInEvent(event);
  m_Renderer->SetTimeSlice(m_iTimeSliceMSecsActive);

  if (event->gotFocus()) {
    emit WindowActive(this);
  }
}

void RenderWindow::focusOutEvent ( QFocusEvent * event ) {
  // call superclass method
  QGLWidget::focusOutEvent(event);
  m_Renderer->SetTimeSlice(m_iTimeSliceMSecsInActive);

  if (!event->gotFocus()) {
    emit WindowInActive(this);
  }
}

void RenderWindow::CheckForRedraw() {
  if (m_Renderer->CheckForRedraw()) {
    makeCurrent();
    update();
  }
}

void RenderWindow::SetBlendPrecision(AbstrRenderer::EBlendPrecision eBlendPrecisionMode) {
  makeCurrent();
  m_Renderer->SetBlendPrecision(eBlendPrecisionMode);
}

void RenderWindow::SetPerfMeasures(unsigned int iMinFramerate, unsigned int iLODDelay, unsigned int iActiveTS, unsigned int iInactiveTS) {
  makeCurrent();
  m_iTimeSliceMSecsActive   = iActiveTS;
  m_iTimeSliceMSecsInActive = iInactiveTS;
  m_Renderer->SetPerfMeasures(iMinFramerate, iLODDelay);
}
<commit_msg>fixed warning on linux<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

//!    File   : RenderWindow.cpp
//!    Author : Jens Krueger
//!             SCI Institute
//!             University of Utah
//!    Date   : July 2008
//
//!    Copyright (C) 2008 SCI Institute

#include "RenderWindow.h"
#include "ImageVis3D.h"

#include <QtGui/QtGui>
#include <QtOpenGL/QtOpenGL>
#include <assert.h>

RenderWindow::RenderWindow(MasterController& masterController, QString dataset, unsigned int iCounter, QGLWidget* glShareWidget, QWidget* parent, Qt::WindowFlags flags) :
  QGLWidget(parent, glShareWidget, flags),
  m_MainWindow((MainWindow*)parent),
  m_Renderer((GPUSBVR*)masterController.RequestNewVolumerenderer(OPENGL_SBVR)),
  m_MasterController(masterController),
  m_iTimeSliceMSecsActive(500),
  m_iTimeSliceMSecsInActive(100),
  m_strDataset(dataset),
  m_vWinDim(0,0)
{
  m_strID = tr("[%1] %2").arg(iCounter).arg(m_strDataset);
  setWindowTitle(m_strID);

  m_Renderer->LoadDataset(m_strDataset.toStdString());

  this->setFocusPolicy(Qt::StrongFocus);
}

RenderWindow::~RenderWindow()
{
  Cleanup();
}

QSize RenderWindow::minimumSizeHint() const
{
  return QSize(50, 50);
}

QSize RenderWindow::sizeHint() const
{
  return QSize(400, 400);
}

void RenderWindow::initializeGL()
{
  static bool bFirstTime = true;
  if (bFirstTime) {
    int err = glewInit();
    if (err != GLEW_OK) {
      m_MasterController.DebugOut()->Error("RenderWindow::initializeGL", "Error initializing GLEW: %s",glewGetErrorString(err));
    } else {
      const GLubyte *vendor=glGetString(GL_VENDOR);
      const GLubyte *renderer=glGetString(GL_RENDERER);
      const GLubyte *version=glGetString(GL_VERSION);
      m_MasterController.DebugOut()->Message("RenderWindow::initializeGL", "Starting up GL! Running on a %s %s with OpenGL version %s",vendor, renderer, version);
    }

    bFirstTime = false;
  }

  if (m_Renderer != NULL) m_Renderer->Initialize();
}

void RenderWindow::paintGL()
{
  if (m_Renderer != NULL) {
    m_Renderer->Paint();
    if (isActiveWindow()) {
        m_MainWindow->SetRenderProgress(m_Renderer->GetFrameProgress(), m_Renderer->GetSubFrameProgress());
    }
  }
}

void RenderWindow::resizeGL(int width, int height)
{
  m_vWinDim = UINTVECTOR2((unsigned int)width, (unsigned int)height);
  if (m_Renderer != NULL) m_Renderer->Resize(UINTVECTOR2(width, height));
}

void RenderWindow::mousePressEvent(QMouseEvent *event)
{
  if (event->button() == Qt::RightButton) {
     // nothing todo yet
  }
  if (event->button() == Qt::LeftButton) {
    m_Renderer->Click(UINTVECTOR2(event->pos().x(), event->pos().y()));
  }
}

void RenderWindow::mouseReleaseEvent(QMouseEvent *event) {
  if (event->button() == Qt::LeftButton) {
    m_Renderer->Release(UINTVECTOR2(event->pos().x(), event->pos().y()));
  }
}

float scale(int max, float w) {
	if (w < 0) {
		return w-(((int)w/max)-1)*max;
	} else {
		return w-((int)w/max)*max;
	}
}

void RenderWindow::mouseMoveEvent(QMouseEvent *event)
{
  if (event->buttons() & Qt::LeftButton) {
    m_Renderer->Drag(UINTVECTOR2(event->x(), event->y()));
    updateGL();
  }
}

void RenderWindow::wheelEvent(QWheelEvent *event) {
  m_Renderer->Zoom(event->delta());
}

void RenderWindow::keyPressEvent ( QKeyEvent * event ) {
  QGLWidget::keyPressEvent(event);

  if (event->key() == Qt::Key_Space) {
    AbstrRenderer::EViewMode eMode = AbstrRenderer::EViewMode((int(m_Renderer->GetViewmode()) + 1) % int(AbstrRenderer::VM_INVALID));
    m_Renderer->SetViewmode(eMode);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }

}

void RenderWindow::ToggleRenderWindowView2x2() {
  if (m_Renderer != NULL) {
    m_Renderer->SetViewmode(AbstrRenderer::VM_TWOBYTWO);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }
}

void RenderWindow::ToggleRenderWindowViewSingle() {
  if (m_Renderer != NULL) {
    m_Renderer->SetViewmode(AbstrRenderer::VM_SINGLE);
    emit RenderWindowViewChanged(int(m_Renderer->GetViewmode()));
    updateGL();
  }
}

void RenderWindow::Cleanup() {
  if (m_Renderer == NULL) return;

  makeCurrent();
  m_Renderer->Cleanup();
  m_MasterController.ReleaseVolumerenderer(m_Renderer);
  m_Renderer = NULL;
}

void RenderWindow::closeEvent(QCloseEvent *event) {
  QGLWidget::closeEvent(event);

  emit WindowClosing(this);
}

void RenderWindow::focusInEvent ( QFocusEvent * event ) {
  // call superclass method
  QGLWidget::focusInEvent(event);
  m_Renderer->SetTimeSlice(m_iTimeSliceMSecsActive);

  if (event->gotFocus()) {
    emit WindowActive(this);
  }
}

void RenderWindow::focusOutEvent ( QFocusEvent * event ) {
  // call superclass method
  QGLWidget::focusOutEvent(event);
  m_Renderer->SetTimeSlice(m_iTimeSliceMSecsInActive);

  if (!event->gotFocus()) {
    emit WindowInActive(this);
  }
}

void RenderWindow::CheckForRedraw() {
  if (m_Renderer->CheckForRedraw()) {
    makeCurrent();
    update();
  }
}

void RenderWindow::SetBlendPrecision(AbstrRenderer::EBlendPrecision eBlendPrecisionMode) {
  makeCurrent();
  m_Renderer->SetBlendPrecision(eBlendPrecisionMode);
}

void RenderWindow::SetPerfMeasures(unsigned int iMinFramerate, unsigned int iLODDelay, unsigned int iActiveTS, unsigned int iInactiveTS) {
  makeCurrent();
  m_iTimeSliceMSecsActive   = iActiveTS;
  m_iTimeSliceMSecsInActive = iInactiveTS;
  m_Renderer->SetPerfMeasures(iMinFramerate, iLODDelay);
}
<|endoftext|>


<commit_before>//===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the mechanism to read an instruction from a bytecode
// stream.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//

#include "ReaderInternals.h"
#include "llvm/iTerminators.h"
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
using namespace llvm;

namespace {
  struct RawInst {       // The raw fields out of the bytecode stream...
    unsigned NumOperands;
    unsigned Opcode;
    unsigned Type;

    RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
            std::vector<unsigned> &Args);
  };
}

RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
                 std::vector<unsigned> &Args) {
  unsigned Op = read(Buf, EndBuf);

  // bits   Instruction format:        Common to all formats
  // --------------------------
  // 01-00: Opcode type, fixed to 1.
  // 07-02: Opcode
  Opcode    = (Op >> 2) & 63;
  Args.resize((Op >> 0) & 03);

  switch (Args.size()) {
  case 1:
    // bits   Instruction format:
    // --------------------------
    // 19-08: Resulting type plane
    // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
    //
    Type    = (Op >>  8) & 4095;
    Args[0] = (Op >> 20) & 4095;
    if (Args[0] == 4095)    // Handle special encoding for 0 operands...
      Args.resize(0);
    break;
  case 2:
    // bits   Instruction format:
    // --------------------------
    // 15-08: Resulting type plane
    // 23-16: Operand #1
    // 31-24: Operand #2
    //
    Type    = (Op >>  8) & 255;
    Args[0] = (Op >> 16) & 255;
    Args[1] = (Op >> 24) & 255;
    break;
  case 3:
    // bits   Instruction format:
    // --------------------------
    // 13-08: Resulting type plane
    // 19-14: Operand #1
    // 25-20: Operand #2
    // 31-26: Operand #3
    //
    Type    = (Op >>  8) & 63;
    Args[0] = (Op >> 14) & 63;
    Args[1] = (Op >> 20) & 63;
    Args[2] = (Op >> 26) & 63;
    break;
  case 0:
    Buf -= 4;  // Hrm, try this again...
    Opcode = read_vbr_uint(Buf, EndBuf);
    Opcode >>= 2;
    Type = read_vbr_uint(Buf, EndBuf);

    unsigned NumOperands = read_vbr_uint(Buf, EndBuf);
    Args.resize(NumOperands);

    if (NumOperands == 0)
      throw std::string("Zero-argument instruction found; this is invalid.");

    for (unsigned i = 0; i != NumOperands; ++i)
      Args[i] = read_vbr_uint(Buf, EndBuf);
    align32(Buf, EndBuf);
    break;
  }
}

void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
                                      const unsigned char *EndBuf,
                                      std::vector<unsigned> &Args,
                                      BasicBlock *BB) {
  Args.clear();
  RawInst RI(Buf, EndBuf, Args);
  const Type *InstTy = getType(RI.Type);

  Instruction *Result = 0;
  if (RI.Opcode >= Instruction::BinaryOpsBegin &&
      RI.Opcode <  Instruction::BinaryOpsEnd  && Args.size() == 2)
    Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
                                    getValue(RI.Type, Args[0]),
                                    getValue(RI.Type, Args[1]));

  switch (RI.Opcode) {
  default:
    if (Result == 0) throw std::string("Illegal instruction read!");
    break;
  case Instruction::VAArg:
    Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::VANext:
    Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::Cast:
    Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::Select:
    Result = new SelectInst(getValue(Type::BoolTyID, Args[0]),
                            getValue(RI.Type, Args[1]),
                            getValue(RI.Type, Args[2]));
    break;
  case Instruction::PHI: {
    if (Args.size() == 0 || (Args.size() & 1))
      throw std::string("Invalid phi node encountered!\n");

    PHINode *PN = new PHINode(InstTy);
    PN->op_reserve(Args.size());
    for (unsigned i = 0, e = Args.size(); i != e; i += 2)
      PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
    Result = PN;
    break;
  }

  case Instruction::Shl:
  case Instruction::Shr:
    Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
                           getValue(RI.Type, Args[0]),
                           getValue(Type::UByteTyID, Args[1]));
    break;
  case Instruction::Ret:
    if (Args.size() == 0)
      Result = new ReturnInst();
    else if (Args.size() == 1)
      Result = new ReturnInst(getValue(RI.Type, Args[0]));
    else
      throw std::string("Unrecognized instruction!");
    break;

  case Instruction::Br:
    if (Args.size() == 1)
      Result = new BranchInst(getBasicBlock(Args[0]));
    else if (Args.size() == 3)
      Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
                              getValue(Type::BoolTyID , Args[2]));
    else
      throw std::string("Invalid number of operands for a 'br' instruction!");
    break;
  case Instruction::Switch: {
    if (Args.size() & 1)
      throw std::string("Switch statement with odd number of arguments!");

    SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
                                   getBasicBlock(Args[1]));
    for (unsigned i = 2, e = Args.size(); i != e; i += 2)
      I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
                 getBasicBlock(Args[i+1]));
    Result = I;
    break;
  }

  case Instruction::Call: {
    if (Args.size() == 0)
      throw std::string("Invalid call instruction encountered!");

    Value *F = getValue(RI.Type, Args[0]);

    // Check to make sure we have a pointer to function type
    const PointerType *PTy = dyn_cast<PointerType>(F->getType());
    if (PTy == 0) throw std::string("Call to non function pointer value!");
    const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
    if (FTy == 0) throw std::string("Call to non function pointer value!");

    std::vector<Value *> Params;
    if (!FTy->isVarArg()) {
      FunctionType::param_iterator It = FTy->param_begin();

      for (unsigned i = 1, e = Args.size(); i != e; ++i) {
        if (It == FTy->param_end())
          throw std::string("Invalid call instruction!");
        Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
      }
      if (It != FTy->param_end())
        throw std::string("Invalid call instruction!");
    } else {
      Args.erase(Args.begin(), Args.begin()+1);

      unsigned FirstVariableOperand;
      if (Args.size() < FTy->getNumParams())
        throw std::string("Call instruction missing operands!");

      // Read all of the fixed arguments
      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
        Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Args[i]));

      FirstVariableOperand = FTy->getNumParams();

      if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
        throw std::string("Invalid call instruction!");

      for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
        Params.push_back(getValue(Args[i], Args[i+1]));
    }

    Result = new CallInst(F, Params);
    break;
  }
  case Instruction::Invoke: {
    if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
    Value *F = getValue(RI.Type, Args[0]);

    // Check to make sure we have a pointer to function type
    const PointerType *PTy = dyn_cast<PointerType>(F->getType());
    if (PTy == 0) throw std::string("Invoke to non function pointer value!");
    const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
    if (FTy == 0) throw std::string("Invoke to non function pointer value!");

    std::vector<Value *> Params;
    BasicBlock *Normal, *Except;

    if (!FTy->isVarArg()) {
      Normal = getBasicBlock(Args[1]);
      Except = getBasicBlock(Args[2]);

      FunctionType::param_iterator It = FTy->param_begin();
      for (unsigned i = 3, e = Args.size(); i != e; ++i) {
        if (It == FTy->param_end())
          throw std::string("Invalid invoke instruction!");
        Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
      }
      if (It != FTy->param_end())
        throw std::string("Invalid invoke instruction!");
    } else {
      Args.erase(Args.begin(), Args.begin()+1);

      Normal = getBasicBlock(Args[0]);
      Except = getBasicBlock(Args[1]);

      unsigned FirstVariableArgument = FTy->getNumParams()+2;
      for (unsigned i = 2; i != FirstVariableArgument; ++i)
        Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
                                  Args[i]));

      if (Args.size()-FirstVariableArgument & 1)  // Must be pairs of type/value
        throw std::string("Invalid invoke instruction!");

      for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
        Params.push_back(getValue(Args[i], Args[i+1]));
    }

    Result = new InvokeInst(F, Normal, Except, Params);
    break;
  }
  case Instruction::Malloc:
    if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid malloc instruction!");

    Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
                            Args.size() ? getValue(Type::UIntTyID,
                                                   Args[0]) : 0);
    break;

  case Instruction::Alloca:
    if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid alloca instruction!");

    Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
                            Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
    break;
  case Instruction::Free:
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid free instruction!");
    Result = new FreeInst(getValue(RI.Type, Args[0]));
    break;
  case Instruction::GetElementPtr: {
    if (Args.size() == 0 || !isa<PointerType>(InstTy))
      throw std::string("Invalid getelementptr instruction!");

    std::vector<Value*> Idx;

    const Type *NextTy = InstTy;
    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
      const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
      if (!TopTy) throw std::string("Invalid getelementptr instruction!");

      unsigned ValIdx = Args[i];
      unsigned IdxTy;
      if (!hasRestrictedGEPTypes) {
        // Struct indices are always uints, sequential type indices can be any
        // of the 32 or 64-bit integer types.  The actual choice of type is
        // encoded in the low two bits of the slot number.
        if (isa<StructType>(TopTy))
          IdxTy = Type::UIntTyID;
        else {
          switch (ValIdx & 3) {
          default:
          case 0: IdxTy = Type::UIntTyID; break;
          case 1: IdxTy = Type::IntTyID; break;
          case 2: IdxTy = Type::ULongTyID; break;
          case 3: IdxTy = Type::LongTyID; break;
          }
          ValIdx >>= 2;
        }
      } else {
        IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
      }

      Idx.push_back(getValue(IdxTy, ValIdx));

      // Convert ubyte struct indices into uint struct indices.
      if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
        if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
          Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);

      NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
    }

    Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
    break;
  }

  case 62:   // volatile load
  case Instruction::Load:
    if (Args.size() != 1 || !isa<PointerType>(InstTy))
      throw std::string("Invalid load instruction!");
    Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
    break;

  case 63:   // volatile store
  case Instruction::Store: {
    if (!isa<PointerType>(InstTy) || Args.size() != 2)
      throw std::string("Invalid store instruction!");

    Value *Ptr = getValue(RI.Type, Args[1]);
    const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
    Result = new StoreInst(getValue(getTypeSlot(ValTy), Args[0]), Ptr,
                           RI.Opcode == 63);
    break;
  }
  case Instruction::Unwind:
    if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
    Result = new UnwindInst();
    break;
  }  // end switch(RI.Opcode)

  unsigned TypeSlot;
  if (Result->getType() == InstTy)
    TypeSlot = RI.Type;
  else
    TypeSlot = getTypeSlot(Result->getType());

  insertValue(Result, TypeSlot, Values);
  BB->getInstList().push_back(Result);
  BCR_TRACE(4, *Result);
}
<commit_msg>Squelch compile-time warning (profile build).<commit_after>//===- ReadInst.cpp - Code to read an instruction from bytecode -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the mechanism to read an instruction from a bytecode
// stream.
//
// Note that this library should be as fast as possible, reentrant, and
// threadsafe!!
//
//===----------------------------------------------------------------------===//

#include "ReaderInternals.h"
#include "llvm/iTerminators.h"
#include "llvm/iMemory.h"
#include "llvm/iPHINode.h"
#include "llvm/iOther.h"
#include "llvm/Module.h"
using namespace llvm;

namespace {
  struct RawInst {       // The raw fields out of the bytecode stream...
    unsigned NumOperands;
    unsigned Opcode;
    unsigned Type;

    RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
            std::vector<unsigned> &Args);
  };
}

RawInst::RawInst(const unsigned char *&Buf, const unsigned char *EndBuf,
                 std::vector<unsigned> &Args) {
  unsigned Op = read(Buf, EndBuf);

  // bits   Instruction format:        Common to all formats
  // --------------------------
  // 01-00: Opcode type, fixed to 1.
  // 07-02: Opcode
  Opcode    = (Op >> 2) & 63;
  Args.resize((Op >> 0) & 03);

  switch (Args.size()) {
  case 1:
    // bits   Instruction format:
    // --------------------------
    // 19-08: Resulting type plane
    // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
    //
    Type    = (Op >>  8) & 4095;
    Args[0] = (Op >> 20) & 4095;
    if (Args[0] == 4095)    // Handle special encoding for 0 operands...
      Args.resize(0);
    break;
  case 2:
    // bits   Instruction format:
    // --------------------------
    // 15-08: Resulting type plane
    // 23-16: Operand #1
    // 31-24: Operand #2
    //
    Type    = (Op >>  8) & 255;
    Args[0] = (Op >> 16) & 255;
    Args[1] = (Op >> 24) & 255;
    break;
  case 3:
    // bits   Instruction format:
    // --------------------------
    // 13-08: Resulting type plane
    // 19-14: Operand #1
    // 25-20: Operand #2
    // 31-26: Operand #3
    //
    Type    = (Op >>  8) & 63;
    Args[0] = (Op >> 14) & 63;
    Args[1] = (Op >> 20) & 63;
    Args[2] = (Op >> 26) & 63;
    break;
  case 0:
    Buf -= 4;  // Hrm, try this again...
    Opcode = read_vbr_uint(Buf, EndBuf);
    Opcode >>= 2;
    Type = read_vbr_uint(Buf, EndBuf);

    unsigned NumOperands = read_vbr_uint(Buf, EndBuf);
    Args.resize(NumOperands);

    if (NumOperands == 0)
      throw std::string("Zero-argument instruction found; this is invalid.");

    for (unsigned i = 0; i != NumOperands; ++i)
      Args[i] = read_vbr_uint(Buf, EndBuf);
    align32(Buf, EndBuf);
    break;
  }
}

void BytecodeParser::ParseInstruction(const unsigned char *&Buf,
                                      const unsigned char *EndBuf,
                                      std::vector<unsigned> &Args,
                                      BasicBlock *BB) {
  Args.clear();
  RawInst RI(Buf, EndBuf, Args);
  const Type *InstTy = getType(RI.Type);

  Instruction *Result = 0;
  if (RI.Opcode >= Instruction::BinaryOpsBegin &&
      RI.Opcode <  Instruction::BinaryOpsEnd  && Args.size() == 2)
    Result = BinaryOperator::create((Instruction::BinaryOps)RI.Opcode,
                                    getValue(RI.Type, Args[0]),
                                    getValue(RI.Type, Args[1]));

  switch (RI.Opcode) {
  default:
    if (Result == 0) throw std::string("Illegal instruction read!");
    break;
  case Instruction::VAArg:
    Result = new VAArgInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::VANext:
    Result = new VANextInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::Cast:
    Result = new CastInst(getValue(RI.Type, Args[0]), getType(Args[1]));
    break;
  case Instruction::Select:
    Result = new SelectInst(getValue(Type::BoolTyID, Args[0]),
                            getValue(RI.Type, Args[1]),
                            getValue(RI.Type, Args[2]));
    break;
  case Instruction::PHI: {
    if (Args.size() == 0 || (Args.size() & 1))
      throw std::string("Invalid phi node encountered!\n");

    PHINode *PN = new PHINode(InstTy);
    PN->op_reserve(Args.size());
    for (unsigned i = 0, e = Args.size(); i != e; i += 2)
      PN->addIncoming(getValue(RI.Type, Args[i]), getBasicBlock(Args[i+1]));
    Result = PN;
    break;
  }

  case Instruction::Shl:
  case Instruction::Shr:
    Result = new ShiftInst((Instruction::OtherOps)RI.Opcode,
                           getValue(RI.Type, Args[0]),
                           getValue(Type::UByteTyID, Args[1]));
    break;
  case Instruction::Ret:
    if (Args.size() == 0)
      Result = new ReturnInst();
    else if (Args.size() == 1)
      Result = new ReturnInst(getValue(RI.Type, Args[0]));
    else
      throw std::string("Unrecognized instruction!");
    break;

  case Instruction::Br:
    if (Args.size() == 1)
      Result = new BranchInst(getBasicBlock(Args[0]));
    else if (Args.size() == 3)
      Result = new BranchInst(getBasicBlock(Args[0]), getBasicBlock(Args[1]),
                              getValue(Type::BoolTyID , Args[2]));
    else
      throw std::string("Invalid number of operands for a 'br' instruction!");
    break;
  case Instruction::Switch: {
    if (Args.size() & 1)
      throw std::string("Switch statement with odd number of arguments!");

    SwitchInst *I = new SwitchInst(getValue(RI.Type, Args[0]),
                                   getBasicBlock(Args[1]));
    for (unsigned i = 2, e = Args.size(); i != e; i += 2)
      I->addCase(cast<Constant>(getValue(RI.Type, Args[i])),
                 getBasicBlock(Args[i+1]));
    Result = I;
    break;
  }

  case Instruction::Call: {
    if (Args.size() == 0)
      throw std::string("Invalid call instruction encountered!");

    Value *F = getValue(RI.Type, Args[0]);

    // Check to make sure we have a pointer to function type
    const PointerType *PTy = dyn_cast<PointerType>(F->getType());
    if (PTy == 0) throw std::string("Call to non function pointer value!");
    const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
    if (FTy == 0) throw std::string("Call to non function pointer value!");

    std::vector<Value *> Params;
    if (!FTy->isVarArg()) {
      FunctionType::param_iterator It = FTy->param_begin();

      for (unsigned i = 1, e = Args.size(); i != e; ++i) {
        if (It == FTy->param_end())
          throw std::string("Invalid call instruction!");
        Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
      }
      if (It != FTy->param_end())
        throw std::string("Invalid call instruction!");
    } else {
      Args.erase(Args.begin(), Args.begin()+1);

      unsigned FirstVariableOperand;
      if (Args.size() < FTy->getNumParams())
        throw std::string("Call instruction missing operands!");

      // Read all of the fixed arguments
      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
        Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Args[i]));

      FirstVariableOperand = FTy->getNumParams();

      if ((Args.size()-FirstVariableOperand) & 1) // Must be pairs of type/value
        throw std::string("Invalid call instruction!");

      for (unsigned i = FirstVariableOperand, e = Args.size(); i != e; i += 2)
        Params.push_back(getValue(Args[i], Args[i+1]));
    }

    Result = new CallInst(F, Params);
    break;
  }
  case Instruction::Invoke: {
    if (Args.size() < 3) throw std::string("Invalid invoke instruction!");
    Value *F = getValue(RI.Type, Args[0]);

    // Check to make sure we have a pointer to function type
    const PointerType *PTy = dyn_cast<PointerType>(F->getType());
    if (PTy == 0) throw std::string("Invoke to non function pointer value!");
    const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
    if (FTy == 0) throw std::string("Invoke to non function pointer value!");

    std::vector<Value *> Params;
    BasicBlock *Normal, *Except;

    if (!FTy->isVarArg()) {
      Normal = getBasicBlock(Args[1]);
      Except = getBasicBlock(Args[2]);

      FunctionType::param_iterator It = FTy->param_begin();
      for (unsigned i = 3, e = Args.size(); i != e; ++i) {
        if (It == FTy->param_end())
          throw std::string("Invalid invoke instruction!");
        Params.push_back(getValue(getTypeSlot(*It++), Args[i]));
      }
      if (It != FTy->param_end())
        throw std::string("Invalid invoke instruction!");
    } else {
      Args.erase(Args.begin(), Args.begin()+1);

      Normal = getBasicBlock(Args[0]);
      Except = getBasicBlock(Args[1]);

      unsigned FirstVariableArgument = FTy->getNumParams()+2;
      for (unsigned i = 2; i != FirstVariableArgument; ++i)
        Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
                                  Args[i]));

      if (Args.size()-FirstVariableArgument & 1)  // Must be pairs of type/value
        throw std::string("Invalid invoke instruction!");

      for (unsigned i = FirstVariableArgument; i < Args.size(); i += 2)
        Params.push_back(getValue(Args[i], Args[i+1]));
    }

    Result = new InvokeInst(F, Normal, Except, Params);
    break;
  }
  case Instruction::Malloc:
    if (Args.size() > 2) throw std::string("Invalid malloc instruction!");
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid malloc instruction!");

    Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
                            Args.size() ? getValue(Type::UIntTyID,
                                                   Args[0]) : 0);
    break;

  case Instruction::Alloca:
    if (Args.size() > 2) throw std::string("Invalid alloca instruction!");
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid alloca instruction!");

    Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
                            Args.size() ? getValue(Type::UIntTyID, Args[0]) :0);
    break;
  case Instruction::Free:
    if (!isa<PointerType>(InstTy))
      throw std::string("Invalid free instruction!");
    Result = new FreeInst(getValue(RI.Type, Args[0]));
    break;
  case Instruction::GetElementPtr: {
    if (Args.size() == 0 || !isa<PointerType>(InstTy))
      throw std::string("Invalid getelementptr instruction!");

    std::vector<Value*> Idx;

    const Type *NextTy = InstTy;
    for (unsigned i = 1, e = Args.size(); i != e; ++i) {
      const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
      if (!TopTy) throw std::string("Invalid getelementptr instruction!");

      unsigned ValIdx = Args[i];
      unsigned IdxTy = 0;
      if (!hasRestrictedGEPTypes) {
        // Struct indices are always uints, sequential type indices can be any
        // of the 32 or 64-bit integer types.  The actual choice of type is
        // encoded in the low two bits of the slot number.
        if (isa<StructType>(TopTy))
          IdxTy = Type::UIntTyID;
        else {
          switch (ValIdx & 3) {
          default:
          case 0: IdxTy = Type::UIntTyID; break;
          case 1: IdxTy = Type::IntTyID; break;
          case 2: IdxTy = Type::ULongTyID; break;
          case 3: IdxTy = Type::LongTyID; break;
          }
          ValIdx >>= 2;
        }
      } else {
        IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
      }

      Idx.push_back(getValue(IdxTy, ValIdx));

      // Convert ubyte struct indices into uint struct indices.
      if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
        if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
          Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);

      NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
    }

    Result = new GetElementPtrInst(getValue(RI.Type, Args[0]), Idx);
    break;
  }

  case 62:   // volatile load
  case Instruction::Load:
    if (Args.size() != 1 || !isa<PointerType>(InstTy))
      throw std::string("Invalid load instruction!");
    Result = new LoadInst(getValue(RI.Type, Args[0]), "", RI.Opcode == 62);
    break;

  case 63:   // volatile store
  case Instruction::Store: {
    if (!isa<PointerType>(InstTy) || Args.size() != 2)
      throw std::string("Invalid store instruction!");

    Value *Ptr = getValue(RI.Type, Args[1]);
    const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
    Result = new StoreInst(getValue(getTypeSlot(ValTy), Args[0]), Ptr,
                           RI.Opcode == 63);
    break;
  }
  case Instruction::Unwind:
    if (Args.size() != 0) throw std::string("Invalid unwind instruction!");
    Result = new UnwindInst();
    break;
  }  // end switch(RI.Opcode)

  unsigned TypeSlot;
  if (Result->getType() == InstTy)
    TypeSlot = RI.Type;
  else
    TypeSlot = getTypeSlot(Result->getType());

  insertValue(Result, TypeSlot, Values);
  BB->getInstList().push_back(Result);
  BCR_TRACE(4, *Result);
}
<|endoftext|>


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

#include "LedControllerRequest.h"
#include "GeneratedTypes.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>

int main(int argc, const char **argv)
{
  LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestS2H);

  printf("Starting LED test\n");

  FILE *pipe = popen("ifconfig eth0", "r");
  char buf[256];
  // read the first line and discard it
  fgets(buf, sizeof(buf), pipe);
  // read the second line
  fgets(buf, sizeof(buf), pipe);
  printf("address line: %s", buf);
  // done with the pipe, close it
  fclose(pipe);
  int addr[5];
  memset(addr, 0, sizeof(addr));
  int status = sscanf(buf, "          inet addr:%d.%d.%d.%d", &addr[0], &addr[1], &addr[2], &addr[3]);
  printf("eth0 addr %d.%d.%d.%d\n", addr[0], addr[1], addr[2], addr[3]);

  sleep(2);

  portalExec_start();

#ifdef BSIM
  // BSIM does not run very many cycles per second
  int blinkinterval = 10;
#else
  int blinkinterval = 100000000; // 100MHz cycles
#endif
  int sleepinterval = 1; // seconds
  for (int i = 0; i < 20; i++) {
    printf("led value %x\n", addr[i % 5]);
    device->setLeds(addr[i % 5], blinkinterval);
    sleep(sleepinterval);
  }
  printf("Done.\n");
}
<commit_msg>fix compiler warnings<commit_after>/* Copyright (c) 2014 Quanta Research Cambridge, Inc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include "LedControllerRequest.h"
#include "GeneratedTypes.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>

int main(int argc, const char **argv)
{
  LedControllerRequestProxy *device = new LedControllerRequestProxy(IfcNames_LedControllerRequestS2H);

  printf("Starting LED test\n");

  FILE *pipe = popen("ifconfig eth0", "r");
  char buf[256];
  // read the first line and discard it
  char *line = fgets(buf, sizeof(buf), pipe);
  // read the second line
  line = fgets(buf, sizeof(buf), pipe);
  printf("address line: %s", line);
  // done with the pipe, close it
  fclose(pipe);
  int addr[5];
  memset(addr, 0, sizeof(addr));
  int status = sscanf(buf, "          inet addr:%d.%d.%d.%d", &addr[0], &addr[1], &addr[2], &addr[3]);
  printf("eth0 addr %d.%d.%d.%d\n", addr[0], addr[1], addr[2], addr[3]);

  sleep(2);

  portalExec_start();

#ifdef BSIM
  // BSIM does not run very many cycles per second
  int blinkinterval = 10;
#else
  int blinkinterval = 100000000; // 100MHz cycles
#endif
  int sleepinterval = 1; // seconds
  for (int i = 0; i < 20; i++) {
    printf("led value %x\n", addr[i % 5]);
    device->setLeds(addr[i % 5], blinkinterval);
    sleep(sleepinterval);
  }
  printf("Done.\n");
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PolarLabelPositionHelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 01:49:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"

// header for class Vector2D
#ifndef _VECTOR2D_HXX
#include <tools/vector2d.hxx>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

PolarLabelPositionHelper::PolarLabelPositionHelper(
                    PolarPlottingPositionHelper* pPosHelper
                    , sal_Int32 nDimensionCount
                    , const uno::Reference< drawing::XShapes >& xLogicTarget
                    , ShapeFactory* pShapeFactory )
                    : LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
                    , m_pPosHelper(pPosHelper)
{
}

PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignment(
        LabelAlignment& rAlignment, bool bOutsidePosition
        , double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis
        , double fLogicInnerRadius, double fLogicOuterRadius
        , double fLogicZ) const
{
    double fWidthAngleDegree = m_pPosHelper->getWidthAngleDegree( fStartLogicValueOnAngleAxis, fEndLogicValueOnAngleAxis );
    double fStartAngleDegree = m_pPosHelper->transformToAngleDegree( fStartLogicValueOnAngleAxis );
    double fAngleDegree = fStartAngleDegree + fWidthAngleDegree/2.0;
    double fAnglePi     = fAngleDegree*F_PI/180.0;

    double fInnerRadius = m_pPosHelper->transformToRadius(fLogicInnerRadius);
    double fOuterRadius = m_pPosHelper->transformToRadius(fLogicOuterRadius);

    double fRadius = 0.0;
    if( bOutsidePosition ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
    {
        fRadius = fOuterRadius;
        if(3!=m_nDimensionCount)
            fRadius += 0.1*fOuterRadius;
    }
    else
        fRadius = fInnerRadius + (fOuterRadius-fInnerRadius)/2.0 ;

    if(3==m_nDimensionCount)
        fAnglePi *= -1.0;
    drawing::Position3D aLogicPos(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ+0.5);
    awt::Point aRet( this->transformLogicToScreenPosition( aLogicPos ) );

    if(3==m_nDimensionCount)
    {
        //check wether the upper or the downer edge is more distant from the center
        //take the farest point to put the label to
        drawing::Position3D aLogicPos2(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5);
        drawing::Position3D aLogicCenter(0,0,fLogicZ);

        awt::Point aP0( this->transformLogicToScreenPosition(
                        drawing::Position3D(0,0,fLogicZ) ) );
        awt::Point aP1(aRet);
        awt::Point aP2( this->transformLogicToScreenPosition(
                        drawing::Position3D(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5) ) );

        Vector2D aV0( aP0.X, aP0.Y );
        Vector2D aV1( aP1.X, aP1.Y );
        Vector2D aV2( aP2.X, aP2.Y );

        double fL1 = (aV1-aV0).GetLength();
        double fL2 = (aV2-aV0).GetLength();

        if(fL2>fL1)
            aRet = aP2;

        //calculate new angle for alignment
        double fDX = aRet.X-aP0.X;
        double fDY = aRet.Y-aP0.Y;
        fDY*=-1.0;//drawing layer has inverse y values
        if( fDX != 0.0 )
        {
            fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
            if(fDX<0.0)
                fAngleDegree+=180.0;
        }
        else
        {
            if(fDY>0.0)
                fAngleDegree = 90.0;
            else
                fAngleDegree = 270.0;
        }
    }
    //------------------------------
    //set LabelAlignment
    if( bOutsidePosition )
    {
        while(fAngleDegree>360.0)
            fAngleDegree-=360.0;
        while(fAngleDegree<0.0)
            fAngleDegree+=360.0;

        if(fAngleDegree==0.0)
            rAlignment = LABEL_ALIGN_CENTER;
        else if(fAngleDegree<=22.5)
            rAlignment = LABEL_ALIGN_RIGHT;
        else if(fAngleDegree<67.5)
            rAlignment = LABEL_ALIGN_RIGHT_TOP;
        else if(fAngleDegree<112.5)
            rAlignment = LABEL_ALIGN_TOP;
        else if(fAngleDegree<=157.5)
            rAlignment = LABEL_ALIGN_LEFT_TOP;
        else if(fAngleDegree<=202.5)
            rAlignment = LABEL_ALIGN_LEFT;
        else if(fAngleDegree<247.5)
            rAlignment = LABEL_ALIGN_LEFT_BOTTOM;
        else if(fAngleDegree<292.5)
            rAlignment = LABEL_ALIGN_BOTTOM;
        else if(fAngleDegree<337.5)
            rAlignment = LABEL_ALIGN_RIGHT_BOTTOM;
        else
            rAlignment = LABEL_ALIGN_RIGHT;
    }
    else
    {
        rAlignment = LABEL_ALIGN_CENTER;
    }
    return aRet;
}

//.............................................................................
} //namespace chart
//.............................................................................
<commit_msg>INTEGRATION: CWS pchfix02 (1.3.80); FILE MERGED 2006/09/01 17:19:01 kaib 1.3.80.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PolarLabelPositionHelper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:37:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"

#include "PolarLabelPositionHelper.hxx"
#include "PlottingPositionHelper.hxx"
#include "CommonConverters.hxx"

// header for class Vector2D
#ifndef _VECTOR2D_HXX
#include <tools/vector2d.hxx>
#endif

//.............................................................................
namespace chart
{
//.............................................................................
using namespace ::com::sun::star;
using namespace ::com::sun::star::chart2;

PolarLabelPositionHelper::PolarLabelPositionHelper(
                    PolarPlottingPositionHelper* pPosHelper
                    , sal_Int32 nDimensionCount
                    , const uno::Reference< drawing::XShapes >& xLogicTarget
                    , ShapeFactory* pShapeFactory )
                    : LabelPositionHelper( pPosHelper, nDimensionCount, xLogicTarget, pShapeFactory )
                    , m_pPosHelper(pPosHelper)
{
}

PolarLabelPositionHelper::~PolarLabelPositionHelper()
{
}

awt::Point PolarLabelPositionHelper::getLabelScreenPositionAndAlignment(
        LabelAlignment& rAlignment, bool bOutsidePosition
        , double fStartLogicValueOnAngleAxis, double fEndLogicValueOnAngleAxis
        , double fLogicInnerRadius, double fLogicOuterRadius
        , double fLogicZ) const
{
    double fWidthAngleDegree = m_pPosHelper->getWidthAngleDegree( fStartLogicValueOnAngleAxis, fEndLogicValueOnAngleAxis );
    double fStartAngleDegree = m_pPosHelper->transformToAngleDegree( fStartLogicValueOnAngleAxis );
    double fAngleDegree = fStartAngleDegree + fWidthAngleDegree/2.0;
    double fAnglePi     = fAngleDegree*F_PI/180.0;

    double fInnerRadius = m_pPosHelper->transformToRadius(fLogicInnerRadius);
    double fOuterRadius = m_pPosHelper->transformToRadius(fLogicOuterRadius);

    double fRadius = 0.0;
    if( bOutsidePosition ) //e.g. for pure pie chart(one ring only) or for angle axis of polyar coordinate system
    {
        fRadius = fOuterRadius;
        if(3!=m_nDimensionCount)
            fRadius += 0.1*fOuterRadius;
    }
    else
        fRadius = fInnerRadius + (fOuterRadius-fInnerRadius)/2.0 ;

    if(3==m_nDimensionCount)
        fAnglePi *= -1.0;
    drawing::Position3D aLogicPos(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ+0.5);
    awt::Point aRet( this->transformLogicToScreenPosition( aLogicPos ) );

    if(3==m_nDimensionCount)
    {
        //check wether the upper or the downer edge is more distant from the center
        //take the farest point to put the label to
        drawing::Position3D aLogicPos2(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5);
        drawing::Position3D aLogicCenter(0,0,fLogicZ);

        awt::Point aP0( this->transformLogicToScreenPosition(
                        drawing::Position3D(0,0,fLogicZ) ) );
        awt::Point aP1(aRet);
        awt::Point aP2( this->transformLogicToScreenPosition(
                        drawing::Position3D(fRadius*cos(fAnglePi),fRadius*sin(fAnglePi),fLogicZ-0.5) ) );

        Vector2D aV0( aP0.X, aP0.Y );
        Vector2D aV1( aP1.X, aP1.Y );
        Vector2D aV2( aP2.X, aP2.Y );

        double fL1 = (aV1-aV0).GetLength();
        double fL2 = (aV2-aV0).GetLength();

        if(fL2>fL1)
            aRet = aP2;

        //calculate new angle for alignment
        double fDX = aRet.X-aP0.X;
        double fDY = aRet.Y-aP0.Y;
        fDY*=-1.0;//drawing layer has inverse y values
        if( fDX != 0.0 )
        {
            fAngleDegree = atan(fDY/fDX)*180.0/F_PI;
            if(fDX<0.0)
                fAngleDegree+=180.0;
        }
        else
        {
            if(fDY>0.0)
                fAngleDegree = 90.0;
            else
                fAngleDegree = 270.0;
        }
    }
    //------------------------------
    //set LabelAlignment
    if( bOutsidePosition )
    {
        while(fAngleDegree>360.0)
            fAngleDegree-=360.0;
        while(fAngleDegree<0.0)
            fAngleDegree+=360.0;

        if(fAngleDegree==0.0)
            rAlignment = LABEL_ALIGN_CENTER;
        else if(fAngleDegree<=22.5)
            rAlignment = LABEL_ALIGN_RIGHT;
        else if(fAngleDegree<67.5)
            rAlignment = LABEL_ALIGN_RIGHT_TOP;
        else if(fAngleDegree<112.5)
            rAlignment = LABEL_ALIGN_TOP;
        else if(fAngleDegree<=157.5)
            rAlignment = LABEL_ALIGN_LEFT_TOP;
        else if(fAngleDegree<=202.5)
            rAlignment = LABEL_ALIGN_LEFT;
        else if(fAngleDegree<247.5)
            rAlignment = LABEL_ALIGN_LEFT_BOTTOM;
        else if(fAngleDegree<292.5)
            rAlignment = LABEL_ALIGN_BOTTOM;
        else if(fAngleDegree<337.5)
            rAlignment = LABEL_ALIGN_RIGHT_BOTTOM;
        else
            rAlignment = LABEL_ALIGN_RIGHT;
    }
    else
    {
        rAlignment = LABEL_ALIGN_CENTER;
    }
    return aRet;
}

//.............................................................................
} //namespace chart
//.............................................................................
<|endoftext|>


<commit_before>#include <map>
#include "test.h"

bool integrity_test(int *unsorted, int *sorted, unsigned int len)
{
	return false;
}

bool sort_test(int *arr, unsigned int len)
{
	for (unsigned int i = 0; i < len - 1; i++)
	{
		if (arr[i] > arr[i + 1])
			return false;
	}

	return true;
}<commit_msg>Implemented integrity test.<commit_after>#include <unordered_map>
#include "test.h"

bool integrity_test(int *unsorted, int *sorted, unsigned int len)
{
	std::unordered_map<unsigned int, int> counts;
	for (unsigned int i = 0; i < len; i++)
	{
		counts[unsorted[i]]++;
		counts[sorted[i]]--;
	}

	for each (auto count in counts)
	{
		if (count.second != 0)
			return false;
	}

	return true;
}

bool sort_test(int *arr, unsigned int len)
{
	for (unsigned int i = 0; i < len - 1; i++)
	{
		if (arr[i] > arr[i + 1])
			return false;
	}

	return true;
}<|endoftext|>


<commit_before>/// @brief computes scales for

#include <boost/foreach.hpp>
#include <boost/range/irange.hpp>

#include <cmath>

namespace core { namespace cordic {
    // n is number of iterations in CORDIC algorithm
    template<size_t n, typename fp>
    double lut<n, fp>::compute_circular_scale(size_t n)
    {
        double scale(1.0);

        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
        {
            scale *= std::sqrt(1 + std::powl(2.0, -2.0 * i));
        }

        return scale;
    }

    template<size_t n, typename fp>
    lut<n, fp> lut<n, fp>::build_circular_scales_lut()
    {
        base_class scales;

        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
        {
            scales[i] = std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
        }

        return this_class(scales);
    }
}}
<commit_msg>circular_scales.inl: refactoring<commit_after>/// @brief computes scales for CORDIC-rotations in case of circular coordiantes

namespace core { namespace cordic {
    template<size_t n, typename fp>
    double lut<n, fp>::circular_scale(size_t n)
    {
        double scale(1.0);

        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
        {
            scale *= std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
        }

        return scale;
    }

    template<size_t n, typename fp>
    lut<n, fp> lut<n, fp>::circular_scales()
    {
        base_class scales;

        BOOST_FOREACH(size_t i, boost::irange<size_t>(0, n, 1))
        {
            scales[i] = std::sqrt(1.0 + std::powl(2.0, -2.0 * i));
        }

        return this_class(scales);
    }
}}
<|endoftext|>


<commit_before>#ifndef VFRAME_NO_3D
#include "V3DScene.h"
#include "V3DObject.h"
#include "V3DBatchModelGroup.h"
#include "V3DShader.h"
#include "V3DCamera.h"
#include <cstring>

V3DScene::V3DScene(float x, float y, unsigned int width, unsigned int height, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
	renderTex.create(width, height, settings);
	Sprite->Position = sf::Vector2f(x, y);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

V3DScene::V3DScene(sf::Vector2f position, sf::Vector2u size, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
	renderTex.create(size.x, size.y, settings);
	Sprite->Position = position;
	Sprite->Size = sf::Vector2f(size);
}

void V3DScene::SetActive(bool value)
{
	renderTex.setActive(value);
}

void V3DScene::PushGLStates()
{
	renderTex.pushGLStates();
}

void V3DScene::PopGLStates()
{
	renderTex.popGLStates();
}

void V3DScene::ResetGLStates()
{
	renderTex.resetGLStates();
}

#include "V3DModel.h"
void V3DScene::Destroy()
{
	VSUPERCLASS::Destroy();

	renderTex.resetGLStates();
	renderTex.setActive(false);

	if (V3DModel::DefaultTexture)
	{
		glDeleteTextures(1, &V3DModel::DefaultTexture);
		V3DModel::DefaultTexture = 0;
	}
}

void V3DScene::Resize(int width, int height)
{
	postProcessTex.create(width, height);
	renderTex.create(width, height, contextSettings);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

void V3DScene::Update(float dt)
{
	VSUPERCLASS::Update(dt);
}

void V3DScene::RenderGroup(VGroup* group)
{
	for (int i = 0; i < group->Length(); i++)
	{
		V3DObject* base = dynamic_cast<V3DObject*>(group->GetGroupItem(i));

		if (base != nullptr)
		{
			base->UpdateShader(Shader.get(), Camera[CurrentCamera].get());
			if (Camera[CurrentCamera]->BoxInView(base->Position, base->GetMinimum(), base->GetMaximum()) && base->exists && base->visible)
			{
				base->Draw(renderTex); //If Renderable 3D Object
			}
		}
		else
		{
			V3DBatchModelGroup* batchGroup = dynamic_cast<V3DBatchModelGroup*>(group->GetGroupItem(i));

			if (batchGroup != nullptr)
			{
				batchGroup->UpdateShader(Camera[CurrentCamera].get(), Shader.get()); //If RenderBatch Group
				batchGroup->Draw(renderTex);
			}
			else
			{
				VGroup* childGroup = dynamic_cast<VGroup*>(group->GetGroupItem(i));
				if (childGroup != nullptr)
				{
					RenderGroup(childGroup); //If regular group.
				}
				else
				{
					group->GetGroupItem(i)->Draw(renderTex); //If nothing else, just draw it.
				}
			}
		}
	}
}

const sf::Texture& V3DScene::GetTexture()
{
	sf::Texture::getMaximumSize();

	renderTex.setActive(true);
	renderTex.clear(BackgroundTint);

	glCheck(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
	glCheck(glEnable(GL_BLEND));
	glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
	glCheck(glEnable(GL_DEPTH_TEST));
	glCheck(glEnable(GL_CULL_FACE));
	glCheck(glCullFace(GL_BACK));
	for (CurrentCamera = 0; CurrentCamera < Camera.size(); CurrentCamera++)
	{
		sf::IntRect Viewport(
			(int)(Camera[CurrentCamera]->Viewport.left		* renderTex.getSize().x),
			(int)(Camera[CurrentCamera]->Viewport.top		* renderTex.getSize().y),
			(int)(Camera[CurrentCamera]->Viewport.width		* renderTex.getSize().x),
			(int)(Camera[CurrentCamera]->Viewport.height	* renderTex.getSize().y)
		);

		glCheck(glViewport(Viewport.left, Viewport.top, Viewport.width, Viewport.height));
		Shader->SetCamera(Camera[CurrentCamera].get());
		Shader->Update();
		Shader->Bind();

		RenderGroup(this);
	}

	renderTex.display();
	renderTex.setActive(false);

	return renderTex.getTexture();
}

const sf::Texture V3DScene::GetTexture(V3DShader* shader, V3DCamera* camera)
{
	std::unique_ptr<V3DShader> uShader(shader);
	std::unique_ptr<V3DCamera> uCamera(camera);

	if (Shader.get() != shader)
		Shader.swap(uShader);

	if (Camera[CurrentCamera].get() != camera)
		Camera[CurrentCamera].swap(uCamera);

	GetTexture();

	if (Shader.get() != shader)
		Shader.swap(uShader);

	if (Camera[CurrentCamera].get() != camera)
		Camera[CurrentCamera].swap(uCamera);

	uShader.release();
	uCamera.release();

	return renderTex.getTexture();
}

void V3DScene::Draw(sf::RenderTarget& RenderTarget)
{
	if (!visible)
		return;

	GetTexture();

	RenderTarget.resetGLStates();
	if (PostEffect != nullptr && VPostEffectBase::isSupported())
	{
		if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
		{
			postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
		}

		PostEffect->Apply(renderTex.getTexture(), postProcessTex);
		postProcessTex.display();

		updateTexture(postProcessTex.getTexture());
	}
	else
	{
		updateTexture(renderTex.getTexture());
	}

	Sprite->Draw(RenderTarget);
}
#endif<commit_msg>Replace dynamic_cast with GroupItemAsType<commit_after>#ifndef VFRAME_NO_3D
#include "V3DScene.h"
#include "V3DObject.h"
#include "V3DBatchModelGroup.h"
#include "V3DShader.h"
#include "V3DCamera.h"
#include <cstring>

V3DScene::V3DScene(float x, float y, unsigned int width, unsigned int height, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
	renderTex.create(width, height, settings);
	Sprite->Position = sf::Vector2f(x, y);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

V3DScene::V3DScene(sf::Vector2f position, sf::Vector2u size, const sf::ContextSettings& settings, unsigned int maxSize) : VRenderGroup(maxSize), contextSettings(settings)
{
	renderTex.create(size.x, size.y, settings);
	Sprite->Position = position;
	Sprite->Size = sf::Vector2f(size);
}

void V3DScene::SetActive(bool value)
{
	renderTex.setActive(value);
}

void V3DScene::PushGLStates()
{
	renderTex.pushGLStates();
}

void V3DScene::PopGLStates()
{
	renderTex.popGLStates();
}

void V3DScene::ResetGLStates()
{
	renderTex.resetGLStates();
}

#include "V3DModel.h"
void V3DScene::Destroy()
{
	VSUPERCLASS::Destroy();

	renderTex.resetGLStates();
	renderTex.setActive(false);

	if (V3DModel::DefaultTexture)
	{
		glDeleteTextures(1, &V3DModel::DefaultTexture);
		V3DModel::DefaultTexture = 0;
	}
}

void V3DScene::Resize(int width, int height)
{
	postProcessTex.create(width, height);
	renderTex.create(width, height, contextSettings);
	Sprite->Size = sf::Vector2f(sf::Vector2u(width, height));
}

void V3DScene::Update(float dt)
{
	VSUPERCLASS::Update(dt);
}

void V3DScene::RenderGroup(VGroup* group)
{
	for (int i = 0; i < group->Length(); i++)
	{
		V3DObject* base = group->GetGroupItemAsType<V3DObject>(i);

		if (base != nullptr)
		{
			base->UpdateShader(Shader.get(), Camera[CurrentCamera].get());
			if (Camera[CurrentCamera]->BoxInView(base->Position, base->GetMinimum(), base->GetMaximum()) && base->exists && base->visible)
			{
				base->Draw(renderTex); //If Renderable 3D Object
			}
		}
		else
		{
			V3DBatchModelGroup* batchGroup = group->GetGroupItemAsType<V3DBatchModelGroup>(i);

			if (batchGroup != nullptr)
			{
				batchGroup->UpdateShader(Camera[CurrentCamera].get(), Shader.get()); //If RenderBatch Group
				batchGroup->Draw(renderTex);
			}
			else
			{
				VGroup* childGroup = group->GetGroupItemAsType<VGroup>(i);
				if (childGroup != nullptr)
				{
					RenderGroup(childGroup); //If regular group.
				}
				else
				{
					group->GetGroupItem(i)->Draw(renderTex); //If nothing else, just draw it.
				}
			}
		}
	}
}

const sf::Texture& V3DScene::GetTexture()
{
	sf::Texture::getMaximumSize();

	renderTex.setActive(true);
	renderTex.clear(BackgroundTint);

	glCheck(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
	glCheck(glEnable(GL_BLEND));
	glCheck(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
	glCheck(glEnable(GL_DEPTH_TEST));
	glCheck(glEnable(GL_CULL_FACE));
	glCheck(glCullFace(GL_BACK));
	for (CurrentCamera = 0; CurrentCamera < Camera.size(); CurrentCamera++)
	{
		sf::IntRect Viewport(
			(int)(Camera[CurrentCamera]->Viewport.left		* renderTex.getSize().x),
			(int)(Camera[CurrentCamera]->Viewport.top		* renderTex.getSize().y),
			(int)(Camera[CurrentCamera]->Viewport.width		* renderTex.getSize().x),
			(int)(Camera[CurrentCamera]->Viewport.height	* renderTex.getSize().y)
		);

		glCheck(glViewport(Viewport.left, Viewport.top, Viewport.width, Viewport.height));
		Shader->SetCamera(Camera[CurrentCamera].get());
		Shader->Update();
		Shader->Bind();

		RenderGroup(this);
	}

	renderTex.display();
	renderTex.setActive(false);

	return renderTex.getTexture();
}

const sf::Texture V3DScene::GetTexture(V3DShader* shader, V3DCamera* camera)
{
	std::unique_ptr<V3DShader> uShader(shader);
	std::unique_ptr<V3DCamera> uCamera(camera);

	if (Shader.get() != shader)
		Shader.swap(uShader);

	if (Camera[CurrentCamera].get() != camera)
		Camera[CurrentCamera].swap(uCamera);

	GetTexture();

	if (Shader.get() != shader)
		Shader.swap(uShader);

	if (Camera[CurrentCamera].get() != camera)
		Camera[CurrentCamera].swap(uCamera);

	uShader.release();
	uCamera.release();

	return renderTex.getTexture();
}

void V3DScene::Draw(sf::RenderTarget& RenderTarget)
{
	if (!visible)
		return;

	GetTexture();

	RenderTarget.resetGLStates();
	if (PostEffect != nullptr && VPostEffectBase::isSupported())
	{
		if (postProcessTex.getSize().x == 0 || postProcessTex.getSize().y == 0)
		{
			postProcessTex.create(renderTex.getSize().x, renderTex.getSize().y);
		}

		PostEffect->Apply(renderTex.getTexture(), postProcessTex);
		postProcessTex.display();

		updateTexture(postProcessTex.getTexture());
	}
	else
	{
		updateTexture(renderTex.getTexture());
	}

	Sprite->Draw(RenderTarget);
}
#endif<|endoftext|>