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

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

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "vtkStarbaseProperty.h"
#include "vtkStarbaseCamera.h"
#include "vtkStarbaseLight.h"
#include "vtkStarbaseRenderWindow.h"
#include "vtkStarbaseRenderer.h"

#define MAX_LIGHTS 16

vtkStarbaseRenderer::vtkStarbaseRenderer()
{
}

// Ask volumes to render themselves.
int vtkStarbaseRenderer::UpdateVolumes()
{
  int count = 0;

  return count;
}

// Internal method temporarily removes lights before reloading them
// into graphics pipeline.
void vtkStarbaseRenderer::ClearLights (void)
{
  light_ambient(this->Fd, this->Ambient[0],
		this->Ambient[1], this->Ambient[2]);
  this->LightSwitch = 0x0001;

  vtkDebugMacro(<< "SB_light_ambient: " << this->Ambient[0] << " " <<
  this->Ambient[1] << " " << this->Ambient[2] << "\n");

  light_switch(this->Fd, this->LightSwitch);

  vtkDebugMacro( << " SB_light_switch: " << this->LightSwitch << "\n");

  this->NumberOfLightsBound = 1;
}

// Ask lights to load themselves into graphics pipeline.
int vtkStarbaseRenderer::UpdateLights ()
{
  vtkLight *light;
  short curLight;
  float status;
  int count;

  // Check if a light is on. If not then make a new light.
  count = 0;
  curLight= this->NumberOfLightsBound;

  for(this->Lights->InitTraversal();
      (light = this->Lights->GetNextItem()); )
    {
    status = light->GetSwitch();
    if ((status > 0.0)&& (curLight < MAX_LIGHTS))
      {
      curLight++;
      count++;
      }
    }

  if( !count )
    {
    vtkDebugMacro(<<"No lights are on, creating one.");
    this->CreateLight();
    }

  count = 0;
  curLight= this->NumberOfLightsBound;

  for (this->Lights->InitTraversal(); (light = this->Lights.GetNextItem()); )
    {

    status = light->GetSwitch();

    // if the light is on then define it and bind it.
    // also make sure we still have room.
    if ((status > 0.0)&& (curLight < MAX_LIGHTS))
      {
      light->Render((vtkRenderer *)this,curLight);
      // increment the current light by one
      curLight++;
      count++;
      }
    }

  this->NumberOfLightsBound = curLight;

  return count;
}

// Concrete starbase render method.
void vtkStarbaseRenderer::DeviceRender(void)
{
  int  actor_count;
  int  volume_count;

  vtkStarbaseRenderWindow *temp;

  // update our Fd first
  temp = (vtkStarbaseRenderWindow *)this->GetRenderWindow();
  this->Fd = temp->GetFd();

  if ( this->TwoSidedLighting )
    {
    bf_control(this->Fd, FALSE, TRUE);
    }
  else
    {
    bf_control(this->Fd, FALSE, FALSE);
    }

  // standard render method
  this->ClearLights();

  this->UpdateCameras();
  this->UpdateLights();

  actor_count = this->UpdateActors();
  volume_count = this->UpdateVolumes();

  if ( !(actor_count + volume_count) )
    {
    vtkWarningMacro(<< "No actors or volumes are on.");
    }
}

// Return center of renderer in display coordinates.
float *vtkStarbaseRenderer::GetCenter()
{
  int *size;

  // get physical window dimensions
  size = this->RenderWindow->GetSize();

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
				/2.0*(float)size[0]);
	this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
				/2.0*(float)size[1]);
	this->Center[1] = this->Center[1]/2.0;
	}
	break;
      default:
	{
	this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
			   /2.0*(float)size[0]);
	this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
			   /2.0*(float)size[1]);
	}
      }
    }
  else
    {
    this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
			    /2.0*(float)size[0]);
    this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
			    /2.0*(float)size[1]);
    }

  return this->Center;
}

// Convert display coordinates to view coordinates.
void vtkStarbaseRenderer::DisplayToView()
{
  float vx,vy,vz;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
	  (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;

	vy = 2.0 * (this->DisplayPoint[1]*2.0 - sizey*this->Viewport[1])/
	  (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
	}
	break;
      default:
	{
	vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
	  (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
	vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
	  (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
	}
      }
    }
  else
    {
    vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
      (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
    vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
      (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
    }

  vz = this->DisplayPoint[2];

  this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}

// Convert view coordinates to display coordinates.
void vtkStarbaseRenderer::ViewToDisplay()
{
  float dx,dy;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
	  (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
	  sizex*this->Viewport[0];
	dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
	  (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
	  sizey*this->Viewport[1];
	dy = dy/2.0;
	}
	break;
      default:
	{
	dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
	  (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
	  sizex*this->Viewport[0];
	dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
	  (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
	  sizey*this->Viewport[1];
	}
      }
    }
  else
    {
    dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
      (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
      sizex*this->Viewport[0];
    dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
      (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
      sizey*this->Viewport[1];
    }

  this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}

// Is a given display point in this renderer's viewport.
int vtkStarbaseRenderer::IsInViewport(int x,int y)
{
  int *size;

  // get physical window dimensions
  size = this->RenderWindow->GetSize();

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	int ty = y*2;

	if ((this->Viewport[0]*size[0] <= x)&&
	    (this->Viewport[2]*size[0] >= x)&&
	    (this->Viewport[1]*size[1] <= ty)&&
	    (this->Viewport[3]*size[1] >= ty))
	  {
	  return 1;
	  }
	}
	break;
      default:
	{
	if ((this->Viewport[0]*size[0] <= x)&&
	    (this->Viewport[2]*size[0] >= x)&&
	    (this->Viewport[1]*size[1] <= y)&&
	    (this->Viewport[3]*size[1] >= y))
	  {
	  return 1;
	  }
	}
      }
    }
  else
    {
    if ((this->Viewport[0]*size[0] <= x)&&
	(this->Viewport[2]*size[0] >= x)&&
	(this->Viewport[1]*size[1] <= y)&&
	(this->Viewport[3]*size[1] >= y))
      {
      return 1;
      }
    }

  return 0;
}

void vtkStarbaseRenderer::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkRenderer::PrintSelf(os,indent);

  os << indent << "Number Of Lights Bound: " <<
    this->NumberOfLightsBound << "\n";

  os << indent << "File Descriptor: " << this->Fd << "\n";

  os << indent << "Light Switch: " << this->LightSwitch << "\n";

}

<commit_msg>ERR: dereferencing error fixed<commit_after>/*=========================================================================

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

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include <iostream.h>
#include "vtkStarbaseProperty.h"
#include "vtkStarbaseCamera.h"
#include "vtkStarbaseLight.h"
#include "vtkStarbaseRenderWindow.h"
#include "vtkStarbaseRenderer.h"

#define MAX_LIGHTS 16

vtkStarbaseRenderer::vtkStarbaseRenderer()
{
}

// Ask volumes to render themselves.
int vtkStarbaseRenderer::UpdateVolumes()
{
  int count = 0;

  return count;
}

// Internal method temporarily removes lights before reloading them
// into graphics pipeline.
void vtkStarbaseRenderer::ClearLights (void)
{
  light_ambient(this->Fd, this->Ambient[0],
		this->Ambient[1], this->Ambient[2]);
  this->LightSwitch = 0x0001;

  vtkDebugMacro(<< "SB_light_ambient: " << this->Ambient[0] << " " <<
  this->Ambient[1] << " " << this->Ambient[2] << "\n");

  light_switch(this->Fd, this->LightSwitch);

  vtkDebugMacro( << " SB_light_switch: " << this->LightSwitch << "\n");

  this->NumberOfLightsBound = 1;
}

// Ask lights to load themselves into graphics pipeline.
int vtkStarbaseRenderer::UpdateLights ()
{
  vtkLight *light;
  short curLight;
  float status;
  int count;

  // Check if a light is on. If not then make a new light.
  count = 0;
  curLight= this->NumberOfLightsBound;

  for(this->Lights->InitTraversal();
      (light = this->Lights->GetNextItem()); )
    {
    status = light->GetSwitch();
    if ((status > 0.0)&& (curLight < MAX_LIGHTS))
      {
      curLight++;
      count++;
      }
    }

  if( !count )
    {
    vtkDebugMacro(<<"No lights are on, creating one.");
    this->CreateLight();
    }

  count = 0;
  curLight= this->NumberOfLightsBound;

  for (this->Lights->InitTraversal(); (light = this->Lights->GetNextItem()); )
    {

    status = light->GetSwitch();

    // if the light is on then define it and bind it.
    // also make sure we still have room.
    if ((status > 0.0)&& (curLight < MAX_LIGHTS))
      {
      light->Render((vtkRenderer *)this,curLight);
      // increment the current light by one
      curLight++;
      count++;
      }
    }

  this->NumberOfLightsBound = curLight;

  return count;
}

// Concrete starbase render method.
void vtkStarbaseRenderer::DeviceRender(void)
{
  int  actor_count;
  int  volume_count;

  vtkStarbaseRenderWindow *temp;

  // update our Fd first
  temp = (vtkStarbaseRenderWindow *)this->GetRenderWindow();
  this->Fd = temp->GetFd();

  if ( this->TwoSidedLighting )
    {
    bf_control(this->Fd, FALSE, TRUE);
    }
  else
    {
    bf_control(this->Fd, FALSE, FALSE);
    }

  // standard render method
  this->ClearLights();

  this->UpdateCameras();
  this->UpdateLights();

  actor_count = this->UpdateActors();
  volume_count = this->UpdateVolumes();

  if ( !(actor_count + volume_count) )
    {
    vtkWarningMacro(<< "No actors or volumes are on.");
    }
}

// Return center of renderer in display coordinates.
float *vtkStarbaseRenderer::GetCenter()
{
  int *size;

  // get physical window dimensions
  size = this->RenderWindow->GetSize();

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
				/2.0*(float)size[0]);
	this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
				/2.0*(float)size[1]);
	this->Center[1] = this->Center[1]/2.0;
	}
	break;
      default:
	{
	this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
			   /2.0*(float)size[0]);
	this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
			   /2.0*(float)size[1]);
	}
      }
    }
  else
    {
    this->Center[0] = ((this->Viewport[2]+this->Viewport[0])
			    /2.0*(float)size[0]);
    this->Center[1] = ((this->Viewport[3]+this->Viewport[1])
			    /2.0*(float)size[1]);
    }

  return this->Center;
}

// Convert display coordinates to view coordinates.
void vtkStarbaseRenderer::DisplayToView()
{
  float vx,vy,vz;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
	  (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;

	vy = 2.0 * (this->DisplayPoint[1]*2.0 - sizey*this->Viewport[1])/
	  (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
	}
	break;
      default:
	{
	vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
	  (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
	vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
	  (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
	}
      }
    }
  else
    {
    vx = 2.0 * (this->DisplayPoint[0] - sizex*this->Viewport[0])/
      (sizex*(this->Viewport[2]-this->Viewport[0])) - 1.0;
    vy = 2.0 * (this->DisplayPoint[1] - sizey*this->Viewport[1])/
      (sizey*(this->Viewport[3]-this->Viewport[1])) - 1.0;
    }

  vz = this->DisplayPoint[2];

  this->SetViewPoint(vx*this->Aspect[0],vy*this->Aspect[1],vz);
}

// Convert view coordinates to display coordinates.
void vtkStarbaseRenderer::ViewToDisplay()
{
  float dx,dy;
  int sizex,sizey;
  int *size;

  /* get physical window dimensions */
  size = this->RenderWindow->GetSize();
  sizex = size[0];
  sizey = size[1];

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
	  (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
	  sizex*this->Viewport[0];
	dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
	  (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
	  sizey*this->Viewport[1];
	dy = dy/2.0;
	}
	break;
      default:
	{
	dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
	  (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
	  sizex*this->Viewport[0];
	dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
	  (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
	  sizey*this->Viewport[1];
	}
      }
    }
  else
    {
    dx = (this->ViewPoint[0]/this->Aspect[0] + 1.0) *
      (sizex*(this->Viewport[2]-this->Viewport[0])) / 2.0 +
      sizex*this->Viewport[0];
    dy = (this->ViewPoint[1]/this->Aspect[1] + 1.0) *
      (sizey*(this->Viewport[3]-this->Viewport[1])) / 2.0 +
      sizey*this->Viewport[1];
    }

  this->SetDisplayPoint(dx,dy,this->ViewPoint[2]);
}

// Is a given display point in this renderer's viewport.
int vtkStarbaseRenderer::IsInViewport(int x,int y)
{
  int *size;

  // get physical window dimensions
  size = this->RenderWindow->GetSize();

  if (this->RenderWindow->GetStereoRender())
    {
    // take into account stereo effects
    switch (this->RenderWindow->GetStereoType())
      {
      case VTK_STEREO_CRYSTAL_EYES:
	{
	int ty = y*2;

	if ((this->Viewport[0]*size[0] <= x)&&
	    (this->Viewport[2]*size[0] >= x)&&
	    (this->Viewport[1]*size[1] <= ty)&&
	    (this->Viewport[3]*size[1] >= ty))
	  {
	  return 1;
	  }
	}
	break;
      default:
	{
	if ((this->Viewport[0]*size[0] <= x)&&
	    (this->Viewport[2]*size[0] >= x)&&
	    (this->Viewport[1]*size[1] <= y)&&
	    (this->Viewport[3]*size[1] >= y))
	  {
	  return 1;
	  }
	}
      }
    }
  else
    {
    if ((this->Viewport[0]*size[0] <= x)&&
	(this->Viewport[2]*size[0] >= x)&&
	(this->Viewport[1]*size[1] <= y)&&
	(this->Viewport[3]*size[1] >= y))
      {
      return 1;
      }
    }

  return 0;
}

void vtkStarbaseRenderer::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkRenderer::PrintSelf(os,indent);

  os << indent << "Number Of Lights Bound: " <<
    this->NumberOfLightsBound << "\n";

  os << indent << "File Descriptor: " << this->Fd << "\n";

  os << indent << "Light Switch: " << this->LightSwitch << "\n";

}

<|endoftext|>


<commit_before>/*
 * ParameterOrbitalWidget.cpp
 *
 * Copyright (C) 2019 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "ParameterOrbitalWidget.h"

using namespace megamol;
using namespace megamol::gui;

ParameterOrbitalWidget::ParameterOrbitalWidget(void)
    : m_rotation(1.0f, 0.0f, 0.0f, 0.0f), m_direction(0.0f, 0.0f, -1.0f) {}

bool megamol::gui::ParameterOrbitalWidget::gizmo3D_rotation_axes(glm::vec4& inout_rotation) {

    bool retval = false;

    if (ImGui::gizmo3D("##gizmo1", this->m_rotation, ImGui::GetNextItemWidth(),
            imguiGizmo::mode3Axes | imguiGizmo::cubeAtOrigin | imguiGizmo::sphereAtOrigin)) {
        inout_rotation = glm::vec4(this->m_rotation.x, this->m_rotation.y, this->m_rotation.z, this->m_rotation.w);
        retval = true;
    } else {
        this->m_rotation = ::quat(inout_rotation.w, inout_rotation.x, inout_rotation.y, inout_rotation.z);
    }

    return retval;
}

bool megamol::gui::ParameterOrbitalWidget::gizmo3D_rotation_direction(glm::vec3& inout_direction) {

    bool retval = false;

    if (ImGui::gizmo3D("##gizmo2", this->m_direction, ImGui::GetNextItemWidth(), imguiGizmo::modeDirection)) {
        inout_direction = glm::vec3(this->m_direction.x, this->m_direction.y, this->m_direction.z) * (-1.0f);
        retval = true;
    } else {
        this->m_direction = ::vec3(inout_direction.x, inout_direction.y, inout_direction.z) * (-1.0f);
    }

    return retval;
}<commit_msg>fixed direction of direction widget<commit_after>/*
 * ParameterOrbitalWidget.cpp
 *
 * Copyright (C) 2019 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "ParameterOrbitalWidget.h"

using namespace megamol;
using namespace megamol::gui;

ParameterOrbitalWidget::ParameterOrbitalWidget(void)
    : m_rotation(1.0f, 0.0f, 0.0f, 0.0f), m_direction(0.0f, 0.0f, -1.0f) {}

bool megamol::gui::ParameterOrbitalWidget::gizmo3D_rotation_axes(glm::vec4& inout_rotation) {

    bool retval = false;

    if (ImGui::gizmo3D("##gizmo1", this->m_rotation, ImGui::GetNextItemWidth(),
            imguiGizmo::mode3Axes | imguiGizmo::cubeAtOrigin | imguiGizmo::sphereAtOrigin)) {
        inout_rotation = glm::vec4(this->m_rotation.x, this->m_rotation.y, this->m_rotation.z, this->m_rotation.w);
        retval = true;
    } else {
        this->m_rotation = ::quat(inout_rotation.w, inout_rotation.x, inout_rotation.y, inout_rotation.z);
    }

    return retval;
}

bool megamol::gui::ParameterOrbitalWidget::gizmo3D_rotation_direction(glm::vec3& inout_direction) {

    bool retval = false;

    if (ImGui::gizmo3D("##gizmo2", this->m_direction, ImGui::GetNextItemWidth(), imguiGizmo::modeDirection)) {
        inout_direction = glm::vec3(this->m_direction.x, this->m_direction.y, this->m_direction.z);
        retval = true;
    } else {
        this->m_direction = ::vec3(inout_direction.x, inout_direction.y, inout_direction.z);
    }

    return retval;
}<|endoftext|>


<commit_before>#include <cmath>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include "World.H"
#include "Unit.H"

#define PI 3.14159

using namespace std;

/* helper that you need to implement

 - move unit by current_speed * heading

 - units only collide with the map border

 - when units hit a wall they stop at the collision point (current_speed=0)
   and collision_hook is called with the previous speed and a vector of bools
   encoding the walls that were hit. This vector is used in collision_hook to
   implement bouncing by only changing the unit's heading, i.e. even when
   bouncing the unit stays at the collision location for the remainder of the
   simulation frame and only starts moving again in the following frame.

 - it is essential that units are located inside the map at all times. There
   can be no overlap. Ensure this property by clipping coordinates after
   moving.

*/

void startShowdownMode(Unit &u, Unit &v,const World &w);

void World::move_unit(Unit &u)
{
  //Take unit speed multiply by heading to get new position
  double futureX = u.pos.x + (u.current_speed*u.heading.x);
  double futureY = u.pos.y + (u.current_speed*u.heading.y);
  //Extra space to leave for a collision. Compensates for rounding errors.
  double buffer = 0.1;
  //Collision occured flag
  bool collision = false;
  bool collisions[4] = {false, false, false, false};
  double prev_speed = u.current_speed;

  //Check to see if movement would result in a collision
  if(futureX+u.radius+buffer >= width) {
    //Collision with Right wall
    futureX = width - u.radius - buffer;
    collision = true;
    collisions[1] = true;
  }
  if(futureX-u.radius-buffer <= 0) {
    //Collision with Left wall
    futureX = u.radius + buffer;
    collision = true;
    collisions[3] = true;
  }
  if(futureY+u.radius+buffer >= height) {
    //Collision with Bottom wall
    futureY = height - u.radius - buffer;
    collision = true;
    collisions[2] = true;
  }
  if(futureY-u.radius-buffer <= 0) {
    //Collision with Top wall
    futureY = u.radius + buffer;
    collision = true;
    collisions[0] = true;
  }

  if(collision) {
	u.current_speed = 0;
    u.collision_hook(prev_speed, collisions);
  }

  //Update unit's position to new position
  u.pos = Vec2(futureX, futureY);

}

// returns policy name
const char *apol2str(AttackPolicy pol)
{
  switch (pol) {
    case ATTACK_WEAKEST:
      return "attack-weakest";
    case ATTACK_CLOSEST:
      return "attack-closest";
    case ATTACK_MOST_DANGEROUS:
      return "attack-most-dangerous";
  }
  return "?";
}

//Clean up
World::~World()
{
  //Delete each unit in units vector
  for(auto &dude : units){
    delete dude;
  }
}

// deducts hit points and calls attack_hook
void World::attack(Unit &attacker, Unit &attacked)
{
  //Reduce attacked unit's health by attack strength of attacker
  attacked.hp -= (int)attacker.damage;
  attack_hook(attacker, attacked);
  //Remove dead is handled by step in World2.C
}

// return a random position at which a circle of that radius fits

Vec2 World::rnd_pos(double radius) const
{
  double slack = radius * 2;

  Vec2 p((width  - 2*slack) * rnd01() + slack,
         (height - 2*slack) * rnd01() + slack);

  // assert circle in rectangle
  assert(p.x > radius && p.x < width - radius);
  assert(p.y > radius && p.y < height - radius);
  return p;
}

// return uniform random heading
// length of vector = 1
Vec2 World::rnd_heading() const
{
  // Generate random value between (0 and 2)*pi radians
  // This should preserve a uniform distribution as the 2*rnd01
  // transforms from an infinite set of points
  double angle = ((this->rnd01())*2)*PI;

  // create Vec2 object with x = cos(angle), y = sin(angle)
  return Vec2(cos(angle), sin(angle));
}

// mirror position with respect to map mid-point
Vec2 World::mirror(const Vec2 &pos) const
{
  //Create Mid-point coordinates
  double midX = width/2;
  double midY = height/2;
  double newX;
  double newY;
  double diff;

  //Set new coordinate to position same distance from midpoint
  //but on the other side of said midpoint
  if(pos.x >= midX) {
    diff = pos.x - midX;
    newX = midX - diff;
  } else {
    diff = midX - pos.x;
    newX = midX + diff;
  }
  if(pos.y >= midY){
    diff = pos.y - midY;
    newY = midY - diff;
  } else {
    diff = midY - pos.y;
    newY = midY + diff;
  }
  return Vec2(newX, newY);

}

// return squared distance between two unit centers
double World::distance2(const Unit &u, const Unit &v)
{
  return pow((v.pos.x - u.pos.x), 2) + pow((v.pos.y - u.pos.y), 2);
}

// return true iff u can attack v, i.e. distance of u's and v's centers is
// less than u's attack distance plus v's radius
bool World::can_attack(const Unit &u, const Unit &v)
{
  double dist = sqrt(distance2(u, v));

  if(dist <= u.attack_radius + v.radius){
    return true;
  } else {
    return false;
  }
}

// populate a vector with enemy units that can be attacked by u;
// clears vector first
void World::enemies_within_attack_range(const Unit &u,
                                        vector<Unit*> &targets) const
{
  targets.clear();

  //Append all units to vector
  for(auto &unit : units) {
    if(can_attack(u, *unit)) {
      if(unit->team != u.team){
        targets.push_back(unit);
      }
    }
  }
}

// return a random unit that can be attacked by u with minimal hp_old value,
// or 0 if none exists
Unit *World::random_weakest_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() ==0) {return 0;}

  //Search for unit with lowest hp
  Unit * lowest = targets[0];
  for(auto &unit: targets) {
    if(unit->hp_old < lowest->hp_old){
      lowest = unit;
    }
  }
  return lowest;
}

// return a random unit that can be attacked by u with minimal distance to
// u, or 0 if none exists
Unit *World::random_closest_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() == 0) {return 0;}

  //Search for unit with lowest distance
  Unit * closest = targets[0];
  for(auto &unit: targets) {
    if(distance2(u, *unit) < distance2(u, *closest)){
      closest = unit;
    }
  }

  return closest;
}

// return a random unit that can be attacked by u with maximal damage/hp_old
// ratio, or 0 if none exists
Unit *World::random_most_dangerous_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() ==0) {return 0;}

  //Search for unit with highest damage/hp remaining ratio
  Unit * baddest = targets[0];
  for(auto &unit: targets) {
    if(unit->damage/unit->hp_old < baddest->damage/baddest->hp_old){
      baddest = unit;
    }
  }

  return baddest;
}

// return score for red: 2 for win, 0 for loss, 1 for draw, -1 for game not
// over yet
int World::red_score() const
{
  //Flags for if red or blue units still exist
  bool red = false;
  bool blue = false;

  if (units.empty()) {
    return 1;
  }

  //Check all remaining units for team affiliations
  for(auto &unit : units){
    if(unit->team == Team::BLUE){
      blue = true;
    }
    if(unit->team == Team::RED){
      red = true;
    }
    //If there are at least one unit of each team game continues
    if(red && blue){
      //If there are is only one unit remaining on each side game enters showdown mode
      if(units.size() == 2){
        startShowdownMode(units[0], units[1], *this); //Last two units moved and thrown towards eachother
      }
      return -1;
    }
  }

  //If in all the remaining units, none are red loss
  if(!red) {
    return 0;
  } else {
    return 2; //Otherwise return win!
  }
}

//Place two units above and below midpoint of map and change headings towards eachother.
void startShowdownMode(Unit &u, Unit &v,const World &w){
  u.pos.x = w.width/2;
  u.pos.y = w.height*3/4;
  v.pos = w.mirror(u.pos);
  u.heading = Vec2(0,-1.0);
  v.heading = Vec2(0,1.0);
}<commit_msg>removed const from startShowdownMode<commit_after>#include <cmath>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include "World.H"
#include "Unit.H"

#define PI 3.14159

using namespace std;

/* helper that you need to implement

 - move unit by current_speed * heading

 - units only collide with the map border

 - when units hit a wall they stop at the collision point (current_speed=0)
   and collision_hook is called with the previous speed and a vector of bools
   encoding the walls that were hit. This vector is used in collision_hook to
   implement bouncing by only changing the unit's heading, i.e. even when
   bouncing the unit stays at the collision location for the remainder of the
   simulation frame and only starts moving again in the following frame.

 - it is essential that units are located inside the map at all times. There
   can be no overlap. Ensure this property by clipping coordinates after
   moving.

*/

void startShowdownMode(Unit &u, Unit &v, World &w);

void World::move_unit(Unit &u)
{
  //Take unit speed multiply by heading to get new position
  double futureX = u.pos.x + (u.current_speed*u.heading.x);
  double futureY = u.pos.y + (u.current_speed*u.heading.y);
  //Extra space to leave for a collision. Compensates for rounding errors.
  double buffer = 0.1;
  //Collision occured flag
  bool collision = false;
  bool collisions[4] = {false, false, false, false};
  double prev_speed = u.current_speed;

  //Check to see if movement would result in a collision
  if(futureX+u.radius+buffer >= width) {
    //Collision with Right wall
    futureX = width - u.radius - buffer;
    collision = true;
    collisions[1] = true;
  }
  if(futureX-u.radius-buffer <= 0) {
    //Collision with Left wall
    futureX = u.radius + buffer;
    collision = true;
    collisions[3] = true;
  }
  if(futureY+u.radius+buffer >= height) {
    //Collision with Bottom wall
    futureY = height - u.radius - buffer;
    collision = true;
    collisions[2] = true;
  }
  if(futureY-u.radius-buffer <= 0) {
    //Collision with Top wall
    futureY = u.radius + buffer;
    collision = true;
    collisions[0] = true;
  }

  if(collision) {
	u.current_speed = 0;
    u.collision_hook(prev_speed, collisions);
  }

  //Update unit's position to new position
  u.pos = Vec2(futureX, futureY);

}

// returns policy name
const char *apol2str(AttackPolicy pol)
{
  switch (pol) {
    case ATTACK_WEAKEST:
      return "attack-weakest";
    case ATTACK_CLOSEST:
      return "attack-closest";
    case ATTACK_MOST_DANGEROUS:
      return "attack-most-dangerous";
  }
  return "?";
}

//Clean up
World::~World()
{
  //Delete each unit in units vector
  for(auto &dude : units){
    delete dude;
  }
}

// deducts hit points and calls attack_hook
void World::attack(Unit &attacker, Unit &attacked)
{
  //Reduce attacked unit's health by attack strength of attacker
  attacked.hp -= (int)attacker.damage;
  attack_hook(attacker, attacked);
  //Remove dead is handled by step in World2.C
}

// return a random position at which a circle of that radius fits

Vec2 World::rnd_pos(double radius) const
{
  double slack = radius * 2;

  Vec2 p((width  - 2*slack) * rnd01() + slack,
         (height - 2*slack) * rnd01() + slack);

  // assert circle in rectangle
  assert(p.x > radius && p.x < width - radius);
  assert(p.y > radius && p.y < height - radius);
  return p;
}

// return uniform random heading
// length of vector = 1
Vec2 World::rnd_heading() const
{
  // Generate random value between (0 and 2)*pi radians
  // This should preserve a uniform distribution as the 2*rnd01
  // transforms from an infinite set of points
  double angle = ((this->rnd01())*2)*PI;

  // create Vec2 object with x = cos(angle), y = sin(angle)
  return Vec2(cos(angle), sin(angle));
}

// mirror position with respect to map mid-point
Vec2 World::mirror(const Vec2 &pos) const
{
  //Create Mid-point coordinates
  double midX = width/2;
  double midY = height/2;
  double newX;
  double newY;
  double diff;

  //Set new coordinate to position same distance from midpoint
  //but on the other side of said midpoint
  if(pos.x >= midX) {
    diff = pos.x - midX;
    newX = midX - diff;
  } else {
    diff = midX - pos.x;
    newX = midX + diff;
  }
  if(pos.y >= midY){
    diff = pos.y - midY;
    newY = midY - diff;
  } else {
    diff = midY - pos.y;
    newY = midY + diff;
  }
  return Vec2(newX, newY);

}

// return squared distance between two unit centers
double World::distance2(const Unit &u, const Unit &v)
{
  return pow((v.pos.x - u.pos.x), 2) + pow((v.pos.y - u.pos.y), 2);
}

// return true iff u can attack v, i.e. distance of u's and v's centers is
// less than u's attack distance plus v's radius
bool World::can_attack(const Unit &u, const Unit &v)
{
  double dist = sqrt(distance2(u, v));

  if(dist <= u.attack_radius + v.radius){
    return true;
  } else {
    return false;
  }
}

// populate a vector with enemy units that can be attacked by u;
// clears vector first
void World::enemies_within_attack_range(const Unit &u,
                                        vector<Unit*> &targets) const
{
  targets.clear();

  //Append all units to vector
  for(auto &unit : units) {
    if(can_attack(u, *unit)) {
      if(unit->team != u.team){
        targets.push_back(unit);
      }
    }
  }
}

// return a random unit that can be attacked by u with minimal hp_old value,
// or 0 if none exists
Unit *World::random_weakest_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() ==0) {return 0;}

  //Search for unit with lowest hp
  Unit * lowest = targets[0];
  for(auto &unit: targets) {
    if(unit->hp_old < lowest->hp_old){
      lowest = unit;
    }
  }
  return lowest;
}

// return a random unit that can be attacked by u with minimal distance to
// u, or 0 if none exists
Unit *World::random_closest_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() == 0) {return 0;}

  //Search for unit with lowest distance
  Unit * closest = targets[0];
  for(auto &unit: targets) {
    if(distance2(u, *unit) < distance2(u, *closest)){
      closest = unit;
    }
  }

  return closest;
}

// return a random unit that can be attacked by u with maximal damage/hp_old
// ratio, or 0 if none exists
Unit *World::random_most_dangerous_target(Unit &u) const
{
  //Create list of possible targets
  vector<Unit*> targets;
  enemies_within_attack_range(u, targets);

  //If there are no available targets
  if(targets.size() ==0) {return 0;}

  //Search for unit with highest damage/hp remaining ratio
  Unit * baddest = targets[0];
  for(auto &unit: targets) {
    if(unit->damage/unit->hp_old < baddest->damage/baddest->hp_old){
      baddest = unit;
    }
  }

  return baddest;
}

// return score for red: 2 for win, 0 for loss, 1 for draw, -1 for game not
// over yet
int World::red_score() const
{
  //Flags for if red or blue units still exist
  bool red = false;
  bool blue = false;

  if (units.empty()) {
    return 1;
  }

  //Check all remaining units for team affiliations
  for(auto &unit : units){
    if(unit->team == Team::BLUE){
      blue = true;
    }
    if(unit->team == Team::RED){
      red = true;
    }
    //If there are at least one unit of each team game continues
    if(red && blue){
      //If there are is only one unit remaining on each side game enters showdown mode
      if(units.size() == 2){
        startShowdownMode(units[0], units[1], *this); //Last two units moved and thrown towards eachother
      }
      return -1;
    }
  }

  //If in all the remaining units, none are red loss
  if(!red) {
    return 0;
  } else {
    return 2; //Otherwise return win!
  }
}

//Place two units above and below midpoint of map and change headings towards eachother.
void startShowdownMode(Unit &u, Unit &v, World &w) {
  u.pos.x = w.width/2;
  u.pos.y = w.height*3/4;
  v.pos = w.mirror(u.pos);
  u.heading = Vec2(0,-1.0);
  v.heading = Vec2(0,1.0);
}<|endoftext|>


<commit_before>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <vector>
#include <algorithm>
#include <functional>
#include "getopt.h"
#include "bitio.h"
#include "h264.h"
#include "md5.h"

#ifdef __RENESAS_VERSION__

#include <machine.h>

extern "C" {
#pragma section FILES

#define O_RDONLY 1
#define O_WRONLY 2
#define MAX_FILESIZE 8 * 1024 * 1024
#define MAX_MD5SIZE 128 * 1024
char InputFile[MAX_FILESIZE];
char OutputFile[MAX_MD5SIZE];

#pragma section
void abort() {while (1);}
static int infilepos;

void exit(int err) {
	while (err) sleep();
}

int fseek(FILE *fp, long offset, int whence) {
	return 0;
}

int open(char *name, int mode, int flg) {
	if (mode & O_RDONLY) {
		infilepos = 0;
	} else if (mode & O_WRONLY) {
		infilepos = 0;
	}
	return 4;
}
int close(int fineno) {return 0;}
int read(int fileno, char *buf, unsigned int count) {
	if (sizeof(InputFile) < infilepos + count) {
		count = sizeof(InputFile) - infilepos;
		if ((signed)count <= 0) {
			return 0;
		}
	}
	memcpy(buf, InputFile + infilepos, count);
	infilepos += count;
	return count;
}
int lseek() {return 0;}
int write(int fileno, char *buf, unsigned int count) {return count;}
char *getenv(const char *name) {return 0;}

}

#endif /* __RENESAS_VERSION__ */

struct Frames {
	std::vector<m2d_frame_t> frame;
	Frames(int width, int height, int num_mem) : frame(num_mem) {
		int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15;
		if (num_mem <= 0 || luma_len <= 0) {
			return;
		}
		std::for_each(frame.begin(), frame.end(), std::bind2nd(Create(), luma_len));
	}
	~Frames() {
		if (frame.empty()) {
			return;
		}
		std::for_each(frame.begin(), frame.end(), Delete());
		frame.clear();
	}
private:
	struct Create : std::binary_function<m2d_frame_t, int, void> {
		void operator()(m2d_frame_t& frm, int luma_len) const {
			frm.luma = new uint8_t[luma_len];
			frm.chroma = new uint8_t[luma_len >> 1];
		}
	};
	struct Delete {
		void operator()(m2d_frame_t& frm) const {
			delete[] frm.luma;
			delete[] frm.chroma;
		}
	};
};

static bool outfilename(char *infilename, char *outfilename, size_t size)
{
	char *start;
	char *end;
	if (!(start = strrchr(infilename, '/')) && !(start = strrchr(infilename, '\\'))) {
		start = infilename;
	} else {
		start += 1;
	}
	end = strrchr(start, '.');
	if (end) {
		*end = '\0';
	}
	if (size <= strlen(start)) {
		return false;
	}
	sprintf(outfilename, "%s.out", start);
	return true;
}

struct input_data_t {
	uint8_t *data_;
	size_t len_;
	size_t pos_;
	void *var_;
	FILE *fo_;
	int dpb_;
	bool raw_;
	bool md5_;
	bool force_exec_;
	input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0), dpb_(-1), raw_(false), md5_(false), force_exec_(false) {
		FILE *fi;
		int opt;
		while ((opt = getopt(argc, argv, "bd:oOx")) != -1) {
			switch (opt) {
			case 'b':
				dpb_ = 1;
				break;
			case 'd':
				dpb_ = strtol(optarg, 0, 0);
				if (32 < (unsigned)dpb_) {
					BlameUser();
					/* NOTREACHED */
				}
				break;
			case 'O':
				md5_ = true;
				break;
			case 'o':
				raw_ = true;
				break;
			case 'x':
				force_exec_ = true;
				break;
			default:
				BlameUser();
				/* NOTREACHED */
			}
		}
		if ((argc <= optind) ||	!(fi = fopen(argv[optind], "rb"))) {
			BlameUser();
			/* NOTREACHED */
		}
		if (md5_ || raw_) {
			char outfile[256];
			if (outfilename(argv[optind], outfile, sizeof(outfile))) {
				fo_ = fopen(outfile, "wb");
			}
		}
#ifdef __RENESAS_VERSION__
		data_ = (uint8_t *)InputFile;
		len_ = sizeof(InputFile);
#else
		fseek(fi, 0, SEEK_END);
		len_ = ftell(fi);
		fseek(fi, 0, SEEK_SET);
		data_ = new uint8_t[len_];
		fread(data_, 1, len_, fi);
#endif
		fclose(fi);
	}
	~input_data_t() {
#ifndef __RENESAS_VERSION__
		delete[] data_;
#endif
		if (fo_) {
			fclose(fo_);
		}
	}
	static size_t write_md5(void *dst, const uint8_t *src, size_t size) {
		md5_append((md5_state_t *)dst, (const md5_byte_t *)src, (int)size);
		return size;
	}
	static size_t write_raw(void *dst, const uint8_t *src, size_t size) {
		return fwrite((const void *)src, 1, size, (FILE *)dst);
	}
	static void write_cropping(const m2d_frame_t *frame, size_t (*writef)(void *dst, const uint8_t *src, size_t size), void *dst) {
		const uint8_t *src;
		int stride, height, width;

		stride = frame->width;
		src = frame->luma + stride * frame->crop[2] + frame->crop[0];
		height = frame->height - frame->crop[2] - frame->crop[3];
		width = stride - frame->crop[0] - frame->crop[1];
		for (int y = 0; y < height; ++y) {
			writef(dst, src, width);
			src += stride;
		}
		src = frame->chroma + stride * (frame->crop[2] >> 1) + frame->crop[0];
		height >>= 1;
		for (int y = 0; y < height; ++y) {
			writef(dst, src, width);
			src += stride;
		}
	}
	static void md5txt(const unsigned char *md5, char *txt)
	{
		for (int i = 0; i < 16; ++i) {
			sprintf(txt + i * 2, "%02xd", *md5++);
		}
		txt[32] = 0x0d;
		txt[33] = 0x0a;
	}
	size_t writeframe(const m2d_frame_t *frame) {
		if (fo_) {
			int luma_size = frame->width * frame->height;
			if (md5_) {
				md5_state_t md5;
				md5_byte_t digest[16];
				char txt[16 * 2 + 2];

				md5_init(&md5);
				write_cropping(frame, write_md5, (void *)&md5);
				md5_finish(&md5, digest);
				md5txt(digest, txt);
				fwrite(txt, 1, sizeof(txt), fo_);
			} else {
				write_cropping(frame, write_raw, (void *)fo_);
			}
			fflush(fo_);
			return luma_size;
		}
		return 0;
	}
	void BlameUser() {
		fprintf(stderr,
			"Usage:\n"
			"\th264dec [-b] [-d <dpb_size>] [-o|O ] <infile>\n"
			"\t\t-b: Bypass DPB\n"
			"\t\t-d <dpb_size>: Specify number of DPB frames -1, 1..16 (default: -1(auto))\n"
			"\t\t-o: RAW output\n"
			"\t\t-O: MD5 output\n"
			"\t\t-x: Mask SIGABRT on error."
			);
		exit(1);
	}
};

static int reread_file(void *var)
{
	input_data_t *d = (input_data_t *)var;
	if (d->pos_ < d->len_) {
		dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_);
		d->pos_ += d->len_;
		return 0;
	} else {
		return -1;
	}
}

#ifdef _M_IX86
#include <crtdbg.h>
#elif defined(__linux__)
#include <pthread.h>
#include <signal.h>
static void trap(int no)
{
	fprintf(stderr, "trap %d\n", no);
	exit(0);
}
#endif

int main(int argc, char *argv[])
{
	h264d_context *h2d;
	int err;

#ifdef _M_IX86
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
//	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
#endif
	h2d = new h264d_context;
	input_data_t data(argc, argv, (void *)h2d);
	if (data.len_ <= 0) {
		delete h2d;
		return -1;
	}
#ifdef __linux__
	if (data.force_exec_) {
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = trap;
		sigaction(SIGABRT, &sa, 0);
		sigaction(SIGSEGV, &sa, 0);
	}
#endif
	err = h264d_init(h2d, data.dpb_, 0, 0);
	if (err) {
		return err;
	}
	err = h264d_read_header(h2d, data.data_, data.len_);
	data.pos_ = data.len_;
	if (err) {
		return err;
	}
	m2d_info_t info;
	h264d_get_info(h2d, &info);
	fprintf(stderr,
		"length: %ld\n"
		"width x height x num: %d x %d x %d\n"
		"Context Size: %ld\n",
		data.len_, info.src_width, info.src_height, info.frame_num, sizeof(h264d_context));
	info.frame_num = (info.frame_num < 3 ? 3 : info.frame_num) + (data.dpb_ < 0 ? 16 : data.dpb_);
	Frames frm(info.src_width, info.src_height, info.frame_num);
	std::vector<uint8_t> second_frame(info.additional_size);
	err = h264d_set_frames(h2d, info.frame_num, &frm.frame[0], &second_frame[0], info.additional_size);
	if (err) {
		return err;
	}
	dec_bits_set_callback(h2d->stream, reread_file, &data);
	m2d_frame_t frame;
	for (int i = 0; i < INT_MAX; ++i) {
		err = h264d_decode_picture(h2d);
		if (err == -1) {
			break;
		}
		while (h264d_get_decoded_frame(h2d, &frame, (data.dpb_ == 1))) {
			data.writeframe(&frame);
		}
		if (err < 0) {
			break;
		}
	}
	while (h264d_get_decoded_frame(h2d, &frame, 1)) {
		data.writeframe(&frame);
	}
	delete h2d;

#ifdef _M_IX86
	assert(_CrtCheckMemory());
#endif
	return (data.force_exec_) ? 0 : ((err == -2) ? 0 : err);
}

<commit_msg>Modify memory allocation from raw pointer.<commit_after>#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include "getopt.h"
#include "bitio.h"
#include "h264.h"
#include "md5.h"

#ifdef __RENESAS_VERSION__

#include <machine.h>

extern "C" {
#pragma section FILES

#define O_RDONLY 1
#define O_WRONLY 2
#define MAX_FILESIZE 8 * 1024 * 1024
#define MAX_MD5SIZE 128 * 1024
char InputFile[MAX_FILESIZE];
char OutputFile[MAX_MD5SIZE];

#pragma section
void abort() {while (1);}
static int infilepos;

void exit(int err) {
	while (err) sleep();
}

int fseek(FILE *fp, long offset, int whence) {
	return 0;
}

int open(char *name, int mode, int flg) {
	if (mode & O_RDONLY) {
		infilepos = 0;
	} else if (mode & O_WRONLY) {
		infilepos = 0;
	}
	return 4;
}
int close(int fineno) {return 0;}
int read(int fileno, char *buf, unsigned int count) {
	if (sizeof(InputFile) < infilepos + count) {
		count = sizeof(InputFile) - infilepos;
		if ((signed)count <= 0) {
			return 0;
		}
	}
	memcpy(buf, InputFile + infilepos, count);
	infilepos += count;
	return count;
}
int lseek() {return 0;}
int write(int fileno, char *buf, unsigned int count) {return count;}
char *getenv(const char *name) {return 0;}

}

#endif /* __RENESAS_VERSION__ */

struct Frames {
	std::vector<m2d_frame_t> frame;
	Frames(int width, int height, int num_mem) : frame(num_mem) {
		int luma_len = ((width + 15) & ~15) * ((height + 15) & ~15) + 15;
		if (num_mem <= 0 || luma_len <= 0) {
			return;
		}
		std::for_each(frame.begin(), frame.end(), std::bind2nd(Create(), luma_len));
	}
	~Frames() {
		if (frame.empty()) {
			return;
		}
		std::for_each(frame.begin(), frame.end(), Delete());
		frame.clear();
	}
private:
	struct Create : std::binary_function<m2d_frame_t, int, void> {
		void operator()(m2d_frame_t& frm, int luma_len) const {
			frm.luma = new uint8_t[luma_len];
			frm.chroma = new uint8_t[luma_len >> 1];
		}
	};
	struct Delete {
		void operator()(m2d_frame_t& frm) const {
			delete[] frm.luma;
			delete[] frm.chroma;
		}
	};
};

static bool outfilename(char *infilename, char *outfilename, size_t size)
{
	char *start;
	char *end;
	if (!(start = strrchr(infilename, '/')) && !(start = strrchr(infilename, '\\'))) {
		start = infilename;
	} else {
		start += 1;
	}
	end = strrchr(start, '.');
	if (end) {
		*end = '\0';
	}
	if (size <= strlen(start)) {
		return false;
	}
	sprintf(outfilename, "%s.out", start);
	return true;
}

struct input_data_t {
	uint8_t *data_;
	size_t len_;
	size_t pos_;
	void *var_;
	FILE *fo_;
	int dpb_;
	bool raw_;
	bool md5_;
	bool force_exec_;
	input_data_t(int argc, char *argv[], void *v) : pos_(0), var_(v), fo_(0), dpb_(-1), raw_(false), md5_(false), force_exec_(false) {
		FILE *fi;
		int opt;
		while ((opt = getopt(argc, argv, "bd:oOx")) != -1) {
			switch (opt) {
			case 'b':
				dpb_ = 1;
				break;
			case 'd':
				dpb_ = strtol(optarg, 0, 0);
				if (32 < (unsigned)dpb_) {
					BlameUser();
					/* NOTREACHED */
				}
				break;
			case 'O':
				md5_ = true;
				break;
			case 'o':
				raw_ = true;
				break;
			case 'x':
				force_exec_ = true;
				break;
			default:
				BlameUser();
				/* NOTREACHED */
			}
		}
		if ((argc <= optind) ||	!(fi = fopen(argv[optind], "rb"))) {
			BlameUser();
			/* NOTREACHED */
		}
		if (md5_ || raw_) {
			char outfile[256];
			if (outfilename(argv[optind], outfile, sizeof(outfile))) {
				fo_ = fopen(outfile, "wb");
			}
		}
#ifdef __RENESAS_VERSION__
		data_ = (uint8_t *)InputFile;
		len_ = sizeof(InputFile);
#else
		fseek(fi, 0, SEEK_END);
		len_ = ftell(fi);
		fseek(fi, 0, SEEK_SET);
		data_ = new uint8_t[len_];
		fread(data_, 1, len_, fi);
#endif
		fclose(fi);
	}
	~input_data_t() {
#ifndef __RENESAS_VERSION__
		delete[] data_;
#endif
		if (fo_) {
			fclose(fo_);
		}
	}
	static size_t write_md5(void *dst, const uint8_t *src, size_t size) {
		md5_append((md5_state_t *)dst, (const md5_byte_t *)src, (int)size);
		return size;
	}
	static size_t write_raw(void *dst, const uint8_t *src, size_t size) {
		return fwrite((const void *)src, 1, size, (FILE *)dst);
	}
	static void write_cropping(const m2d_frame_t *frame, size_t (*writef)(void *dst, const uint8_t *src, size_t size), void *dst) {
		const uint8_t *src;
		int stride, height, width;

		stride = frame->width;
		src = frame->luma + stride * frame->crop[2] + frame->crop[0];
		height = frame->height - frame->crop[2] - frame->crop[3];
		width = stride - frame->crop[0] - frame->crop[1];
		for (int y = 0; y < height; ++y) {
			writef(dst, src, width);
			src += stride;
		}
		src = frame->chroma + stride * (frame->crop[2] >> 1) + frame->crop[0];
		height >>= 1;
		for (int y = 0; y < height; ++y) {
			writef(dst, src, width);
			src += stride;
		}
	}
	static void md5txt(const unsigned char *md5, char *txt)
	{
		for (int i = 0; i < 16; ++i) {
			sprintf(txt + i * 2, "%02xd", *md5++);
		}
		txt[32] = 0x0d;
		txt[33] = 0x0a;
	}
	size_t writeframe(const m2d_frame_t *frame) {
		if (fo_) {
			int luma_size = frame->width * frame->height;
			if (md5_) {
				md5_state_t md5;
				md5_byte_t digest[16];
				char txt[16 * 2 + 2];

				md5_init(&md5);
				write_cropping(frame, write_md5, (void *)&md5);
				md5_finish(&md5, digest);
				md5txt(digest, txt);
				fwrite(txt, 1, sizeof(txt), fo_);
			} else {
				write_cropping(frame, write_raw, (void *)fo_);
			}
			fflush(fo_);
			return luma_size;
		}
		return 0;
	}
	void BlameUser() {
		fprintf(stderr,
			"Usage:\n"
			"\th264dec [-b] [-d <dpb_size>] [-o|O ] <infile>\n"
			"\t\t-b: Bypass DPB\n"
			"\t\t-d <dpb_size>: Specify number of DPB frames -1, 1..16 (default: -1(auto))\n"
			"\t\t-o: RAW output\n"
			"\t\t-O: MD5 output\n"
			"\t\t-x: Mask SIGABRT on error."
			);
		exit(1);
	}
};

static int reread_file(void *var)
{
	input_data_t *d = (input_data_t *)var;
	if (d->pos_ < d->len_) {
		dec_bits_set_data(((h264d_context *)d->var_)->stream, d->data_ + d->pos_, d->len_);
		d->pos_ += d->len_;
		return 0;
	} else {
		return -1;
	}
}

#ifdef _M_IX86
#include <crtdbg.h>
#elif defined(__linux__)
#include <pthread.h>
#include <signal.h>
static void trap(int no)
{
	fprintf(stderr, "trap %d\n", no);
	exit(0);
}
#endif

int main(int argc, char *argv[])
{
	int err;

#ifdef _M_IX86
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_WNDW);
//	_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_WNDW);
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
#endif
	std::auto_ptr<h264d_context> h2d(new h264d_context);
	input_data_t data(argc, argv, (void *)h2d.get());
	if (data.len_ <= 0) {
		return -1;
	}
#ifdef __linux__
	if (data.force_exec_) {
		struct sigaction sa;
		memset(&sa, 0, sizeof(sa));
		sa.sa_handler = trap;
		sigaction(SIGABRT, &sa, 0);
		sigaction(SIGSEGV, &sa, 0);
	}
#endif
	err = h264d_init(h2d.get(), data.dpb_, 0, 0);
	if (err) {
		return err;
	}
	err = h264d_read_header(h2d.get(), data.data_, data.len_);
	data.pos_ = data.len_;
	if (err) {
		return err;
	}
	m2d_info_t info;
	h264d_get_info(h2d.get(), &info);
	fprintf(stderr,
		"length: %ld\n"
		"width x height x num: %d x %d x %d\n"
		"Context Size: %ld\n",
		data.len_, info.src_width, info.src_height, info.frame_num, sizeof(h264d_context));
	info.frame_num = (info.frame_num < 3 ? 3 : info.frame_num) + (data.dpb_ < 0 ? 16 : data.dpb_);
	Frames frm(info.src_width, info.src_height, info.frame_num);
	std::vector<uint8_t> second_frame(info.additional_size);
	err = h264d_set_frames(h2d.get(), info.frame_num, &frm.frame[0], &second_frame[0], info.additional_size);
	if (err) {
		return err;
	}
	dec_bits_set_callback(h2d.get()->stream, reread_file, &data);
	m2d_frame_t frame;
	for (int i = 0; i < INT_MAX; ++i) {
		err = h264d_decode_picture(h2d.get());
		if (err == -1) {
			break;
		}
		while (h264d_get_decoded_frame(h2d.get(), &frame, (data.dpb_ == 1))) {
			data.writeframe(&frame);
		}
		if (err < 0) {
			break;
		}
	}
	while (h264d_get_decoded_frame(h2d.get(), &frame, 1)) {
		data.writeframe(&frame);
	}

#ifdef _M_IX86
	assert(_CrtCheckMemory());
#endif
	return (data.force_exec_) ? 0 : ((err == -2) ? 0 : err);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cshtyp.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:18:35 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _CSHTYP_HXX
#define _CSHTYP_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwPaM;
class SwCntntFrm;
class SwLayoutFrm;

// eine Struktur fuer den SwPaM. In dieser stehen die Methoden-Pointer
// fuer das richtungsabhaengige Bewegen des Cursors.
struct SwMoveFnCollection;
typedef SwMoveFnCollection* SwMoveFn;

// Type-Definition fuer die CrsrShell
// Richtungsparameter fuer MovePage ( wird in SwCntntFrm initialisiert )
typedef SwLayoutFrm * (*SwWhichPage)( const SwLayoutFrm * );
typedef SwCntntFrm  * (*SwPosPage)( const SwLayoutFrm * );
extern SwWhichPage fnPagePrev, fnPageCurr, fnPageNext;
extern SwPosPage fnPageStart, fnPageEnd;

// Richtungsparameter fuer MovePara ( wird in SwPaM initialisiert )
typedef SwMoveFnCollection* SwPosPara;
typedef FASTBOOL (*SwWhichPara)( SwPaM&, SwPosPara );
extern SwWhichPara fnParaPrev, fnParaCurr, fnParaNext;
extern SwPosPara fnParaStart, fnParaEnd;

// Richtungsparameter fuer MoveSection
typedef SwMoveFnCollection* SwPosSection;
typedef FASTBOOL (*SwWhichSection)( SwPaM&, SwPosSection );
extern SwWhichSection fnSectionPrev, fnSectionCurr, fnSectionNext;
extern SwPosSection fnSectionStart, fnSectionEnd;

// Richtungsparameter fuer MoveTable
typedef SwMoveFnCollection* SwPosTable;
typedef FASTBOOL (*SwWhichTable)( SwPaM&, SwPosTable, FASTBOOL bInReadOnly );
extern SwWhichTable fnTablePrev, fnTableCurr, fnTableNext;
extern SwPosTable fnTableStart, fnTableEnd;

// Richtungsparameter fuer MoveColumn
typedef SwLayoutFrm * (*SwWhichColumn)( const SwLayoutFrm * );
typedef SwCntntFrm  * (*SwPosColumn)( const SwLayoutFrm * );
extern SwWhichColumn fnColumnPrev, fnColumnCurr, fnColumnNext;
extern SwPosColumn fnColumnStart, fnColumnEnd;

// Richtungsparameter fuer MoveRegion   (Bereiche!)
typedef SwMoveFnCollection* SwPosRegion;
typedef FASTBOOL (*SwWhichRegion)( SwPaM&, SwPosRegion, FASTBOOL bInReadOnly );
extern SwWhichRegion fnRegionPrev, fnRegionCurr, fnRegionNext, fnRegionCurrAndSkip;
extern SwPosRegion fnRegionStart, fnRegionEnd;

/*
 * folgende Kombinationen sind erlaubt:
 *  - suche einen im Body:                  -> FND_IN_BODY
 *  - suche alle im Body:                   -> FND_IN_BODYONLY | FND_IN_SELALL
 *  - suche in Selectionen: einen / alle    -> FND_IN_SEL  [ | FND_IN_SELALL ]
 *  - suche im nicht Body: einen / alle     -> FND_IN_OTHER [ | FND_IN_SELALL ]
 *  - suche ueberall alle:                  -> FND_IN_SELALL
 */
enum FindRanges
{
    FND_IN_BODY     = 0x00,     // suche "eins" mur im Body-Text
    FND_IN_OTHER    = 0x02,     // suche "alles" in Footer/Header/Fly...
    FND_IN_SEL      = 0x04,     // suche in Selectionen
    FND_IN_BODYONLY = 0x08,     // suche nur im Body - nur in Verbindung mit
                                // FND_IN_SELALL !!!
    FND_IN_SELALL   = 0x01      // - alle ( nur im nicht Body und Selectionen)
};

enum SwDocPositions
{
    DOCPOS_START,
    DOCPOS_CURR,
    DOCPOS_END,
    DOCPOS_OTHERSTART,
    DOCPOS_OTHEREND
};

SW_DLLPUBLIC SwWhichPara GetfnParaCurr(); //CHINA001
SW_DLLPUBLIC SwPosPara GetfnParaStart(); //CHINA001
SW_DLLPUBLIC SwPosPara GetfnParaEnd(); //CHINA001

SW_DLLPUBLIC SwWhichTable GetfnTablePrev(); //CHINA001
SW_DLLPUBLIC SwWhichTable GetfnTableCurr(); //CHINA001
SW_DLLPUBLIC SwPosTable GetfnTableStart(); //CHINA001
SW_DLLPUBLIC SwPosTable GetfnTableEnd(); //CHINA001

#endif  // _CSHTYP_HXX
<commit_msg>INTEGRATION: CWS swwarnings (1.7.242); FILE MERGED 2007/04/03 12:57:04 tl 1.7.242.2: #i69287# warning-free code 2007/02/22 15:05:35 tl 1.7.242.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: cshtyp.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 07:58:02 $
 *
 *  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
 *
 ************************************************************************/
#ifndef _CSHTYP_HXX
#define _CSHTYP_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SwPaM;
class SwCntntFrm;
class SwLayoutFrm;

// eine Struktur fuer den SwPaM. In dieser stehen die Methoden-Pointer
// fuer das richtungsabhaengige Bewegen des Cursors.
struct SwMoveFnCollection;
typedef SwMoveFnCollection* SwMoveFn;

// Type-Definition fuer die CrsrShell
// Richtungsparameter fuer MovePage ( wird in SwCntntFrm initialisiert )
typedef SwLayoutFrm * (*SwWhichPage)( const SwLayoutFrm * );
typedef SwCntntFrm  * (*SwPosPage)( const SwLayoutFrm * );
extern SwWhichPage fnPagePrev, fnPageCurr, fnPageNext;
extern SwPosPage fnPageStart, fnPageEnd;

// Richtungsparameter fuer MovePara ( wird in SwPaM initialisiert )
typedef SwMoveFnCollection* SwPosPara;
typedef BOOL (*SwWhichPara)( SwPaM&, SwPosPara );
extern SwWhichPara fnParaPrev, fnParaCurr, fnParaNext;
extern SwPosPara fnParaStart, fnParaEnd;

// Richtungsparameter fuer MoveSection
typedef SwMoveFnCollection* SwPosSection;
typedef BOOL (*SwWhichSection)( SwPaM&, SwPosSection );
extern SwWhichSection fnSectionPrev, fnSectionCurr, fnSectionNext;
extern SwPosSection fnSectionStart, fnSectionEnd;

// Richtungsparameter fuer MoveTable
typedef SwMoveFnCollection* SwPosTable;
typedef BOOL (*SwWhichTable)( SwPaM&, SwPosTable, BOOL bInReadOnly );
extern SwWhichTable fnTablePrev, fnTableCurr, fnTableNext;
extern SwPosTable fnTableStart, fnTableEnd;

// Richtungsparameter fuer MoveColumn
typedef SwLayoutFrm * (*SwWhichColumn)( const SwLayoutFrm * );
typedef SwCntntFrm  * (*SwPosColumn)( const SwLayoutFrm * );
extern SwWhichColumn fnColumnPrev, fnColumnCurr, fnColumnNext;
extern SwPosColumn fnColumnStart, fnColumnEnd;

// Richtungsparameter fuer MoveRegion   (Bereiche!)
typedef SwMoveFnCollection* SwPosRegion;
typedef BOOL (*SwWhichRegion)( SwPaM&, SwPosRegion, BOOL bInReadOnly );
extern SwWhichRegion fnRegionPrev, fnRegionCurr, fnRegionNext, fnRegionCurrAndSkip;
extern SwPosRegion fnRegionStart, fnRegionEnd;

/*
 * folgende Kombinationen sind erlaubt:
 *  - suche einen im Body:                  -> FND_IN_BODY
 *  - suche alle im Body:                   -> FND_IN_BODYONLY | FND_IN_SELALL
 *  - suche in Selectionen: einen / alle    -> FND_IN_SEL  [ | FND_IN_SELALL ]
 *  - suche im nicht Body: einen / alle     -> FND_IN_OTHER [ | FND_IN_SELALL ]
 *  - suche ueberall alle:                  -> FND_IN_SELALL
 */
enum FindRanges
{
    FND_IN_BODY     = 0x00,     // suche "eins" mur im Body-Text
    FND_IN_OTHER    = 0x02,     // suche "alles" in Footer/Header/Fly...
    FND_IN_SEL      = 0x04,     // suche in Selectionen
    FND_IN_BODYONLY = 0x08,     // suche nur im Body - nur in Verbindung mit
                                // FND_IN_SELALL !!!
    FND_IN_SELALL   = 0x01      // - alle ( nur im nicht Body und Selectionen)
};

enum SwDocPositions
{
    DOCPOS_START,
    DOCPOS_CURR,
    DOCPOS_END,
    DOCPOS_OTHERSTART,
    DOCPOS_OTHEREND
};

SW_DLLPUBLIC SwWhichPara GetfnParaCurr();
SW_DLLPUBLIC SwPosPara GetfnParaStart();
SW_DLLPUBLIC SwPosPara GetfnParaEnd();

SW_DLLPUBLIC SwWhichTable GetfnTablePrev();
SW_DLLPUBLIC SwWhichTable GetfnTableCurr();
SW_DLLPUBLIC SwPosTable GetfnTableStart();
SW_DLLPUBLIC SwPosTable GetfnTableEnd();

#endif  // _CSHTYP_HXX
<|endoftext|>


<commit_before>/*
 * Louvain.cpp
 *
 *  Created on: 25.02.2013
 *      Author: Matthias Stumpp
 */

#include "KERNIGHANLIN_Stumpp.h"

namespace NetworKit {

cluster CL0 = 0;
cluster CL1 = 1;

KERNIGHAN_LIN::KERNIGHAN_LIN() {
}

KERNIGHAN_LIN::~KERNIGHAN_LIN() {
}

// compute initial gain for all nodes in graph
void KERNIGHAN_LIN::computeGainAllNodes(Graph& g, Clustering& c, NodeMap<double>& gain) {
	g.forNodes([&](node u) {
		this->computeGainForNode(g, u, c, gain);
	});
}

// compute initial gain for a certain node
void KERNIGHAN_LIN::computeGainForNode(Graph& g, node u, Clustering& c, NodeMap<double>& gain) {
	double samePart = 0.0, otherPart = 0.0;
	g.forWeightedNeighborsOf(u, [&](node v, edgeweight w) {
		if (c.inSameCluster(u, v)) {
			samePart += w;
		} else {
			otherPart += w;
		}
	});
	gain[u] = otherPart-samePart;
}

Clustering KERNIGHAN_LIN::partition(Graph& g, Clustering& c) {

	EdgeCut edgeCut;
	double cut = edgeCut.getQuality(c, g);
	DEBUG("KL start with edge cut " << cut);

	// unmark all nodes
	// false -> not visited, true otherwise
	NodeMap<char> marker(g.numberOfNodes(), 'f');
	// keeps the gain
	NodeMap<double> gain(g.numberOfNodes(), 0.0);
	// compute initial gain for all nodes
	TRACE("KL: start computing initial gains");
	this->computeGainAllNodes(g, c, gain);
	TRACE("KL: have computed initial gains");

	bool improved = false;
	std::vector<count> numCl = c.clusterSizes();
	count min = *min_element(std::begin(numCl), std::end(numCl));
	for (count n=0; n<min; n++) {
		TRACE("KL iteration " << n);

		double currentBest = 0.0;
		node best_u = none;
		node best_v = none;
		auto computeBestGain = [&](node u, node v, edgeweight w) {
			// continue if nodes in same cluster
			// or u or v have been vistited already
			if (c.inSameCluster(u, v) || marker[u] == 't' || marker[v] == 't')
				return;

			// compute edge gain
			double runningGain = gain[u]+gain[v]-2*w;
			if (runningGain > currentBest) {
				improved = true;
				currentBest = runningGain;
				best_u = u;
				best_v = v;
			}
		};
		g.forWeightedEdges(computeBestGain);

		// no more improvements
		if (currentBest == 0.0)
			break;

		// otherwise, move nodes to other cluster
		if (c.clusterOf(best_u) == CL0) {
			c.moveToCluster(CL1, best_u);
			c.moveToCluster(CL0, best_v);
		} else {
			c.moveToCluster(CL0, best_u);
			c.moveToCluster(CL1, best_v);
		}
		// set marker to true, meaning node has been visited
		marker[best_u] = 't';
		marker[best_v] = 't';
		// recompute gain of nodes in neighbourhood of best two nodes
		this->computeGainForNode(g, best_u, c, gain);
		this->computeGainForNode(g, best_v, c, gain);
	}

	// either recursibely call or return
	if (improved)
		return this->partition(g, c);
	return c;
}

Clustering KERNIGHAN_LIN::run(Graph& graph) {
	Graph g = graph;

	// initialization
	// initial random partitioning
	ClusteringGenerator clusteringGenerator;
	TRACE("KL: start computing initial partition");
	Clustering clustering = clusteringGenerator.makeRandomClustering(g, 2);
	TRACE("KL: have computed initial partition, start KL pass");
	return this->partition(g, clustering);
}

std::string KERNIGHAN_LIN::toString() const {
	return "KERNIGHAN_LIN implementation by M. Stumpp";
}

} /* namespace NetworKit */
<commit_msg>Aenderungen am KL-Code von Hrn. Stumpp<commit_after>/*
 * Louvain.cpp
 *
 *  Created on: 25.02.2013
 *      Author: Matthias Stumpp
 */

#include "KERNIGHANLIN_Stumpp.h"

namespace NetworKit {

cluster CL0 = 0;
cluster CL1 = 1;

KERNIGHAN_LIN::KERNIGHAN_LIN() {
}

KERNIGHAN_LIN::~KERNIGHAN_LIN() {
}

// compute initial gain for all nodes in graph
void KERNIGHAN_LIN::computeGainAllNodes(Graph& g, Clustering& c, NodeMap<double>& gain) {
	g.forNodes([&](node u) {
		this->computeGainForNode(g, u, c, gain);
	});
}

// compute initial gain for a certain node
void KERNIGHAN_LIN::computeGainForNode(Graph& g, node u, Clustering& c, NodeMap<double>& gain) {
	double samePart = 0.0, otherPart = 0.0;
	g.forWeightedNeighborsOf(u, [&](node v, edgeweight w) {
		if (c.inSameCluster(u, v)) {
			samePart += w;
		} else {
			otherPart += w;
		}
	});
	gain[u] = otherPart-samePart;
}

Clustering KERNIGHAN_LIN::partition(Graph& g, Clustering& c) {

	EdgeCut edgeCut;
	double cut = edgeCut.getQuality(c, g);
	DEBUG("KL start with edge cut " << cut);

	// unmark all nodes
	// false -> not visited, true otherwise
	NodeMap<char> marker(g.numberOfNodes(), 'f');
	// keeps the gain
	NodeMap<double> gain(g.numberOfNodes(), 0.0);
	// compute initial gain for all nodes
	TRACE("KL: start computing initial gains");
	this->computeGainAllNodes(g, c, gain);
	TRACE("KL: have computed initial gains");

	bool improved = false;
	std::vector<count> numCl = c.clusterSizes();
	count min = *min_element(std::begin(numCl), std::end(numCl));
	for (count n=0; n<min; n++) {
		TRACE("KL iteration " << n);

		double currentBest = 0.0;
		node best_u = none;
		node best_v = none;
		auto computeBestGain = [&](node u, node v, edgeweight w) {
			// continue if nodes in same cluster
			// or u or v have been vistited already
			if (c.inSameCluster(u, v) || marker[u] == 't' || marker[v] == 't')
				return;

			// compute edge gain
			double runningGain = gain[u]+gain[v]-2*w;
			if (runningGain > currentBest) {
				improved = true;
				currentBest = runningGain;
				best_u = u;
				best_v = v;
			}
		};
		g.forNodePairs(computeBestGain);

		// no more improvements
		if (currentBest == 0.0)
			break;

		// otherwise, move nodes to other cluster
		if (c.clusterOf(best_u) == CL0) {
			c.moveToCluster(CL1, best_u);
			c.moveToCluster(CL0, best_v);
		} else {
			c.moveToCluster(CL0, best_u);
			c.moveToCluster(CL1, best_v);
		}
		// set marker to true, meaning node has been visited
		marker[best_u] = 't';
		marker[best_v] = 't';
		// recompute gain of nodes in neighbourhood of best two nodes
		// FIXME: iterate over neighbors of best_u and best_v
		this->computeGainForNode(g, best_u, c, gain);
		this->computeGainForNode(g, best_v, c, gain);
	}

	// either recursibely call or return
	if (improved)
		return this->partition(g, c);
	return c;
}

Clustering KERNIGHAN_LIN::run(Graph& graph) {
	Graph g = graph;

	// initialization
	// initial random partitioning
	ClusteringGenerator clusteringGenerator;
	TRACE("KL: start computing initial partition");
	Clustering clustering = clusteringGenerator.makeRandomClustering(g, 2);
	TRACE("KL: have computed initial partition, start KL pass");
	return this->partition(g, clustering);
}

std::string KERNIGHAN_LIN::toString() const {
	return "KERNIGHAN_LIN implementation by M. Stumpp";
}

} /* namespace NetworKit */
<|endoftext|>


<commit_before>#include <common/buffer.h>
#include <common/test.h>

#define	FILL_BYTE	(0xa5)
#define	FILL_NUMBER	(1024)
#define	FILL_LENGTH	(242)

int
main(void)
{
	TestGroup g("/test/buffer/cut1", "Buffer::cut #1");

	Buffer big;

	big.append("Hello, ");
	size_t headerlen = big.length();

	uint8_t fill[FILL_LENGTH];
	unsigned i;
	for (i = 0; i < sizeof fill; i++) {
		fill[i] = FILL_BYTE;
	}

	for (i = 0; i < FILL_NUMBER; i++) {
		big.append(fill, sizeof fill);
	}

	big.append("world!\n");

	{
		Test _(g, "Cut fill bytes.");

		Buffer small(big);
		small.cut(headerlen, FILL_NUMBER * FILL_LENGTH);
		if (small.equal("Hello, world!\n"))
			_.pass();
	}

	{
		Test _(g, "Proxy skip and trim.");

		big.cut(0, headerlen);
		big.cut(FILL_NUMBER * FILL_LENGTH, big.length() - (FILL_NUMBER * FILL_LENGTH));
		if (big.length() == FILL_NUMBER * FILL_LENGTH)
			_.pass();
	}

	{
		Test _(g, "Correct fill byte checksum.");

		uint64_t sum = 0;
		while (!big.empty()) {
			sum += big.peek();
			big.skip(1);
		}

		sum /= FILL_LENGTH * FILL_NUMBER * FILL_BYTE;
		if (sum == 1)
			_.pass();
	}

	return (0);
}
<commit_msg>Use lots of different fill lengths.<commit_after>#include <common/buffer.h>
#include <common/test.h>

#define	FILL_BYTE	(0xa5)
#define	FILL_NUMBER	(1024)
#define	FILL_LENGTH	(242)

int
main(void)
{
	TestGroup g("/test/buffer/cut1", "Buffer::cut #1");

	unsigned n;
	for (n = 1; n <= FILL_LENGTH; n++) {
		Buffer big;

		big.append("Hello, ");
		size_t headerlen = big.length();

		uint8_t fill[n];
		unsigned i;
		for (i = 0; i < sizeof fill; i++) {
			fill[i] = FILL_BYTE;
		}

		for (i = 0; i < FILL_NUMBER; i++) {
			big.append(fill, sizeof fill);
		}

		big.append("world!\n");

		{
			Test _(g, "Cut fill bytes.");

			Buffer small(big);
			small.cut(headerlen, FILL_NUMBER * n);
			if (small.equal("Hello, world!\n"))
				_.pass();
		}

		{
			Test _(g, "Proxy skip and trim.");

			big.cut(0, headerlen);
			big.cut(FILL_NUMBER * n, big.length() - (FILL_NUMBER * n));
			if (big.length() == FILL_NUMBER * n)
				_.pass();
		}

		{
			Test _(g, "Correct fill byte checksum.");

			uint64_t sum = 0;
			while (!big.empty()) {
				sum += big.peek();
				big.skip(1);
			}

			sum /= FILL_NUMBER * n * FILL_BYTE;
			if (sum == 1)
				_.pass();
		}
	}

	return (0);
}
<|endoftext|>


<commit_before>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "effectmanager.h"

#include <gst/interfaces/propertyprobe.h>
#include "backend.h"
#include "gsthelper.h"

/*
 * This class manages the list of currently
 * available audio effects.
 */

namespace Phonon
{
namespace Gstreamer
{

EffectInfo::EffectInfo(const QString &name, const QString &description,
                       const QString &author)
        : m_name(name)
        , m_description(description)
        , m_author(author) {}

EffectManager::EffectManager(Backend *backend)
        : QObject(backend)
        , m_backend(backend)
{
    GList *factoryList = gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
    QString name;
    QString klass;
    QString description;
    QString author;
    for (GList* iter = g_list_first(factoryList); iter != NULL ; iter = g_list_next(iter)) {
        GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
        klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));
        if (klass == QLatin1String("Filter/Effect/Audio")) {
            name = GST_PLUGIN_FEATURE_NAME(feature);

            // These plugins simply make no sense to the frontend:
            // "audiorate" Should be internal
            // "volume" not needed
            // "equalizer-nbands" not really useful at the moment

            // These plugins simply don't work or have major stability issues:
            // "iir" Does not seem to do much at the moment
            // "audioinvert" Only works for some streams, should be invesigated
            // "lpwsinc" Crashes for large values of filter kernel
            // "name" Crashes for large values of filter kernel

            // Seems to be working, but not well tested:
            // name == "rglimiter" Seems functional
            // name == "rgvolume" Seems to be working

            QString pluginString = qgetenv("PHONON_GST_ALL_EFFECTS");
            bool acceptAll = pluginString.toInt();

            if (acceptAll
                // Plugins that have been accepted so far
                 || name == QLatin1String("audiopanorama")
                 || name == QLatin1String("audioamplify")
                 || name == QLatin1String("audiodynamic")
                 || name == QLatin1String("equalizer-10bands")
                 || name == QLatin1String("speed"))
                {
                    description = gst_element_factory_get_description (GST_ELEMENT_FACTORY(feature));
                    author = gst_element_factory_get_author (GST_ELEMENT_FACTORY(feature));
                    EffectInfo *effect = new EffectInfo(name, description, author);
                    m_audioEffectList.append(effect);

#ifdef __GNUC__
#warning TODO - get rid of equalizer name mapping (also see audioeffect.cpp)
#endif
                    // Map the GStreamer name to the name used by Xine, to allow
                    // API consumers that think KEqualizer is a persistant name
                    // to have a working equalizer with GStreamer too (e.g. Amarok).
                    if (name == QLatin1String("equalizer-10bands")) {
                        m_audioEffectList.append(new EffectInfo(
                                                     QLatin1String("KEqualizer"),
                                                     QLatin1String("Compatibility effect. Do not use in new software!"),
                                                     author));
                    }
            }
        }
    }
    g_list_free(factoryList);
}

EffectManager::~EffectManager()
{
    qDeleteAll(m_audioEffectList);
    m_audioEffectList.clear();
}

/**
  * Returns a list of available audio effects
  */
const QList<EffectInfo*> EffectManager::audioEffects() const
{
    return m_audioEffectList;
}

}
}
<commit_msg>Port effectmanager.cpp to GStreamer 1.0<commit_after>/*  This file is part of the KDE project.

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    This library is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 2.1 or 3 of the License.

    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, see <http://www.gnu.org/licenses/>.
*/

#include "effectmanager.h"
#include "phonon-config-gstreamer.h"
#include <gst/gst.h>

#include "backend.h"
#include "gsthelper.h"

/*
 * This class manages the list of currently
 * available audio effects.
 */

namespace Phonon
{
namespace Gstreamer
{

EffectInfo::EffectInfo(const QString &name, const QString &description,
                       const QString &author)
        : m_name(name)
        , m_description(description)
        , m_author(author) {}

EffectManager::EffectManager(Backend *backend)
        : QObject(backend)
        , m_backend(backend)
{
    GList *factoryList =
        #if GST_VERSION < GST_VERSION_CHECK (1,0,0,0)
            gst_registry_get_feature_list(gst_registry_get_default (), GST_TYPE_ELEMENT_FACTORY);
        #else
            gst_registry_get_feature_list(gst_registry_get (), GST_TYPE_ELEMENT_FACTORY);
        #endif
    QString name;
    QString klass;
    QString description;
    QString author;
    for (GList* iter = g_list_first(factoryList); iter != NULL ; iter = g_list_next(iter)) {
        GstPluginFeature *feature = GST_PLUGIN_FEATURE(iter->data);
        klass = gst_element_factory_get_klass(GST_ELEMENT_FACTORY(feature));
        if (klass == QLatin1String("Filter/Effect/Audio")) {
            name = GST_OBJECT_NAME(feature);

            // These plugins simply make no sense to the frontend:
            // "audiorate" Should be internal
            // "volume" not needed
            // "equalizer-nbands" not really useful at the moment

            // These plugins simply don't work or have major stability issues:
            // "iir" Does not seem to do much at the moment
            // "audioinvert" Only works for some streams, should be invesigated
            // "lpwsinc" Crashes for large values of filter kernel
            // "name" Crashes for large values of filter kernel

            // Seems to be working, but not well tested:
            // name == "rglimiter" Seems functional
            // name == "rgvolume" Seems to be working

            QString pluginString = qgetenv("PHONON_GST_ALL_EFFECTS");
            bool acceptAll = pluginString.toInt();

            if (acceptAll
                // Plugins that have been accepted so far
                 || name == QLatin1String("audiopanorama")
                 || name == QLatin1String("audioamplify")
                 || name == QLatin1String("audiodynamic")
                 || name == QLatin1String("equalizer-10bands")
                 || name == QLatin1String("speed"))
                {
                    description = gst_element_factory_get_description (GST_ELEMENT_FACTORY(feature));
                    author = gst_element_factory_get_author (GST_ELEMENT_FACTORY(feature));
                    EffectInfo *effect = new EffectInfo(name, description, author);
                    m_audioEffectList.append(effect);

#ifdef __GNUC__
#warning TODO - get rid of equalizer name mapping (also see audioeffect.cpp)
#endif
                    // Map the GStreamer name to the name used by Xine, to allow
                    // API consumers that think KEqualizer is a persistant name
                    // to have a working equalizer with GStreamer too (e.g. Amarok).
                    if (name == QLatin1String("equalizer-10bands")) {
                        m_audioEffectList.append(new EffectInfo(
                                                     QLatin1String("KEqualizer"),
                                                     QLatin1String("Compatibility effect. Do not use in new software!"),
                                                     author));
                    }
            }
        }
    }
    g_list_free(factoryList);
}

EffectManager::~EffectManager()
{
    qDeleteAll(m_audioEffectList);
    m_audioEffectList.clear();
}

/**
  * Returns a list of available audio effects
  */
const QList<EffectInfo*> EffectManager::audioEffects() const
{
    return m_audioEffectList;
}

}
}
<|endoftext|>