<commit_before>// Ouzel by Elviss Strazdins

#ifndef OUZEL_GRAPHICS_METALRENDERDEVICE_HPP
#define OUZEL_GRAPHICS_METALRENDERDEVICE_HPP

#include "../../core/Setup.h"

#if OUZEL_COMPILE_METAL

#include <map>
#include <memory>
#include <vector>

#ifdef __OBJC__
#  import <CoreVideo/CoreVideo.h>
#  import <QuartzCore/QuartzCore.h>
#  import <Metal/Metal.h>
typedef CAMetalLayer* CAMetalLayerPtr;
typedef id<MTLDevice> MTLDevicePtr;
typedef id<MTLBuffer> MTLBufferPtr;
typedef MTLRenderPassDescriptor* MTLRenderPassDescriptorPtr;
typedef id<MTLSamplerState> MTLSamplerStatePtr;
typedef id<MTLCommandQueue> MTLCommandQueuePtr;
typedef id<MTLRenderPipelineState> MTLRenderPipelineStatePtr;
typedef id<MTLTexture> MTLTexturePtr;
typedef id<MTLDepthStencilState> MTLDepthStencilStatePtr;
#else
#  include <objc/objc.h>
#  include <objc/NSObjCRuntime.h>
using CAMetalLayerPtr = id;
using MTLDevicePtr = id;
using MTLBufferPtr = id;
using MTLRenderPassDescriptorPtr = id;
using MTLSamplerStatePtr = id;
using MTLCommandBufferPtr = id;
using MTLCommandQueuePtr = id;
using MTLRenderCommandEncoderPtr = id;
using MTLRenderPipelineStatePtr = id;
using MTLTexturePtr = id;
using MTLDepthStencilStatePtr = id;
using MTLPixelFormat = NSUInteger;
using MTLLoadAction = NSUInteger;
#endif

#include "../RenderDevice.hpp"
#include "MetalPointer.hpp"
#include "MetalShader.hpp"
#include "MetalTexture.hpp"
#include "../../platform/dispatch/DispatchSemaphore.hpp"

namespace ouzel::graphics::metal
{
    class BlendState;
    class Shader;

    class RenderDevice: public graphics::RenderDevice
    {
        friend Graphics;
    public:
        static constexpr std::size_t bufferSize = 1024U * 1024U; // size of shader constant buffer
        static constexpr std::size_t bufferCount = 3U; // allow encoding up to 3 command buffers simultaneously

        static bool available();

        auto& getDevice() const noexcept { return device; }

        MTLSamplerStatePtr getSamplerState(const SamplerStateDescriptor& descriptor);

        template <class T>
        auto getResource(std::size_t id) const
        {
            return id ? static_cast<T*>(resources[id - 1].get()) : nullptr;
        }

    protected:
        RenderDevice(const Settings& settings,
                     core::Window& newWindow,
                     const std::function<void(const Event&)>& initCallback);

        void process() override;
        void generateScreenshot(const std::string& filename) override;

        class PipelineStateDesc final
        {
        public:
            BlendState* blendState = nullptr;
            Shader* shader = nullptr;
            NSUInteger sampleCount = 0;
            std::vector<MTLPixelFormat> colorFormats;
            MTLPixelFormat depthFormat;
            MTLPixelFormat stencilFormat;

            bool operator<(const PipelineStateDesc& other) const noexcept
            {
                return std::tie(blendState, shader, sampleCount, colorFormats, depthFormat) <
                    std::tie(other.blendState, other.shader, other.sampleCount, colorFormats, other.depthFormat);
            }
        };

        MTLRenderPipelineStatePtr getPipelineState(const PipelineStateDesc& desc);

        Pointer<MTLDevicePtr> device;
        Pointer<MTLCommandQueuePtr> metalCommandQueue;
        CAMetalLayerPtr metalLayer = nil;
        Pointer<MTLTexturePtr> currentMetalTexture;

        struct ShaderConstantBuffer final
        {
            std::vector<Pointer<MTLBufferPtr>> buffers;
            std::uint32_t index = 0;
            std::uint32_t offset = 0;
        };

        std::uint32_t shaderConstantBufferIndex = 0;
        ShaderConstantBuffer shaderConstantBuffers[bufferCount];

        Pointer<MTLRenderPassDescriptorPtr> renderPassDescriptor;
        Pointer<MTLDepthStencilStatePtr> defaultDepthStencilState;

        Pointer<MTLTexturePtr> msaaTexture;
        Pointer<MTLTexturePtr> depthTexture;
        std::map<SamplerStateDescriptor, Pointer<MTLSamplerStatePtr>> samplerStates;

        MTLPixelFormat colorFormat;
        MTLPixelFormat depthFormat;
        MTLPixelFormat stencilFormat;

        platform::dispatch::DispatchSemaphore inflightSemaphore{bufferCount};

        std::map<PipelineStateDesc, Pointer<MTLRenderPipelineStatePtr>> pipelineStates;

        std::vector<std::unique_ptr<RenderResource>> resources;
    };
}

#endif

#endif // OUZEL_GRAPHICS_METALRENDERDEVICE_HPP
<commit_msg>Use array for shader constant buffers<commit_after>// Ouzel by Elviss Strazdins

#ifndef OUZEL_GRAPHICS_METALRENDERDEVICE_HPP
#define OUZEL_GRAPHICS_METALRENDERDEVICE_HPP

#include "../../core/Setup.h"

#if OUZEL_COMPILE_METAL

#include <array>
#include <map>
#include <memory>
#include <vector>

#ifdef __OBJC__
#  import <CoreVideo/CoreVideo.h>
#  import <QuartzCore/QuartzCore.h>
#  import <Metal/Metal.h>
typedef CAMetalLayer* CAMetalLayerPtr;
typedef id<MTLDevice> MTLDevicePtr;
typedef id<MTLBuffer> MTLBufferPtr;
typedef MTLRenderPassDescriptor* MTLRenderPassDescriptorPtr;
typedef id<MTLSamplerState> MTLSamplerStatePtr;
typedef id<MTLCommandQueue> MTLCommandQueuePtr;
typedef id<MTLRenderPipelineState> MTLRenderPipelineStatePtr;
typedef id<MTLTexture> MTLTexturePtr;
typedef id<MTLDepthStencilState> MTLDepthStencilStatePtr;
#else
#  include <objc/objc.h>
#  include <objc/NSObjCRuntime.h>
using CAMetalLayerPtr = id;
using MTLDevicePtr = id;
using MTLBufferPtr = id;
using MTLRenderPassDescriptorPtr = id;
using MTLSamplerStatePtr = id;
using MTLCommandBufferPtr = id;
using MTLCommandQueuePtr = id;
using MTLRenderCommandEncoderPtr = id;
using MTLRenderPipelineStatePtr = id;
using MTLTexturePtr = id;
using MTLDepthStencilStatePtr = id;
using MTLPixelFormat = NSUInteger;
using MTLLoadAction = NSUInteger;
#endif

#include "../RenderDevice.hpp"
#include "MetalPointer.hpp"
#include "MetalShader.hpp"
#include "MetalTexture.hpp"
#include "../../platform/dispatch/DispatchSemaphore.hpp"

namespace ouzel::graphics::metal
{
    class BlendState;
    class Shader;

    class RenderDevice: public graphics::RenderDevice
    {
        friend Graphics;
    public:
        static constexpr std::size_t bufferSize = 1024U * 1024U; // size of shader constant buffer
        static constexpr std::size_t bufferCount = 3U; // allow encoding up to 3 command buffers simultaneously

        static bool available();

        auto& getDevice() const noexcept { return device; }

        MTLSamplerStatePtr getSamplerState(const SamplerStateDescriptor& descriptor);

        template <class T>
        auto getResource(std::size_t id) const
        {
            return id ? static_cast<T*>(resources[id - 1].get()) : nullptr;
        }

    protected:
        RenderDevice(const Settings& settings,
                     core::Window& newWindow,
                     const std::function<void(const Event&)>& initCallback);

        void process() override;
        void generateScreenshot(const std::string& filename) override;

        class PipelineStateDesc final
        {
        public:
            BlendState* blendState = nullptr;
            Shader* shader = nullptr;
            NSUInteger sampleCount = 0;
            std::vector<MTLPixelFormat> colorFormats;
            MTLPixelFormat depthFormat;
            MTLPixelFormat stencilFormat;

            bool operator<(const PipelineStateDesc& other) const noexcept
            {
                return std::tie(blendState, shader, sampleCount, colorFormats, depthFormat) <
                    std::tie(other.blendState, other.shader, other.sampleCount, colorFormats, other.depthFormat);
            }
        };

        MTLRenderPipelineStatePtr getPipelineState(const PipelineStateDesc& desc);

        Pointer<MTLDevicePtr> device;
        Pointer<MTLCommandQueuePtr> metalCommandQueue;
        CAMetalLayerPtr metalLayer = nil;
        Pointer<MTLTexturePtr> currentMetalTexture;

        struct ShaderConstantBuffer final
        {
            std::vector<Pointer<MTLBufferPtr>> buffers;
            std::uint32_t index = 0;
            std::uint32_t offset = 0;
        };

        std::uint32_t shaderConstantBufferIndex = 0;
        std::array<ShaderConstantBuffer, bufferCount> shaderConstantBuffers;

        Pointer<MTLRenderPassDescriptorPtr> renderPassDescriptor;
        Pointer<MTLDepthStencilStatePtr> defaultDepthStencilState;

        Pointer<MTLTexturePtr> msaaTexture;
        Pointer<MTLTexturePtr> depthTexture;
        std::map<SamplerStateDescriptor, Pointer<MTLSamplerStatePtr>> samplerStates;

        MTLPixelFormat colorFormat;
        MTLPixelFormat depthFormat;
        MTLPixelFormat stencilFormat;

        platform::dispatch::DispatchSemaphore inflightSemaphore{bufferCount};

        std::map<PipelineStateDesc, Pointer<MTLRenderPipelineStatePtr>> pipelineStates;

        std::vector<std::unique_ptr<RenderResource>> resources;
    };
}

#endif

#endif // OUZEL_GRAPHICS_METALRENDERDEVICE_HPP
<|endoftext|>


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

#include <floatwin.hxx>
#include <bitmap.hxx>
#include <image.hxx>

// -----------
// - Defines -
// -----------

#define WHEELMODE_NONE      0x00000000UL
#define WHEELMODE_VH        0x00000001UL
#define WHEELMODE_V         0x00000002UL
#define WHEELMODE_H         0x00000004UL
#define WHEELMODE_SCROLL_VH 0x00000008UL
#define WHEELMODE_SCROLL_V  0x00000010UL
#define WHEELMODE_SCROLL_H  0x00000020UL

// -------------------
// - ImplWheelWindow -
// -------------------

class Timer;

class ImplWheelWindow : public FloatingWindow
{
private:

    ImageList           maImgList;
    Bitmap              maWheelBmp;
    CommandScrollData   maCommandScrollData;
    Point               maLastMousePos;
    Point               maCenter;
    Timer*              mpTimer;
    ULONG               mnRepaintTime;
    ULONG               mnTimeout;
    ULONG               mnWheelMode;
    ULONG               mnMaxWidth;
    ULONG               mnActWidth;
    ULONG               mnActDist;
    long                mnActDeltaX;
    long                mnActDeltaY;

    void                ImplCreateImageList();
    void                ImplSetRegion( const Bitmap& rRegionBmp );
    PointerStyle        ImplGetMousePointer( long nDistX, long nDistY );
    void                ImplDrawWheel();
    void                ImplRecalcScrollValues();

                        DECL_LINK( ImplScrollHdl, Timer* pTimer );

protected:

    virtual void        Paint( const Rectangle& rRect );
    virtual void        MouseMove( const MouseEvent& rMEvt );
    virtual void        MouseButtonUp( const MouseEvent& rMEvt );

public:

                        ImplWheelWindow( Window* pParent );
                        ~ImplWheelWindow();

    void                ImplSetWheelMode( ULONG nWheelMode );
    ULONG               ImplGetWheelMode() const { return mnWheelMode; }
};
<commit_msg>INTEGRATION: CWS warnings01 (1.2.70); FILE MERGED 2005/11/10 20:06:35 pl 1.2.70.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scrwnd.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 19:40:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <floatwin.hxx>
#include <bitmap.hxx>
#include <image.hxx>

// -----------
// - Defines -
// -----------

#define WHEELMODE_NONE      0x00000000UL
#define WHEELMODE_VH        0x00000001UL
#define WHEELMODE_V         0x00000002UL
#define WHEELMODE_H         0x00000004UL
#define WHEELMODE_SCROLL_VH 0x00000008UL
#define WHEELMODE_SCROLL_V  0x00000010UL
#define WHEELMODE_SCROLL_H  0x00000020UL

// -------------------
// - ImplWheelWindow -
// -------------------

class Timer;

class ImplWheelWindow : public FloatingWindow
{
private:

    ImageList           maImgList;
    Bitmap              maWheelBmp;
    CommandScrollData   maCommandScrollData;
    Point               maLastMousePos;
    Point               maCenter;
    Timer*              mpTimer;
    ULONG               mnRepaintTime;
    ULONG               mnTimeout;
    ULONG               mnWheelMode;
    ULONG               mnMaxWidth;
    ULONG               mnActWidth;
    ULONG               mnActDist;
    long                mnActDeltaX;
    long                mnActDeltaY;

    void                ImplCreateImageList();
    void                ImplSetRegion( const Bitmap& rRegionBmp );
    using Window::ImplGetMousePointer;
    PointerStyle        ImplGetMousePointer( long nDistX, long nDistY );
    void                ImplDrawWheel();
    void                ImplRecalcScrollValues();

                        DECL_LINK( ImplScrollHdl, Timer* pTimer );

protected:

    virtual void        Paint( const Rectangle& rRect );
    virtual void        MouseMove( const MouseEvent& rMEvt );
    virtual void        MouseButtonUp( const MouseEvent& rMEvt );

public:

                        ImplWheelWindow( Window* pParent );
                        ~ImplWheelWindow();

    void                ImplSetWheelMode( ULONG nWheelMode );
    ULONG               ImplGetWheelMode() const { return mnWheelMode; }
};
<|endoftext|>


<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <bh.h>
#include <vector>
#include "array.h"
#include "mapping.h"
#include "pgrid.h"
#include "exec.h"
#include "comm.h"
#include "except.h"
#include "batch.h"
#include "tmp.h"

/* Reduces the input chunk to the output chunk.
 * @opcode   The opcode of the reduce function.
 * @axis     The axis to reduce
 * @out      The output chunk
 * @in       The input chunk
*/
static void reduce_chunk(bh_opcode opcode, bh_intp axis,
                         const bh_view &out, const bh_view &in)
{
    bh_instruction inst;
    inst.opcode = opcode;
    inst.operand[0] = out;
    inst.operand[1] = in;
    inst.constant.value.int64 = axis;
    inst.constant.type = BH_INT64;
    batch_schedule_inst(inst);
}

/* Apply the reduce instruction for a vector input and scalar output.
 * @inst    The reduce instruction.
 * @opcode  The opcode of the reduce function.
*/
static void reduce_vector(bh_instruction *inst, bh_opcode opcode)
{
    assert(inst->operand[1].ndim == 1);
    bh_intp axis = inst->constant.value.int64;
    assert(axis == 0);

    //For the mapping we have to "broadcast" the 'axis' dimension to an
    //output array view.
    bh_view bcast_out  = inst->operand[0];
    bcast_out.base      = bh_base_array(&inst->operand[0]);
    bcast_out.ndim      = 1;
    bcast_out.shape[0]  = inst->operand[1].shape[0];
    bcast_out.stride[0] = 0;

    std::vector<ary_chunk> chunks;
    bh_view operands[] = {bcast_out, inst->operand[1]};
    mapping_chunks(2, operands, chunks);
    assert(chunks.size() > 0);

    //Master-tmp array that the master will reduce in the end.
    bh_base *mtmp = tmp_get_ary(bh_base_array(&inst->operand[1])->type, pgrid_worldsize);
    bh_intp mtmp_count=0;//Number of scalars received

    ary_chunk *out = &chunks[0];//The output chunks are all identical
    out->ary.shape[0] = 1;//Remove the broadcasted dimension
    for(std::vector<ary_chunk>::size_type c=0; c < chunks.size(); c += 2)
    {
        ary_chunk *in  = &chunks[c+1];
        if(pgrid_myrank == in->rank)//We own the input chunk
        {
            //Local-tmp array that the process will reduce
            bh_view ltmp;
            ltmp.ndim = 1;
            ltmp.shape[0] = 1;
            ltmp.stride[0] = 1;

            if(pgrid_myrank == out->rank)//We also own the output chunk
            {
                //Lets write directly to the master-tmp array
                ltmp.base = mtmp;
                ltmp.start = mtmp_count;
                reduce_chunk(inst->opcode, axis, ltmp, in->ary);
            }
            else
            {
                //Lets write to a tmp array and send it to the master-process
                ltmp.base = tmp_get_ary(bh_base_array(&in->ary)->type, 1);
                ltmp.start = 0;
                reduce_chunk(inst->opcode, axis, ltmp, in->ary);

                //Send to output owner's mtmp array
                bh_view tmp_view = ltmp;
                tmp_view.base = bh_base_array(&ltmp);
                batch_schedule_comm(1, out->rank, tmp_view);

                //Lets free the tmp array
                batch_schedule_inst(BH_FREE, bh_base_array(&ltmp));
                batch_schedule_inst(BH_DISCARD, bh_base_array(&ltmp));
            }
            if(in->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(&in->ary));
                batch_schedule_inst(BH_DISCARD, bh_base_array(&in->ary));
            }
        }

        if(pgrid_myrank == out->rank)//We own the output chunk
        {
            if(pgrid_myrank != in->rank)//We don't own the input chunk
            {
                //Create a tmp view for receiving
                bh_view recv_view;
                recv_view.base = mtmp;
                recv_view.ndim = 1;
                recv_view.shape[0] = 1;
                recv_view.stride[0] = 1;
                recv_view.start = mtmp_count;

                //Recv from input owner's ltmp to the output owner's mtmp array
                batch_schedule_comm(0, in->rank, recv_view);
            }
            ++mtmp_count;//One scalar added to the master-tmp array
        }
        else
        {   //Only one process can own the final output scalar
            assert(mtmp_count == 0);
        }
    }

    //Lets reduce the master-tmp array if we own it
    if(pgrid_myrank == out->rank && mtmp_count > 0)
    {
        assert(mtmp_count <= pgrid_worldsize);
        //Now we know the number of received scalars
        bh_view tmp;
        tmp.base = mtmp;
        tmp.start = 0;
        tmp.ndim = 1;
        tmp.shape[0] = mtmp_count;
        tmp.stride[0] = 1;
        reduce_chunk(inst->opcode, axis, out->ary, tmp);
        //Only the master needs to cleanup 'mtmp'
        batch_schedule_inst(BH_FREE, mtmp);
        batch_schedule_inst(BH_DISCARD, mtmp);
    }
}

/* Apply the reduce instruction.
 * @inst    The reduce instruction.
 * @opcode  The opcode of the reduce function.
*/
void ufunc_reduce(bh_instruction *inst, bh_opcode opcode)
{
    std::vector<ary_chunk> chunks;
    bh_intp axis = inst->constant.value.int64;

    try
    {
        if(inst->operand[1].ndim == 1)//"Reducing" to a scalar.
            return reduce_vector(inst, opcode);

        //For the mapping we have to "broadcast" the 'axis' dimension to an
        //output array view.
        bh_view bcast_output     = inst->operand[0];
        bcast_output.base        = bh_base_array(&inst->operand[0]);
        bcast_output.ndim        = inst->operand[1].ndim;
        memcpy(bcast_output.shape, inst->operand[1].shape, bcast_output.ndim * sizeof(bh_intp));

        //Insert a zero-stride into the 'axis' dimension
        for(bh_intp i=0; i<axis; ++i)
            bcast_output.stride[i] = inst->operand[0].stride[i];
        bcast_output.stride[axis] = 0;
        for(bh_intp i=axis+1; i<bcast_output.ndim; ++i)
            bcast_output.stride[i] = inst->operand[0].stride[i-1];

        bh_view operands[] = {bcast_output, inst->operand[1]};
        mapping_chunks(2, operands, chunks);
        assert(chunks.size() > 0);

        //First we handle all chunks that computes the first row
        for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += 2)
        {
            ary_chunk *out_chunk = &chunks[c];
            ary_chunk *in_chunk  = &chunks[c+1];
            bh_view   *out       = &out_chunk->ary;
            bh_view   *in        = &in_chunk->ary;

            if(out_chunk->coord[axis] > 0)
                continue;//Not the first row.

            //Lets remove the "broadcasted" dimension from the output again
            out->ndim = inst->operand[0].ndim;
            for(bh_intp i=axis; i<out->ndim; ++i)
            {
                out->shape[i] = out->shape[i+1];
                out->stride[i] = out->stride[i+1];
            }

            //And reduce the 'axis' dimension of the input chunk
            bh_view tmp = *out;
            tmp.base = tmp_get_ary(bh_base_array(out)->type, bh_nelements(out->ndim, out->shape));
            tmp.start = 0;
            bh_set_contiguous_stride(&tmp);
            if(pgrid_myrank == in_chunk->rank)
            {
                reduce_chunk(inst->opcode, axis, tmp, *in);
                if(in_chunk->temporary)
                    batch_schedule_inst(BH_DISCARD, bh_base_array(in));
            }

            //Lets make sure that all processes have the needed input data.
            comm_array_data(tmp, in_chunk->rank, out_chunk->rank);

            if(pgrid_myrank != out_chunk->rank)
                continue;//We do not own the output chunk

            //Finally, we have to "reduce" the local chunks together
            bh_view ops[] = {*out, tmp};
            batch_schedule_inst(BH_IDENTITY, ops, NULL);

            //Cleanup
            batch_schedule_inst(BH_FREE, bh_base_array(&tmp));
            batch_schedule_inst(BH_DISCARD, bh_base_array(&tmp));
            if(out_chunk->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(out));
                batch_schedule_inst(BH_DISCARD, bh_base_array(out));
            }
        }

        //Then we handle all the rest.
        for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += 2)
        {
            ary_chunk *out_chunk = &chunks[c];
            ary_chunk *in_chunk  = &chunks[c+1];
            bh_view *out         = &out_chunk->ary;
            bh_view *in          = &in_chunk->ary;

            if(out_chunk->coord[axis] == 0)
                continue;//The first row

            //Lets remove the "broadcasted" dimension from the output again
            out->ndim = inst->operand[0].ndim;
            for(bh_intp i=axis; i<out->ndim; ++i)
            {
                out->shape[i] = out->shape[i+1];
                out->stride[i] = out->stride[i+1];
            }

            //And reduce the 'axis' dimension of the input chunk
            bh_view tmp;
            tmp = *out;
            tmp.base = tmp_get_ary(bh_base_array(out)->type, bh_nelements(out->ndim, out->shape));
            tmp.start = 0;
            bh_set_contiguous_stride(&tmp);
            if(pgrid_myrank == in_chunk->rank)
            {
                reduce_chunk(inst->opcode, axis, tmp, *in);
                if(in_chunk->temporary)
                {
                    batch_schedule_inst(BH_FREE, bh_base_array(in));
                    batch_schedule_inst(BH_DISCARD, bh_base_array(in));
                }
            }

            //Lets make sure that all processes have the needed input data.
            comm_array_data(tmp, in_chunk->rank, out_chunk->rank);

            if(pgrid_myrank != out_chunk->rank)
                continue;//We do not own the output chunk

            //Finally, we have to "reduce" the local chunks together
            bh_view ops[] = {*out, *out, tmp};
            batch_schedule_inst(opcode, ops, NULL);

            //Cleanup
            batch_schedule_inst(BH_FREE, bh_base_array(&tmp));
            batch_schedule_inst(BH_DISCARD, bh_base_array(&tmp));
            if(out_chunk->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(out));
                batch_schedule_inst(BH_DISCARD, bh_base_array(out));
            }
        }
    }
    catch(std::exception& e)
    {
        fprintf(stderr, "[CLUSTER-VEM] Unhandled exception when reducing: \"%s\"", e.what());
    }
}
<commit_msg>now all processes will cleanup the temp array used for communication<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.

Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.

Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the
GNU Lesser General Public License along with Bohrium.

If not, see <http://www.gnu.org/licenses/>.
*/

#include <cassert>
#include <bh.h>
#include <vector>
#include "array.h"
#include "mapping.h"
#include "pgrid.h"
#include "exec.h"
#include "comm.h"
#include "except.h"
#include "batch.h"
#include "tmp.h"

/* Reduces the input chunk to the output chunk.
 * @opcode   The opcode of the reduce function.
 * @axis     The axis to reduce
 * @out      The output chunk
 * @in       The input chunk
*/
static void reduce_chunk(bh_opcode opcode, bh_intp axis,
                         const bh_view &out, const bh_view &in)
{
    bh_instruction inst;
    inst.opcode = opcode;
    inst.operand[0] = out;
    inst.operand[1] = in;
    inst.constant.value.int64 = axis;
    inst.constant.type = BH_INT64;
    batch_schedule_inst(inst);
}

/* Apply the reduce instruction for a vector input and scalar output.
 * @inst    The reduce instruction.
 * @opcode  The opcode of the reduce function.
*/
static void reduce_vector(bh_instruction *inst, bh_opcode opcode)
{
    assert(inst->operand[1].ndim == 1);
    bh_intp axis = inst->constant.value.int64;
    assert(axis == 0);

    //For the mapping we have to "broadcast" the 'axis' dimension to an
    //output array view.
    bh_view bcast_out  = inst->operand[0];
    bcast_out.base      = bh_base_array(&inst->operand[0]);
    bcast_out.ndim      = 1;
    bcast_out.shape[0]  = inst->operand[1].shape[0];
    bcast_out.stride[0] = 0;

    std::vector<ary_chunk> chunks;
    bh_view operands[] = {bcast_out, inst->operand[1]};
    mapping_chunks(2, operands, chunks);
    assert(chunks.size() > 0);

    //Master-tmp array that the master will reduce in the end.
    bh_base *mtmp = tmp_get_ary(bh_base_array(&inst->operand[1])->type, pgrid_worldsize);
    bh_intp mtmp_count=0;//Number of scalars received

    ary_chunk *out = &chunks[0];//The output chunks are all identical
    out->ary.shape[0] = 1;//Remove the broadcasted dimension
    for(std::vector<ary_chunk>::size_type c=0; c < chunks.size(); c += 2)
    {
        ary_chunk *in  = &chunks[c+1];
        if(pgrid_myrank == in->rank)//We own the input chunk
        {
            //Local-tmp array that the process will reduce
            bh_view ltmp;
            ltmp.ndim = 1;
            ltmp.shape[0] = 1;
            ltmp.stride[0] = 1;

            if(pgrid_myrank == out->rank)//We also own the output chunk
            {
                //Lets write directly to the master-tmp array
                ltmp.base = mtmp;
                ltmp.start = mtmp_count;
                reduce_chunk(inst->opcode, axis, ltmp, in->ary);
            }
            else
            {
                //Lets write to a tmp array and send it to the master-process
                ltmp.base = tmp_get_ary(bh_base_array(&in->ary)->type, 1);
                ltmp.start = 0;
                reduce_chunk(inst->opcode, axis, ltmp, in->ary);

                //Send to output owner's mtmp array
                bh_view tmp_view = ltmp;
                tmp_view.base = bh_base_array(&ltmp);
                batch_schedule_comm(1, out->rank, tmp_view);

                //Lets free the tmp array
                batch_schedule_inst(BH_FREE, bh_base_array(&ltmp));
                batch_schedule_inst(BH_DISCARD, bh_base_array(&ltmp));
            }
            if(in->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(&in->ary));
                batch_schedule_inst(BH_DISCARD, bh_base_array(&in->ary));
            }
        }

        if(pgrid_myrank == out->rank)//We own the output chunk
        {
            if(pgrid_myrank != in->rank)//We don't own the input chunk
            {
                //Create a tmp view for receiving
                bh_view recv_view;
                recv_view.base = mtmp;
                recv_view.ndim = 1;
                recv_view.shape[0] = 1;
                recv_view.stride[0] = 1;
                recv_view.start = mtmp_count;

                //Recv from input owner's ltmp to the output owner's mtmp array
                batch_schedule_comm(0, in->rank, recv_view);
            }
            ++mtmp_count;//One scalar added to the master-tmp array
        }
        else
        {   //Only one process can own the final output scalar
            assert(mtmp_count == 0);
        }
    }

    //Lets reduce the master-tmp array if we own it
    if(pgrid_myrank == out->rank && mtmp_count > 0)
    {
        assert(mtmp_count <= pgrid_worldsize);
        //Now we know the number of received scalars
        bh_view tmp;
        tmp.base = mtmp;
        tmp.start = 0;
        tmp.ndim = 1;
        tmp.shape[0] = mtmp_count;
        tmp.stride[0] = 1;
        reduce_chunk(inst->opcode, axis, out->ary, tmp);
        //Only the master needs to cleanup 'mtmp'
        batch_schedule_inst(BH_FREE, mtmp);
        batch_schedule_inst(BH_DISCARD, mtmp);
    }
}

/* Apply the reduce instruction.
 * @inst    The reduce instruction.
 * @opcode  The opcode of the reduce function.
*/
void ufunc_reduce(bh_instruction *inst, bh_opcode opcode)
{
    std::vector<ary_chunk> chunks;
    bh_intp axis = inst->constant.value.int64;

    try
    {
        if(inst->operand[1].ndim == 1)//"Reducing" to a scalar.
            return reduce_vector(inst, opcode);

        //For the mapping we have to "broadcast" the 'axis' dimension to an
        //output array view.
        bh_view bcast_output     = inst->operand[0];
        bcast_output.base        = bh_base_array(&inst->operand[0]);
        bcast_output.ndim        = inst->operand[1].ndim;
        memcpy(bcast_output.shape, inst->operand[1].shape, bcast_output.ndim * sizeof(bh_intp));

        //Insert a zero-stride into the 'axis' dimension
        for(bh_intp i=0; i<axis; ++i)
            bcast_output.stride[i] = inst->operand[0].stride[i];
        bcast_output.stride[axis] = 0;
        for(bh_intp i=axis+1; i<bcast_output.ndim; ++i)
            bcast_output.stride[i] = inst->operand[0].stride[i-1];

        bh_view operands[] = {bcast_output, inst->operand[1]};
        mapping_chunks(2, operands, chunks);
        assert(chunks.size() > 0);

        //First we handle all chunks that computes the first row
        for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += 2)
        {
            ary_chunk *out_chunk = &chunks[c];
            ary_chunk *in_chunk  = &chunks[c+1];
            bh_view   *out       = &out_chunk->ary;
            bh_view   *in        = &in_chunk->ary;

            if(out_chunk->coord[axis] > 0)
                continue;//Not the first row.

            //Lets remove the "broadcasted" dimension from the output again
            out->ndim = inst->operand[0].ndim;
            for(bh_intp i=axis; i<out->ndim; ++i)
            {
                out->shape[i] = out->shape[i+1];
                out->stride[i] = out->stride[i+1];
            }

            //And reduce the 'axis' dimension of the input chunk
            bh_view tmp = *out;
            tmp.base = tmp_get_ary(bh_base_array(out)->type, bh_nelements(out->ndim, out->shape));
            tmp.start = 0;
            bh_set_contiguous_stride(&tmp);
            if(pgrid_myrank == in_chunk->rank)
            {
                reduce_chunk(inst->opcode, axis, tmp, *in);
                if(in_chunk->temporary)
                {
                    batch_schedule_inst(BH_FREE, bh_base_array(in));
                    batch_schedule_inst(BH_DISCARD, bh_base_array(in));
                }
            }

            //Lets make sure that all processes have the needed input data.
            comm_array_data(tmp, in_chunk->rank, out_chunk->rank);

            if(pgrid_myrank == out_chunk->rank)
            {
                //Finally, we have to "reduce" the local chunks together
                bh_view ops[] = {*out, tmp};
                batch_schedule_inst(BH_IDENTITY, ops, NULL);
            }

            //Cleanup
            batch_schedule_inst(BH_FREE, bh_base_array(&tmp));
            batch_schedule_inst(BH_DISCARD, bh_base_array(&tmp));
            if(out_chunk->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(out));
                batch_schedule_inst(BH_DISCARD, bh_base_array(out));
            }
        }

        //Then we handle all the rest.
        for(std::vector<ary_chunk>::size_type c=0; c < chunks.size();c += 2)
        {
            ary_chunk *out_chunk = &chunks[c];
            ary_chunk *in_chunk  = &chunks[c+1];
            bh_view *out         = &out_chunk->ary;
            bh_view *in          = &in_chunk->ary;

            if(out_chunk->coord[axis] == 0)
                continue;//The first row

            //Lets remove the "broadcasted" dimension from the output again
            out->ndim = inst->operand[0].ndim;
            for(bh_intp i=axis; i<out->ndim; ++i)
            {
                out->shape[i] = out->shape[i+1];
                out->stride[i] = out->stride[i+1];
            }

            //And reduce the 'axis' dimension of the input chunk
            bh_view tmp;
            tmp = *out;
            tmp.base = tmp_get_ary(bh_base_array(out)->type, bh_nelements(out->ndim, out->shape));
            tmp.start = 0;
            bh_set_contiguous_stride(&tmp);
            if(pgrid_myrank == in_chunk->rank)
            {
                reduce_chunk(inst->opcode, axis, tmp, *in);
                if(in_chunk->temporary)
                {
                    batch_schedule_inst(BH_FREE, bh_base_array(in));
                    batch_schedule_inst(BH_DISCARD, bh_base_array(in));
                }
            }

            //Lets make sure that all processes have the needed input data.
            comm_array_data(tmp, in_chunk->rank, out_chunk->rank);

            if(pgrid_myrank == out_chunk->rank)
            {
                //Finally, we have to "reduce" the local chunks together
                bh_view ops[] = {*out, *out, tmp};
                batch_schedule_inst(opcode, ops, NULL);
            }

            //Cleanup
            batch_schedule_inst(BH_FREE, bh_base_array(&tmp));
            batch_schedule_inst(BH_DISCARD, bh_base_array(&tmp));
            if(out_chunk->temporary)
            {
                batch_schedule_inst(BH_FREE, bh_base_array(out));
                batch_schedule_inst(BH_DISCARD, bh_base_array(out));
            }
        }
    }
    catch(std::exception& e)
    {
        fprintf(stderr, "[CLUSTER-VEM] Unhandled exception when reducing: \"%s\"", e.what());
    }
}
<|endoftext|>


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

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

#include "componentmodule.cxx"

<commit_msg>INTEGRATION: CWS changefileheader (1.3.276); FILE MERGED 2008/03/31 12:31:38 rt 1.3.276.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: modulepreload.cxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include "componentmodule.cxx"

<|endoftext|>


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

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <rtl/ref.hxx>
#include <rtl/ustring.hxx>
#include <osl/conditn.hxx>
#include <osl/file.h>

struct DownloadInteractionHandler : public rtl::IReference
{
    // called if the destination file already exists, but resume is false
    virtual bool downloadTargetExists(const rtl::OUString& rFileName) = 0;

    // called when curl reports an error
    virtual void downloadStalled(const rtl::OUString& rErrorMessage) = 0;

    // progress handler
    virtual void downloadProgressAt(sal_Int8 nPercent) = 0;

    // called on first progress notification
    virtual void downloadStarted(const rtl::OUString& rFileName, sal_Int64 nFileSize) = 0;

    // called when download has been finished
    virtual void downloadFinished(const rtl::OUString& rFileName) = 0;
};

class Download
{
public:
    Download(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& xContext,
             const rtl::Reference< DownloadInteractionHandler >& rHandler) : m_xContext(xContext), m_aHandler(rHandler) {};

    // returns true when the content of rURL was successfully written to rLocalFile
    bool start(const rtl::OUString& rURL, const rtl::OUString& rFile, const rtl::OUString& rDestinationDir);

    // stops the download after the next write operation
    void stop();

    // returns true if the stop condition is set
    bool isStopped() const
        { return sal_True == const_cast <Download *> (this)->m_aCondition.check(); };

protected:

    // Determines the appropriate proxy settings for the given URL. Returns true if a proxy should be used
    void getProxyForURL(const rtl::OUString& rURL, rtl::OString& rHost, sal_Int32& rPort) const;

private:
    osl::Condition m_aCondition;
    const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& m_xContext;
    const rtl::Reference< DownloadInteractionHandler > m_aHandler;
};

<commit_msg>INTEGRATION: CWS changefileheader (1.3.118); FILE MERGED 2008/04/01 12:29:58 thb 1.3.118.2: #i85898# Stripping all external header guards 2008/03/31 12:32:13 rt 1.3.118.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: download.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <com/sun/star/uno/XComponentContext.hpp>

#include <rtl/ref.hxx>
#include <rtl/ustring.hxx>
#include <osl/conditn.hxx>
#include <osl/file.h>

struct DownloadInteractionHandler : public rtl::IReference
{
    // called if the destination file already exists, but resume is false
    virtual bool downloadTargetExists(const rtl::OUString& rFileName) = 0;

    // called when curl reports an error
    virtual void downloadStalled(const rtl::OUString& rErrorMessage) = 0;

    // progress handler
    virtual void downloadProgressAt(sal_Int8 nPercent) = 0;

    // called on first progress notification
    virtual void downloadStarted(const rtl::OUString& rFileName, sal_Int64 nFileSize) = 0;

    // called when download has been finished
    virtual void downloadFinished(const rtl::OUString& rFileName) = 0;
};

class Download
{
public:
    Download(const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& xContext,
             const rtl::Reference< DownloadInteractionHandler >& rHandler) : m_xContext(xContext), m_aHandler(rHandler) {};

    // returns true when the content of rURL was successfully written to rLocalFile
    bool start(const rtl::OUString& rURL, const rtl::OUString& rFile, const rtl::OUString& rDestinationDir);

    // stops the download after the next write operation
    void stop();

    // returns true if the stop condition is set
    bool isStopped() const
        { return sal_True == const_cast <Download *> (this)->m_aCondition.check(); };

protected:

    // Determines the appropriate proxy settings for the given URL. Returns true if a proxy should be used
    void getProxyForURL(const rtl::OUString& rURL, rtl::OString& rHost, sal_Int32& rPort) const;

private:
    osl::Condition m_aCondition;
    const com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext >& m_xContext;
    const rtl::Reference< DownloadInteractionHandler > m_aHandler;
};

<|endoftext|>


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

#include "ReprojectionFilter.hpp"

#include <pdal/PointView.hpp>
#include <pdal/GlobalEnvironment.hpp>

#include <gdal.h>
#include <ogr_spatialref.h>

#include <memory>

namespace pdal
{

static PluginInfo const s_info = PluginInfo(
    "filters.reprojection",
    "Reproject data using GDAL from one coordinate system to another.",
    "http://pdal.io/stages/filters.reprojection.html" );

CREATE_STATIC_PLUGIN(1, 0, ReprojectionFilter, Filter, s_info)

std::string ReprojectionFilter::getName() const { return s_info.name; }

ReprojectionFilter::ReprojectionFilter() : m_inferInputSRS(true),
    m_in_ref_ptr(NULL), m_out_ref_ptr(NULL), m_transform_ptr(NULL), m_cullBadPoints(false)
{}

ReprojectionFilter::~ReprojectionFilter()
{
    if (m_transform_ptr)
        OCTDestroyCoordinateTransformation(m_transform_ptr);
    if (m_in_ref_ptr)
        OSRDestroySpatialReference(m_in_ref_ptr);
    if (m_out_ref_ptr)
        OSRDestroySpatialReference(m_out_ref_ptr);
}

void ReprojectionFilter::processOptions(const Options& options)
{
    try
    {
       m_outSRS = options.getValueOrThrow<pdal::SpatialReference>("out_srs");
    }
    catch (std::invalid_argument)
    {
        std::string srs = options.getValueOrDefault<std::string>("out_srs", "");
        std::ostringstream oss;
        oss << "Stage " << getName() << " has invalid spatial reference "
            "specification for 'out_srs' option: '" << srs << "'.";
        throw pdal_error(oss.str());
    }
    catch (Option::not_found)
    {
        std::ostringstream oss;
        oss << "Stage " << getName() << " missing required option 'out_srs'.";
        throw Option::not_found(oss.str());
    }

    if (options.hasOption("in_srs"))
    {
        try
        {
            m_inSRS = options.getValueOrThrow<pdal::SpatialReference>("in_srs");
        }
        catch (std::invalid_argument)
        {
            std::string srs =
                options.getValueOrDefault<std::string>("in_srs", "");
            std::ostringstream oss;
            oss << "Stage " << getName() << " has invalid spatial reference "
                "specification for 'in_srs' option: '" << srs << "'.";
            throw pdal_error(oss.str());
        }
        m_inferInputSRS = false;
    }

    m_cullBadPoints = options.getValueOrDefault("cull_unprojectable_points", false);
}

void ReprojectionFilter::initialize()
{
    GlobalEnvironment::get().initializeGDAL(log(), isDebug());
}

void ReprojectionFilter::ready(PointTableRef table)
{
    if (m_inferInputSRS)
    {
        m_inSRS = table.spatialRef();
        if (m_inSRS.getWKT().empty())
            throw pdal_error("Source data has no spatial reference and none "
                "is specified with the 'in_srs' option.");
    }

    m_in_ref_ptr = OSRNewSpatialReference(0);
    m_out_ref_ptr = OSRNewSpatialReference(0);

    int result =
        OSRSetFromUserInput(m_in_ref_ptr,
            m_inSRS.getWKT(pdal::SpatialReference::eCompoundOK).c_str());
    if (result != OGRERR_NONE)
    {
        std::ostringstream msg;
        msg << "Invalid input spatial reference '" << m_inSRS.getWKT() <<
            "'.  This is usually caused by a bad value for the 'in_srs'"
            "option or an invalid spatial reference in the source file.";
        throw pdal_error(msg.str());
    }

    result = OSRSetFromUserInput(m_out_ref_ptr,
        m_outSRS.getWKT(pdal::SpatialReference::eCompoundOK).c_str());
    if (result != OGRERR_NONE)
    {
        std::ostringstream msg;
        msg << "Invalid output spatial reference '" << m_outSRS.getWKT() <<
            "'.  This is usually caused by a bad value for the 'out_srs'"
            "option.";
        throw pdal_error(msg.str());
    }

    m_transform_ptr = OCTNewCoordinateTransformation(m_in_ref_ptr, m_out_ref_ptr);
    if (!m_transform_ptr)
    {
        std::string msg = "Could not construct CoordinateTransformation in "
            "ReprojectionFilter:: ";
        throw std::runtime_error(msg);
    }

    setSpatialReference(m_outSRS);
}

bool ReprojectionFilter::transform(double& x, double& y, double& z)
{
    try
    {
        // OCTTransform will throw via GDAL error handler
        // if there is an error. We don't expect the return value
        // unless the GDAL handler gets shut off for whatever reason. In
        // that case, we'll just throw.
        if (OCTTransform(m_transform_ptr, 1, &x, &y, &z))
        {
            return true;
        }
        else
        {
            std::ostringstream msg;
            msg << "Could not project point for ReprojectionTransform::" <<
                CPLGetLastErrorMsg();
            throw pdal_error(msg.str());
        }
    }
    catch (pdal::pdal_error& e)
    {
        if (m_cullBadPoints) return false;
        else throw e.what();
    }
}

PointViewSet ReprojectionFilter::run(PointViewPtr view)
{
    PointViewSet viewSet;
    PointViewPtr outView = view->makeNew();

    double x, y, z;

    for (PointId id = 0; id < view->size(); ++id)
    {
        x = view->getFieldAs<double>(Dimension::Id::X, id);
        y = view->getFieldAs<double>(Dimension::Id::Y, id);
        z = view->getFieldAs<double>(Dimension::Id::Z, id);

        if (transform(x, y, z))
        {
            view->setField(Dimension::Id::X, id, x);
            view->setField(Dimension::Id::Y, id, y);
            view->setField(Dimension::Id::Z, id, z);
            outView->appendPoint(*view, id);
        }
    }
    viewSet.insert(outView);

    return viewSet;
}

void ReprojectionFilter::filter(PointView& view)
{
    double x, y, z;

    for (PointId id = 0; id < view.size(); ++id)
    {
        x = view.getFieldAs<double>(Dimension::Id::X, id);
        y = view.getFieldAs<double>(Dimension::Id::Y, id);
        z = view.getFieldAs<double>(Dimension::Id::Z, id);

        OCTTransform(m_transform_ptr, 1, &x, &y, &z);

        view.setField(Dimension::Id::X, id, x);
        view.setField(Dimension::Id::Y, id, y);
        view.setField(Dimension::Id::Z, id, z);
    }
}

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

#include "ReprojectionFilter.hpp"

#include <pdal/PointView.hpp>
#include <pdal/GlobalEnvironment.hpp>

#include <gdal.h>
#include <ogr_spatialref.h>

#include <memory>

namespace pdal
{

static PluginInfo const s_info = PluginInfo(
    "filters.reprojection",
    "Reproject data using GDAL from one coordinate system to another.",
    "http://pdal.io/stages/filters.reprojection.html" );

CREATE_STATIC_PLUGIN(1, 0, ReprojectionFilter, Filter, s_info)

std::string ReprojectionFilter::getName() const { return s_info.name; }

ReprojectionFilter::ReprojectionFilter() : m_inferInputSRS(true),
    m_in_ref_ptr(NULL), m_out_ref_ptr(NULL), m_transform_ptr(NULL), m_cullBadPoints(false)
{}

ReprojectionFilter::~ReprojectionFilter()
{
    if (m_transform_ptr)
        OCTDestroyCoordinateTransformation(m_transform_ptr);
    if (m_in_ref_ptr)
        OSRDestroySpatialReference(m_in_ref_ptr);
    if (m_out_ref_ptr)
        OSRDestroySpatialReference(m_out_ref_ptr);
}

void ReprojectionFilter::processOptions(const Options& options)
{
    try
    {
       m_outSRS = options.getValueOrThrow<pdal::SpatialReference>("out_srs");
    }
    catch (std::invalid_argument)
    {
        std::string srs = options.getValueOrDefault<std::string>("out_srs", "");
        std::ostringstream oss;
        oss << "Stage " << getName() << " has invalid spatial reference "
            "specification for 'out_srs' option: '" << srs << "'.";
        throw pdal_error(oss.str());
    }
    catch (Option::not_found)
    {
        std::ostringstream oss;
        oss << "Stage " << getName() << " missing required option 'out_srs'.";
        throw Option::not_found(oss.str());
    }

    if (options.hasOption("in_srs"))
    {
        try
        {
            m_inSRS = options.getValueOrThrow<pdal::SpatialReference>("in_srs");
        }
        catch (std::invalid_argument)
        {
            std::string srs =
                options.getValueOrDefault<std::string>("in_srs", "");
            std::ostringstream oss;
            oss << "Stage " << getName() << " has invalid spatial reference "
                "specification for 'in_srs' option: '" << srs << "'.";
            throw pdal_error(oss.str());
        }
        m_inferInputSRS = false;
    }

    m_cullBadPoints = options.getValueOrDefault("cull_unprojectable_points", false);
}

void ReprojectionFilter::initialize()
{
    GlobalEnvironment::get().initializeGDAL(log(), isDebug());
}

void ReprojectionFilter::ready(PointTableRef table)
{
    if (m_inferInputSRS)
    {
        m_inSRS = table.spatialRef();
        if (m_inSRS.getWKT().empty())
            throw pdal_error("Source data has no spatial reference and none "
                "is specified with the 'in_srs' option.");
    }

    m_in_ref_ptr = OSRNewSpatialReference(0);
    m_out_ref_ptr = OSRNewSpatialReference(0);

    int result =
        OSRSetFromUserInput(m_in_ref_ptr,
            m_inSRS.getWKT(pdal::SpatialReference::eCompoundOK).c_str());
    if (result != OGRERR_NONE)
    {
        std::ostringstream msg;
        msg << "Invalid input spatial reference '" << m_inSRS.getWKT() <<
            "'.  This is usually caused by a bad value for the 'in_srs'"
            "option or an invalid spatial reference in the source file.";
        throw pdal_error(msg.str());
    }

    result = OSRSetFromUserInput(m_out_ref_ptr,
        m_outSRS.getWKT(pdal::SpatialReference::eCompoundOK).c_str());
    if (result != OGRERR_NONE)
    {
        std::ostringstream msg;
        msg << "Invalid output spatial reference '" << m_outSRS.getWKT() <<
            "'.  This is usually caused by a bad value for the 'out_srs'"
            "option.";
        throw pdal_error(msg.str());
    }

    m_transform_ptr = OCTNewCoordinateTransformation(m_in_ref_ptr, m_out_ref_ptr);
    if (!m_transform_ptr)
    {
        std::string msg = "Could not construct CoordinateTransformation in "
            "ReprojectionFilter:: ";
        throw std::runtime_error(msg);
    }

    setSpatialReference(m_outSRS);
}

bool ReprojectionFilter::transform(double& x, double& y, double& z)
{
    try
    {
        // OCTTransform will throw via GDAL error handler
        // if there is an error. We don't expect the return value
        // unless the GDAL handler gets shut off for whatever reason. In
        // that case, we'll just throw.
        if (OCTTransform(m_transform_ptr, 1, &x, &y, &z))
        {
            return true;
        }
        else
        {
            std::ostringstream msg;
            msg << "Could not project point for ReprojectionTransform::" <<
                CPLGetLastErrorMsg();
            throw pdal_error(msg.str());
        }
    }
    catch (pdal::pdal_error& e)
    {
        if (m_cullBadPoints) return false;
        else throw e;
    }
}

PointViewSet ReprojectionFilter::run(PointViewPtr view)
{
    PointViewSet viewSet;
    PointViewPtr outView = view->makeNew();

    double x, y, z;

    for (PointId id = 0; id < view->size(); ++id)
    {
        x = view->getFieldAs<double>(Dimension::Id::X, id);
        y = view->getFieldAs<double>(Dimension::Id::Y, id);
        z = view->getFieldAs<double>(Dimension::Id::Z, id);

        if (transform(x, y, z))
        {
            view->setField(Dimension::Id::X, id, x);
            view->setField(Dimension::Id::Y, id, y);
            view->setField(Dimension::Id::Z, id, z);
            outView->appendPoint(*view, id);
        }
    }
    viewSet.insert(outView);

    return viewSet;
}

void ReprojectionFilter::filter(PointView& view)
{
    double x, y, z;

    for (PointId id = 0; id < view.size(); ++id)
    {
        x = view.getFieldAs<double>(Dimension::Id::X, id);
        y = view.getFieldAs<double>(Dimension::Id::Y, id);
        z = view.getFieldAs<double>(Dimension::Id::Z, id);

        OCTTransform(m_transform_ptr, 1, &x, &y, &z);

        view.setField(Dimension::Id::X, id, x);
        view.setField(Dimension::Id::Y, id, y);
        view.setField(Dimension::Id::Z, id, z);
    }
}

} // namespace pdal
<|endoftext|>


<commit_before><commit_msg>loplugin:stringconstant<commit_after><|endoftext|>


<commit_before>/*
 * card.cpp
 *
 *  Created on: Mar 7, 2016
 *      Author: Tumblr
 */

#include "card.h"
#include "console/utils.h"

using namespace std;

// Default contructor. This should rarely be called
// except for maybe when a token creature is generated
Card::Card() {
	// TODO Auto-generated constructor stub
	build_card("void");
}

Card::~Card() {
	// TODO Auto-generated destructor stub
}

void Card::build_card(string arg) {
	// TODO have card stats based on
	// input arg. This method is not set
	// in stone and can change to improve
	// performance and build times
	if      (arg == name)    return;
	else if (arg == "test1") {
		attack = 4;
		health = 2;
		cost = 3;
		currHP = health;
		ability = "Does a thing.";
		name = "Test1";
	} else if (arg == "test2") {
		attack = 3;
		health = 3;
		cost = 3;
		currHP = health;
		ability = "Does a thing.";
		name = "Test2";
	} else if (arg == "test3") {
		attack = 2;
		health = 2;
		cost = 2;
		currHP = health;
		ability = "Does a thing.";
		name = "Test3";
	} else if (arg == "void") {
		attack = 1;
		health = 1;
		cost = 1;
		currHP = health;
		ability = "Does a thing.";
		name = "Void";
	}

	image.set_image(load_file("card_template"));

	image.parse_flag("{0}", name, "left-pad");
	image.parse_flag("{1}", std::to_string(cost), "left-pad");
	image.parse_flag("{2}", ability);
	image.parse_flag("{3}", std::to_string(attack), "left-pad");
    image.parse_flag("{4}", std::to_string(currHP), "right-pad");
}

bool Card::trigger() {
	// TODO have the card's ability work here
	// so that at the start and end of each turn all cards
	// in play can have their tigger() called and their
	// ability checked. It should return true if the trigger
	// conditions are met. and goes off; false otherwise.

	// we should save looking at this for last. Many abilities
	// will be similar. So there must be a better way to have the
	// trigger work given the card name, without a uniquie ability
	// for each card.
	return true;
}

// Prints the card name in the form:
// NAME
// DESCRIPTION OF ABILITY
// (or flavor text)
// Atk/Def
string Card::to_string() {
	string ret = name + "\n";
	ret += ability + "\n";
	ret += std::to_string(attack) + "/" + std::to_string(currHP);
	return ret;
}
<commit_msg>See previous commit<commit_after>/*
 * card.cpp
 *
 *  Created on: Mar 7, 2016
 *      Author: Tumblr
 */

#include "card.h"
#include "utils.h"

using namespace std;

// Default contructor. This should rarely be called
// except for maybe when a token creature is generated
Card::Card() {
	// TODO Auto-generated constructor stub
	build_card("void");
}

Card::~Card() {
	// TODO Auto-generated destructor stub
}

void Card::build_card(string arg) {
	// TODO have card stats based on
	// input arg. This method is not set
	// in stone and can change to improve
	// performance and build times
	if      (arg == name)    return;
	else if (arg == "test1") {
		attack = 4;
		health = 2;
		cost = 3;
		currHP = health;
		ability = "Does a thing.";
		name = "Test1";
	} else if (arg == "test2") {
		attack = 3;
		health = 3;
		cost = 3;
		currHP = health;
		ability = "Does a thing.";
		name = "Test2";
	} else if (arg == "test3") {
		attack = 2;
		health = 2;
		cost = 2;
		currHP = health;
		ability = "Does a thing.";
		name = "Test3";
	} else if (arg == "void") {
		attack = 1;
		health = 1;
		cost = 1;
		currHP = health;
		ability = "Does a thing.";
		name = "Void";
	}

	image.set_image(load_file("card_template"));

	image.parse_flag("{0}", name, "left-pad");
	image.parse_flag("{1}", std::to_string(cost), "left-pad");
	image.parse_flag("{2}", ability);
	image.parse_flag("{3}", std::to_string(attack), "left-pad");
    image.parse_flag("{4}", std::to_string(currHP), "right-pad");
}

bool Card::trigger() {
	// TODO have the card's ability work here
	// so that at the start and end of each turn all cards
	// in play can have their tigger() called and their
	// ability checked. It should return true if the trigger
	// conditions are met. and goes off; false otherwise.

	// we should save looking at this for last. Many abilities
	// will be similar. So there must be a better way to have the
	// trigger work given the card name, without a uniquie ability
	// for each card.
	return true;
}

// Prints the card name in the form:
// NAME
// DESCRIPTION OF ABILITY
// (or flavor text)
// Atk/Def
string Card::to_string() {
	string ret = name + "\n";
	ret += ability + "\n";
	ret += std::to_string(attack) + "/" + std::to_string(currHP);
	return ret;
}
<|endoftext|>


<commit_before>#include  "Library/Property/AEndable.hh"

using namespace fwk;

AEndable::AEndable(void):
  _end(false),
  _endLock()
{}

AEndable::~AEndable(void) {}

void  AEndable::end(void) {
  {
    SCOPELOCK(&(this->_endLock));
    if (!(this->isEnding())) {
      this->isEnding(true);
    }
  }

  this->onEnd();
}

bool  AEndable::isEnding(void) const {
  return this->_end;
}

void  AEndable::isEnding(bool state) {
  this->_end = state;
}
<commit_msg>onEnd fix<commit_after>#include  "Library/Property/AEndable.hh"

using namespace fwk;

AEndable::AEndable(void):
  _end(false),
  _endLock()
{}

AEndable::~AEndable(void) {}

void  AEndable::end(void) {
  bool callOnEnd = false;

  {
    SCOPELOCK(&(this->_endLock));
    if (!(this->isEnding())) {
      this->isEnding(true);
      callOnEnd = true;
    }
  }

  if (callOnEnd) {
    this->onEnd();
  }
}

bool  AEndable::isEnding(void) const {
  return this->_end;
}

void  AEndable::isEnding(bool state) {
  this->_end = state;
}
<|endoftext|>


<commit_before>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <GL/glew.h>

#include "vvcanvas.h"

#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>

#include <QSettings>
#include <QTimer>

#include <iostream>

using vox::vvObjView;

vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
  : QGLWidget(format, parent)
  , _vd(NULL)
  , _renderer(NULL)
  , _projectionType(vox::vvObjView::PERSPECTIVE)
  , _doubleBuffering(format.doubleBuffer())
  , _superSamples(format.samples())
  , _stillQuality(1.0f)
  , _movingQuality(1.0f)
  , _spinAnimation(false)
  , _mouseButton(Qt::NoButton)
{
  vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");

  if (filename != "")
  {
    _vd = new vvVolDesc(filename.toStdString().c_str());
  }
  else
  {
    // load default volume
    _vd = new vvVolDesc;
    _vd->vox[0] = 32;
    _vd->vox[1] = 32;
    _vd->vox[2] = 32;
    _vd->frames = 0;
  }

  // init ui
  setMouseTracking(true);
  setFocusPolicy(Qt::StrongFocus);

  // read persistent settings
  QSettings settings;
  QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
  _bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());

  _animTimer = new QTimer(this);
  connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));

  _spinTimer = new QTimer(this);
  connect(_spinTimer, SIGNAL(timeout()), this, SLOT(repeatLastRotation()));
}

vvCanvas::~vvCanvas()
{
  vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");

  delete _renderer;
  delete _vd;
}

void vvCanvas::setVolDesc(vvVolDesc* vd)
{
  vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");

  delete _vd;
  _vd = vd;

  if (_vd != NULL)
  {
    createRenderer();
  }

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  std::string str;
  _vd->makeInfoString(&str);
  emit statusMessage(str);
  emit newVolDesc(_vd);
}

void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
  vvDebugMsg::msg(3, "vvCanvas::setPlugins()");

  _plugins = plugins;
}

vvVolDesc* vvCanvas::getVolDesc() const
{
  vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");

  return _vd;
}

vvRenderer* vvCanvas::getRenderer() const
{
  vvDebugMsg::msg(3, "vvCanvas::getRenderer()");

  return _renderer;
}

void vvCanvas::loadCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::loadCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.loadCamera(ba.data());
}

void vvCanvas::saveCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::saveCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.saveCamera(ba.data());
}

void vvCanvas::initializeGL()
{
  vvDebugMsg::msg(1, "vvCanvas::initializeGL()");

  glewInit();
  init();
}

void vvCanvas::paintGL()
{
  vvDebugMsg::msg(3, "vvCanvas::paintGL()");

  if (_renderer == NULL)
  {
    return;
  }

  if (_doubleBuffering)
  {
    glDrawBuffer(GL_BACK);
  }
  else
  {
    glDrawBuffer(GL_FRONT);
  }

  glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  _ov.setModelviewMatrix(vvObjView::CENTER);

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->prerender();
    }
  }

  _renderer->renderVolumeGL();

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->postrender();
    }
  }
}

void vvCanvas::resizeGL(const int w, const int h)
{
  vvDebugMsg::msg(3, "vvCanvas::resizeGL()");

  glViewport(0, 0, w, h);
  if (h > 0)
  {
    _ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
  }
  updateGL();

  emit resized(QSize(w, h));
}

void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");

  switch (_mouseButton)
  {
  case Qt::LeftButton:
  {
    _lastRotation = _ov._camera.trackballRotation(width(), height(),
      _lastMousePos.x(), _lastMousePos.y(),
      event->pos().x(), event->pos().y());
    if (_spinAnimation)
    {
      repeatLastRotation();
    }
    break;
  }
  case Qt::MiddleButton:
  {
    const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
    const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
    const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
    vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
    _ov._camera.translate(pan[0], -pan[1], 0.0f);
    break;
  }
  case Qt::RightButton:
  {
    const float factor = event->pos().y() - _lastMousePos.y();
    _ov._camera.translate(0.0f, 0.0f, factor);
    break;
  }
  default:
    break;
  }
  _lastMousePos = event->pos();
  updateGL();
}

void vvCanvas::mousePressEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");

  _stillQuality = _renderer->getParameter(vvRenderer::VV_QUALITY);
  _renderer->setParameter(vvRenderer::VV_QUALITY, _movingQuality);
  _mouseButton = event->button();
  _lastMousePos = event->pos();
  _lastRotation.identity();
  if (_spinAnimation)
  {
    _spinTimer->stop();
  }
}

void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");

  _mouseButton = Qt::NoButton;
  _renderer->setParameter(vvRenderer::VV_QUALITY, _stillQuality);
  updateGL();
}

void vvCanvas::init()
{
  vvDebugMsg::msg(3, "vvCanvas::init()");

  vvFileIO* fio = new vvFileIO;
  fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
  delete fio;

  // default transfer function
  if (_vd->tf.isEmpty())
  {
    _vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
    _vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
  }

  // init renderer
  if (_vd != NULL)
  {
    _currentRenderer = "planar";
    _currentOptions["voxeltype"] = "arb";
    createRenderer();
  }

  updateProjection();

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::createRenderer()
{
  vvDebugMsg::msg(3, "vvCanvas::createRenderer()");

  vvRenderState state;
  if (_renderer)
  {
    state = *_renderer;
    delete _renderer;
  }

  const float DEFAULT_OBJ_SIZE = 0.6f;
  _vd->resizeEdgeMax(_ov.getViewportWidth() * DEFAULT_OBJ_SIZE);

  _renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), _currentOptions);

  // set boundary color to inverse of background
  vvColor invColor;
  if (_bgColor[0] + _bgColor[1] + _bgColor[2] > 1.5f)
  {
    invColor = vvColor(0.0f, 0.0f, 0.0f);
  }
  else
  {
    invColor = vvColor(1.0f, 1.0f, 1.0f);
  }
  _renderer->setParameter(vvRenderState::VV_BOUND_COLOR, invColor);
  _renderer->setParameter(vvRenderState::VV_CLIP_COLOR, invColor);
}

void vvCanvas::updateProjection()
{
  vvDebugMsg::msg(3, "vvCanvas::updateProjection()");

  if (_projectionType == vvObjView::PERSPECTIVE)
  {
    _ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
  else if (_projectionType == vvObjView::ORTHO)
  {
    _ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
}

void vvCanvas::setCurrentFrame(const int frame)
{
  vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");

  _renderer->setCurrentFrame(frame);
  emit currentFrame(frame);

  // inform plugins of new frame
  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->timestep();
  }

  updateGL();
}

void vvCanvas::setRenderer(const std::string& name, const vvRendererFactory::Options& options)
{
  vvDebugMsg::msg(3, "vvCanvas::setRenderer()");

  _currentRenderer = name;
  _currentOptions = options;
  createRenderer();
  updateGL();
}

void vvCanvas::setParameter(vvParameters::ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  switch (param)
  {
  case vvParameters::VV_BG_COLOR:
    _bgColor = value;
    break;
  case vvParameters::VV_DOUBLEBUFFERING:
    _doubleBuffering = value;
    break;
  case vvParameters::VV_MOVING_QUALITY:
    _movingQuality = value;
    break;
  case vvParameters::VV_SUPERSAMPLES:
    _superSamples = value;
    break;
  case vvParameters::VV_PROJECTIONTYPE:
    _projectionType = static_cast<vvObjView::ProjectionType>(value.asInt());
    updateProjection();
  case vvParameters::VV_SPIN_ANIMATION:
    _spinAnimation = value;
    break;
  default:
    break;
  }
  updateGL();
}

void vvCanvas::setParameter(vvRenderer::ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  if (_renderer != NULL)
  {
    _renderer->setParameter(param, value);
    updateGL();
  }
}

vvParam vvCanvas::getParameter(vvParameters::ParameterType param) const
{
  switch (param)
  {
  case vvParameters::VV_BG_COLOR:
    return _bgColor;
  case vvParameters::VV_DOUBLEBUFFERING:
    return _doubleBuffering;
  case vvParameters::VV_SUPERSAMPLES:
    return _superSamples;
  case vvParameters::VV_PROJECTIONTYPE:
    return static_cast<int>(_projectionType);
  case vvParameters::VV_SPIN_ANIMATION:
    return _spinAnimation;
  default:
    return vvParam();
  }
}

vvParam vvCanvas::getParameter(vvRenderer::ParameterType param) const
{
  if (_renderer != NULL)
  {
    return _renderer->getParameter(param);
  }
  return vvParam();
}

void vvCanvas::startAnimation(const double fps)
{
  vvDebugMsg::msg(3, "vvCanvas::startAnimation()");

  _vd->dt = 1.0f / static_cast<float>(fps);
  const float delay = std::abs(_vd->dt * 1000.0f);
  _animTimer->start(static_cast<int>(delay));
}

void vvCanvas::stopAnimation()
{
  vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");

  _animTimer->stop();
}

void vvCanvas::setTimeStep(const int step)
{
  vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");

  int f = step;
  while (f < 0)
  {
    f += _vd->frames;
  }

  while (f >= _vd->frames)
  {
    f -= _vd->frames;
  }

  setCurrentFrame(f);
}

void vvCanvas::incTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f >= _vd->frames - 1) ? 0 : f + 1;
  setCurrentFrame(f);
}

void vvCanvas::decTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f <= 0) ? _vd->frames - 1 : f - 1;
  setCurrentFrame(f);
}

void vvCanvas::firstTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");

  setCurrentFrame(0);
}

void vvCanvas::lastTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");

  setCurrentFrame(_vd->frames - 1);
}

void vvCanvas::repeatLastRotation()
{
  vvDebugMsg::msg(3, "vvCanvas::repeatLastRotation()");

  _ov._camera.multiplyRight(_lastRotation);
  updateGL();

  const float spindelay = 0.05f;
  const float delay = std::abs(spindelay * 1000.0f);
  _spinTimer->start(static_cast<int>(delay));
}

<commit_msg>Bug fix: no fall-through intended in switch<commit_after>// Virvo - Virtual Reality Volume Rendering
// Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University
// Contact: Jurgen P. Schulze, jschulze@ucsd.edu
//
// This file is part of Virvo.
//
// Virvo is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library (see license.txt); if not, write to the
// Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

#include <GL/glew.h>

#include "vvcanvas.h"

#include <virvo/vvdebugmsg.h>
#include <virvo/vvfileio.h>
#include <virvo/vvgltools.h>

#include <QSettings>
#include <QTimer>

#include <iostream>

using vox::vvObjView;

vvCanvas::vvCanvas(const QGLFormat& format, const QString& filename, QWidget* parent)
  : QGLWidget(format, parent)
  , _vd(NULL)
  , _renderer(NULL)
  , _projectionType(vox::vvObjView::PERSPECTIVE)
  , _doubleBuffering(format.doubleBuffer())
  , _superSamples(format.samples())
  , _stillQuality(1.0f)
  , _movingQuality(1.0f)
  , _spinAnimation(false)
  , _mouseButton(Qt::NoButton)
{
  vvDebugMsg::msg(1, "vvCanvas::vvCanvas()");

  if (filename != "")
  {
    _vd = new vvVolDesc(filename.toStdString().c_str());
  }
  else
  {
    // load default volume
    _vd = new vvVolDesc;
    _vd->vox[0] = 32;
    _vd->vox[1] = 32;
    _vd->vox[2] = 32;
    _vd->frames = 0;
  }

  // init ui
  setMouseTracking(true);
  setFocusPolicy(Qt::StrongFocus);

  // read persistent settings
  QSettings settings;
  QColor qcolor = settings.value("canvas/bgcolor").value<QColor>();
  _bgColor = vvColor(qcolor.redF(), qcolor.greenF(), qcolor.blueF());

  _animTimer = new QTimer(this);
  connect(_animTimer, SIGNAL(timeout()), this, SLOT(incTimeStep()));

  _spinTimer = new QTimer(this);
  connect(_spinTimer, SIGNAL(timeout()), this, SLOT(repeatLastRotation()));
}

vvCanvas::~vvCanvas()
{
  vvDebugMsg::msg(1, "vvCanvas::~vvCanvas()");

  delete _renderer;
  delete _vd;
}

void vvCanvas::setVolDesc(vvVolDesc* vd)
{
  vvDebugMsg::msg(3, "vvCanvas::setVolDesc()");

  delete _vd;
  _vd = vd;

  if (_vd != NULL)
  {
    createRenderer();
  }

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  std::string str;
  _vd->makeInfoString(&str);
  emit statusMessage(str);
  emit newVolDesc(_vd);
}

void vvCanvas::setPlugins(const QList<vvPlugin*>& plugins)
{
  vvDebugMsg::msg(3, "vvCanvas::setPlugins()");

  _plugins = plugins;
}

vvVolDesc* vvCanvas::getVolDesc() const
{
  vvDebugMsg::msg(3, "vvCanvas::getVolDesc()");

  return _vd;
}

vvRenderer* vvCanvas::getRenderer() const
{
  vvDebugMsg::msg(3, "vvCanvas::getRenderer()");

  return _renderer;
}

void vvCanvas::loadCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::loadCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.loadCamera(ba.data());
}

void vvCanvas::saveCamera(const QString& filename)
{
  vvDebugMsg::msg(3, "vvCanvas::saveCamera()");

  QByteArray ba = filename.toLatin1();
  _ov.saveCamera(ba.data());
}

void vvCanvas::initializeGL()
{
  vvDebugMsg::msg(1, "vvCanvas::initializeGL()");

  glewInit();
  init();
}

void vvCanvas::paintGL()
{
  vvDebugMsg::msg(3, "vvCanvas::paintGL()");

  if (_renderer == NULL)
  {
    return;
  }

  if (_doubleBuffering)
  {
    glDrawBuffer(GL_BACK);
  }
  else
  {
    glDrawBuffer(GL_FRONT);
  }

  glClearColor(_bgColor[0], _bgColor[1], _bgColor[2], 0.0f);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  glMatrixMode(GL_MODELVIEW);
  _ov.setModelviewMatrix(vvObjView::CENTER);

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->prerender();
    }
  }

  _renderer->renderVolumeGL();

  foreach (vvPlugin* plugin, _plugins)
  {
    if (plugin->isActive())
    {
      plugin->postrender();
    }
  }
}

void vvCanvas::resizeGL(const int w, const int h)
{
  vvDebugMsg::msg(3, "vvCanvas::resizeGL()");

  glViewport(0, 0, w, h);
  if (h > 0)
  {
    _ov.setAspectRatio(static_cast<float>(w) / static_cast<float>(h));
  }
  updateGL();

  emit resized(QSize(w, h));
}

void vvCanvas::mouseMoveEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseMoveEvent()");

  switch (_mouseButton)
  {
  case Qt::LeftButton:
  {
    _lastRotation = _ov._camera.trackballRotation(width(), height(),
      _lastMousePos.x(), _lastMousePos.y(),
      event->pos().x(), event->pos().y());
    if (_spinAnimation)
    {
      repeatLastRotation();
    }
    break;
  }
  case Qt::MiddleButton:
  {
    const float pixelInWorld = _ov.getViewportWidth() / static_cast<float>(width());
    const float dx = static_cast<float>(event->pos().x() - _lastMousePos.x());
    const float dy = static_cast<float>(event->pos().y() - _lastMousePos.y());
    vvVector2f pan(pixelInWorld * dx, pixelInWorld * dy);
    _ov._camera.translate(pan[0], -pan[1], 0.0f);
    break;
  }
  case Qt::RightButton:
  {
    const float factor = event->pos().y() - _lastMousePos.y();
    _ov._camera.translate(0.0f, 0.0f, factor);
    break;
  }
  default:
    break;
  }
  _lastMousePos = event->pos();
  updateGL();
}

void vvCanvas::mousePressEvent(QMouseEvent* event)
{
  vvDebugMsg::msg(3, "vvCanvas::mousePressEvent()");

  _stillQuality = _renderer->getParameter(vvRenderer::VV_QUALITY);
  _renderer->setParameter(vvRenderer::VV_QUALITY, _movingQuality);
  _mouseButton = event->button();
  _lastMousePos = event->pos();
  _lastRotation.identity();
  if (_spinAnimation)
  {
    _spinTimer->stop();
  }
}

void vvCanvas::mouseReleaseEvent(QMouseEvent*)
{
  vvDebugMsg::msg(3, "vvCanvas::mouseReleaseEvent()");

  _mouseButton = Qt::NoButton;
  _renderer->setParameter(vvRenderer::VV_QUALITY, _stillQuality);
  updateGL();
}

void vvCanvas::init()
{
  vvDebugMsg::msg(3, "vvCanvas::init()");

  vvFileIO* fio = new vvFileIO;
  fio->loadVolumeData(_vd, vvFileIO::ALL_DATA);
  delete fio;

  // default transfer function
  if (_vd->tf.isEmpty())
  {
    _vd->tf.setDefaultAlpha(0, _vd->real[0], _vd->real[1]);
    _vd->tf.setDefaultColors((_vd->chan == 1) ? 0 : 3, _vd->real[0], _vd->real[1]);
  }

  // init renderer
  if (_vd != NULL)
  {
    _currentRenderer = "planar";
    _currentOptions["voxeltype"] = "arb";
    createRenderer();
  }

  updateProjection();

  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->setVolDesc(_vd);
  }

  emit newVolDesc(_vd);
}

void vvCanvas::createRenderer()
{
  vvDebugMsg::msg(3, "vvCanvas::createRenderer()");

  vvRenderState state;
  if (_renderer)
  {
    state = *_renderer;
    delete _renderer;
  }

  const float DEFAULT_OBJ_SIZE = 0.6f;
  _vd->resizeEdgeMax(_ov.getViewportWidth() * DEFAULT_OBJ_SIZE);

  _renderer = vvRendererFactory::create(_vd, state, _currentRenderer.c_str(), _currentOptions);

  // set boundary color to inverse of background
  vvColor invColor;
  if (_bgColor[0] + _bgColor[1] + _bgColor[2] > 1.5f)
  {
    invColor = vvColor(0.0f, 0.0f, 0.0f);
  }
  else
  {
    invColor = vvColor(1.0f, 1.0f, 1.0f);
  }
  _renderer->setParameter(vvRenderState::VV_BOUND_COLOR, invColor);
  _renderer->setParameter(vvRenderState::VV_CLIP_COLOR, invColor);
}

void vvCanvas::updateProjection()
{
  vvDebugMsg::msg(3, "vvCanvas::updateProjection()");

  if (_projectionType == vvObjView::PERSPECTIVE)
  {
    _ov.setProjection(vvObjView::PERSPECTIVE, vvObjView::DEF_FOV, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
  else if (_projectionType == vvObjView::ORTHO)
  {
    _ov.setProjection(vvObjView::ORTHO, vvObjView::DEF_VIEWPORT_WIDTH, vvObjView::DEF_CLIP_NEAR, vvObjView::DEF_CLIP_FAR);
  }
}

void vvCanvas::setCurrentFrame(const int frame)
{
  vvDebugMsg::msg(3, "vvCanvas::setCurrentFrame()");

  _renderer->setCurrentFrame(frame);
  emit currentFrame(frame);

  // inform plugins of new frame
  foreach (vvPlugin* plugin, _plugins)
  {
    plugin->timestep();
  }

  updateGL();
}

void vvCanvas::setRenderer(const std::string& name, const vvRendererFactory::Options& options)
{
  vvDebugMsg::msg(3, "vvCanvas::setRenderer()");

  _currentRenderer = name;
  _currentOptions = options;
  createRenderer();
  updateGL();
}

void vvCanvas::setParameter(vvParameters::ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  switch (param)
  {
  case vvParameters::VV_BG_COLOR:
    _bgColor = value;
    break;
  case vvParameters::VV_DOUBLEBUFFERING:
    _doubleBuffering = value;
    break;
  case vvParameters::VV_MOVING_QUALITY:
    _movingQuality = value;
    break;
  case vvParameters::VV_SUPERSAMPLES:
    _superSamples = value;
    break;
  case vvParameters::VV_PROJECTIONTYPE:
    _projectionType = static_cast<vvObjView::ProjectionType>(value.asInt());
    updateProjection();
    break;
  case vvParameters::VV_SPIN_ANIMATION:
    _spinAnimation = value;
    break;
  default:
    break;
  }
  updateGL();
}

void vvCanvas::setParameter(vvRenderer::ParameterType param, const vvParam& value)
{
  vvDebugMsg::msg(3, "vvCanvas::setParameter()");

  if (_renderer != NULL)
  {
    _renderer->setParameter(param, value);
    updateGL();
  }
}

vvParam vvCanvas::getParameter(vvParameters::ParameterType param) const
{
  switch (param)
  {
  case vvParameters::VV_BG_COLOR:
    return _bgColor;
  case vvParameters::VV_DOUBLEBUFFERING:
    return _doubleBuffering;
  case vvParameters::VV_SUPERSAMPLES:
    return _superSamples;
  case vvParameters::VV_PROJECTIONTYPE:
    return static_cast<int>(_projectionType);
  case vvParameters::VV_SPIN_ANIMATION:
    return _spinAnimation;
  default:
    return vvParam();
  }
}

vvParam vvCanvas::getParameter(vvRenderer::ParameterType param) const
{
  if (_renderer != NULL)
  {
    return _renderer->getParameter(param);
  }
  return vvParam();
}

void vvCanvas::startAnimation(const double fps)
{
  vvDebugMsg::msg(3, "vvCanvas::startAnimation()");

  _vd->dt = 1.0f / static_cast<float>(fps);
  const float delay = std::abs(_vd->dt * 1000.0f);
  _animTimer->start(static_cast<int>(delay));
}

void vvCanvas::stopAnimation()
{
  vvDebugMsg::msg(3, "vvCanvas::stopAnimation()");

  _animTimer->stop();
}

void vvCanvas::setTimeStep(const int step)
{
  vvDebugMsg::msg(3, "vvCanvas::setTimeStep()");

  int f = step;
  while (f < 0)
  {
    f += _vd->frames;
  }

  while (f >= _vd->frames)
  {
    f -= _vd->frames;
  }

  setCurrentFrame(f);
}

void vvCanvas::incTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::incTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f >= _vd->frames - 1) ? 0 : f + 1;
  setCurrentFrame(f);
}

void vvCanvas::decTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::decTimeStep()");

  int f = _renderer->getCurrentFrame();
  f = (f <= 0) ? _vd->frames - 1 : f - 1;
  setCurrentFrame(f);
}

void vvCanvas::firstTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::firstTimeStep()");

  setCurrentFrame(0);
}

void vvCanvas::lastTimeStep()
{
  vvDebugMsg::msg(3, "vvCanvas::lastTimeStep()");

  setCurrentFrame(_vd->frames - 1);
}

void vvCanvas::repeatLastRotation()
{
  vvDebugMsg::msg(3, "vvCanvas::repeatLastRotation()");

  _ov._camera.multiplyRight(_lastRotation);
  updateGL();

  const float spindelay = 0.05f;
  const float delay = std::abs(spindelay * 1000.0f);
  _spinTimer->start(static_cast<int>(delay));
}

<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

#include "date.h"
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/date_time/posix_time/posix_time.hpp"
#include <boost/algorithm/string.hpp>

int Date::GetCurrentWeek() {
    boost::gregorian::date today = boost::gregorian::day_clock::local_day();
    boost::gregorian::date ref(2014, 9, 1);
    float weeks = ((float) (today - ref).days()) / (float) 7;
    return (int) std::ceil(weeks);
}

boost::posix_time::ptime Date::DateFromIsoString(std::string date) {
    //Adapt the string
    date.pop_back(); // remove the trailing Z
    boost::erase_all(date, "-");
    boost::erase_all(date, ":");

    return boost::posix_time::from_iso_string(date);
}

<commit_msg>Fixed week calculation<commit_after>#include <iostream>
#include <cmath>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "date.h"
#include <boost/algorithm/string.hpp>

int Date::GetCurrentWeek() {
    boost::gregorian::date today = boost::gregorian::day_clock::local_day();
    boost::gregorian::date ref(2014, 8, 30);
    float weeks = ((float) (today - ref).days()) / (float) 7;
    return (int) std::ceil(weeks);
}

boost::posix_time::ptime Date::DateFromIsoString(std::string date) {
    //Adapt the string
    date.pop_back(); // remove the trailing Z
    boost::erase_all(date, "-");
    boost::erase_all(date, ":");

    return boost::posix_time::from_iso_string(date);
}
<|endoftext|>