<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);

        // Inside the grid
        if (box.intersects(ray.getOrigin()))
        {
            return ray.getOrigin();
        }

        // Outside the grid, ray intersects it
        std::pair<bool, Real> intersection = ray.intersects(box);
        if (intersection.first)
        {
            Vector3 direction = ray.getDirection().normalisedCopy();
            return ray.getOrigin() + direction * intersection.second;
        }

        // Outside the grid, ray doesn't intersect it
        return ray.getOrigin();
    }

    //-----------------------------------------------------------------------

    Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
        Vector3 direction = ray.getDirection().normalisedCopy();
        Vector3 invertedDirection = (Real)-1.0 * direction;
        Vector3 origin = ray.getOrigin() + direction * box.getSize().length();

        Ray inverted(origin, invertedDirection);
        std::pair<bool, Real> intersection = inverted.intersects(box);
        if (intersection.first)
        {
            return origin + invertedDirection * intersection.second;
        }
        return ray.getOrigin() + direction * maxDistance;
    }

    //-----------------------------------------------------------------------

    GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
        mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
    {
    }

    //-----------------------------------------------------------------------

    GridSource::~GridSource(void)
    {
    }

    //-----------------------------------------------------------------------

    Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Vector3 normal;
        if (mTrilinearGradient)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Vector3 f000 = getGradient(x0, y0, z0);
            Vector3 f100 = getGradient(x1, y0, z0);
            Vector3 f010 = getGradient(x0, y1, z0);
            Vector3 f001 = getGradient(x0, y0, z1);
            Vector3 f101 = getGradient(x1, y0, z1);
            Vector3 f011 = getGradient(x0, y1, z1);
            Vector3 f110 = getGradient(x1, y1, z0);
            Vector3 f111 = getGradient(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            normal = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

            normal *= (Real)-1.0;
        }
        else
        {
            normal = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
            normal *= (Real)-1.0;
        }
        return Vector4(normal.x, normal.y, normal.z, getValue(position));
    }

    //-----------------------------------------------------------------------

    Real GridSource::getValue(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Real value;
        if (mTrilinearValue)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Real f000 = getVolumeGridValue(x0, y0, z0);
            Real f100 = getVolumeGridValue(x1, y0, z0);
            Real f010 = getVolumeGridValue(x0, y1, z0);
            Real f001 = getVolumeGridValue(x0, y0, z1);
            Real f101 = getVolumeGridValue(x1, y0, z1);
            Real f011 = getVolumeGridValue(x0, y1, z1);
            Real f110 = getVolumeGridValue(x1, y1, z0);
            Real f111 = getVolumeGridValue(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            value = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

        }
        else
        {
            // Nearest neighbour else
            size_t x = (size_t)(scaledPosition.x + (Real)0.5);
            size_t y = (size_t)(scaledPosition.y + (Real)0.5);
            size_t z = (size_t)(scaledPosition.z + (Real)0.5);
            value = (Real)getVolumeGridValue(x, y, z);
        }
        return value;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getWidth(void) const
    {
        return mWidth;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getHeight(void) const
    {
        return mHeight;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getDepth(void) const
    {
        return mDepth;
    }

    //-----------------------------------------------------------------------

    void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 &center, Real radius)
    {
        Real worldWidthScale = (Real)1.0 / mPosXScale;
        Real worldHeightScale = (Real)1.0 / mPosYScale;
        Real worldDepthScale = (Real)1.0 / mPosZScale;

        operation->setSourceA(this);
        operation->setSourceB(source);
        // No need for trilineaer interpolation here as we iterate over the
        // cells anyway.
        bool oldTrilinearValue = mTrilinearValue;
        mTrilinearValue = false;
        float value;
        int x, y;
        Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
        int xStart = Math::Clamp((size_t)(scaledCenter.x - radius * mPosXScale), (size_t)0, mWidth);
        int xEnd = Math::Clamp((size_t)(scaledCenter.x + radius * mPosXScale), (size_t)0, mWidth);
        int yStart = Math::Clamp((size_t)(scaledCenter.y - radius * mPosYScale), (size_t)0, mHeight);
        int yEnd = Math::Clamp((size_t)(scaledCenter.y + radius * mPosYScale), (size_t)0, mHeight);
        int zStart = Math::Clamp((size_t)(scaledCenter.z - radius * mPosZScale), (size_t)0, mDepth);
        int zEnd = Math::Clamp((size_t)(scaledCenter.z + radius * mPosZScale), (size_t)0, mDepth);
        Vector3 pos;
        for (int z = zStart; z < zEnd; ++z)
        {
            for (y = yStart; y < yEnd; ++y)
            {
                for (x = xStart; x < xEnd; ++x)
                {
                    pos.x = x * worldWidthScale;
                    pos.y =  y * worldHeightScale;
                    pos.z = z * worldDepthScale;
                    value = operation->getValue(pos);
                    setVolumeGridValue(x, y, z, value);
                }
            }
        }

        mTrilinearValue = oldTrilinearValue;
    }

    //-----------------------------------------------------------------------

    Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
    {
        return mVolumeSpaceToWorldSpaceFactor;
    }
}
}<commit_msg>Volume Rendering: Better variable name<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

Copyright (c) 2000-2013 Torus Knot Software Ltd
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 "OgreVolumeGridSource.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreVector3.h"
#include "OgreColourValue.h"
#include "OgreMemoryAllocatorConfig.h"
#include "OgreLogManager.h"
#include "OgreTimer.h"

namespace Ogre {
namespace Volume {

    Vector3 GridSource::getIntersectionStart(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);

        // Inside the grid
        if (box.intersects(ray.getOrigin()))
        {
            return ray.getOrigin();
        }

        // Outside the grid, ray intersects it
        std::pair<bool, Real> intersection = ray.intersects(box);
        if (intersection.first)
        {
            Vector3 direction = ray.getDirection().normalisedCopy();
            return ray.getOrigin() + direction * intersection.second;
        }

        // Outside the grid, ray doesn't intersect it
        return ray.getOrigin();
    }

    //-----------------------------------------------------------------------

    Vector3 GridSource::getIntersectionEnd(const Ray &ray, Real maxDistance) const
    {
        AxisAlignedBox box((Real)0, (Real)0, (Real)0, (Real)mWidth / mPosXScale, (Real)mHeight / mPosYScale, (Real)mDepth / mPosZScale);
        Vector3 direction = ray.getDirection().normalisedCopy();
        Vector3 invertedDirection = (Real)-1.0 * direction;
        Vector3 origin = ray.getOrigin() + direction * box.getSize().length();

        Ray inverted(origin, invertedDirection);
        std::pair<bool, Real> intersection = inverted.intersects(box);
        if (intersection.first)
        {
            return origin + invertedDirection * intersection.second;
        }
        return ray.getOrigin() + direction * maxDistance;
    }

    //-----------------------------------------------------------------------

    GridSource::GridSource(bool trilinearValue, bool trilinearGradient, bool sobelGradient) :
        mTrilinearValue(trilinearValue), mTrilinearGradient(trilinearGradient), mSobelGradient(sobelGradient)
    {
    }

    //-----------------------------------------------------------------------

    GridSource::~GridSource(void)
    {
    }

    //-----------------------------------------------------------------------

    Vector4 GridSource::getValueAndGradient(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Vector3 gradient;
        if (mTrilinearGradient)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Vector3 f000 = getGradient(x0, y0, z0);
            Vector3 f100 = getGradient(x1, y0, z0);
            Vector3 f010 = getGradient(x0, y1, z0);
            Vector3 f001 = getGradient(x0, y0, z1);
            Vector3 f101 = getGradient(x1, y0, z1);
            Vector3 f011 = getGradient(x0, y1, z1);
            Vector3 f110 = getGradient(x1, y1, z0);
            Vector3 f111 = getGradient(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            gradient = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

            gradient *= (Real)-1.0;
        }
        else
        {
            gradient = getGradient((size_t)(scaledPosition.x + (Real)0.5), (size_t)(scaledPosition.y + (Real)0.5), (size_t)(scaledPosition.z + (Real)0.5));
            gradient *= (Real)-1.0;
        }
        return Vector4(gradient.x, gradient.y, gradient.z, getValue(position));
    }

    //-----------------------------------------------------------------------

    Real GridSource::getValue(const Vector3 &position) const
    {
        Vector3 scaledPosition(position.x * mPosXScale, position.y * mPosYScale, position.z * mPosZScale);
        Real value;
        if (mTrilinearValue)
        {
            size_t x0 = (size_t)scaledPosition.x;
            size_t x1 = (size_t)ceil(scaledPosition.x);
            size_t y0 = (size_t)scaledPosition.y;
            size_t y1 = (size_t)ceil(scaledPosition.y);
            size_t z0 = (size_t)scaledPosition.z;
            size_t z1 = (size_t)ceil(scaledPosition.z);

            Real dX = scaledPosition.x - (Real)x0;
            Real dY = scaledPosition.y - (Real)y0;
            Real dZ = scaledPosition.z - (Real)z0;

            Real f000 = getVolumeGridValue(x0, y0, z0);
            Real f100 = getVolumeGridValue(x1, y0, z0);
            Real f010 = getVolumeGridValue(x0, y1, z0);
            Real f001 = getVolumeGridValue(x0, y0, z1);
            Real f101 = getVolumeGridValue(x1, y0, z1);
            Real f011 = getVolumeGridValue(x0, y1, z1);
            Real f110 = getVolumeGridValue(x1, y1, z0);
            Real f111 = getVolumeGridValue(x1, y1, z1);

            Real oneMinX = (Real)1.0 - dX;
            Real oneMinY = (Real)1.0 - dY;
            Real oneMinZ = (Real)1.0 - dZ;
            Real oneMinXoneMinY = oneMinX * oneMinY;
            Real dXOneMinY = dX * oneMinY;

            value = oneMinZ * (f000 * oneMinXoneMinY
                + f100 * dXOneMinY
                + f010 * oneMinX * dY)
                + dZ * (f001 * oneMinXoneMinY
                + f101 * dXOneMinY
                + f011 * oneMinX * dY)
                + dX * dY * (f110 * oneMinZ
                + f111 * dZ);

        }
        else
        {
            // Nearest neighbour else
            size_t x = (size_t)(scaledPosition.x + (Real)0.5);
            size_t y = (size_t)(scaledPosition.y + (Real)0.5);
            size_t z = (size_t)(scaledPosition.z + (Real)0.5);
            value = (Real)getVolumeGridValue(x, y, z);
        }
        return value;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getWidth(void) const
    {
        return mWidth;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getHeight(void) const
    {
        return mHeight;
    }

    //-----------------------------------------------------------------------

    size_t GridSource::getDepth(void) const
    {
        return mDepth;
    }

    //-----------------------------------------------------------------------

    void GridSource::combineWithSource(CSGOperationSource *operation, Source *source, const Vector3 &center, Real radius)
    {
        Real worldWidthScale = (Real)1.0 / mPosXScale;
        Real worldHeightScale = (Real)1.0 / mPosYScale;
        Real worldDepthScale = (Real)1.0 / mPosZScale;

        operation->setSourceA(this);
        operation->setSourceB(source);
        // No need for trilineaer interpolation here as we iterate over the
        // cells anyway.
        bool oldTrilinearValue = mTrilinearValue;
        mTrilinearValue = false;
        float value;
        int x, y;
        Vector3 scaledCenter(center.x * mPosXScale, center.y * mPosYScale, center.z * mPosZScale);
        int xStart = Math::Clamp((size_t)(scaledCenter.x - radius * mPosXScale), (size_t)0, mWidth);
        int xEnd = Math::Clamp((size_t)(scaledCenter.x + radius * mPosXScale), (size_t)0, mWidth);
        int yStart = Math::Clamp((size_t)(scaledCenter.y - radius * mPosYScale), (size_t)0, mHeight);
        int yEnd = Math::Clamp((size_t)(scaledCenter.y + radius * mPosYScale), (size_t)0, mHeight);
        int zStart = Math::Clamp((size_t)(scaledCenter.z - radius * mPosZScale), (size_t)0, mDepth);
        int zEnd = Math::Clamp((size_t)(scaledCenter.z + radius * mPosZScale), (size_t)0, mDepth);
        Vector3 pos;
        for (int z = zStart; z < zEnd; ++z)
        {
            for (y = yStart; y < yEnd; ++y)
            {
                for (x = xStart; x < xEnd; ++x)
                {
                    pos.x = x * worldWidthScale;
                    pos.y =  y * worldHeightScale;
                    pos.z = z * worldDepthScale;
                    value = operation->getValue(pos);
                    setVolumeGridValue(x, y, z, value);
                }
            }
        }

        mTrilinearValue = oldTrilinearValue;
    }

    //-----------------------------------------------------------------------

    Real GridSource::getVolumeSpaceToWorldSpaceFactor(void) const
    {
        return mVolumeSpaceToWorldSpaceFactor;
    }
}
}<|endoftext|>


<commit_before>#include "../base/SRC_FIRST.hpp"
#include "overlay_element.hpp"

namespace graphics
{
  OverlayElement::~OverlayElement()
  {}

  OverlayElement::Params::Params()
    : m_pivot(0, 0),
      m_position(EPosAboveRight),
      m_depth(maxDepth),
      m_userInfo()
  {}

  OverlayElement::OverlayElement(Params const & p)
    : m_pivot(p.m_pivot),
      m_position(p.m_position),
      m_depth(p.m_depth),
      m_isNeedRedraw(true),
      m_isFrozen(false),
      m_isVisible(true),
      m_isValid(true),
      m_isDirtyRect(true),
      m_isDirtyLayout(true),
      m_isDirtyRoughRect(true),
      m_userInfo(p.m_userInfo)
  {}

  m2::PointD const OverlayElement::computeTopLeft(m2::PointD const & sz,
                                                  m2::PointD const & pv,
                                                  EPosition pos)
  {
    m2::PointD res;

    if (pos & EPosLeft)
      res.x = pv.x - sz.x;
    else if (pos & EPosRight)
      res.x = pv.x;
    else
      res.x = pv.x - sz.x / 2;

    if (pos & EPosAbove)
      res.y = pv.y - sz.y;
    else if (pos & EPosUnder)
      res.y = pv.y;
    else
      res.y = pv.y - sz.y / 2;

    return res;
  }

  void OverlayElement::offset(m2::PointD const & offs)
  {
    setPivot(pivot() + offs);
    setIsDirtyRect(true);
  }

  m2::PointD const & OverlayElement::pivot() const
  {
    return m_pivot;
  }

  void OverlayElement::setPivot(m2::PointD const & pivot)
  {
    m_pivot = pivot;
    setIsDirtyRect(true);
  }

  graphics::EPosition OverlayElement::position() const
  {
    return m_position;
  }

  void OverlayElement::setPosition(graphics::EPosition pos)
  {
    m_position = pos;
    setIsDirtyRect(true);
  }

  double OverlayElement::depth() const
  {
    return m_depth;
  }

  void OverlayElement::setDepth(double depth)
  {
    m_depth = depth;
  }

  bool OverlayElement::isFrozen() const
  {
    return m_isFrozen;
  }

  void OverlayElement::setIsFrozen(bool flag)
  {
    m_isFrozen = flag;
  }

  bool OverlayElement::isNeedRedraw() const
  {
    return m_isNeedRedraw;
  }

  void OverlayElement::setIsNeedRedraw(bool flag)
  {
    m_isNeedRedraw = flag;
  }

  bool OverlayElement::isVisible() const
  {
    return m_isVisible;
  }

  void OverlayElement::setIsVisible(bool flag)
  {
    m_isVisible = flag;
  }

  bool OverlayElement::isDirtyLayout() const
  {
   return m_isDirtyLayout;
  }

  void OverlayElement::setIsDirtyLayout(bool flag) const
  {
    m_isDirtyLayout = flag;
    if (flag)
      setIsDirtyRect(true);
  }

  bool OverlayElement::isDirtyRect() const
  {
    return m_isDirtyRect;
  }

  void OverlayElement::setIsDirtyRect(bool flag) const
  {
    if (flag)
      m_isDirtyRoughRect = true;
    m_isDirtyRect = flag;
  }

  m2::RectD const & OverlayElement::roughBoundRect() const
  {
    if (m_isDirtyRoughRect)
    {
      for (int i = 0; i < boundRects().size(); ++i)
        if (i == 0)
          m_roughBoundRect = boundRects()[i].GetGlobalRect();
        else
          m_roughBoundRect.Add(boundRects()[i].GetGlobalRect());

      m_isDirtyRoughRect = false;
    }
    return m_roughBoundRect;
  }

  bool OverlayElement::hitTest(m2::PointD const & pt) const
  {
    vector<m2::AnyRectD> const & rects = boundRects();

    for (vector<m2::AnyRectD>::const_iterator it = rects.begin(); it != rects.end(); ++it)
      if (it->IsPointInside(pt))
        return true;

    return false;
  }

  bool OverlayElement::isValid() const
  {
    return m_isValid;
  }

  void OverlayElement::setIsValid(bool flag)
  {
    m_isValid = flag;
  }

  bool OverlayElement::roughHitTest(m2::PointD const & pt) const
  {
    return roughBoundRect().IsPointInside(pt);
  }

  OverlayElement::UserInfo const & OverlayElement::userInfo() const
  {
    return m_userInfo;
  }

  m2::PointD const OverlayElement::point(EPosition pos) const
  {
    /// @todo It's better to call roughBoundRect(), or place ASSERT(!m_isDirtyRoughRect, ()) here.
    /// In general there is no need to store m_roughBoundRect at all.
    /// It's calculating time is fast, because elements already cache vector<m2::AnyRectD>.

    m2::PointD res = m_roughBoundRect.Center();

    if (pos & EPosLeft)
      res.x = m_roughBoundRect.minX();
    if (pos & EPosRight)
      res.x = m_roughBoundRect.maxX();

    if (pos & EPosAbove)
      res.y = m_roughBoundRect.minY();
    if (pos & EPosUnder)
      res.y = m_roughBoundRect.maxY();

    return res;
  }

  bool OverlayElement::hasSharpGeometry() const
  {
    return false;
  }

  double OverlayElement::priority() const
  {
    return m_depth;
  }

}
<commit_msg>default value for OverlayElement was made zero.<commit_after>#include "../base/SRC_FIRST.hpp"
#include "overlay_element.hpp"

namespace graphics
{
  OverlayElement::~OverlayElement()
  {}

  OverlayElement::Params::Params()
    : m_pivot(0, 0),
      m_position(EPosAboveRight),
      m_depth(0),
      m_userInfo()
  {}

  OverlayElement::OverlayElement(Params const & p)
    : m_pivot(p.m_pivot),
      m_position(p.m_position),
      m_depth(p.m_depth),
      m_isNeedRedraw(true),
      m_isFrozen(false),
      m_isVisible(true),
      m_isValid(true),
      m_isDirtyRect(true),
      m_isDirtyLayout(true),
      m_isDirtyRoughRect(true),
      m_userInfo(p.m_userInfo)
  {}

  m2::PointD const OverlayElement::computeTopLeft(m2::PointD const & sz,
                                                  m2::PointD const & pv,
                                                  EPosition pos)
  {
    m2::PointD res;

    if (pos & EPosLeft)
      res.x = pv.x - sz.x;
    else if (pos & EPosRight)
      res.x = pv.x;
    else
      res.x = pv.x - sz.x / 2;

    if (pos & EPosAbove)
      res.y = pv.y - sz.y;
    else if (pos & EPosUnder)
      res.y = pv.y;
    else
      res.y = pv.y - sz.y / 2;

    return res;
  }

  void OverlayElement::offset(m2::PointD const & offs)
  {
    setPivot(pivot() + offs);
    setIsDirtyRect(true);
  }

  m2::PointD const & OverlayElement::pivot() const
  {
    return m_pivot;
  }

  void OverlayElement::setPivot(m2::PointD const & pivot)
  {
    m_pivot = pivot;
    setIsDirtyRect(true);
  }

  graphics::EPosition OverlayElement::position() const
  {
    return m_position;
  }

  void OverlayElement::setPosition(graphics::EPosition pos)
  {
    m_position = pos;
    setIsDirtyRect(true);
  }

  double OverlayElement::depth() const
  {
    return m_depth;
  }

  void OverlayElement::setDepth(double depth)
  {
    m_depth = depth;
  }

  bool OverlayElement::isFrozen() const
  {
    return m_isFrozen;
  }

  void OverlayElement::setIsFrozen(bool flag)
  {
    m_isFrozen = flag;
  }

  bool OverlayElement::isNeedRedraw() const
  {
    return m_isNeedRedraw;
  }

  void OverlayElement::setIsNeedRedraw(bool flag)
  {
    m_isNeedRedraw = flag;
  }

  bool OverlayElement::isVisible() const
  {
    return m_isVisible;
  }

  void OverlayElement::setIsVisible(bool flag)
  {
    m_isVisible = flag;
  }

  bool OverlayElement::isDirtyLayout() const
  {
   return m_isDirtyLayout;
  }

  void OverlayElement::setIsDirtyLayout(bool flag) const
  {
    m_isDirtyLayout = flag;
    if (flag)
      setIsDirtyRect(true);
  }

  bool OverlayElement::isDirtyRect() const
  {
    return m_isDirtyRect;
  }

  void OverlayElement::setIsDirtyRect(bool flag) const
  {
    if (flag)
      m_isDirtyRoughRect = true;
    m_isDirtyRect = flag;
  }

  m2::RectD const & OverlayElement::roughBoundRect() const
  {
    if (m_isDirtyRoughRect)
    {
      for (int i = 0; i < boundRects().size(); ++i)
        if (i == 0)
          m_roughBoundRect = boundRects()[i].GetGlobalRect();
        else
          m_roughBoundRect.Add(boundRects()[i].GetGlobalRect());

      m_isDirtyRoughRect = false;
    }
    return m_roughBoundRect;
  }

  bool OverlayElement::hitTest(m2::PointD const & pt) const
  {
    vector<m2::AnyRectD> const & rects = boundRects();

    for (vector<m2::AnyRectD>::const_iterator it = rects.begin(); it != rects.end(); ++it)
      if (it->IsPointInside(pt))
        return true;

    return false;
  }

  bool OverlayElement::isValid() const
  {
    return m_isValid;
  }

  void OverlayElement::setIsValid(bool flag)
  {
    m_isValid = flag;
  }

  bool OverlayElement::roughHitTest(m2::PointD const & pt) const
  {
    return roughBoundRect().IsPointInside(pt);
  }

  OverlayElement::UserInfo const & OverlayElement::userInfo() const
  {
    return m_userInfo;
  }

  m2::PointD const OverlayElement::point(EPosition pos) const
  {
    /// @todo It's better to call roughBoundRect(), or place ASSERT(!m_isDirtyRoughRect, ()) here.
    /// In general there is no need to store m_roughBoundRect at all.
    /// It's calculating time is fast, because elements already cache vector<m2::AnyRectD>.

    m2::PointD res = m_roughBoundRect.Center();

    if (pos & EPosLeft)
      res.x = m_roughBoundRect.minX();
    if (pos & EPosRight)
      res.x = m_roughBoundRect.maxX();

    if (pos & EPosAbove)
      res.y = m_roughBoundRect.minY();
    if (pos & EPosUnder)
      res.y = m_roughBoundRect.maxY();

    return res;
  }

  bool OverlayElement::hasSharpGeometry() const
  {
    return false;
  }

  double OverlayElement::priority() const
  {
    return m_depth;
  }

}
<|endoftext|>


<commit_before>/*
 * tests/wobbly_test.cpp
 *
 * Tests for the "wobbly" spring model.
 *
 * See LICENCE.md for Copyright information.
 */
#include <array>                        // for array
#include <functional>                   // for function, __base
#include <memory>                       // for unique_ptr
#include <sstream>                      // for char_traits, etc
#include <type_traits>                  // for move

#include <stdlib.h>                     // for exit

#include <boost/test/utils/wrap_stringstream.hpp>  // for operator<<

#include <gmock/gmock-matchers.h>       // for EXPECT_THAT, etc
#include <gtest/gtest-death-test.h>     // for DeathTest, ExitedWithCode, etc
#include <gtest/gtest.h>                // for AssertHelper, TEST_F, etc
#include <gmock/gmock.h>                // IWYU pragma: keep

#include <wobbly/wobbly.h>    // for PointView, Point, Vector

#include <wobbly_internal.h>            // for Spring, etc
#include "boost_geometry.h"             // IWYU pragma: keep

#include <mathematical_model_matcher.h>  // for Eq, EqDispatchHelper, etc
#include <ostream_point_operator.h>     // for operator<<

using ::testing::ExitedWithCode;
using ::testing::Not;
using ::testing::Test;

using ::wobbly::matchers::Eq;
using ::wobbly::matchers::SatisfiesModel;

using ::wobbly::models::Linear;

namespace bg = boost::geometry;

namespace
{
    class SingleObjectStorage
    {
        public:

            SingleObjectStorage ()
            {
                storage.fill (0);
            }

            wobbly::PointView <double> Position ()
            {
                return wobbly::PointView <double> (storage, 0);
            }

            wobbly::PointView <double> Velocity ()
            {
                return wobbly::PointView <double> (storage, 1);
            }

            wobbly::PointView <double> Force ()
            {
                return wobbly::PointView <double> (storage, 2);
            }

        private:

            std::array <double, 6> storage;
    };

    class SingleObjectStorageView
    {
        public:

            SingleObjectStorageView (SingleObjectStorage &storage) :
                position (storage.Position ()),
                velocity (storage.Velocity ()),
                force (storage.Force ())
            {
            }

            wobbly::PointView <double> position;
            wobbly::PointView <double> velocity;
            wobbly::PointView <double> force;
    };

    constexpr double FirstPositionX = 50.0f;
    constexpr double FirstPositionY = 50.0f;

    constexpr double SecondPositionX = 100.0f;
    constexpr double SecondPositionY = 100.0f;

    constexpr double SpringConstant = 0.5f;

    TEST (Spring, MoveConstructorNoExcept)
    {
        SingleObjectStorage storageA, storageB;

        EXPECT_NO_THROW ({
            wobbly::Spring a (storageA.Force (),
                              storageB.Force (),
                              storageA.Position (),
                              storageB.Position (),
                              wobbly::Vector (0, 0));
            wobbly::Spring b (std::move (a));
        });
    }

    TEST (Spring, MoveAssignToSelf)
    {
        SingleObjectStorage storageA, storageB;

        EXPECT_EXIT ({
            wobbly::Spring a (storageA.Force (),
                              storageB.Force (),
                              storageA.Position (),
                              storageB.Position (),
                              wobbly::Vector (0, 0));

            a = std::move (a);
            exit (0);
        }, ExitedWithCode (0), "");
    }

    class Springs :
        public ::testing::Test
    {
        public:

            Springs ():
                desiredDistance (SecondPositionX - FirstPositionX,
                                 SecondPositionY - FirstPositionY),
                first (firstStorage),
                second (secondStorage),
                spring (firstStorage.Force (),
                        secondStorage.Force (),
                        firstStorage.Position (),
                        secondStorage.Position (),
                        desiredDistance)
            {
                bg::assign_point (first.position,
                                  wobbly::Point (FirstPositionX,
                                                 FirstPositionY));
                bg::assign_point (second.position,
                                  wobbly::Point (SecondPositionX,
                                                 SecondPositionY));
            }

        protected:

            wobbly::Vector desiredDistance;

        private:

            SingleObjectStorage firstStorage;
            SingleObjectStorage secondStorage;

        protected:

            SingleObjectStorageView first;
            SingleObjectStorageView second;
            wobbly::Spring spring;
    };

    TEST_F (Springs, NoForceAppliedWhenNoDeltaFromDesired)
    {
        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force,
                     Eq (wobbly::Vector (0, 0)));
        EXPECT_THAT (second.force,
                     Eq (wobbly::Vector (0, 0)));
    }

    template <typename Position>
    wobbly::Vector
    ForceForSpring (Position      const &first,
                    Position      const &second,
                    wobbly::Vector const &desired)
    {
        wobbly::Vector expectedForce;
        bg::assign (expectedForce, second);
        bg::subtract_point (expectedForce, first);
        bg::subtract_point (expectedForce, desired);
        bg::multiply_value (expectedForce, SpringConstant);
        bg::divide_value (expectedForce, 2);

        return expectedForce;
    }

    TEST_F (Springs, ForceAppliedToFirstObjectProportianalToPositiveDistanceSK)
    {
        bg::assign (first.position,
                    wobbly::Vector (FirstPositionX - 10.0f,
                                    FirstPositionY - 10.0f));
        wobbly::Vector expectedForce (ForceForSpring (first.position,
                                                      second.position,
                                                      desiredDistance));

        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceAppliedToSecondObjectProportionalToNegativeDistanceSK)
    {
        bg::assign (first.position, wobbly::Vector (FirstPositionX - 10.0f,
                                                    FirstPositionY - 10.0f));
        wobbly::Vector negativeDistance (desiredDistance);
        bg::multiply_value (negativeDistance, -1.0f);

        wobbly::Vector expectedForce (ForceForSpring (second.position,
                                                      first.position,
                                                      negativeDistance));

        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (second.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceAccumulatesWithApplications)
    {
        bg::assign (first.position,
                    wobbly::Vector (FirstPositionX - 10.0f,
                                    FirstPositionY - 10.0f));
        wobbly::Vector expectedForce (ForceForSpring (first.position,
                                                      second.position,
                                                      desiredDistance));

        /* Scalar for single spring */
        unsigned int const nApplications = 3;
        bg::multiply_value (expectedForce, nApplications);

        for (unsigned int i = 0; i < nApplications; ++i)
            spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceRelationshipIsLinearlyRelatedToDistance)
    {
        std::function <double (int)> forceByDistanceFunction =
            [this](int delta) -> double {
                bg::assign (first.force, wobbly::Vector (0, 0));
                bg::assign (second.force, wobbly::Vector (0, 0));
                bg::assign (first.position,
                            wobbly::Vector (FirstPositionX - delta,
                                            FirstPositionY));
                bg::assign (second.position,
                            wobbly::Vector (SecondPositionX + delta,
                                            SecondPositionY));

                spring.ApplyForces (SpringConstant);

                return bg::get <0> (first.force);
            };

        EXPECT_THAT (forceByDistanceFunction,
                     SatisfiesModel (Linear <double> ()));
    }

    TEST_F (Springs, ForceClippedWithVerySmallDelta)
    {
        double const justBelowThreshold = FirstPositionX -
                                          wobbly::Spring::ClipThreshold * 1.1;

        bg::assign (first.position,
                    wobbly::Vector (justBelowThreshold, FirstPositionY));
        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (wobbly::Vector (0, 0)));
    }

    TEST_F (Springs, ApplyForcesReturnsTrueIfForceRemaining)
    {
        /* Change the position of one object, that will cause forces
         * to be exerted
         */
        bg::assign (first.position, wobbly::Vector (FirstPositionX - 10,
                                                    FirstPositionY));

        EXPECT_TRUE (spring.ApplyForces (SpringConstant));
    }

    TEST_F (Springs, ApplyForcesReturnsFalseIfNoForceRemaining)
    {
        /* Where there is no delta, there is no force */
        EXPECT_FALSE (spring.ApplyForces (0.0f));
    }

    double const SpringScaleFactor = 2.0f;

    TEST_F (Springs, ForceExistsAfterLengthScaled)
    {
        spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
                                            SpringScaleFactor));
        EXPECT_TRUE (spring.ApplyForces (SpringConstant));
    }

    TEST_F (Springs, NoForceAfterLengthScaledAndObjectsMoved)
    {
        /* Calculate distance between first and second, then adjust
         * second object's position to be distance * scaleFactor */
        wobbly::Vector distance;
        bg::assign (distance, second.position);
        bg::subtract_point (distance, first.position);
        bg::subtract_point (second.position, distance);
        bg::multiply_value (distance, SpringScaleFactor);
        bg::add_point (second.position, distance);

        spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
                                            SpringScaleFactor));
        EXPECT_FALSE (spring.ApplyForces (SpringConstant));
    }
}
<commit_msg>spring_test: Remove MoveAssignToSelf<commit_after>/*
 * tests/wobbly_test.cpp
 *
 * Tests for the "wobbly" spring model.
 *
 * See LICENCE.md for Copyright information.
 */
#include <array>                        // for array
#include <functional>                   // for function, __base
#include <memory>                       // for unique_ptr
#include <sstream>                      // for char_traits, etc
#include <type_traits>                  // for move

#include <stdlib.h>                     // for exit

#include <boost/test/utils/wrap_stringstream.hpp>  // for operator<<

#include <gmock/gmock-matchers.h>       // for EXPECT_THAT, etc
#include <gtest/gtest-death-test.h>     // for DeathTest, ExitedWithCode, etc
#include <gtest/gtest.h>                // for AssertHelper, TEST_F, etc
#include <gmock/gmock.h>                // IWYU pragma: keep

#include <wobbly/wobbly.h>    // for PointView, Point, Vector

#include <wobbly_internal.h>            // for Spring, etc
#include "boost_geometry.h"             // IWYU pragma: keep

#include <mathematical_model_matcher.h>  // for Eq, EqDispatchHelper, etc
#include <ostream_point_operator.h>     // for operator<<

using ::testing::ExitedWithCode;
using ::testing::Not;
using ::testing::Test;

using ::wobbly::matchers::Eq;
using ::wobbly::matchers::SatisfiesModel;

using ::wobbly::models::Linear;

namespace bg = boost::geometry;

namespace
{
    class SingleObjectStorage
    {
        public:

            SingleObjectStorage ()
            {
                storage.fill (0);
            }

            wobbly::PointView <double> Position ()
            {
                return wobbly::PointView <double> (storage, 0);
            }

            wobbly::PointView <double> Velocity ()
            {
                return wobbly::PointView <double> (storage, 1);
            }

            wobbly::PointView <double> Force ()
            {
                return wobbly::PointView <double> (storage, 2);
            }

        private:

            std::array <double, 6> storage;
    };

    class SingleObjectStorageView
    {
        public:

            SingleObjectStorageView (SingleObjectStorage &storage) :
                position (storage.Position ()),
                velocity (storage.Velocity ()),
                force (storage.Force ())
            {
            }

            wobbly::PointView <double> position;
            wobbly::PointView <double> velocity;
            wobbly::PointView <double> force;
    };

    constexpr double FirstPositionX = 50.0f;
    constexpr double FirstPositionY = 50.0f;

    constexpr double SecondPositionX = 100.0f;
    constexpr double SecondPositionY = 100.0f;

    constexpr double SpringConstant = 0.5f;

    TEST (Spring, MoveConstructorNoExcept)
    {
        SingleObjectStorage storageA, storageB;

        EXPECT_NO_THROW ({
            wobbly::Spring a (storageA.Force (),
                              storageB.Force (),
                              storageA.Position (),
                              storageB.Position (),
                              wobbly::Vector (0, 0));
            wobbly::Spring b (std::move (a));
        });
    }

    class Springs :
        public ::testing::Test
    {
        public:

            Springs ():
                desiredDistance (SecondPositionX - FirstPositionX,
                                 SecondPositionY - FirstPositionY),
                first (firstStorage),
                second (secondStorage),
                spring (firstStorage.Force (),
                        secondStorage.Force (),
                        firstStorage.Position (),
                        secondStorage.Position (),
                        desiredDistance)
            {
                bg::assign_point (first.position,
                                  wobbly::Point (FirstPositionX,
                                                 FirstPositionY));
                bg::assign_point (second.position,
                                  wobbly::Point (SecondPositionX,
                                                 SecondPositionY));
            }

        protected:

            wobbly::Vector desiredDistance;

        private:

            SingleObjectStorage firstStorage;
            SingleObjectStorage secondStorage;

        protected:

            SingleObjectStorageView first;
            SingleObjectStorageView second;
            wobbly::Spring spring;
    };

    TEST_F (Springs, NoForceAppliedWhenNoDeltaFromDesired)
    {
        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force,
                     Eq (wobbly::Vector (0, 0)));
        EXPECT_THAT (second.force,
                     Eq (wobbly::Vector (0, 0)));
    }

    template <typename Position>
    wobbly::Vector
    ForceForSpring (Position      const &first,
                    Position      const &second,
                    wobbly::Vector const &desired)
    {
        wobbly::Vector expectedForce;
        bg::assign (expectedForce, second);
        bg::subtract_point (expectedForce, first);
        bg::subtract_point (expectedForce, desired);
        bg::multiply_value (expectedForce, SpringConstant);
        bg::divide_value (expectedForce, 2);

        return expectedForce;
    }

    TEST_F (Springs, ForceAppliedToFirstObjectProportianalToPositiveDistanceSK)
    {
        bg::assign (first.position,
                    wobbly::Vector (FirstPositionX - 10.0f,
                                    FirstPositionY - 10.0f));
        wobbly::Vector expectedForce (ForceForSpring (first.position,
                                                      second.position,
                                                      desiredDistance));

        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceAppliedToSecondObjectProportionalToNegativeDistanceSK)
    {
        bg::assign (first.position, wobbly::Vector (FirstPositionX - 10.0f,
                                                    FirstPositionY - 10.0f));
        wobbly::Vector negativeDistance (desiredDistance);
        bg::multiply_value (negativeDistance, -1.0f);

        wobbly::Vector expectedForce (ForceForSpring (second.position,
                                                      first.position,
                                                      negativeDistance));

        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (second.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceAccumulatesWithApplications)
    {
        bg::assign (first.position,
                    wobbly::Vector (FirstPositionX - 10.0f,
                                    FirstPositionY - 10.0f));
        wobbly::Vector expectedForce (ForceForSpring (first.position,
                                                      second.position,
                                                      desiredDistance));

        /* Scalar for single spring */
        unsigned int const nApplications = 3;
        bg::multiply_value (expectedForce, nApplications);

        for (unsigned int i = 0; i < nApplications; ++i)
            spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (expectedForce));
    }

    TEST_F (Springs, ForceRelationshipIsLinearlyRelatedToDistance)
    {
        std::function <double (int)> forceByDistanceFunction =
            [this](int delta) -> double {
                bg::assign (first.force, wobbly::Vector (0, 0));
                bg::assign (second.force, wobbly::Vector (0, 0));
                bg::assign (first.position,
                            wobbly::Vector (FirstPositionX - delta,
                                            FirstPositionY));
                bg::assign (second.position,
                            wobbly::Vector (SecondPositionX + delta,
                                            SecondPositionY));

                spring.ApplyForces (SpringConstant);

                return bg::get <0> (first.force);
            };

        EXPECT_THAT (forceByDistanceFunction,
                     SatisfiesModel (Linear <double> ()));
    }

    TEST_F (Springs, ForceClippedWithVerySmallDelta)
    {
        double const justBelowThreshold = FirstPositionX -
                                          wobbly::Spring::ClipThreshold * 1.1;

        bg::assign (first.position,
                    wobbly::Vector (justBelowThreshold, FirstPositionY));
        spring.ApplyForces (SpringConstant);

        EXPECT_THAT (first.force, Eq (wobbly::Vector (0, 0)));
    }

    TEST_F (Springs, ApplyForcesReturnsTrueIfForceRemaining)
    {
        /* Change the position of one object, that will cause forces
         * to be exerted
         */
        bg::assign (first.position, wobbly::Vector (FirstPositionX - 10,
                                                    FirstPositionY));

        EXPECT_TRUE (spring.ApplyForces (SpringConstant));
    }

    TEST_F (Springs, ApplyForcesReturnsFalseIfNoForceRemaining)
    {
        /* Where there is no delta, there is no force */
        EXPECT_FALSE (spring.ApplyForces (0.0f));
    }

    double const SpringScaleFactor = 2.0f;

    TEST_F (Springs, ForceExistsAfterLengthScaled)
    {
        spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
                                            SpringScaleFactor));
        EXPECT_TRUE (spring.ApplyForces (SpringConstant));
    }

    TEST_F (Springs, NoForceAfterLengthScaledAndObjectsMoved)
    {
        /* Calculate distance between first and second, then adjust
         * second object's position to be distance * scaleFactor */
        wobbly::Vector distance;
        bg::assign (distance, second.position);
        bg::subtract_point (distance, first.position);
        bg::subtract_point (second.position, distance);
        bg::multiply_value (distance, SpringScaleFactor);
        bg::add_point (second.position, distance);

        spring.ScaleLength (wobbly::Vector (SpringScaleFactor,
                                            SpringScaleFactor));
        EXPECT_FALSE (spring.ApplyForces (SpringConstant));
    }
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>

using namespace std;

struct UnionFind {
  vector<int> p, rank, setSize;
  int numSets;

  UnionFind(int N) {
    setSize.assign(N, 1);
    numSets = N;
    rank.assign(N, 0);
    p.assign(N, 0);
    for (int i = 0; i < N; i++) p[i] = i;
  }

  int findSet(int i) {
    return (p[i] == i) ? i : (p[i] = findSet(p[i]));
  }

  bool isSameSet(int i, int j) {
    return findSet(i) == findSet(j);
  }

  void unionSet(int i, int j) {
    if (!isSameSet(i, j)) {
      numSets--;
      int x = findSet(i), y = findSet(j);
      if (rank[x] > rank[y]) {
        p[y] = x; setSize[x] += setSize[y];
      } else {
        p[x] = y; setSize[y] += setSize[x];
        if (rank[x] == rank[y])
          rank[y]++;
      }
    }
  }
  int numDisjointSets() {
    return numSets;
  }

  int sizeOfSet(int i) {
    return setSize[findSet(i)];
  }
};

int main() {

}<commit_msg>Reindent UnionFind<commit_after>#include <bits/stdc++.h>

using namespace std;

struct UnionFind {
	vector<int> p, rank, setSize;
	int numSets;

	UnionFind(int N) {
		setSize.assign(N, 1);
		numSets = N;
		rank.assign(N, 0);
		p.assign(N, 0);
		for (int i = 0; i < N; i++) p[i] = i;
	}

	int findSet(int i) {
		return (p[i] == i) ? i : (p[i] = findSet(p[i]));
	}

	bool isSameSet(int i, int j) {
		return findSet(i) == findSet(j);
	}

	void unionSet(int i, int j) {
		if (!isSameSet(i, j)) {
			numSets--;
			int x = findSet(i), y = findSet(j);
			if (rank[x] > rank[y]) {
				p[y] = x; setSize[x] += setSize[y];
			} else {
				p[x] = y; setSize[y] += setSize[x];
				if (rank[x] == rank[y])
					rank[y]++;
			}
		}
	}
	int numDisjointSets() {
		return numSets;
	}

	int sizeOfSet(int i) {
		return setSize[findSet(i)];
	}
};

int main() {

}<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/system/touchpad_settings.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "content/public/browser/browser_thread.h"

using content::BrowserThread;

namespace {

const char kLockOnIdleSuspendPath[] =
    "/var/lib/power_manager/lock_on_idle_suspend";

void EnableScreenLockOnFileThread(bool enable) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
    std::string config = base::StringPrintf("%d", enable);
    file_util::WriteFile(FilePath(kLockOnIdleSuspendPath),
                         config.c_str(),
                         config.size());
  }
}

}  // namespace

namespace chromeos {
namespace system {
namespace screen_locker_settings {

void EnableScreenLock(bool enable) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Run this on the FILE thread.
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&EnableScreenLockOnFileThread, enable));
}

}  // namespace screen_locker_settings
}  // namespace system
}  // namespace chromeos
<commit_msg>Fix erroneous include in screen_locker_settings.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/system/screen_locker_settings.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/system/runtime_environment.h"
#include "content/public/browser/browser_thread.h"

using content::BrowserThread;

namespace {

const char kLockOnIdleSuspendPath[] =
    "/var/lib/power_manager/lock_on_idle_suspend";

void EnableScreenLockOnFileThread(bool enable) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  if (chromeos::system::runtime_environment::IsRunningOnChromeOS()) {
    std::string config = base::StringPrintf("%d", enable);
    file_util::WriteFile(FilePath(kLockOnIdleSuspendPath),
                         config.c_str(),
                         config.size());
  }
}

}  // namespace

namespace chromeos {
namespace system {
namespace screen_locker_settings {

void EnableScreenLock(bool enable) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // Run this on the FILE thread.
  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(&EnableScreenLockOnFileThread, enable));
}

}  // namespace screen_locker_settings
}  // namespace system
}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/browser_dialogs.h"

#include <gtk/gtk.h>

#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/logging_chrome.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/result_codes.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/gtk/gtk_signal.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/gtk_util.h"
#include "ui/gfx/image/image.h"

namespace {

// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
 public:
  HungRendererDialogGtk();
  virtual ~HungRendererDialogGtk() {}
  void ShowForTabContents(TabContents* hung_contents);
  void EndForTabContents(TabContents* hung_contents);

 private:
  // The GtkTreeView column ids.
  enum {
    COL_FAVICON,
    COL_TITLE,
    COL_COUNT,
  };

  // Create the gtk dialog and add the widgets.
  void Init();

  CHROMEGTK_CALLBACK_1(HungRendererDialogGtk, void, OnResponse, int);

  GtkDialog* dialog_;
  GtkListStore* model_;
  TabContents* contents_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};

// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;

// The response ID for the "Kill pages" button.  Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;

HungRendererDialogGtk::HungRendererDialogGtk()
    : dialog_(NULL), model_(NULL), contents_(NULL) {
  Init();
}

void HungRendererDialogGtk::Init() {
  dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
      NULL,  // No parent because tabs can span multiple windows.
      GTK_DIALOG_NO_SEPARATOR,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
      kKillPagesButtonResponse,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
      GTK_RESPONSE_OK,
      NULL));
  gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
  g_signal_connect(dialog_, "delete-event",
                   G_CALLBACK(gtk_widget_hide_on_delete), NULL);
  g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);

  // We have an hbox with the frozen icon on the left.  On the right,
  // we have a vbox with the unresponsive text on top and a table of
  // tabs on bottom.
  // ·-----------------------------------·
  // |·---------------------------------·|
  // ||·----·|·------------------------·||
  // |||icon|||                        |||
  // ||·----·|| The folowing page(s).. |||
  // ||      ||                        |||
  // ||      ||------------------------|||
  // ||      || table of tabs          |||
  // ||      |·------------------------·||
  // |·---------------------------------·|
  // |                                   |
  // |         kill button    wait button|
  // ·-----------------------------------·
  GtkWidget* content_area = gtk_dialog_get_content_area(dialog_);
  gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
  gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);

  // Wrap the icon in a vbox so it stays top aligned.
  GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  GdkPixbuf* icon_pixbuf = rb.GetNativeImageNamed(IDR_FROZEN_TAB_ICON);
  GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);

  GtkWidget* vbox = gtk_vbox_new(FALSE, ui::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);

  GtkWidget* text = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);

  GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
      GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
                                      GTK_SHADOW_ETCHED_IN);
  gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);

  // The list of hung tabs is GtkTreeView with a GtkListStore as the model.
  model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
  GtkWidget* tree_view = gtk_tree_view_new_with_model(
      GTK_TREE_MODEL(model_));
  g_object_unref(model_);
  gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
  GtkTreeViewColumn* column = gtk_tree_view_column_new();
  GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
  gtk_tree_view_column_pack_start(column, renderer, FALSE);
  gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
  renderer = gtk_cell_renderer_text_new();
  gtk_tree_view_column_pack_start(column, renderer, TRUE);
  gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);

  gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
  gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}

void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
  DCHECK(hung_contents && dialog_);
  contents_ = hung_contents;
  gtk_list_store_clear(model_);

  GtkTreeIter tree_iter;
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->tab_contents()->GetRenderProcessHost() ==
        hung_contents->GetRenderProcessHost()) {
      gtk_list_store_append(model_, &tree_iter);
      std::string title = UTF16ToUTF8(it->tab_contents()->GetTitle());
      if (title.empty())
        title = UTF16ToUTF8(TabContentsWrapper::GetDefaultTitle());
      SkBitmap favicon = it->favicon_tab_helper()->GetFavicon();

      GdkPixbuf* pixbuf = NULL;
      if (favicon.width() > 0)
        pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
      gtk_list_store_set(model_, &tree_iter,
          COL_FAVICON, pixbuf,
          COL_TITLE, title.c_str(),
          -1);
      if (pixbuf)
        g_object_unref(pixbuf);
    }
  }
  gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}

void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
  DCHECK(contents);
  if (contents_ && contents_->GetRenderProcessHost() ==
      contents->GetRenderProcessHost()) {
    gtk_widget_hide(GTK_WIDGET(dialog_));
    // Since we're closing, we no longer need this TabContents.
    contents_ = NULL;
  }
}

// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
  DCHECK(g_instance == this);
  switch (response_id) {
    case kKillPagesButtonResponse:
      // Kill the process.
      if (contents_ && contents_->GetRenderProcessHost()) {
        base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
                          content::RESULT_CODE_HUNG, false);
      }
      break;

    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_DELETE_EVENT:
      // Start waiting again for responsiveness.
      if (contents_ && contents_->render_view_host())
        contents_->render_view_host()->RestartHangMonitorTimeout();
      break;
    default:
      NOTREACHED();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog_));
  delete g_instance;
  g_instance = NULL;
}

}  // namespace

namespace browser {

void ShowHungRendererDialog(TabContents* contents) {
  if (!logging::DialogsAreSuppressed()) {
    if (!g_instance)
      g_instance = new HungRendererDialogGtk();
    g_instance->ShowForTabContents(contents);
  }
}

void HideHungRendererDialog(TabContents* contents) {
  if (!logging::DialogsAreSuppressed() && g_instance)
    g_instance->EndForTabContents(contents);
}

}  // namespace browser
<commit_msg>[Linux] Observer initiating tab for destruction in hung-renderer dialog.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/browser_dialogs.h"

#include <gtk/gtk.h>

#include "base/process_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/favicon/favicon_tab_helper.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/gtk/gtk_util.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/common/logging_chrome.h"
#include "content/browser/renderer_host/render_process_host.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/result_codes.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/gtk/gtk_hig_constants.h"
#include "ui/base/gtk/gtk_signal.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/gtk_util.h"
#include "ui/gfx/image/image.h"

namespace {

// A wrapper class that represents the Gtk dialog.
class HungRendererDialogGtk {
 public:
  HungRendererDialogGtk();
  virtual ~HungRendererDialogGtk() {}
  void ShowForTabContents(TabContents* hung_contents);
  void Hide();
  void EndForTabContents(TabContents* hung_contents);

 private:
  // Dismiss the panel if |contents_| is closed or its renderer exits.
  class TabContentsObserverImpl : public TabContentsObserver {
   public:
    TabContentsObserverImpl(HungRendererDialogGtk* dialog,
                            TabContents* contents)
        : TabContentsObserver(contents),
          dialog_(dialog) {
    }

    // TabContentsObserver overrides:
    virtual void RenderViewGone() OVERRIDE {
      dialog_->Hide();
    }
    virtual void TabContentsDestroyed(TabContents* tab) OVERRIDE {
      dialog_->Hide();
    }

   private:
    HungRendererDialogGtk* dialog_;  // weak

    DISALLOW_COPY_AND_ASSIGN(TabContentsObserverImpl);
  };

  // The GtkTreeView column ids.
  enum {
    COL_FAVICON,
    COL_TITLE,
    COL_COUNT,
  };

  // Create the gtk dialog and add the widgets.
  void Init();

  CHROMEGTK_CALLBACK_1(HungRendererDialogGtk, void, OnResponse, int);

  GtkDialog* dialog_;
  GtkListStore* model_;
  TabContents* contents_;
  scoped_ptr<TabContentsObserverImpl> contents_observer_;

  DISALLOW_COPY_AND_ASSIGN(HungRendererDialogGtk);
};

// We only support showing one of these at a time per app.
HungRendererDialogGtk* g_instance = NULL;

// The response ID for the "Kill pages" button.  Anything positive should be
// fine (the built in GtkResponseTypes are negative numbers).
const int kKillPagesButtonResponse = 1;

HungRendererDialogGtk::HungRendererDialogGtk()
    : dialog_(NULL), model_(NULL), contents_(NULL) {
  Init();
}

void HungRendererDialogGtk::Init() {
  dialog_ = GTK_DIALOG(gtk_dialog_new_with_buttons(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE).c_str(),
      NULL,  // No parent because tabs can span multiple windows.
      GTK_DIALOG_NO_SEPARATOR,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_END).c_str(),
      kKillPagesButtonResponse,
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT).c_str(),
      GTK_RESPONSE_OK,
      NULL));
  gtk_dialog_set_default_response(dialog_, GTK_RESPONSE_OK);
  g_signal_connect(dialog_, "delete-event",
                   G_CALLBACK(gtk_widget_hide_on_delete), NULL);
  g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseThunk), this);

  // We have an hbox with the frozen icon on the left.  On the right,
  // we have a vbox with the unresponsive text on top and a table of
  // tabs on bottom.
  // ·-----------------------------------·
  // |·---------------------------------·|
  // ||·----·|·------------------------·||
  // |||icon|||                        |||
  // ||·----·|| The folowing page(s).. |||
  // ||      ||                        |||
  // ||      ||------------------------|||
  // ||      || table of tabs          |||
  // ||      |·------------------------·||
  // |·---------------------------------·|
  // |                                   |
  // |         kill button    wait button|
  // ·-----------------------------------·
  GtkWidget* content_area = gtk_dialog_get_content_area(dialog_);
  gtk_box_set_spacing(GTK_BOX(content_area), ui::kContentAreaSpacing);

  GtkWidget* hbox = gtk_hbox_new(FALSE, 12);
  gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);

  // Wrap the icon in a vbox so it stays top aligned.
  GtkWidget* icon_vbox = gtk_vbox_new(FALSE, 0);
  gtk_box_pack_start(GTK_BOX(hbox), icon_vbox, FALSE, FALSE, 0);
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  GdkPixbuf* icon_pixbuf = rb.GetNativeImageNamed(IDR_FROZEN_TAB_ICON);
  GtkWidget* icon = gtk_image_new_from_pixbuf(icon_pixbuf);
  gtk_box_pack_start(GTK_BOX(icon_vbox), icon, FALSE, FALSE, 0);

  GtkWidget* vbox = gtk_vbox_new(FALSE, ui::kControlSpacing);
  gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);

  GtkWidget* text = gtk_label_new(
      l10n_util::GetStringUTF8(IDS_BROWSER_HANGMONITOR_RENDERER).c_str());
  gtk_label_set_line_wrap(GTK_LABEL(text), TRUE);
  gtk_box_pack_start(GTK_BOX(vbox), text, FALSE, FALSE, 0);

  GtkWidget* scroll_list = gtk_scrolled_window_new(NULL, NULL);
  gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scroll_list),
      GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
  gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scroll_list),
                                      GTK_SHADOW_ETCHED_IN);
  gtk_box_pack_start(GTK_BOX(vbox), scroll_list, TRUE, TRUE, 0);

  // The list of hung tabs is GtkTreeView with a GtkListStore as the model.
  model_ = gtk_list_store_new(COL_COUNT, GDK_TYPE_PIXBUF, G_TYPE_STRING);
  GtkWidget* tree_view = gtk_tree_view_new_with_model(
      GTK_TREE_MODEL(model_));
  g_object_unref(model_);
  gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(tree_view), FALSE);
  GtkTreeViewColumn* column = gtk_tree_view_column_new();
  GtkCellRenderer* renderer = gtk_cell_renderer_pixbuf_new();
  gtk_tree_view_column_pack_start(column, renderer, FALSE);
  gtk_tree_view_column_add_attribute(column, renderer, "pixbuf", COL_FAVICON);
  renderer = gtk_cell_renderer_text_new();
  gtk_tree_view_column_pack_start(column, renderer, TRUE);
  gtk_tree_view_column_add_attribute(column, renderer, "text", COL_TITLE);

  gtk_tree_view_append_column(GTK_TREE_VIEW(tree_view), column);
  gtk_container_add(GTK_CONTAINER(scroll_list), tree_view);
}

void HungRendererDialogGtk::ShowForTabContents(TabContents* hung_contents) {
  DCHECK(hung_contents && dialog_);
  contents_ = hung_contents;
  contents_observer_.reset(new TabContentsObserverImpl(this, contents_));
  gtk_list_store_clear(model_);

  GtkTreeIter tree_iter;
  for (TabContentsIterator it; !it.done(); ++it) {
    if (it->tab_contents()->GetRenderProcessHost() ==
        hung_contents->GetRenderProcessHost()) {
      gtk_list_store_append(model_, &tree_iter);
      std::string title = UTF16ToUTF8(it->tab_contents()->GetTitle());
      if (title.empty())
        title = UTF16ToUTF8(TabContentsWrapper::GetDefaultTitle());
      SkBitmap favicon = it->favicon_tab_helper()->GetFavicon();

      GdkPixbuf* pixbuf = NULL;
      if (favicon.width() > 0)
        pixbuf = gfx::GdkPixbufFromSkBitmap(&favicon);
      gtk_list_store_set(model_, &tree_iter,
          COL_FAVICON, pixbuf,
          COL_TITLE, title.c_str(),
          -1);
      if (pixbuf)
        g_object_unref(pixbuf);
    }
  }
  gtk_util::ShowDialog(GTK_WIDGET(dialog_));
}

void HungRendererDialogGtk::Hide() {
  gtk_widget_hide(GTK_WIDGET(dialog_));
  // Since we're closing, we no longer need this TabContents.
  contents_observer_.reset();
  contents_ = NULL;
}

void HungRendererDialogGtk::EndForTabContents(TabContents* contents) {
  DCHECK(contents);
  if (contents_ && contents_->GetRenderProcessHost() ==
      contents->GetRenderProcessHost()) {
    Hide();
  }
}

// When the user clicks a button on the dialog or closes the dialog, this
// callback is called.
void HungRendererDialogGtk::OnResponse(GtkWidget* dialog, int response_id) {
  DCHECK(g_instance == this);
  switch (response_id) {
    case kKillPagesButtonResponse:
      // Kill the process.
      if (contents_ && contents_->GetRenderProcessHost()) {
        base::KillProcess(contents_->GetRenderProcessHost()->GetHandle(),
                          content::RESULT_CODE_HUNG, false);
      }
      break;

    case GTK_RESPONSE_OK:
    case GTK_RESPONSE_DELETE_EVENT:
      // Start waiting again for responsiveness.
      if (contents_ && contents_->render_view_host())
        contents_->render_view_host()->RestartHangMonitorTimeout();
      break;
    default:
      NOTREACHED();
  }

  gtk_widget_destroy(GTK_WIDGET(dialog_));
  delete g_instance;
  g_instance = NULL;
}

}  // namespace

namespace browser {

void ShowHungRendererDialog(TabContents* contents) {
  if (!logging::DialogsAreSuppressed()) {
    if (!g_instance)
      g_instance = new HungRendererDialogGtk();
    g_instance->ShowForTabContents(contents);
  }
}

void HideHungRendererDialog(TabContents* contents) {
  if (!logging::DialogsAreSuppressed() && g_instance)
    g_instance->EndForTabContents(contents);
}

}  // namespace browser
<|endoftext|>


<commit_before>#pragma once

#include <depthai-shared/common/EepromData.hpp>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/datatype/RawStereoDepthConfig.hpp"

namespace dai {

/**
 * Specify properties for StereoDepth
 */
struct StereoDepthProperties {
    struct RectificationMesh {
        /**
         * Uri which points to the mesh array for 'left' input rectification
         */
        std::string meshLeftUri;
        /**
         * Uri which points to the mesh array for 'right' input rectification
         */
        std::string meshRightUri;
        /**
         * Mesh array size in bytes, for each of 'left' and 'right' (need to match)
         */
        tl::optional<std::uint32_t> meshSize;
        /**
         * Distance between mesh points, in the horizontal direction
         */
        uint16_t stepWidth = 16;
        /**
         * Distance between mesh points, in the vertical direction
         */
        uint16_t stepHeight = 16;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);
    };

    /// Initial stereo config
    RawStereoDepthConfig initialConfig;

    /// Whether to wait for config at 'inputConfig' IO
    bool inputConfigSync = false;

    using MedianFilter = dai::MedianFilter;

    /**
     * Align the disparity/depth to the perspective of a rectified output, or center it
     */
    enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };

    /**
     * Set the disparity/depth alignment to the perspective of a rectified output, or center it
     */
    DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;
    /**
     * Which camera to align disparity/depth to.
     * When configured (not AUTO), takes precedence over 'depthAlign'
     */
    CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;

    bool enableRectification = true;

    /**
     * Disparity range increased from 96 to 192, combined from full resolution and downscaled images.
     * Suitable for short range objects
     */
    bool enableExtendedDisparity = false;
    /**
     * Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels
     */
    std::int32_t rectifyEdgeFillColor = -1;
    /**
     * Input frame width. Optional (taken from MonoCamera nodes if they exist)
     */
    tl::optional<std::int32_t> width;
    /**
     * Input frame height. Optional (taken from MonoCamera nodes if they exist)
     */
    tl::optional<std::int32_t> height;
    /**
     * Output disparity/depth width. Currently only used when aligning to RGB
     */
    tl::optional<std::int32_t> outWidth;
    /**
     * Output disparity/depth height. Currently only used when aligning to RGB
     */
    tl::optional<std::int32_t> outHeight;
    /**
     * Whether to keep aspect ratio of the input (rectified) or not
     */
    bool outKeepAspectRatio = true;

    /**
     * Specify a direct warp mesh to be used for rectification,
     * instead of intrinsics + extrinsic matrices
     */
    RectificationMesh mesh;

    /**
     * Whether to enable switching stereo modes at runtime or not.
     * E.g. standard to subpixel, standard+LR-check to subpixel + LR-check.
     * Note: It will allocate resources for worst cases scenario,
     * should be enabled only if dynamic mode switch is required.
     * Default value: false.
     */
    bool enableRuntimeStereoModeSwitch = false;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,
                                   initialConfig,
                                   inputConfigSync,
                                   depthAlign,
                                   depthAlignCamera,
                                   enableRectification,
                                   enableExtendedDisparity,
                                   rectifyEdgeFillColor,
                                   width,
                                   height,
                                   outWidth,
                                   outHeight,
                                   outKeepAspectRatio,
                                   mesh,
                                   enableRuntimeStereoModeSwitch);

}  // namespace dai
<commit_msg>Add numFramePools to properties<commit_after>#pragma once

#include <depthai-shared/common/EepromData.hpp>
#include <depthai-shared/common/optional.hpp>
#include <nlohmann/json.hpp>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/datatype/RawStereoDepthConfig.hpp"

namespace dai {

/**
 * Specify properties for StereoDepth
 */
struct StereoDepthProperties {
    struct RectificationMesh {
        /**
         * Uri which points to the mesh array for 'left' input rectification
         */
        std::string meshLeftUri;
        /**
         * Uri which points to the mesh array for 'right' input rectification
         */
        std::string meshRightUri;
        /**
         * Mesh array size in bytes, for each of 'left' and 'right' (need to match)
         */
        tl::optional<std::uint32_t> meshSize;
        /**
         * Distance between mesh points, in the horizontal direction
         */
        uint16_t stepWidth = 16;
        /**
         * Distance between mesh points, in the vertical direction
         */
        uint16_t stepHeight = 16;

        NLOHMANN_DEFINE_TYPE_INTRUSIVE(RectificationMesh, meshLeftUri, meshRightUri, meshSize, stepWidth, stepHeight);
    };

    /// Initial stereo config
    RawStereoDepthConfig initialConfig;

    /// Whether to wait for config at 'inputConfig' IO
    bool inputConfigSync = false;

    using MedianFilter = dai::MedianFilter;

    /**
     * Align the disparity/depth to the perspective of a rectified output, or center it
     */
    enum class DepthAlign : int32_t { RECTIFIED_RIGHT, RECTIFIED_LEFT, CENTER };

    /**
     * Set the disparity/depth alignment to the perspective of a rectified output, or center it
     */
    DepthAlign depthAlign = DepthAlign::RECTIFIED_RIGHT;
    /**
     * Which camera to align disparity/depth to.
     * When configured (not AUTO), takes precedence over 'depthAlign'
     */
    CameraBoardSocket depthAlignCamera = CameraBoardSocket::AUTO;

    bool enableRectification = true;

    /**
     * Disparity range increased from 96 to 192, combined from full resolution and downscaled images.
     * Suitable for short range objects
     */
    bool enableExtendedDisparity = false;
    /**
     * Fill color for missing data at frame edges: grayscale 0..255, or -1 to replicate pixels
     */
    std::int32_t rectifyEdgeFillColor = -1;
    /**
     * Input frame width. Optional (taken from MonoCamera nodes if they exist)
     */
    tl::optional<std::int32_t> width;
    /**
     * Input frame height. Optional (taken from MonoCamera nodes if they exist)
     */
    tl::optional<std::int32_t> height;
    /**
     * Output disparity/depth width. Currently only used when aligning to RGB
     */
    tl::optional<std::int32_t> outWidth;
    /**
     * Output disparity/depth height. Currently only used when aligning to RGB
     */
    tl::optional<std::int32_t> outHeight;
    /**
     * Whether to keep aspect ratio of the input (rectified) or not
     */
    bool outKeepAspectRatio = true;

    /**
     * Specify a direct warp mesh to be used for rectification,
     * instead of intrinsics + extrinsic matrices
     */
    RectificationMesh mesh;

    /**
     * Whether to enable switching stereo modes at runtime or not.
     * E.g. standard to subpixel, standard+LR-check to subpixel + LR-check.
     * Note: It will allocate resources for worst cases scenario,
     * should be enabled only if dynamic mode switch is required.
     * Default value: false.
     */
    bool enableRuntimeStereoModeSwitch = false;

    /// Num frames in output pool
    int numFramesPool = 3;
};

NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(StereoDepthProperties,
                                   initialConfig,
                                   inputConfigSync,
                                   depthAlign,
                                   depthAlignCamera,
                                   enableRectification,
                                   enableExtendedDisparity,
                                   rectifyEdgeFillColor,
                                   width,
                                   height,
                                   outWidth,
                                   outHeight,
                                   outKeepAspectRatio,
                                   mesh,
                                   enableRuntimeStereoModeSwitch,
                                   numFramesPool);

}  // namespace dai
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    %M%
  Language:  C++
  Date:      %D%
  Version:   %V%

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkMCubesWriter.h"
#include "vtkByteSwap.h"
#include "vtkNormals.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkMCubesWriter* vtkMCubesWriter::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMCubesWriter");
  if(ret)
    {
    return (vtkMCubesWriter*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkMCubesWriter;
}

// Create object.
vtkMCubesWriter::vtkMCubesWriter()
{
  this->LimitsFileName = NULL;
}

vtkMCubesWriter::~vtkMCubesWriter()
{
  if ( this->LimitsFileName )
    {
    delete [] this->LimitsFileName;
    }
}
static void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys);
static void WriteLimits(FILE *fp, float *bounds);

// Write out data in MOVIE.BYU format.
void vtkMCubesWriter::WriteData()
{
  vtkPoints *pts;
  vtkNormals *normals;
  vtkCellArray *polys;
  vtkPolyData *input=this->GetInput();

  polys = input->GetPolys();
  pts = input->GetPoints();
  if (pts == NULL || polys == NULL )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }

  normals = input->GetPointData()->GetNormals();
  if (normals == NULL )
    {
    vtkErrorMacro(<<"No normals to write!: use vtkPolyDataNormals to generate them");
    return;
    }

  if ( this->FileName == NULL)
    {
    vtkErrorMacro(<< "Please specify FileName to write");
    return;
    }

  vtkDebugMacro("Writing MCubes tri file");
  FILE *fp;
  if ((fp = fopen(this->FileName, "w")) == NULL)
    {
    vtkErrorMacro(<< "Couldn't open file: " << this->FileName);
    return;
    }
  WriteMCubes (fp, pts, normals, polys);
  fclose (fp);

  if (this->LimitsFileName) {
      vtkDebugMacro("Writing MCubes limits file");
      if ((fp = fopen(this->LimitsFileName, "w")) == NULL)
        {
        vtkErrorMacro(<< "Couldn't open file: " << this->LimitsFileName);
        return;
        }
        WriteLimits (fp, input->GetBounds ());
      fclose (fp);
  }
}

void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys)
{
  typedef struct {float x[3], n[3];} pointType;
  pointType point;
  int i;
  int npts, *indx;

//
//  Write out triangle polygons.  In not a triangle polygon, create triangles.
//
  for (polys->InitTraversal(); polys->GetNextCell(npts,indx); )
    {
    for (i=0; i < 3; i++)
	{
	pts->GetPoint(indx[i],&point.x[0]);
	normals->GetNormal(indx[i],&point.n[0]);
	vtkByteSwap::SwapWrite4BERange((float *) (&point),6,fp);
	}
    }
}
void WriteLimits(FILE *fp, float *bounds)
{
  vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
  vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
}

void vtkMCubesWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataWriter::PrintSelf(os,indent);

  os << indent << "Limits File Name: "
     << (this->LimitsFileName ? this->LimitsFileName : "(none)") << "\n";
}

<commit_msg>ENH:Minor formatting tweaks<commit_after>/*=========================================================================

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

Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

=========================================================================*/
#include "vtkMCubesWriter.h"
#include "vtkByteSwap.h"
#include "vtkNormals.h"
#include "vtkObjectFactory.h"

//--------------------------------------------------------------------------
vtkMCubesWriter* vtkMCubesWriter::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMCubesWriter");
  if(ret)
    {
    return (vtkMCubesWriter*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkMCubesWriter;
}

// Create object.
vtkMCubesWriter::vtkMCubesWriter()
{
  this->LimitsFileName = NULL;
}

vtkMCubesWriter::~vtkMCubesWriter()
{
  if ( this->LimitsFileName )
    {
    delete [] this->LimitsFileName;
    }
}
static void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys);
static void WriteLimits(FILE *fp, float *bounds);

// Write out data in MOVIE.BYU format.
void vtkMCubesWriter::WriteData()
{
  vtkPoints *pts;
  vtkNormals *normals;
  vtkCellArray *polys;
  vtkPolyData *input=this->GetInput();

  polys = input->GetPolys();
  pts = input->GetPoints();
  if (pts == NULL || polys == NULL )
    {
    vtkErrorMacro(<<"No data to write!");
    return;
    }

  normals = input->GetPointData()->GetNormals();
  if (normals == NULL )
    {
    vtkErrorMacro(<<"No normals to write!: use vtkPolyDataNormals to generate them");
    return;
    }

  if ( this->FileName == NULL)
    {
    vtkErrorMacro(<< "Please specify FileName to write");
    return;
    }

  vtkDebugMacro("Writing MCubes tri file");
  FILE *fp;
  if ((fp = fopen(this->FileName, "w")) == NULL)
    {
    vtkErrorMacro(<< "Couldn't open file: " << this->FileName);
    return;
    }
  WriteMCubes (fp, pts, normals, polys);
  fclose (fp);

  if (this->LimitsFileName)
    {
    vtkDebugMacro("Writing MCubes limits file");
    if ((fp = fopen(this->LimitsFileName, "w")) == NULL)
      {
      vtkErrorMacro(<< "Couldn't open file: " << this->LimitsFileName);
      return;
      }
    WriteLimits (fp, input->GetBounds ());
    fclose (fp);
  }
}

void WriteMCubes(FILE *fp, vtkPoints *pts, vtkNormals *normals, vtkCellArray *polys)
{
  typedef struct {float x[3], n[3];} pointType;
  pointType point;
  int i;
  int npts, *indx;

  //  Write out triangle polygons.  In not a triangle polygon, create triangles.
  //
  for (polys->InitTraversal(); polys->GetNextCell(npts,indx); )
    {
    for (i=0; i < 3; i++)
      {
      pts->GetPoint(indx[i],&point.x[0]);
      normals->GetNormal(indx[i],&point.n[0]);
      vtkByteSwap::SwapWrite4BERange((float *) (&point),6,fp);
      }
    }
}
void WriteLimits(FILE *fp, float *bounds)
{
  vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
  vtkByteSwap::SwapWrite4BERange((float *) bounds,6,fp);
}

void vtkMCubesWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkPolyDataWriter::PrintSelf(os,indent);

  os << indent << "Limits File Name: "
     << (this->LimitsFileName ? this->LimitsFileName : "(none)") << "\n";
}

<|endoftext|>