<commit_before>// Copyright 2014 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/compiler/ast/namespace.h"

#include "base/logging.h"
#include "elang/compiler/ast/alias.h"
#include "elang/compiler/ast/class.h"
#include "elang/compiler/ast/namespace_body.h"
#include "elang/compiler/modifiers_builder.h"
#include "elang/compiler/token_type.h"

namespace elang {
namespace compiler {
namespace ast {

namespace {
Modifiers GetNamespaceModifiers() {
  ModifiersBuilder builder;
  builder.SetPublic();
  return builder.Get();
}
}  // namespace

//////////////////////////////////////////////////////////////////////
//
// MemberContainer
//
MemberContainer::MemberContainer(Zone* zone,
                                 NamespaceBody* namespace_body,
                                 Modifiers modifiers,
                                 Token* keyword,
                                 Token* name)
    : NamespaceMember(namespace_body, modifiers, keyword, name),
      bodies_(zone),
      map_(zone) {
}

void MemberContainer::AcceptForMembers(Visitor* visitor) {
  for (auto const name_member : map_)
    name_member.second->Accept(visitor);
}

void MemberContainer::AddMember(NamespaceMember* member) {
  DCHECK_EQ(this, member->owner());
  DCHECK(!member->is<Alias>());
  // We keep first member declaration.
  if (FindMember(member->name()))
    return;
  map_[member->name()->simple_name()] = member;
}

void MemberContainer::AddNamespaceBody(NamespaceBody* namespace_body) {
  bodies_.push_back(namespace_body);
}

NamespaceMember* MemberContainer::FindMember(AtomicString* name) {
  auto const it = map_.find(name);
  return it == map_.end() ? nullptr : it->second;
}

NamespaceMember* MemberContainer::FindMember(Token* name) {
  return FindMember(name->simple_name());
}

//////////////////////////////////////////////////////////////////////
//
// Namespace
//
Namespace::Namespace(Zone* zone,
                     NamespaceBody* namespace_body,
                     Token* keyword,
                     Token* name)
    : MemberContainer(zone,
                      namespace_body,
                      GetNamespaceModifiers(),
                      keyword,
                      name) {
  DCHECK_EQ(keyword, TokenType::Namespace);
}

}  // namespace ast
}  // namespace compiler
}  // namespace elang
<commit_msg>elang/compiler/ast: Make |MemberContainer::AcceptForMembers()| to accept for all members including |Alias| and |Import|.<commit_after>// Copyright 2014 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "elang/compiler/ast/namespace.h"

#include "base/logging.h"
#include "elang/compiler/ast/alias.h"
#include "elang/compiler/ast/class.h"
#include "elang/compiler/ast/namespace_body.h"
#include "elang/compiler/modifiers_builder.h"
#include "elang/compiler/token_type.h"

namespace elang {
namespace compiler {
namespace ast {

namespace {
Modifiers GetNamespaceModifiers() {
  ModifiersBuilder builder;
  builder.SetPublic();
  return builder.Get();
}
}  // namespace

//////////////////////////////////////////////////////////////////////
//
// MemberContainer
//
MemberContainer::MemberContainer(Zone* zone,
                                 NamespaceBody* namespace_body,
                                 Modifiers modifiers,
                                 Token* keyword,
                                 Token* name)
    : NamespaceMember(namespace_body, modifiers, keyword, name),
      bodies_(zone),
      map_(zone) {
}

void MemberContainer::AcceptForMembers(Visitor* visitor) {
  for (auto const body : bodies_) {
    for (auto const member : body->members())
      member->Accept(visitor);
  }
}

void MemberContainer::AddMember(NamespaceMember* member) {
  DCHECK_EQ(this, member->owner());
  DCHECK(!member->is<Alias>());
  // We keep first member declaration.
  if (FindMember(member->name()))
    return;
  map_[member->name()->simple_name()] = member;
}

void MemberContainer::AddNamespaceBody(NamespaceBody* namespace_body) {
  bodies_.push_back(namespace_body);
}

NamespaceMember* MemberContainer::FindMember(AtomicString* name) {
  auto const it = map_.find(name);
  return it == map_.end() ? nullptr : it->second;
}

NamespaceMember* MemberContainer::FindMember(Token* name) {
  return FindMember(name->simple_name());
}

//////////////////////////////////////////////////////////////////////
//
// Namespace
//
Namespace::Namespace(Zone* zone,
                     NamespaceBody* namespace_body,
                     Token* keyword,
                     Token* name)
    : MemberContainer(zone,
                      namespace_body,
                      GetNamespaceModifiers(),
                      keyword,
                      name) {
  DCHECK_EQ(keyword, TokenType::Namespace);
}

}  // namespace ast
}  // namespace compiler
}  // namespace elang
<|endoftext|>


<commit_before>#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <iostream>

#include "IMU_Detector.h"
#include "Mahony_Filter.h"
#include "Complementary_Filter.h"

using namespace flyhero;

QueueHandle_t data_queue;

void imu_task(void *args);
void log_task(void *args);

extern "C" void app_main(void)
{
    // Initialize NVS
    esp_err_t nvs_status = nvs_flash_init();

    if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ESP_ERROR_CHECK(nvs_flash_init());
    }

    data_queue = xQueueCreate(10, sizeof(IMU::Euler_Angles));

    xTaskCreatePinnedToCore(log_task, "Log task", 4096, NULL, 2, NULL, 1);
    xTaskCreatePinnedToCore(imu_task, "IMU task", 4096, NULL, 2, NULL, 0);
}

void imu_task(void *args)
{
    IMU& imu = IMU_Detector::Detect_IMU();

    imu.Init();

    while (!imu.Start())
    {
        std::cout << "Calibrating..." << std::endl;
        imu.Calibrate();
    }

    //Mahony_Filter mahony(100, 0);
    Complementary_Filter complementary(0.98f);

    IMU::Sensor_Data accel, gyro;
    IMU::Euler_Angles euler;

    uint8_t i = 0;

    while (true)
    {
        if (imu.Data_Ready())
        {
            imu.Read_Data(accel, gyro);

            //mahony.Compute(accel, gyro, euler);
            complementary.Compute(accel, gyro, euler);

            i++;

            if (i % 100 == 0)
            {
                i = 0;

                if (xQueueSendToBack(data_queue, &euler, 0) != pdTRUE)
                    break;
            }
        }
    }
}

void log_task(void *args)
{
    IMU::Euler_Angles euler;

    while (true)
    {
        if (xQueueReceive(data_queue, &euler, 0) == pdTRUE)
            std::cout << euler.roll << " " << euler.pitch << " " << euler.yaw << std::endl;
    }
}<commit_msg>(IMU main): print euler data at same frequency for every IMU<commit_after>#include <freertos/FreeRTOS.h>
#include <freertos/queue.h>
#include <iostream>

#include "IMU_Detector.h"
#include "Mahony_Filter.h"
#include "Complementary_Filter.h"

using namespace flyhero;

QueueHandle_t data_queue;

void imu_task(void *args);
void log_task(void *args);

extern "C" void app_main(void)
{
    // Initialize NVS
    esp_err_t nvs_status = nvs_flash_init();

    if (nvs_status == ESP_ERR_NVS_NO_FREE_PAGES)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ESP_ERROR_CHECK(nvs_flash_init());
    }

    data_queue = xQueueCreate(10, sizeof(IMU::Euler_Angles));

    xTaskCreatePinnedToCore(log_task, "Log task", 4096, NULL, 2, NULL, 1);
    xTaskCreatePinnedToCore(imu_task, "IMU task", 4096, NULL, 2, NULL, 0);
}

void imu_task(void *args)
{
    IMU& imu = IMU_Detector::Detect_IMU();

    imu.Init();

    while (!imu.Start())
    {
        std::cout << "Calibrating..." << std::endl;
        imu.Calibrate();
    }

    //Mahony_Filter mahony(100, 0);
    Complementary_Filter complementary(0.98f);

    IMU::Sensor_Data accel, gyro;
    IMU::Euler_Angles euler;

    uint8_t i = 0;

    while (true)
    {
        if (imu.Data_Ready())
        {
            imu.Read_Data(accel, gyro);

            //mahony.Compute(accel, gyro, euler);
            complementary.Compute(accel, gyro, euler);

            i++;

            if (i == imu.Get_Sample_Rate() / 10)
            {
                i = 0;

                if (xQueueSendToBack(data_queue, &euler, 0) != pdTRUE)
                    break;
            }
        }
    }
}

void log_task(void *args)
{
    IMU::Euler_Angles euler;

    while (true)
    {
        if (xQueueReceive(data_queue, &euler, 0) == pdTRUE)
            std::cout << euler.roll << " " << euler.pitch << " " << euler.yaw << std::endl;
    }
}<|endoftext|>


<commit_before>
/**
 * This file is part of the boostcache package.
 *
 * (c) Azat Khuzhin <a3at.mail@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "avltree.h"

namespace Db
{
    std::hash<AvlTree::Key> AvlTree::m_keyHashFunction = std::hash<AvlTree::Key>();

    AvlTree::AvlTree()
        : Interface()
        , m_deleteDisposer(m_nodes)
        , m_tree(new Tree)
    {
    }

    std::string AvlTree::get(const CommandHandler::Arguments &arguments)
    {
        Node findMe(arguments[1]);

        // get shared lock
        boost::shared_lock<boost::shared_mutex> lock(m_access);

        Tree::const_iterator found = m_tree->find(findMe);
        if (found == m_tree->end()) {
            return CommandHandler::REPLY_NIL;
        }
        return CommandHandler::toReplyString(found->get().value);
    }

    std::string AvlTree::set(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Node findMe(arguments[1]);
        Tree::iterator found = m_tree->find(findMe);
        if (found != m_tree->end()) {
            found->get().value = arguments[2] /* value */;
            return CommandHandler::REPLY_OK;
        }

        m_nodes.push_back(Node(Node::Data(arguments[1] /* key */,
                                          arguments[2] /* value */)));
        m_nodes.back().get().listIterator = --m_nodes.end();
        m_tree->insert_unique(m_nodes.back());

        return CommandHandler::REPLY_OK;
    }

    std::string AvlTree::del(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Node findMe(arguments[1]);
        Tree::const_iterator found = m_tree->find(findMe);
        if (found == m_tree->end()) {
            return CommandHandler::REPLY_FALSE;
        }
        m_tree->erase_and_dispose(found, m_deleteDisposer);

        return CommandHandler::REPLY_OK;
    }
}
<commit_msg>[db] avltree: del(): return REPLY_TRUE instead of REPLY_OK<commit_after>
/**
 * This file is part of the boostcache package.
 *
 * (c) Azat Khuzhin <a3at.mail@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#include "avltree.h"

namespace Db
{
    std::hash<AvlTree::Key> AvlTree::m_keyHashFunction = std::hash<AvlTree::Key>();

    AvlTree::AvlTree()
        : Interface()
        , m_deleteDisposer(m_nodes)
        , m_tree(new Tree)
    {
    }

    std::string AvlTree::get(const CommandHandler::Arguments &arguments)
    {
        Node findMe(arguments[1]);

        // get shared lock
        boost::shared_lock<boost::shared_mutex> lock(m_access);

        Tree::const_iterator found = m_tree->find(findMe);
        if (found == m_tree->end()) {
            return CommandHandler::REPLY_NIL;
        }
        return CommandHandler::toReplyString(found->get().value);
    }

    std::string AvlTree::set(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Node findMe(arguments[1]);
        Tree::iterator found = m_tree->find(findMe);
        if (found != m_tree->end()) {
            found->get().value = arguments[2] /* value */;
            return CommandHandler::REPLY_OK;
        }

        m_nodes.push_back(Node(Node::Data(arguments[1] /* key */,
                                          arguments[2] /* value */)));
        m_nodes.back().get().listIterator = --m_nodes.end();
        m_tree->insert_unique(m_nodes.back());

        return CommandHandler::REPLY_OK;
    }

    std::string AvlTree::del(const CommandHandler::Arguments &arguments)
    {
        // get exclusive lock
        boost::upgrade_lock<boost::shared_mutex> lock(m_access);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

        Node findMe(arguments[1]);
        Tree::const_iterator found = m_tree->find(findMe);
        if (found == m_tree->end()) {
            return CommandHandler::REPLY_FALSE;
        }
        m_tree->erase_and_dispose(found, m_deleteDisposer);

        return CommandHandler::REPLY_TRUE;
    }
}
<|endoftext|>


<commit_before>// @(#)root/hist:$Id$
// Author: Rene Brun   14/07/2009

/*************************************************************************
 * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGraphTime.h"
#include "TVirtualPad.h"
#include "TH1.h"
#include "TROOT.h"
#include "TObjArray.h"
#include "TSystem.h"

ClassImp(TGraphTime)

//______________________________________________________________________________
//
// TGraphTime is used to draw a set of objects evolving with nsteps in time between tmin and tmax.
// each time step has a new list of objects. This list can be identical to
// the list of objects in the previous steps, but with different attributes.
//   see example of use in $ROOTSYS/tutorials/graphs/gtime.C

//______________________________________________________________________________
TGraphTime::TGraphTime(): TNamed()
{
   // default constructor.

   fSleepTime = 0;
   fNsteps    = 0;
   fXmin      = 0;
   fXmax      = 1;
   fYmin      = 0;
   fYmax      = 1;
   fSteps     = 0;
   fFrame     = 0;
}

//______________________________________________________________________________
TGraphTime::TGraphTime(Int_t nsteps, Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax)
      :TNamed()
{
   // Create a TGraphTime with nsteps in range [xmin,xmax][ymin,ymax]

   if (nsteps <= 0) {
      Warning("TGraphTime", "Number of steps %d changed to 100",nsteps);
      nsteps = 100;
   }
   fSleepTime = 0;
   fNsteps    = nsteps;
   fXmin      = xmin;
   fXmax      = xmax;
   fYmin      = ymin;
   fYmax      = ymax;
   fSteps     = new TObjArray(nsteps+1);
   fFrame     = new TH1D("frame","",100,fXmin,fXmax);
   fFrame->SetMinimum(ymin);
   fFrame->SetMaximum(ymax);
   fFrame->SetStats(0);
}

//______________________________________________________________________________
TGraphTime::~TGraphTime()
{
   // GraphTime default destructor.

   if (!fSteps) return;
   fSteps->Delete();
   delete fSteps; fSteps=0;
}

//______________________________________________________________________________
TGraphTime::TGraphTime(const TGraphTime &gtime) : TNamed(gtime)
{
   // copy constructor.

   fSleepTime = gtime.fSleepTime;
   fNsteps    = gtime.fNsteps;
   fXmin      = gtime.fXmin;
   fXmax      = gtime.fXmax;
   fYmin      = gtime.fYmin;
   fYmax      = gtime.fYmax;
   fSteps     = new TObjArray(fNsteps+1);
   fFrame     = new TH1D("frame","",100,fXmin,fXmax);
   fFrame->SetMinimum(fYmin);
   fFrame->SetMaximum(fYmax);
   fFrame->SetStats(0);
}

//______________________________________________________________________________
Int_t TGraphTime::Add(const TObject *obj, Int_t slot, Option_t *option)
{
   // Add one object to a time slot.
   // TGraphTime becomes the owner of this object.
   // object will be drawn with option

   if (!fSteps) {
      fNsteps = 100;
      fSteps = new TObjArray(fNsteps+1);
   }
   if (slot < 0 || slot >= fNsteps) return -1;
   TList *list = (TList*)fSteps->UncheckedAt(slot);
   if (!list) {
      list = new TList();
      fSteps->AddAt(list,slot);
   }
   list->Add((TObject*)obj, option);
   return slot;
}

//______________________________________________________________________________
void TGraphTime::Draw(Option_t *option)
{
   // Draw this TGraphTime.
   // for each time step the list of objects added to this step are drawn.

   if (!gPad) {
      gROOT->MakeDefCanvas();
      gPad->SetFillColor(41);
      gPad->SetFrameFillColor(19);
      gPad->SetGrid();
   }
   if (fFrame) {
      fFrame->SetTitle(GetTitle());
      fFrame->Draw();
   }
   Paint(option);

}

//______________________________________________________________________________
void TGraphTime::Paint(Option_t *option)
{
   // Paint all objects added to each time step

   TString opt = option;
   opt.ToLower();
   TObject *frame = gPad->GetPrimitive("frame");
   TList *list = 0;

   for (Int_t s=0;s<fNsteps;s++) {
      list = (TList*)fSteps->UncheckedAt(s);
      if (list) {
         gPad->GetListOfPrimitives()->Remove(frame);
         gPad->GetListOfPrimitives()->Clear();
         if (frame) gPad->GetListOfPrimitives()->Add(frame);
         list->Draw("");
         gPad->Update();
         if (fSleepTime > 0) gSystem->Sleep(fSleepTime);
      }
   }
}
<commit_msg>Use effectively the objects draw options when specified.<commit_after>// @(#)root/hist:$Id$
// Author: Rene Brun   14/07/2009

/*************************************************************************
 * Copyright (C) 1995-2009, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGraphTime.h"
#include "TVirtualPad.h"
#include "TH1.h"
#include "TROOT.h"
#include "TObjArray.h"
#include "TSystem.h"

ClassImp(TGraphTime)

//______________________________________________________________________________
//
// TGraphTime is used to draw a set of objects evolving with nsteps in time between tmin and tmax.
// each time step has a new list of objects. This list can be identical to
// the list of objects in the previous steps, but with different attributes.
//   see example of use in $ROOTSYS/tutorials/graphs/gtime.C

//______________________________________________________________________________
TGraphTime::TGraphTime(): TNamed()
{
   // default constructor.

   fSleepTime = 0;
   fNsteps    = 0;
   fXmin      = 0;
   fXmax      = 1;
   fYmin      = 0;
   fYmax      = 1;
   fSteps     = 0;
   fFrame     = 0;
}

//______________________________________________________________________________
TGraphTime::TGraphTime(Int_t nsteps, Double_t xmin, Double_t ymin, Double_t xmax, Double_t ymax)
      :TNamed()
{
   // Create a TGraphTime with nsteps in range [xmin,xmax][ymin,ymax]

   if (nsteps <= 0) {
      Warning("TGraphTime", "Number of steps %d changed to 100",nsteps);
      nsteps = 100;
   }
   fSleepTime = 0;
   fNsteps    = nsteps;
   fXmin      = xmin;
   fXmax      = xmax;
   fYmin      = ymin;
   fYmax      = ymax;
   fSteps     = new TObjArray(nsteps+1);
   fFrame     = new TH1D("frame","",100,fXmin,fXmax);
   fFrame->SetMinimum(ymin);
   fFrame->SetMaximum(ymax);
   fFrame->SetStats(0);
}

//______________________________________________________________________________
TGraphTime::~TGraphTime()
{
   // GraphTime default destructor.

   if (!fSteps) return;
   fSteps->Delete();
   delete fSteps; fSteps=0;
}

//______________________________________________________________________________
TGraphTime::TGraphTime(const TGraphTime &gtime) : TNamed(gtime)
{
   // copy constructor.

   fSleepTime = gtime.fSleepTime;
   fNsteps    = gtime.fNsteps;
   fXmin      = gtime.fXmin;
   fXmax      = gtime.fXmax;
   fYmin      = gtime.fYmin;
   fYmax      = gtime.fYmax;
   fSteps     = new TObjArray(fNsteps+1);
   fFrame     = new TH1D("frame","",100,fXmin,fXmax);
   fFrame->SetMinimum(fYmin);
   fFrame->SetMaximum(fYmax);
   fFrame->SetStats(0);
}

//______________________________________________________________________________
Int_t TGraphTime::Add(const TObject *obj, Int_t slot, Option_t *option)
{
   // Add one object to a time slot.
   // TGraphTime becomes the owner of this object.
   // object will be drawn with option

   if (!fSteps) {
      fNsteps = 100;
      fSteps = new TObjArray(fNsteps+1);
   }
   if (slot < 0 || slot >= fNsteps) return -1;
   TList *list = (TList*)fSteps->UncheckedAt(slot);
   if (!list) {
      list = new TList();
      fSteps->AddAt(list,slot);
   }
   list->Add((TObject*)obj, option);
   return slot;
}

//______________________________________________________________________________
void TGraphTime::Draw(Option_t *option)
{
   // Draw this TGraphTime.
   // for each time step the list of objects added to this step are drawn.

   if (!gPad) {
      gROOT->MakeDefCanvas();
      gPad->SetFillColor(41);
      gPad->SetFrameFillColor(19);
      gPad->SetGrid();
   }
   if (fFrame) {
      fFrame->SetTitle(GetTitle());
      fFrame->Draw();
   }
   Paint(option);

}

//______________________________________________________________________________
void TGraphTime::Paint(Option_t *option)
{
   // Paint all objects added to each time step

   TString opt = option;
   opt.ToLower();
   TObject *frame = gPad->GetPrimitive("frame");
   TList *list = 0;
   TObjLink *lnk;

   for (Int_t s=0;s<fNsteps;s++) {
      list = (TList*)fSteps->UncheckedAt(s);
      if (list) {
         gPad->GetListOfPrimitives()->Remove(frame);
         gPad->GetListOfPrimitives()->Clear();
         if (frame) gPad->GetListOfPrimitives()->Add(frame);
         lnk = list->FirstLink();
         while(lnk) {
            TObject *obj = lnk->GetObject();
            obj->Draw(lnk->GetAddOption());
            lnk = lnk->Next();
         }
         gPad->Update();
         if (fSleepTime > 0) gSystem->Sleep(fSleepTime);
      }
   }
}
<|endoftext|>


<commit_before>/**
 * \file dcs/memory.hpp
 *
 * \brief Smart pointers are objects which store pointers to dynamically
 * allocated (heap) objects.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_SMART_PTR_HPP
#define DCS_SMART_PTR_HPP

#if __cplusplus > 201103L
// C++0x has smart-pointers
# 	include <memory>
# 	define DCS_MEMORY_NS_ ::std
#else
// Use Boost smart-pointers
# 	include <dcs/detail/config/boost.hpp>
# 	if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(102300)
# 		error "Required Boost library version >= 1.23."
# 	endif
# 	include <boost/smart_ptr.hpp>
# 	include <boost/smart_ptr/make_shared.hpp>
# 	define DCS_MEMORY_NS_ ::boost
#endif // __cplusplus

namespace dcs {

/// Object ownership shared among multiple pointers (\sa \c boost::shared_ptr).
using DCS_MEMORY_NS_::shared_ptr;
/// Non-owning observers of an object owned by \c shared_ptr.
using DCS_MEMORY_NS_::weak_ptr;
///
using DCS_MEMORY_NS_::static_pointer_cast;
///
using DCS_MEMORY_NS_::dynamic_pointer_cast;
///
using DCS_MEMORY_NS_::const_pointer_cast;
///
using DCS_MEMORY_NS_::get_deleter;
///
using DCS_MEMORY_NS_::swap;
///
//using DCS_MEMORY_NS_::owner_less;
///
using DCS_MEMORY_NS_::enable_shared_from_this;
///
using DCS_MEMORY_NS_::make_shared;
///
using DCS_MEMORY_NS_::allocate_shared;

/// Shared ownership of objects with an embedded reference count.
using ::boost::intrusive_ptr;
/// Array ownership shared among multiple pointers.
using ::boost::shared_array;
/// Simple sole ownership of arrays. Noncopyable.
using ::boost::scoped_array;
/// Simple sole ownership of single objects. Noncopyable.
using ::boost::scoped_ptr;
///
using ::boost::get_pointer;

} // Namespace dcs

#endif // DCS_SMART_PTR_HPP
<commit_msg>[memory] Added functions for converting an std::shared_ptr to boost::shared_ptr and vice versa<commit_after>/**
 * \file dcs/memory.hpp
 *
 * \brief Smart pointers are objects which store pointers to dynamically
 * allocated (heap) objects.
 *
 * \author Marco Guazzone (marco.guazzone@gmail.com)
 *
 *

 *
 * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef DCS_SMART_PTR_HPP
#define DCS_SMART_PTR_HPP

#include <dcs/macro.hpp>

#ifdef DCS_MACRO_CXX11
// C++11 has smart-pointers
# 	include <memory>
# 	define DCS_MEMORY_NS_ ::std
#else
// Use Boost smart-pointers
# 	include <dcs/detail/config/boost.hpp>
# 	if !DCS_DETAIL_CONFIG_BOOST_CHECK_VERSION(102300)
# 		error "Required Boost library version >= 1.23."
# 	endif
# 	include <boost/smart_ptr.hpp>
# 	include <boost/smart_ptr/make_shared.hpp>
# 	define DCS_MEMORY_NS_ ::boost
#endif // DCS_MACRO_CXX11

namespace dcs {

/// Object ownership shared among multiple pointers (\sa \c boost::shared_ptr).
using DCS_MEMORY_NS_::shared_ptr;
/// Non-owning observers of an object owned by \c shared_ptr.
using DCS_MEMORY_NS_::weak_ptr;
///
using DCS_MEMORY_NS_::static_pointer_cast;
///
using DCS_MEMORY_NS_::dynamic_pointer_cast;
///
using DCS_MEMORY_NS_::const_pointer_cast;
///
using DCS_MEMORY_NS_::get_deleter;
///
using DCS_MEMORY_NS_::swap;
///
//using DCS_MEMORY_NS_::owner_less;
///
using DCS_MEMORY_NS_::enable_shared_from_this;
///
using DCS_MEMORY_NS_::make_shared;
///
using DCS_MEMORY_NS_::allocate_shared;

/// Shared ownership of objects with an embedded reference count.
using ::boost::intrusive_ptr;
/// Array ownership shared among multiple pointers.
using ::boost::shared_array;
/// Simple sole ownership of arrays. Noncopyable.
using ::boost::scoped_array;
/// Simple sole ownership of single objects. Noncopyable.
using ::boost::scoped_ptr;
///
using ::boost::get_pointer;

#ifdef DCS_MACRO_CXX11

// Conversion functions between boost::shared_ptr and std::shared_ptr (and vice versa)

template<typename T>
boost::shared_ptr<T> make_shared_ptr(std::shared_ptr<T>& ptr)
{
    return boost::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

template<typename T>
std::shared_ptr<T> make_shared_ptr(boost::shared_ptr<T>& ptr)
{
    return std::shared_ptr<T>(ptr.get(), [ptr](T*) mutable {ptr.reset();});
}

#endif // DCS_MACRO_CXX11

} // Namespace dcs

#endif // DCS_SMART_PTR_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2011
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
 #include <vector>
using std::string;
using std::ofstream;
using std::vector;

#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;

#ifndef CL_DATA_HPP
#define CL_DATA_HPP

namespace isa {

namespace OpenCL {

template< typename T > class CLData {
public:
	CLData(string name, bool deletePolicy = false);
	~CLData();

	inline string getName() const;

	// Allocation of host data
	void allocateHostData(vector < T > * data);
	void allocateHostData(long long unsigned int nrElements);
	void deleteHostData();

	// Allocation of device data
	void allocateDeviceData(cl::Buffer * data, size_t size);
	void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
	void allocateDeviceData() throw (OpenCLError);
	void allocateSharedDeviceData() throw (OpenCLError);
	void deleteDeviceData();
	inline void setDeviceReadOnly();
	inline void setDeviceWriteOnly();
	inline void setDeviceReadWrite();

	// Memory transfers
	void copyHostToDevice(bool async = false) throw (OpenCLError);
	void copyDeviceToHost(bool async = false) throw (OpenCLError);
	void dumpDeviceToDisk() throw (OpenCLError);

	// OpenCL
	inline void setCLContext(cl::Context * context);
	inline void setCLQueue(cl::CommandQueue * queue);

	// Access host data
	inline T * getHostData();
	inline T * getHostDataAt(long long unsigned int startingPoint);
	inline void * getRawHostData();
	inline void * getRawHostDataAt(long long unsigned int startingPoint);
	inline size_t getHostDataSize() const;
	inline const T operator[](long long unsigned int item) const;
	inline const T getHostDataItem(long long unsigned int item) const;

	// Modify host data
	inline void setHostDataItem(long long unsigned int item, T value);

	// Access device data
	inline cl::Buffer * getDeviceData();
	inline size_t getDeviceDataSize() const;

	// Timers
	inline Timer & getH2DTimer();
	inline Timer & getD2HTimer();

private:
	cl::Context * clContext;
	cl::CommandQueue * clQueue;
	Timer timerH2D;
	Timer timerD2H;

	bool deleteHost;
	bool deviceReadOnly;
	bool deviceWriteOnly;
	vector< T > * hostData;
	cl::Buffer * deviceData;
	size_t deviceDataSize;

	string name;
};

// Implementations

template< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(0), deviceData(0), deviceDataSize(0), name(name) {}

template< typename T > CLData< T >::~CLData() {
	deleteHostData();
	deleteDeviceData();
}

template< typename T > void CLData< T >::allocateHostData(vector< T > * data) {
	deleteHostData();
	hostData = data;
}

template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
	size_t newSize = nrElements * sizeof(T);

	deleteHostData();
	hostData = new vector< T >(newSize);
}

template< typename T > void CLData< T >::deleteHostData() {
	if ( deleteHost != 0 ) {
		delete hostData;
	}
}

template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
	deleteDeviceData();

	deviceData = data;
	deviceDataSize = size;
}

template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
	size_t newSize = nrElements * sizeof(T);

	if ( newSize != deviceDataSize ) {
		deleteDeviceData();

		try {
			if ( deviceReadOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
			} else if ( deviceWriteOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
			} else {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
			}
		} catch ( cl::Error err ) {
			deviceDataSize = 0;
			throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
		}
		deviceDataSize = newSize;
	}
}

template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::deleteDeviceData() {
	if ( deviceDataSize != 0 ) {
		delete deviceData;
		deviceData = 0;
		deviceDataSize = 0;
	}
}

template< typename T > inline void CLData< T >::setDeviceReadOnly() {
	deviceReadOnly = true;
	deviceWriteOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
	deviceWriteOnly = true;
	deviceReadOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceReadWrite() {
	deviceWriteOnly = false;
	deviceReadOnly = false;
}

template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerH2D.start();
			clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerH2D.stop();
		} catch ( cl::Error err ) {
			timerH2D.reset();
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
}

template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}
	else {
		cl::Event clEvent;

		try {
			timerD2H.start();
			clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerD2H.stop();
		} catch ( cl::Error err ) {
			timerD2H.reset();
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}

}

template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
	CLData< T > temp = CLData< T >("temp", true);

	temp.setCLContext(clContext);
	temp.setCLQueue(clQueue);
	temp.allocateHostData(hostDataSize / sizeof(T));
	temp.allocateDeviceData(deviceData, deviceDataSize);
	temp.copyDeviceToHost();

	ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
	oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
	oFile.close();
}

template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
	clContext = context;
}

template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
	clQueue = queue;
}

template< typename T > inline T * CLData< T >::getHostData() {
	return hostData->data();
}

template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
	return hostData->at(startingPoint);
}

template< typename T > inline void * CLData< T >::getRawHostData() {
	return reinterpret_cast< void * >(hostData->data());
}

template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
	return reinterpret_cast< void * >(hostData->data() + startingPoint);
}

template< typename T > inline size_t CLData< T >::getHostDataSize() const {
	return hostData->size();
}

template< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {
	return hostData->at(item);
}

template< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {
	return hostData->at(item);
}

template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
	return deviceData;
}

template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
	return deviceDataSize;
}

template< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {
	hostData->at(item) = value;
}

template< typename T > inline string CLData< T >::getName() const {
	return name;
}

template< typename T > inline Timer & CLData< T >::getH2DTimer() {
	return timerH2D;
}

template< typename T > inline Timer & CLData< T >::getD2HTimer() {
	return timerD2H;
}

} // OpenCL
} // isa

#endif // CL_DATA_HPP
<commit_msg>I decided that is better to have a statically allocated std::vector to store the host data instead of a dynamic allocated one.<commit_after>/*
 * Copyright (C) 2011
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <string>
#include <cstring>
#include <fstream>
 #include <vector>
using std::string;
using std::ofstream;
using std::vector;

#include <utils.hpp>
#include <Exceptions.hpp>
#include <Timer.hpp>
using isa::utils::toStringValue;
using isa::Exceptions::OpenCLError;
using isa::utils::Timer;

#ifndef CL_DATA_HPP
#define CL_DATA_HPP

namespace isa {

namespace OpenCL {

template< typename T > class CLData {
public:
	CLData(string name, bool deletePolicy = false);
	~CLData();

	inline string getName() const;

	// Allocation of host data
	void allocateHostData(vector < T > & data);
	void allocateHostData(long long unsigned int nrElements);
	void deleteHostData();

	// Allocation of device data
	void allocateDeviceData(cl::Buffer * data, size_t size);
	void allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError);
	void allocateDeviceData() throw (OpenCLError);
	void allocateSharedDeviceData() throw (OpenCLError);
	void deleteDeviceData();
	inline void setDeviceReadOnly();
	inline void setDeviceWriteOnly();
	inline void setDeviceReadWrite();

	// Memory transfers
	void copyHostToDevice(bool async = false) throw (OpenCLError);
	void copyDeviceToHost(bool async = false) throw (OpenCLError);
	void dumpDeviceToDisk() throw (OpenCLError);

	// OpenCL
	inline void setCLContext(cl::Context * context);
	inline void setCLQueue(cl::CommandQueue * queue);

	// Access host data
	inline T * getHostData();
	inline T * getHostDataAt(long long unsigned int startingPoint);
	inline void * getRawHostData();
	inline void * getRawHostDataAt(long long unsigned int startingPoint);
	inline size_t getHostDataSize() const;
	inline const T operator[](long long unsigned int item) const;
	inline const T getHostDataItem(long long unsigned int item) const;

	// Modify host data
	inline void setHostDataItem(long long unsigned int item, T value);

	// Access device data
	inline cl::Buffer * getDeviceData();
	inline size_t getDeviceDataSize() const;

	// Timers
	inline Timer & getH2DTimer();
	inline Timer & getD2HTimer();

private:
	cl::Context * clContext;
	cl::CommandQueue * clQueue;
	Timer timerH2D;
	Timer timerD2H;

	bool deleteHost;
	bool deviceReadOnly;
	bool deviceWriteOnly;
	vector< T > hostData;
	size_t hostDataSize;
	cl::Buffer * deviceData;
	size_t deviceDataSize;

	string name;
};

// Implementations

template< typename T > CLData< T >::CLData(string name, bool deletePolicy) : clContext(0), clQueue(0), timerH2D(Timer("H2D")), timerD2H(Timer("D2H")), deleteHost(deletePolicy), deviceReadOnly(false), deviceWriteOnly(false), hostData(vector< T >()), hostDataSize(0), deviceData(0), deviceDataSize(0), name(name) {}

template< typename T > CLData< T >::~CLData() {
	deleteHostData();
	deleteDeviceData();
}

template< typename T > void CLData< T >::allocateHostData(vector< T > & data) {
	hostData = data;
	hostDataSize = hostData.size() * sizeof(T);
}

template< typename T > void CLData< T >::allocateHostData(long long unsigned int nrElements) {
	hostData = vector< T >(nrElements, 0);
	hostDataSize = nrElements * sizeof(T);
}

template< typename T > void CLData< T >::deleteHostData() {
	if ( deleteHost ) {
		hostData = vector< T >();
	}
}

template< typename T > void CLData< T >::allocateDeviceData(cl::Buffer * data, size_t size) {
	deleteDeviceData();

	deviceData = data;
	deviceDataSize = size;
}

template< typename T > void CLData< T >::allocateDeviceData(long long unsigned int nrElements) throw (OpenCLError) {
	size_t newSize = nrElements * sizeof(T);

	if ( newSize != deviceDataSize ) {
		deleteDeviceData();

		try {
			if ( deviceReadOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, newSize, NULL, NULL);
			} else if ( deviceWriteOnly ) {
				deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, newSize, NULL, NULL);
			} else {
				deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, newSize, NULL, NULL);
			}
		} catch ( cl::Error err ) {
			deviceDataSize = 0;
			throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
		}
		deviceDataSize = newSize;
	}
}

template< typename T > void CLData< T >::allocateDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_ONLY, hostDataSize, NULL, NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_WRITE_ONLY, hostDataSize, NULL, NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_READ_WRITE, hostDataSize, NULL, NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::allocateSharedDeviceData() throw (OpenCLError) {
	deleteDeviceData();

	try {
		if ( deviceReadOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY, hostDataSize, getRawHostData(), NULL);
		} else if ( deviceWriteOnly ) {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY, hostDataSize, getRawHostData(), NULL);
		} else {
			deviceData = new cl::Buffer(*clContext, CL_MEM_USE_HOST_PTR | CL_MEM_READ_WRITE, hostDataSize, getRawHostData(), NULL);
		}
	} catch ( cl::Error err ) {
		deviceDataSize = 0;
		throw  OpenCLError("Impossible to allocate " + name + " device memory: " + toStringValue< cl_int >(err.err()));
	}
	deviceDataSize = hostDataSize;
}

template< typename T > void CLData< T >::deleteDeviceData() {
	if ( deviceDataSize != 0 ) {
		delete deviceData;
		deviceData = 0;
		deviceDataSize = 0;
	}
}

template< typename T > inline void CLData< T >::setDeviceReadOnly() {
	deviceReadOnly = true;
	deviceWriteOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceWriteOnly() {
	deviceWriteOnly = true;
	deviceReadOnly = false;
}

template< typename T > inline void CLData< T >::setDeviceReadWrite() {
	deviceWriteOnly = false;
	deviceReadOnly = false;
}

template< typename T > void CLData< T >::copyHostToDevice(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueWriteBuffer(*deviceData, CL_FALSE, 0, deviceDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	} else {
		cl::Event clEvent;

		try {
			timerH2D.start();
			clQueue->enqueueWriteBuffer(*deviceData, CL_TRUE, 0, deviceDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerH2D.stop();
		} catch ( cl::Error err ) {
			timerH2D.reset();
			throw OpenCLError("Impossible to copy " + name + " to device: " + toStringValue< cl_int >(err.err()));
		}
	}
}

template< typename T > void CLData< T >::copyDeviceToHost(bool async) throw (OpenCLError) {
	if ( hostDataSize != deviceDataSize ) {
		throw OpenCLError("Impossible to copy " + name + ": different memory sizes.");
	}

	if ( async ) {
		try {
			clQueue->enqueueReadBuffer(*deviceData, CL_FALSE, 0, hostDataSize, getRawHostData(), NULL, NULL);
		} catch ( cl::Error err ) {
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	} else {
		cl::Event clEvent;

		try {
			timerD2H.start();
			clQueue->enqueueReadBuffer(*deviceData, CL_TRUE, 0, hostDataSize, getRawHostData(), NULL, &clEvent);
			clEvent.wait();
			timerD2H.stop();
		} catch ( cl::Error err ) {
			timerD2H.reset();
			throw OpenCLError("Impossible to copy " + name + " to host: " + toStringValue< cl_int >(err.err()));
		}
	}

}

template< typename T > void CLData< T >::dumpDeviceToDisk() throw (OpenCLError) {
	CLData< T > temp = CLData< T >("temp", true);

	temp.setCLContext(clContext);
	temp.setCLQueue(clQueue);
	temp.allocateHostData(hostData.size());
	temp.allocateDeviceData(deviceData, deviceDataSize);
	temp.copyDeviceToHost();

	ofstream oFile(("./" + name + ".bin").c_str(), ofstream::binary);
	oFile.write(reinterpret_cast< char * >(temp.getRawHostData()), temp.getHostDataSize());
	oFile.close();
}

template< typename T > inline void CLData< T >::setCLContext(cl::Context * context) {
	clContext = context;
}

template< typename T > inline void CLData< T >::setCLQueue(cl::CommandQueue * queue) {
	clQueue = queue;
}

template< typename T > inline T * CLData< T >::getHostData() {
	return hostData.data();
}

template< typename T > inline T * CLData< T >::getHostDataAt(long long unsigned int startingPoint) {
	return hostData.data() + startingPoint;
}

template< typename T > inline void * CLData< T >::getRawHostData() {
	return reinterpret_cast< void * >(hostData.data());
}

template< typename T > inline void * CLData< T >::getRawHostDataAt(long long unsigned int startingPoint) {
	return reinterpret_cast< void * >(hostData.data() + startingPoint);
}

template< typename T > inline size_t CLData< T >::getHostDataSize() const {
	return hostDataSize;
}

template< typename T > inline const T CLData< T >::operator[](long long unsigned int item) const {
	return hostData[item];
}

template< typename T > inline const T CLData< T >::getHostDataItem(long long unsigned int item) const {
	return hostData[item];
}

template< typename T > inline cl::Buffer * CLData< T >::getDeviceData() {
	return deviceData;
}

template< typename T > inline size_t CLData< T >::getDeviceDataSize() const {
	return deviceDataSize;
}

template< typename T > inline void CLData< T >::setHostDataItem(long long unsigned int item, T value) {
	hostData[item] = value;
}

template< typename T > inline string CLData< T >::getName() const {
	return name;
}

template< typename T > inline Timer & CLData< T >::getH2DTimer() {
	return timerH2D;
}

template< typename T > inline Timer & CLData< T >::getD2HTimer() {
	return timerD2H;
}

} // OpenCL
} // isa

#endif // CL_DATA_HPP
<|endoftext|>


<commit_before>/*

Copyright (c) 2014, Arvid Norberg
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 the author 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 "libtorrent/session.hpp"
#include "libtorrent/escape_string.hpp" // for from_hex
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp" // for bencode()
#include "libtorrent/kademlia/item.hpp" // for sign_mutable_item
#include "ed25519.h"
#include <boost/bind.hpp>

#include <stdlib.h>

using namespace libtorrent;

#ifdef TORRENT_DISABLE_DHT

int main(int argc, char* argv[])
{
	fprintf(stderr, "not built with DHT support\n");
	return 1;
}

#else

void usage()
{
	fprintf(stderr,
		"USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n"
		"get <hash>                - retrieves and prints out the immutable\n"
		"                            item stored under hash.\n"
		"put <string>              - puts the specified string as an immutable\n"
		"                            item onto the DHT. The resulting target hash\n"
		"gen-key <key-file>        - generate ed25519 keypair and save it in\n"
		"                            the specified file\n"
		"mput <key-file> <string>  - puts the specified string as a mutable\n"
		"                            object under the public key in key-file\n"
		"mget <public-key>         - get a mutable object under the specified\n"
		"                            public key\n"
		);
	exit(1);
}

std::auto_ptr<alert> wait_for_alert(session& s, int alert_type)
{
	std::auto_ptr<alert> ret;
	bool found = false;
	while (!found)
	{
		s.wait_for_alert(seconds(5));

		std::deque<alert*> alerts;
		s.pop_alerts(&alerts);
		for (std::deque<alert*>::iterator i = alerts.begin()
			, end(alerts.end()); i != end; ++i)
		{
			if ((*i)->type() != alert_type)
			{
				static int spinner = 0;
				static const char anim[] = {'-', '\\', '|', '/'};
				printf("\r%c", anim[spinner]);
				fflush(stdout);
				spinner = (spinner + 1) & 3;
				//print some alerts?
				delete *i;
				continue;
			}
			ret = std::auto_ptr<alert>(*i);
			found = true;
		}
	}
	printf("\n");
	return ret;
}

void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq
	, std::string const& salt, char const* public_key, char const* private_key
	, char const* str)
{
	using libtorrent::dht::sign_mutable_item;

	e = std::string(str);
	std::vector<char> buf;
	bencode(std::back_inserter(buf), e);
	++seq;
	sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size())
		, std::pair<char const*, int>(&salt[0], salt.size())
		, seq
		, public_key
		, private_key
		, sig.data());
}

void bootstrap(session& s)
{
	printf("bootstrapping\n");
	wait_for_alert(s, dht_bootstrap_alert::alert_type);
}

int main(int argc, char* argv[])
{
	// skip pointer to self
	++argv;
	--argc;

	if (argc < 1) usage();

	if (strcmp(argv[0], "gen-key") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		unsigned char seed[32];
		ed25519_create_seed(seed);

		FILE* f = fopen(argv[0], "wb+");
		if (f == NULL)
		{
			fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n"
				, argv[0], errno, strerror(errno));
			return 1;
		}

		fwrite(seed, 1, 32, f);
		fclose(f);
		return 0;
	}

	session s;
	s.set_alert_mask(0xffffffff);

	s.add_dht_router(std::pair<std::string, int>("router.utorrent.com", 6881));

	FILE* f = fopen(".dht", "rb");
	if (f != NULL)
	{
		fseek(f, 0, SEEK_END);
		int size = ftell(f);
		fseek(f, 0, SEEK_SET);
		if (size > 0)
		{
			std::vector<char> state;
			state.resize(size);
			fread(&state[0], 1, state.size(), f);

			lazy_entry e;
			error_code ec;
			lazy_bdecode(&state[0], &state[0] + state.size(), e, ec);
			if (ec)
				fprintf(stderr, "failed to parse .dht file: (%d) %s\n"
					, ec.value(), ec.message().c_str());
			else
				s.load_state(e);
		}
		fclose(f);
	}

	if (strcmp(argv[0], "get") == 0)
	{
		++argv;
		--argc;

		if (argc < 1) usage();

		if (strlen(argv[0]) != 40)
		{
			fprintf(stderr, "the hash is expected to be 40 hex characters\n");
			usage();
		}
		sha1_hash target;
		bool ret = from_hex(argv[0], 40, (char*)&target[0]);
		if (!ret)
		{
			fprintf(stderr, "invalid hex encoding of target hash\n");
			return 1;
		}

		bootstrap(s);
		s.dht_get_item(target);

		printf("GET %s\n", to_hex(target.to_string()).c_str());

		std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type);

		dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get());
		entry data;
		if (item)
			data.swap(item->item);

		printf("%s", data.to_string().c_str());
	}
	else if (strcmp(argv[0], "put") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		entry data;
		data = std::string(argv[0]);

		bootstrap(s);
		sha1_hash target = s.dht_put_item(data);

		printf("PUT %s\n", to_hex(target.to_string()).c_str());

		wait_for_alert(s, dht_put_alert::alert_type);
	}
	else if (strcmp(argv[0], "mput") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		FILE* f = fopen(argv[0], "rb+");
		if (f == NULL)
		{
			fprintf(stderr, "failed to open file \"%s\": (%d) %s\n"
				, argv[0], errno, strerror(errno));
			return 1;
		}

		unsigned char seed[32];
		fread(seed, 1, 32, f);
		fclose(f);

		++argv;
		--argc;
		if (argc < 1) usage();

		boost::array<char, 32> public_key;
		boost::array<char, 64> private_key;
		ed25519_create_keypair((unsigned char*)public_key.data()
			, (unsigned char*)private_key.data(), seed);

		bootstrap(s);
		s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4
			, public_key.data(), private_key.data(), argv[0]));

		printf("public key: %s\n", to_hex(std::string(public_key.data()
			, public_key.size())).c_str());

		wait_for_alert(s, dht_put_alert::alert_type);
	}
	else if (strcmp(argv[0], "mget") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		int len = strlen(argv[0]);
		if (len != 64)
		{
			fprintf(stderr, "public key is expected to be 64 hex digits\n");
			return 1;
		}
		boost::array<char, 32> public_key;
		bool ret = from_hex(argv[0], len, &public_key[0]);
		if (!ret)
		{
			fprintf(stderr, "invalid hex encoding of public key\n");
			return 1;
		}

		bootstrap(s);
		s.dht_get_item(public_key);

		std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type);

		dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get());
		entry data;
		if (item)
			data.swap(item->item);

		printf("%s", data.to_string().c_str());
	}
	else
	{
		usage();
	}

	entry e;
	s.save_state(e, session::save_dht_state);
	std::vector<char> state;
	bencode(std::back_inserter(state), e);
	f = fopen(".dht", "wb+");
	if (f == NULL)
	{
		fprintf(stderr, "failed to open file .dht for writing");
		return 1;
	}
	fwrite(&state[0], 1, state.size(), f);
	fclose(f);
}

#endif

<commit_msg>fix no-deprecated functions build<commit_after>/*

Copyright (c) 2014, Arvid Norberg
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 the author 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 "libtorrent/session.hpp"
#include "libtorrent/escape_string.hpp" // for from_hex
#include "libtorrent/alert_types.hpp"
#include "libtorrent/bencode.hpp" // for bencode()
#include "libtorrent/kademlia/item.hpp" // for sign_mutable_item
#include "ed25519.h"
#include <boost/bind.hpp>

#include <stdlib.h>

using namespace libtorrent;

#ifdef TORRENT_DISABLE_DHT

int main(int argc, char* argv[])
{
	fprintf(stderr, "not built with DHT support\n");
	return 1;
}

#else

void usage()
{
	fprintf(stderr,
		"USAGE:\ndht <command> <arg>\n\nCOMMANDS:\n"
		"get <hash>                - retrieves and prints out the immutable\n"
		"                            item stored under hash.\n"
		"put <string>              - puts the specified string as an immutable\n"
		"                            item onto the DHT. The resulting target hash\n"
		"gen-key <key-file>        - generate ed25519 keypair and save it in\n"
		"                            the specified file\n"
		"mput <key-file> <string>  - puts the specified string as a mutable\n"
		"                            object under the public key in key-file\n"
		"mget <public-key>         - get a mutable object under the specified\n"
		"                            public key\n"
		);
	exit(1);
}

std::auto_ptr<alert> wait_for_alert(session& s, int alert_type)
{
	std::auto_ptr<alert> ret;
	bool found = false;
	while (!found)
	{
		s.wait_for_alert(seconds(5));

		std::deque<alert*> alerts;
		s.pop_alerts(&alerts);
		for (std::deque<alert*>::iterator i = alerts.begin()
			, end(alerts.end()); i != end; ++i)
		{
			if ((*i)->type() != alert_type)
			{
				static int spinner = 0;
				static const char anim[] = {'-', '\\', '|', '/'};
				printf("\r%c", anim[spinner]);
				fflush(stdout);
				spinner = (spinner + 1) & 3;
				//print some alerts?
				delete *i;
				continue;
			}
			ret = std::auto_ptr<alert>(*i);
			found = true;
		}
	}
	printf("\n");
	return ret;
}

void put_string(entry& e, boost::array<char, 64>& sig, boost::uint64_t& seq
	, std::string const& salt, char const* public_key, char const* private_key
	, char const* str)
{
	using libtorrent::dht::sign_mutable_item;

	e = std::string(str);
	std::vector<char> buf;
	bencode(std::back_inserter(buf), e);
	++seq;
	sign_mutable_item(std::pair<char const*, int>(&buf[0], buf.size())
		, std::pair<char const*, int>(&salt[0], salt.size())
		, seq
		, public_key
		, private_key
		, sig.data());
}

void bootstrap(session& s)
{
	printf("bootstrapping\n");
	wait_for_alert(s, dht_bootstrap_alert::alert_type);
}

int main(int argc, char* argv[])
{
	// skip pointer to self
	++argv;
	--argc;

	if (argc < 1) usage();

	if (strcmp(argv[0], "gen-key") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		unsigned char seed[32];
		ed25519_create_seed(seed);

		FILE* f = fopen(argv[0], "wb+");
		if (f == NULL)
		{
			fprintf(stderr, "failed to open file for writing \"%s\": (%d) %s\n"
				, argv[0], errno, strerror(errno));
			return 1;
		}

		fwrite(seed, 1, 32, f);
		fclose(f);
		return 0;
	}

	settings_pack sett;
	sett.set_int(settings_pack::alert_mask, 0xffffffff);
	session s(sett);

	s.add_dht_router(std::pair<std::string, int>("router.utorrent.com", 6881));

	FILE* f = fopen(".dht", "rb");
	if (f != NULL)
	{
		fseek(f, 0, SEEK_END);
		int size = ftell(f);
		fseek(f, 0, SEEK_SET);
		if (size > 0)
		{
			std::vector<char> state;
			state.resize(size);
			fread(&state[0], 1, state.size(), f);

			lazy_entry e;
			error_code ec;
			lazy_bdecode(&state[0], &state[0] + state.size(), e, ec);
			if (ec)
				fprintf(stderr, "failed to parse .dht file: (%d) %s\n"
					, ec.value(), ec.message().c_str());
			else
				s.load_state(e);
		}
		fclose(f);
	}

	if (strcmp(argv[0], "get") == 0)
	{
		++argv;
		--argc;

		if (argc < 1) usage();

		if (strlen(argv[0]) != 40)
		{
			fprintf(stderr, "the hash is expected to be 40 hex characters\n");
			usage();
		}
		sha1_hash target;
		bool ret = from_hex(argv[0], 40, (char*)&target[0]);
		if (!ret)
		{
			fprintf(stderr, "invalid hex encoding of target hash\n");
			return 1;
		}

		bootstrap(s);
		s.dht_get_item(target);

		printf("GET %s\n", to_hex(target.to_string()).c_str());

		std::auto_ptr<alert> a = wait_for_alert(s, dht_immutable_item_alert::alert_type);

		dht_immutable_item_alert* item = alert_cast<dht_immutable_item_alert>(a.get());
		entry data;
		if (item)
			data.swap(item->item);

		printf("%s", data.to_string().c_str());
	}
	else if (strcmp(argv[0], "put") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		entry data;
		data = std::string(argv[0]);

		bootstrap(s);
		sha1_hash target = s.dht_put_item(data);

		printf("PUT %s\n", to_hex(target.to_string()).c_str());

		wait_for_alert(s, dht_put_alert::alert_type);
	}
	else if (strcmp(argv[0], "mput") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		FILE* f = fopen(argv[0], "rb+");
		if (f == NULL)
		{
			fprintf(stderr, "failed to open file \"%s\": (%d) %s\n"
				, argv[0], errno, strerror(errno));
			return 1;
		}

		unsigned char seed[32];
		fread(seed, 1, 32, f);
		fclose(f);

		++argv;
		--argc;
		if (argc < 1) usage();

		boost::array<char, 32> public_key;
		boost::array<char, 64> private_key;
		ed25519_create_keypair((unsigned char*)public_key.data()
			, (unsigned char*)private_key.data(), seed);

		bootstrap(s);
		s.dht_put_item(public_key, boost::bind(&put_string, _1, _2, _3, _4
			, public_key.data(), private_key.data(), argv[0]));

		printf("public key: %s\n", to_hex(std::string(public_key.data()
			, public_key.size())).c_str());

		wait_for_alert(s, dht_put_alert::alert_type);
	}
	else if (strcmp(argv[0], "mget") == 0)
	{
		++argv;
		--argc;
		if (argc < 1) usage();

		int len = strlen(argv[0]);
		if (len != 64)
		{
			fprintf(stderr, "public key is expected to be 64 hex digits\n");
			return 1;
		}
		boost::array<char, 32> public_key;
		bool ret = from_hex(argv[0], len, &public_key[0]);
		if (!ret)
		{
			fprintf(stderr, "invalid hex encoding of public key\n");
			return 1;
		}

		bootstrap(s);
		s.dht_get_item(public_key);

		std::auto_ptr<alert> a = wait_for_alert(s, dht_mutable_item_alert::alert_type);

		dht_mutable_item_alert* item = alert_cast<dht_mutable_item_alert>(a.get());
		entry data;
		if (item)
			data.swap(item->item);

		printf("%s", data.to_string().c_str());
	}
	else
	{
		usage();
	}

	entry e;
	s.save_state(e, session::save_dht_state);
	std::vector<char> state;
	bencode(std::back_inserter(state), e);
	f = fopen(".dht", "wb+");
	if (f == NULL)
	{
		fprintf(stderr, "failed to open file .dht for writing");
		return 1;
	}
	fwrite(&state[0], 1, state.size(), f);
	fclose(f);
}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xwin.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2004-02-25 17:10:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "xwin.hxx"
#ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_
#include <com/sun/star/lang/SystemDependent.hpp>
#endif

using namespace ::com::sun::star;

ContainerWindowWrapper::ContainerWindowWrapper(HWND aHwnd)
    : m_aHwnd(aHwnd),
      m_pDisposeEventListeners(0)
{
}

ContainerWindowWrapper::~ContainerWindowWrapper()
{
    delete m_pDisposeEventListeners;
}

void SAL_CALL
ContainerWindowWrapper::dispose(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);

    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }

    if(pDisposeEventListeners) {
        lang::EventObject aEvt;
        aEvt.Source = static_cast< awt::XWindow* >(this);

        pDisposeEventListeners->disposeAndClear(aEvt);
    }
}

void SAL_CALL
ContainerWindowWrapper::addEventListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XEventListener >& Listener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }

    if(! pDisposeEventListeners)
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners =
            new cppu::OInterfaceContainerHelper(m_aMutex);
    }

    pDisposeEventListeners->addInterface( Listener );
}

void SAL_CALL
ContainerWindowWrapper::removeEventListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XEventListener >& Listener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }
    if( pDisposeEventListeners )
        pDisposeEventListeners->removeInterface( Listener );
}

// XSystemDependentWindowPeer

::com::sun::star::uno::Any SAL_CALL
ContainerWindowWrapper::getWindowHandle(
    const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId,
    sal_Int16 SystemType
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    if(SystemType == lang::SystemDependent::SYSTEM_WIN32 ||
       SystemType == lang::SystemDependent::SYSTEM_WIN16)
    {
        uno::Any aAny;
        sal_Int32 nHwnd = sal_Int32(m_aHwnd);
        aAny <<= nHwnd;
        return aAny;
    }
    else
        return uno::Any();
}

void SAL_CALL
ContainerWindowWrapper::setPosSize(
    sal_Int32 X,
    sal_Int32 Y,
    sal_Int32 Width,
    sal_Int32 Height,
    sal_Int16 Flags
)
    throw (
        ::com::sun::star::uno::RuntimeException)
{

}

::com::sun::star::awt::Rectangle SAL_CALL
ContainerWindowWrapper::getPosSize(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    return awt::Rectangle();
}

void SAL_CALL
ContainerWindowWrapper::setVisible(
    sal_Bool Visible
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::setEnable(
    sal_Bool Enable
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::setFocus(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addWindowListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XWindowListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeWindowListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XWindowListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addFocusListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeFocusListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addKeyListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XKeyListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeKeyListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XKeyListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addMouseListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeMouseListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addMouseMotionListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseMotionListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeMouseMotionListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseMotionListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addPaintListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XPaintListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removePaintListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XPaintListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.32); FILE MERGED 2005/09/05 18:46:13 rt 1.2.32.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xwin.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:55: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 "xwin.hxx"
#ifndef _COM_SUN_STAR_LANG_SYSTEMDEPENDENT_HPP_
#include <com/sun/star/lang/SystemDependent.hpp>
#endif

using namespace ::com::sun::star;

ContainerWindowWrapper::ContainerWindowWrapper(HWND aHwnd)
    : m_aHwnd(aHwnd),
      m_pDisposeEventListeners(0)
{
}

ContainerWindowWrapper::~ContainerWindowWrapper()
{
    delete m_pDisposeEventListeners;
}

void SAL_CALL
ContainerWindowWrapper::dispose(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);

    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }

    if(pDisposeEventListeners) {
        lang::EventObject aEvt;
        aEvt.Source = static_cast< awt::XWindow* >(this);

        pDisposeEventListeners->disposeAndClear(aEvt);
    }
}

void SAL_CALL
ContainerWindowWrapper::addEventListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XEventListener >& Listener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }

    if(! pDisposeEventListeners)
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners =
            new cppu::OInterfaceContainerHelper(m_aMutex);
    }

    pDisposeEventListeners->addInterface( Listener );
}

void SAL_CALL
ContainerWindowWrapper::removeEventListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::lang::XEventListener >& Listener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    cppu::OInterfaceContainerHelper *pDisposeEventListeners(0);
    {
        osl::MutexGuard aGuard(m_aMutex);
        pDisposeEventListeners = m_pDisposeEventListeners;
    }
    if( pDisposeEventListeners )
        pDisposeEventListeners->removeInterface( Listener );
}

// XSystemDependentWindowPeer

::com::sun::star::uno::Any SAL_CALL
ContainerWindowWrapper::getWindowHandle(
    const ::com::sun::star::uno::Sequence< sal_Int8 >& ProcessId,
    sal_Int16 SystemType
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    if(SystemType == lang::SystemDependent::SYSTEM_WIN32 ||
       SystemType == lang::SystemDependent::SYSTEM_WIN16)
    {
        uno::Any aAny;
        sal_Int32 nHwnd = sal_Int32(m_aHwnd);
        aAny <<= nHwnd;
        return aAny;
    }
    else
        return uno::Any();
}

void SAL_CALL
ContainerWindowWrapper::setPosSize(
    sal_Int32 X,
    sal_Int32 Y,
    sal_Int32 Width,
    sal_Int32 Height,
    sal_Int16 Flags
)
    throw (
        ::com::sun::star::uno::RuntimeException)
{

}

::com::sun::star::awt::Rectangle SAL_CALL
ContainerWindowWrapper::getPosSize(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{
    return awt::Rectangle();
}

void SAL_CALL
ContainerWindowWrapper::setVisible(
    sal_Bool Visible
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::setEnable(
    sal_Bool Enable
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::setFocus(
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addWindowListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XWindowListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeWindowListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XWindowListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addFocusListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeFocusListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addKeyListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XKeyListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeKeyListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XKeyListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addMouseListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeMouseListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addMouseMotionListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseMotionListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removeMouseMotionListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XMouseMotionListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::addPaintListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XPaintListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}

void SAL_CALL
ContainerWindowWrapper::removePaintListener(
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XPaintListener >& xListener
)
    throw (
        ::com::sun::star::uno::RuntimeException
    )
{

}
<|endoftext|>


<commit_before>#include "LARASURF.H"

#include "CAMERA.H"
#include "COLLIDE.H"
#include "CONTROL.H"
#include "DRAW.H"
#include "LARA.H"
#include "LARAFIRE.H"
#include "SPECIFIC.H"
#include INPUT_H
#include "LARASWIM.H"

#if PSX_VERSION
#include "COLLIDE_S.H"
#endif

void lara_col_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DDBC(<), 4E220(<) (F)
{
	if (item->goal_anim_state == STATE_LARA_UNDERWATER_FORWARD)
	{
		item->goal_anim_state = STATE_LARA_UNDERWATER_DIVING;
		item->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;
		item->pos.x_rot = ANGLE(-45);
		item->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;
		item->fallspeed = 80;
		lara.water_status = LW_UNDERWATER;
	}
	lara.move_angle = item->pos.y_rot;
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD90(<), 4E1F4(<) (F)
{
	lara.move_angle = item->pos.y_rot + ANGLE(90);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD64(<), 4E1C8(<) (F)
{
	lara.move_angle = item->pos.y_rot - ANGLE(90);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD38(<), 4E19C(<) (F)
{
	lara.move_angle = item->pos.y_rot - ANGLE(180);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DCE8(<), 4E14C(<) (F)
{
	coll->bad_neg = -384;
	lara.move_angle = item->pos.y_rot;
	LaraSurfaceCollision(item, coll);
	LaraTestWaterClimbOut(item, coll);
}

void lara_as_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DBA0, 4E004 (F)
{
	item->fallspeed -= 4;
	if (item->fallspeed < 0)
		item->fallspeed = 0;

	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	if (input & IN_LOOK)
	{
		LookUpDown();
		return;
	}

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(4);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(4);
	}

	if(input & IN_FORWARD)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_FORWARD;
	}
	else if(input & IN_BACK)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_BACK;
	}

	if (input & IN_LSTEP)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_LEFT;
	}
	else if(input & IN_RSTEP)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_RIGHT;
	}

	if (input & IN_JUMP)
	{
		if (++lara.dive_count == 10)
			item->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;
	}
	else
	{
		lara.dive_count = 0;
	}
}

void lara_as_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DAF8, 4DF5C (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_RSTEP))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DA50(<), 4DEB4(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_LSTEP))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D9A8(<), 4DE0C(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_BACK))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D8E4(<), 4DD48(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(4);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(4);
	}

	if (!(input & IN_FORWARD))
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	if (input & IN_JUMP)
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void LaraSurface(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D684, 4DAE8 (F)
{
	camera.target_elevation = ANGLE(-22);

	coll->bad_pos = -BAD_HEIGHT;
	coll->bad_neg = -128;
	coll->bad_ceiling = 100;

	coll->old.x = item->pos.x_pos;
	coll->old.y = item->pos.y_pos;
	coll->old.z = item->pos.z_pos;

	coll->slopes_are_walls = 0;
	coll->slopes_are_pits = 0;
	coll->lava_is_pit = 0;

	coll->enable_baddie_push = FALSE;
	coll->enable_spaz = FALSE;

	coll->radius = 100;
	coll->trigger = 0;

	if (input & IN_LOOK && lara.look)
		LookLeftRight();
	else
		ResetLook();

	lara.look = TRUE;

	lara_control_routines[item->current_anim_state](item, coll);

	item->pos.z_rot = CLAMPADD(item->pos.z_rot, ANGLE(-2), ANGLE(2));

	if (lara.current_active && lara.water_status != LW_FLYCHEAT)
		LaraWaterCurrent(coll);

	AnimateLara(item);

	item->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> W2V_SHIFT;
	item->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> W2V_SHIFT;

	LaraBaddieCollision(item, coll);

	lara_collision_routines[item->current_anim_state](item, coll);

	UpdateLaraRoom(item, 100);

	LaraGun();

	TestTriggers(coll->trigger, 0, 0);
}

void LaraSurfaceCollision(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D4F0(<), 4D954(<) (F)
{
	coll->facing = lara.move_angle;
	GetCollisionInfo(coll, item->pos.x_pos, item->pos.y_pos + 700, item->pos.z_pos, item->room_number, 800);
	ShiftItem(item, coll);
	if (coll->coll_type & (CT_FRONT | CT_TOP | CT_TOP_FRONT | CT_CLAMP) ||
		coll->mid_floor < 0 && (coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL))
	{
		item->fallspeed = 0;
		item->pos.x_pos = coll->old.x;
		item->pos.y_pos = coll->old.y;
		item->pos.z_pos = coll->old.z;
	}
	else if (coll->coll_type == CT_LEFT)
	{
		item->pos.y_rot += ANGLE(5);
	}
	else if (coll->coll_type == CT_RIGHT)
	{
		item->pos.y_rot -= ANGLE(5);
	}
	if (GetWaterHeight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, item->room_number) - item->pos.y_pos > -100)
	{
		LaraTestWaterStepOut(item, coll);
	}
	else
	{
		item->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;
		item->current_anim_state = STATE_LARA_UNDERWATER_DIVING;
		item->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;
		item->pos.x_rot = ANGLE(-90);
		item->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;
		item->fallspeed = 80;
		lara.water_status = LW_UNDERWATER;
	}
}

int LaraTestWaterClimbOut(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D22C, 4D690
{
	UNIMPLEMENTED();
	return 0;
}

int LaraTestWaterStepOut(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D100, 4D564 (F)
{
	if (coll->coll_type == CT_FRONT || coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL || coll->mid_floor >= 0)
	{
		return 0;
	}

	if (coll->mid_floor >= -128)
	{
		if (item->goal_anim_state == STATE_LARA_ONWATER_LEFT)
		{
			item->goal_anim_state = STATE_LARA_WALK_LEFT;
		}
		else if (item->goal_anim_state == STATE_LARA_ONWATER_RIGHT)
		{
			item->goal_anim_state = STATE_LARA_WALK_RIGHT;
		}
		else
		{
			item->anim_number = ANIMATION_LARA_WADE;
			item->frame_number = anims[ANIMATION_LARA_WADE].frame_base;
			item->goal_anim_state = STATE_LARA_WADE_FORWARD;
			item->current_anim_state = STATE_LARA_WADE_FORWARD;
		}
	}
	else
	{
		item->anim_number = ANIMATION_LARA_ONWATER_TO_WADE_DEEP;
		item->frame_number = anims[ANIMATION_LARA_ONWATER_TO_WADE_DEEP].frame_base;
		item->current_anim_state = STATE_LARA_ONWATER_EXIT;
		item->goal_anim_state = STATE_LARA_STOP;
	}

	item->pos.y_pos += coll->front_floor + 695;

	UpdateLaraRoom(item, -381);

	item->pos.z_rot = 0;
	item->pos.x_rot = 0;

	item->gravity_status = TRUE;
	item->speed = 0;
	item->fallspeed = 0;

	lara.water_status = LW_WADE;

	return 1;
}
<commit_msg>[Game]: Correct LaraSurface.<commit_after>#include "LARASURF.H"

#include "CAMERA.H"
#include "COLLIDE.H"
#include "CONTROL.H"
#include "DRAW.H"
#include "LARA.H"
#include "LARAFIRE.H"
#include "SPECIFIC.H"
#include INPUT_H
#include "LARASWIM.H"

#if PSX_VERSION
#include "COLLIDE_S.H"
#endif

void lara_col_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DDBC(<), 4E220(<) (F)
{
	if (item->goal_anim_state == STATE_LARA_UNDERWATER_FORWARD)
	{
		item->goal_anim_state = STATE_LARA_UNDERWATER_DIVING;
		item->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;
		item->pos.x_rot = ANGLE(-45);
		item->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;
		item->fallspeed = 80;
		lara.water_status = LW_UNDERWATER;
	}
	lara.move_angle = item->pos.y_rot;
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD90(<), 4E1F4(<) (F)
{
	lara.move_angle = item->pos.y_rot + ANGLE(90);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD64(<), 4E1C8(<) (F)
{
	lara.move_angle = item->pos.y_rot - ANGLE(90);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DD38(<), 4E19C(<) (F)
{
	lara.move_angle = item->pos.y_rot - ANGLE(180);
	LaraSurfaceCollision(item, coll);
}

void lara_col_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DCE8(<), 4E14C(<) (F)
{
	coll->bad_neg = -384;
	lara.move_angle = item->pos.y_rot;
	LaraSurfaceCollision(item, coll);
	LaraTestWaterClimbOut(item, coll);
}

void lara_as_surftread(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DBA0, 4E004 (F)
{
	item->fallspeed -= 4;
	if (item->fallspeed < 0)
		item->fallspeed = 0;

	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	if (input & IN_LOOK)
	{
		LookUpDown();
		return;
	}

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(4);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(4);
	}

	if(input & IN_FORWARD)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_FORWARD;
	}
	else if(input & IN_BACK)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_BACK;
	}

	if (input & IN_LSTEP)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_LEFT;
	}
	else if(input & IN_RSTEP)
	{
		item->goal_anim_state = STATE_LARA_ONWATER_RIGHT;
	}

	if (input & IN_JUMP)
	{
		if (++lara.dive_count == 10)
			item->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;
	}
	else
	{
		lara.dive_count = 0;
	}
}

void lara_as_surfright(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DAF8, 4DF5C (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_RSTEP))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfleft(struct ITEM_INFO* item, struct COLL_INFO* coll)//4DA50(<), 4DEB4(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_LSTEP))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfback(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D9A8(<), 4DE0C(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(2);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(2);
	}

	if (!(input & IN_BACK))
	{
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	}

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void lara_as_surfswim(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D8E4(<), 4DD48(<) (F)
{
	if (item->hit_points <= 0)
	{
		item->goal_anim_state = STATE_LARA_WATER_DEATH;

		return;
	}

	lara.dive_count = 0;

	if (input & IN_LEFT)
	{
		item->pos.y_rot -= ANGLE(4);
	}
	else if (input & IN_RIGHT)
	{
		item->pos.y_rot += ANGLE(4);
	}

	if (!(input & IN_FORWARD))
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;
	if (input & IN_JUMP)
		item->goal_anim_state = STATE_LARA_ONWATER_STOP;

	item->fallspeed += 8;
	if (item->fallspeed > 60)
		item->fallspeed = 60;
}

void LaraSurface(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D684, 4DAE8 (F)
{
	camera.target_elevation = ANGLE(-22);

	coll->bad_pos = -BAD_HEIGHT;
	coll->bad_neg = -128;
	coll->bad_ceiling = 100;

	coll->old.x = item->pos.x_pos;
	coll->old.y = item->pos.y_pos;
	coll->old.z = item->pos.z_pos;

	coll->slopes_are_walls = 0;
	coll->slopes_are_pits = 0;
	coll->lava_is_pit = 0;

	coll->enable_baddie_push = FALSE;
	coll->enable_spaz = FALSE;

	coll->radius = 100;
	coll->trigger = 0;

	if (input & IN_LOOK && lara.look)
		LookLeftRight();
	else
		ResetLook();

	lara.look = TRUE;

	lara_control_routines[item->current_anim_state](item, coll);

	item->pos.z_rot = CLAMPADD(item->pos.z_rot, ANGLE(-2), ANGLE(2));

	if (lara.current_active && lara.water_status != LW_FLYCHEAT)
		LaraWaterCurrent(coll);

	AnimateLara(item);

#if PSX_VERSION
	item->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> 14;
	item->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> 14;
#elif PC_VERSION
	item->pos.x_pos += item->fallspeed * SIN(lara.move_angle) >> W2V_SHIFT;
	item->pos.z_pos += item->fallspeed * COS(lara.move_angle) >> W2V_SHIFT;
#endif

	LaraBaddieCollision(item, coll);

	lara_collision_routines[item->current_anim_state](item, coll);

	UpdateLaraRoom(item, 100);

	LaraGun();

	TestTriggers(coll->trigger, 0, 0);
}

void LaraSurfaceCollision(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D4F0(<), 4D954(<) (F)
{
	coll->facing = lara.move_angle;
	GetCollisionInfo(coll, item->pos.x_pos, item->pos.y_pos + 700, item->pos.z_pos, item->room_number, 800);
	ShiftItem(item, coll);
	if (coll->coll_type & (CT_FRONT | CT_TOP | CT_TOP_FRONT | CT_CLAMP) ||
		coll->mid_floor < 0 && (coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL))
	{
		item->fallspeed = 0;
		item->pos.x_pos = coll->old.x;
		item->pos.y_pos = coll->old.y;
		item->pos.z_pos = coll->old.z;
	}
	else if (coll->coll_type == CT_LEFT)
	{
		item->pos.y_rot += ANGLE(5);
	}
	else if (coll->coll_type == CT_RIGHT)
	{
		item->pos.y_rot -= ANGLE(5);
	}
	if (GetWaterHeight(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, item->room_number) - item->pos.y_pos > -100)
	{
		LaraTestWaterStepOut(item, coll);
	}
	else
	{
		item->goal_anim_state = STATE_LARA_UNDERWATER_FORWARD;
		item->current_anim_state = STATE_LARA_UNDERWATER_DIVING;
		item->anim_number = ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE;
		item->pos.x_rot = ANGLE(-90);
		item->frame_number = anims[ANIMATION_LARA_FREE_FALL_TO_UNDERWATER_ALTERNATE].frame_base;
		item->fallspeed = 80;
		lara.water_status = LW_UNDERWATER;
	}
}

int LaraTestWaterClimbOut(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D22C, 4D690
{
	UNIMPLEMENTED();
	return 0;
}

int LaraTestWaterStepOut(struct ITEM_INFO* item, struct COLL_INFO* coll)//4D100, 4D564 (F)
{
	if (coll->coll_type == CT_FRONT || coll->mid_type == BIG_SLOPE || coll->mid_type == DIAGONAL || coll->mid_floor >= 0)
	{
		return 0;
	}

	if (coll->mid_floor >= -128)
	{
		if (item->goal_anim_state == STATE_LARA_ONWATER_LEFT)
		{
			item->goal_anim_state = STATE_LARA_WALK_LEFT;
		}
		else if (item->goal_anim_state == STATE_LARA_ONWATER_RIGHT)
		{
			item->goal_anim_state = STATE_LARA_WALK_RIGHT;
		}
		else
		{
			item->anim_number = ANIMATION_LARA_WADE;
			item->frame_number = anims[ANIMATION_LARA_WADE].frame_base;
			item->goal_anim_state = STATE_LARA_WADE_FORWARD;
			item->current_anim_state = STATE_LARA_WADE_FORWARD;
		}
	}
	else
	{
		item->anim_number = ANIMATION_LARA_ONWATER_TO_WADE_DEEP;
		item->frame_number = anims[ANIMATION_LARA_ONWATER_TO_WADE_DEEP].frame_base;
		item->current_anim_state = STATE_LARA_ONWATER_EXIT;
		item->goal_anim_state = STATE_LARA_STOP;
	}

	item->pos.y_pos += coll->front_floor + 695;

	UpdateLaraRoom(item, -381);

	item->pos.z_rot = 0;
	item->pos.x_rot = 0;

	item->gravity_status = TRUE;
	item->speed = 0;
	item->fallspeed = 0;

	lara.water_status = LW_WADE;

	return 1;
}
<|endoftext|>