<commit_before>#include "V3DPipelineLayout.h"
#include "V3DDevice.h"
#include "V3DDescriptorSetLayout.h"

/******************************/
/* public - V3DPipelineLayout */
/******************************/

V3DPipelineLayout* V3DPipelineLayout::Create()
{
	return V3D_NEW_T(V3DPipelineLayout);
}

V3D_RESULT V3DPipelineLayout::Initialize(IV3DDevice* pDevice, uint32_t constantCount, V3DConstantDesc* pConstants, uint32_t descriptorSetLayoutCount, IV3DDescriptorSetLayout** ppDescriptorSetLayouts)
{
	V3D_ASSERT(pDevice != nullptr);

	m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));

	// ----------------------------------------------------------------------------------------------------
	// RX^g
	// ----------------------------------------------------------------------------------------------------

	STLVector<VkPushConstantRange> vkConstantRanges;
	vkConstantRanges.resize(constantCount);
	for (uint32_t i = 0; i < constantCount; i++)
	{
		const V3DConstantDesc& src = pConstants[i];
		VkPushConstantRange& dst = vkConstantRanges[i];

		dst.stageFlags = ToVkShaderStageFlags(src.shaderStageFlags);
		dst.offset = src.offset;
		dst.size = src.size;

		m_Constants.push_back(src);
	}

	// ----------------------------------------------------------------------------------------------------
	// fXNv^ZbgCAEg
	// ----------------------------------------------------------------------------------------------------

	STLVector<VkDescriptorSetLayout> vkDescriptorSetLayouts;
	vkDescriptorSetLayouts.resize(descriptorSetLayoutCount);

	m_DescriptorSetLayouts.reserve(descriptorSetLayoutCount);

	for (uint32_t i = 0; i < descriptorSetLayoutCount; i++)
	{
		vkDescriptorSetLayouts[i] = static_cast<V3DDescriptorSetLayout*>(ppDescriptorSetLayouts[i])->GetSource().descriptorSetLayout;
		m_DescriptorSetLayouts.push_back(V3D_TO_ADD_REF(ppDescriptorSetLayouts[i]));
	}

	// ----------------------------------------------------------------------------------------------------
	// pCvCCAEg쐬
	// ----------------------------------------------------------------------------------------------------

	VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {};
	pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
	pipelineLayoutCreateInfo.pNext = nullptr;
	pipelineLayoutCreateInfo.pushConstantRangeCount = static_cast<uint32_t>(vkConstantRanges.size());
	pipelineLayoutCreateInfo.pPushConstantRanges = vkConstantRanges.data();
	pipelineLayoutCreateInfo.setLayoutCount = static_cast<uint32_t>(vkDescriptorSetLayouts.size());
	pipelineLayoutCreateInfo.pSetLayouts = vkDescriptorSetLayouts.data();

	VkResult vkResult = vkCreatePipelineLayout(m_pDevice->GetSource().device, &pipelineLayoutCreateInfo, nullptr, &m_Source.pipelineLayout);
	if (vkResult != VK_SUCCESS)
	{
		return ToV3DResult(vkResult);
	}

	return V3D_OK;
}

const V3DPipelineLayout::Source& V3DPipelineLayout::GetSource() const
{
	return m_Source;
}

/****************************************/
/* public override - IV3DPipelineLayout */
/****************************************/

uint32_t V3DPipelineLayout::GetConstantCount() const
{
	return static_cast<uint32_t>(m_Constants.size());
}

const V3DConstantDesc& V3DPipelineLayout::GetConstantDesc(uint32_t constantIndex) const
{
	return m_Constants[constantIndex];
}

uint32_t V3DPipelineLayout::GetDescriptorSetCount() const
{
	return static_cast<uint32_t>(m_DescriptorSetLayouts.size());
}

void V3DPipelineLayout::GetDescriptorSetLayout(uint32_t descriptorSetIndex, IV3DDescriptorSetLayout** ppDescriptorLayout)
{
	(*ppDescriptorLayout) = V3D_TO_ADD_REF(m_DescriptorSetLayouts[descriptorSetIndex]);
}

/*************************************/
/* public override - IV3DDeviceChild */
/*************************************/

void V3DPipelineLayout::GetDevice(IV3DDevice** ppDevice)
{
	(*ppDevice) = V3D_TO_ADD_REF(m_pDevice);
}

/********************************/
/* public override - IV3DObject */
/********************************/

int64_t V3DPipelineLayout::GetRefCount() const
{
	return m_RefCounter;
}

void V3DPipelineLayout::AddRef()
{
	++m_RefCounter;
}

void V3DPipelineLayout::Release()
{
	if (--m_RefCounter == 0)
	{
		V3D_DELETE_THIS_T(this, V3DPipelineLayout);
	}
}

/*******************************/
/* private - V3DPipelineLayout */
/*******************************/

V3DPipelineLayout::V3DPipelineLayout() :
	m_RefCounter(1),
	m_pDevice(nullptr)
{
	m_Source.pipelineLayout = VK_NULL_HANDLE;
}

V3DPipelineLayout::~V3DPipelineLayout()
{
	if (m_Source.pipelineLayout != VK_NULL_HANDLE)
	{
		vkDestroyPipelineLayout(m_pDevice->GetSource().device, m_Source.pipelineLayout, nullptr);
	}

	if (m_DescriptorSetLayouts.empty() == false)
	{
		STLVector<IV3DDescriptorSetLayout*>::iterator it_begin = m_DescriptorSetLayouts.begin();
		STLVector<IV3DDescriptorSetLayout*>::iterator it_end = m_DescriptorSetLayouts.end();
		STLVector<IV3DDescriptorSetLayout*>::iterator it;

		for (it = it_begin; it != it_end; ++it)
		{
			V3D_RELEASE((*it));
		}
	}

	V3D_RELEASE(m_pDevice);
}
<commit_msg>メンテナンス<commit_after>#include "V3DPipelineLayout.h"
#include "V3DDevice.h"
#include "V3DDescriptorSetLayout.h"

/******************************/
/* public - V3DPipelineLayout */
/******************************/

V3DPipelineLayout* V3DPipelineLayout::Create()
{
	return V3D_NEW_T(V3DPipelineLayout);
}

V3D_RESULT V3DPipelineLayout::Initialize(IV3DDevice* pDevice, uint32_t constantCount, V3DConstantDesc* pConstants, uint32_t descriptorSetLayoutCount, IV3DDescriptorSetLayout** ppDescriptorSetLayouts)
{
	V3D_ASSERT(pDevice != nullptr);

	m_pDevice = V3D_TO_ADD_REF(static_cast<V3DDevice*>(pDevice));

	// ----------------------------------------------------------------------------------------------------
	// RX^g
	// ----------------------------------------------------------------------------------------------------

	STLVector<VkPushConstantRange> vkConstantRanges;

	if (constantCount > 0)
	{
		vkConstantRanges.reserve(constantCount);
		m_Constants.reserve(constantCount);

		for (uint32_t i = 0; i < constantCount; i++)
		{
			const V3DConstantDesc& src = pConstants[i];
			VkPushConstantRange dst{};

			dst.stageFlags = ToVkShaderStageFlags(src.shaderStageFlags);
			dst.offset = src.offset;
			dst.size = src.size;

			vkConstantRanges.push_back(dst);
			m_Constants.push_back(src);
		}
	}

	// ----------------------------------------------------------------------------------------------------
	// fXNv^ZbgCAEg
	// ----------------------------------------------------------------------------------------------------

	STLVector<VkDescriptorSetLayout> vkDescriptorSetLayouts;

	if (descriptorSetLayoutCount > 0)
	{
		vkDescriptorSetLayouts.reserve(descriptorSetLayoutCount);
		m_DescriptorSetLayouts.reserve(descriptorSetLayoutCount);

		for (uint32_t i = 0; i < descriptorSetLayoutCount; i++)
		{
			V3DDescriptorSetLayout* pInternalDescriptorSet = static_cast<V3DDescriptorSetLayout*>(ppDescriptorSetLayouts[i]);

			vkDescriptorSetLayouts.push_back(pInternalDescriptorSet->GetSource().descriptorSetLayout);
			m_DescriptorSetLayouts.push_back(V3D_TO_ADD_REF(pInternalDescriptorSet));
		}
	}

	// ----------------------------------------------------------------------------------------------------
	// pCvCCAEg쐬
	// ----------------------------------------------------------------------------------------------------

	VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = {};
	pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
	pipelineLayoutCreateInfo.pNext = nullptr;
	pipelineLayoutCreateInfo.pushConstantRangeCount = static_cast<uint32_t>(vkConstantRanges.size());
	pipelineLayoutCreateInfo.pPushConstantRanges = vkConstantRanges.data();
	pipelineLayoutCreateInfo.setLayoutCount = static_cast<uint32_t>(vkDescriptorSetLayouts.size());
	pipelineLayoutCreateInfo.pSetLayouts = vkDescriptorSetLayouts.data();

	VkResult vkResult = vkCreatePipelineLayout(m_pDevice->GetSource().device, &pipelineLayoutCreateInfo, nullptr, &m_Source.pipelineLayout);
	if (vkResult != VK_SUCCESS)
	{
		return ToV3DResult(vkResult);
	}

	return V3D_OK;
}

const V3DPipelineLayout::Source& V3DPipelineLayout::GetSource() const
{
	return m_Source;
}

/****************************************/
/* public override - IV3DPipelineLayout */
/****************************************/

uint32_t V3DPipelineLayout::GetConstantCount() const
{
	return static_cast<uint32_t>(m_Constants.size());
}

const V3DConstantDesc& V3DPipelineLayout::GetConstantDesc(uint32_t constantIndex) const
{
	return m_Constants[constantIndex];
}

uint32_t V3DPipelineLayout::GetDescriptorSetCount() const
{
	return static_cast<uint32_t>(m_DescriptorSetLayouts.size());
}

void V3DPipelineLayout::GetDescriptorSetLayout(uint32_t descriptorSetIndex, IV3DDescriptorSetLayout** ppDescriptorLayout)
{
	(*ppDescriptorLayout) = V3D_TO_ADD_REF(m_DescriptorSetLayouts[descriptorSetIndex]);
}

/*************************************/
/* public override - IV3DDeviceChild */
/*************************************/

void V3DPipelineLayout::GetDevice(IV3DDevice** ppDevice)
{
	(*ppDevice) = V3D_TO_ADD_REF(m_pDevice);
}

/********************************/
/* public override - IV3DObject */
/********************************/

int64_t V3DPipelineLayout::GetRefCount() const
{
	return m_RefCounter;
}

void V3DPipelineLayout::AddRef()
{
	++m_RefCounter;
}

void V3DPipelineLayout::Release()
{
	if (--m_RefCounter == 0)
	{
		V3D_DELETE_THIS_T(this, V3DPipelineLayout);
	}
}

/*******************************/
/* private - V3DPipelineLayout */
/*******************************/

V3DPipelineLayout::V3DPipelineLayout() :
	m_RefCounter(1),
	m_pDevice(nullptr)
{
	m_Source.pipelineLayout = VK_NULL_HANDLE;
}

V3DPipelineLayout::~V3DPipelineLayout()
{
	if (m_Source.pipelineLayout != VK_NULL_HANDLE)
	{
		vkDestroyPipelineLayout(m_pDevice->GetSource().device, m_Source.pipelineLayout, nullptr);
	}

	if (m_DescriptorSetLayouts.empty() == false)
	{
		STLVector<IV3DDescriptorSetLayout*>::iterator it_begin = m_DescriptorSetLayouts.begin();
		STLVector<IV3DDescriptorSetLayout*>::iterator it_end = m_DescriptorSetLayouts.end();
		STLVector<IV3DDescriptorSetLayout*>::iterator it;

		for (it = it_begin; it != it_end; ++it)
		{
			V3D_RELEASE((*it));
		}
	}

	V3D_RELEASE(m_pDevice);
}
<|endoftext|>


<commit_before>/*
  Copyright (c) 2011, The Mineserver Project
  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 The Mineserver Project 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 HOLDER 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 <boost/lexical_cast.hpp>

#include <mineserver/game.h>
#include <mineserver/network/client.h>
#include <mineserver/network/message.h>
#include <mineserver/network/message/blockplacement.h>

#include <mineserver/watcher/blockplacement.h>

void Mineserver::Watcher_BlockPlacement::operator()(Mineserver::Game::pointer_t game, Mineserver::Network_Client::pointer_t client, Mineserver::Network_Message::pointer_t message) const
{
  std::cout << "Block-placement watcher called!" << std::endl;
  const Mineserver::Network_Message_BlockPlacement* msg = reinterpret_cast<Mineserver::Network_Message_BlockPlacement*>(&(*message));

  //if (msg->itemId==-1) { return; }

  Mineserver::World::pointer_t world = game->getWorld(0);

  int chunk_x, chunk_z;
  x = msg->x / 16;
  z = msg->z / 16;

  if (!world->hasChunk(chunk_x, chunk_z))
  {
    std::cout << "Chunk " << chunk_x << "," << chunk_z << " not found!" << std::endl;
  }
  else
  {
    Mineserver::World_Chunk::pointer_t chunk = world->getChunk(chunk_x, chunk_z);

    int x, y, z, type;
    x = msg->x;
    y = msg->y;
    z = msg->z;
    type = chunk->getBlockType(x, y, z);

    std::string text = "§4You interacted with block id ";
    text += boost::lexical_cast<std::string>(type) + " at ";
    text += boost::lexical_cast<std::string>(x) + ",";
    text += boost::lexical_cast<std::string>(y) + ",";
    text += boost::lexical_cast<std::string>(z) + "!";
	  game->chat(client, text, game->chatSelf);

    // (TODO) interpret block action

  }
}

<commit_msg>Bleh.<commit_after>/*
  Copyright (c) 2011, The Mineserver Project
  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 The Mineserver Project 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 HOLDER 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 <boost/lexical_cast.hpp>

#include <mineserver/game.h>
#include <mineserver/network/client.h>
#include <mineserver/network/message.h>
#include <mineserver/network/message/blockplacement.h>

#include <mineserver/watcher/blockplacement.h>

void Mineserver::Watcher_BlockPlacement::operator()(Mineserver::Game::pointer_t game, Mineserver::Network_Client::pointer_t client, Mineserver::Network_Message::pointer_t message) const
{
  std::cout << "Block-placement watcher called!" << std::endl;
  const Mineserver::Network_Message_BlockPlacement* msg = reinterpret_cast<Mineserver::Network_Message_BlockPlacement*>(&(*message));

  //if (msg->itemId==-1) { return; }

  Mineserver::World::pointer_t world = game->getWorld(0);

  int chunk_x, chunk_z;
  chunk_x = msg->x / 16;
  chunk_z = msg->z / 16;

  if (!world->hasChunk(chunk_x, chunk_z))
  {
    std::cout << "Chunk " << chunk_x << "," << chunk_z << " not found!" << std::endl;
  }
  else
  {
    Mineserver::World_Chunk::pointer_t chunk = world->getChunk(chunk_x, chunk_z);

    int x, y, z, type;
    x = msg->x;
    y = msg->y;
    z = msg->z;
    type = chunk->getBlockType(x, y, z);

    std::string text = "§4You interacted with block id ";
    text += boost::lexical_cast<std::string>(type) + " at ";
    text += boost::lexical_cast<std::string>(x) + ",";
    text += boost::lexical_cast<std::string>(y) + ",";
    text += boost::lexical_cast<std::string>(z) + "!";
	  game->chat(client, text, game->chatSelf);

    // (TODO) interpret block action

  }
}

<|endoftext|>


<commit_before>/**
 * @file
 * @brief Implementation of RCE Writer Module
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "RCEWriterModule.hpp"

#include <string>
#include <utility>

#include <TBranchElement.h>
#include <TClass.h>
#include <TDirectory.h>

#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/type.h"

#include "objects/Object.hpp"
#include "objects/objects.h"

using namespace allpix;

RCEWriterModule::RCEWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo_mgr)
    : Module(std::move(config)), geo_mgr_(geo_mgr) {
    // Bind to PixelHitMessage
    messenger->bindMulti(this, &RCEWriterModule::pixel_hit_messages_);

    config_.setDefault("file_name", "rce-data.root");
    config_.setDefault("geometry_file", "rce-geo.conf");
}

void RCEWriterModule::init() {
    // We need a sorted list of names to assign monotonic, numeric ids
    std::vector<std::string> detector_names;
    for(const auto& detector : geo_mgr_->getDetectors())
        detector_names.push_back(detector->getName());
    std::sort(detector_names.begin(), detector_names.end());

    // Open output data file
    std::string file_name = createOutputFile(add_file_extension(config_.get<std::string>("file_name"), "root"));
    output_file_ = std::make_unique<TFile>(file_name.c_str(), "RECREATE");
    output_file_->cd();

    // Initialize the events tree
    event_tree_ = new TTree("Event", "");
    event_tree_->Branch("TimeStamp", &timestamp_);
    event_tree_->Branch("FrameNumber", &frame_number_);
    event_tree_->Branch("TriggerTime", &trigger_time_);
    event_tree_->Branch("TriggerOffset", &trigger_offset_);
    event_tree_->Branch("TriggerInfo", &trigger_info_);
    event_tree_->Branch("Invalid", &invalid_);

    // For each detector name, initialize an instance of SensorData
    int det_index = 0;
    for(const auto& detector_name : detector_names) {
        auto& sensor = sensors_[detector_name];
        // Create directories for each detector
        std::string det_dir_name = "Plane" + std::to_string(det_index);
        TDirectory* detector = output_file_->mkdir(det_dir_name.c_str());
        detector->cd();
        det_index += 1;

        // Initialize the struct for each detector
        sensor.tree = new TTree("Hits", "");
        LOG(TRACE) << "Detector name is: " << detector_name;
        // initialze tree branches for each instance of the sensorData
        sensor.tree->Branch("NHits", &sensor.nhits_);
        sensor.tree->Branch("PixX", &sensor.pix_x_, "PixX[NHits]/I");
        sensor.tree->Branch("PixY", &sensor.pix_y_, "PixY[NHits]/I");
        sensor.tree->Branch("Value", &sensor.value_, "Value[NHits]/I");
        sensor.tree->Branch("Timing", &sensor.timing_, "Timing[NHits]/I");
        sensor.tree->Branch("HitInCluster", &sensor.hit_in_cluster_, "HitInCluster[NHits]/I");
    }
}

void RCEWriterModule::run(unsigned int event_id) {
    // fill per-event data
    timestamp_ = 0;
    frame_number_ = event_id;
    trigger_time_ = 0;
    trigger_offset_ = 0;
    trigger_info_ = 0;
    invalid_ = false;

    LOG(TRACE) << "Writing new objects to the Events tree";
    // Fill the events tree
    event_tree_->Fill();

    // reset all per-sensor trees
    for(auto& item : sensors_)
        item.second.nhits_ = 0;

    // Loop over the pixel hit messages
    for(const auto& hit_msg : pixel_hit_messages_) {

        std::string detector_name = hit_msg->getDetector()->getName();
        auto& sensor = sensors_[detector_name];

        // Loop over all the hits
        for(const auto& hit : hit_msg->getData()) {
            int i = sensor.nhits_;

            if(sensor.kMaxHits <= sensor.nhits_) {
                LOG(ERROR) << "More than " << sensor.kMaxHits << " in detector " << detector_name << " for RCEWriter";
                continue;
            }

            // Fill the tree with received messages
            sensor.nhits_ += 1;
            sensor.pix_x_[i] = static_cast<Int_t>(hit.getPixel().getIndex().x()); // NOLINT
            sensor.pix_y_[i] = static_cast<Int_t>(hit.getPixel().getIndex().y()); // NOLINT
            sensor.value_[i] = static_cast<Int_t>(hit.getSignal());               // NOLINT
            // Set the  Timing and HitInCluster for each sesnor_tree (= 0 for now)
            sensor.timing_[i] = 0;         // NOLINT
            sensor.hit_in_cluster_[i] = 0; // NOLINT

            LOG(TRACE) << "Detector Name: " << detector_name << ", X: " << hit.getPixel().getIndex().x()
                       << ", Y:" << hit.getPixel().getIndex().y() << ", Signal: " << hit.getSignal();
        }
    }

    // Loop over all the detectors to fill all corresponding sensor trees
    for(auto& item : sensors_) {
        LOG(TRACE) << "Writing new objects to the Sensor Tree for " << item.first;
        item.second.tree->Fill();
    }
}

void RCEWriterModule::finalize() {
    LOG(TRACE) << "Writing objects to file";
    // Finish writing to the output file
    output_file_->Write();
}
<commit_msg>RCEWriter: fix output paths<commit_after>/**
 * @file
 * @brief Implementation of RCE Writer Module
 * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
 * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
 * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
 * Intergovernmental Organization or submit itself to any jurisdiction.
 */

#include "RCEWriterModule.hpp"

#include <string>
#include <utility>

#include <TBranchElement.h>
#include <TClass.h>
#include <TDirectory.h>

#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/type.h"

#include "objects/Object.hpp"
#include "objects/objects.h"

using namespace allpix;

RCEWriterModule::RCEWriterModule(Configuration config, Messenger* messenger, GeometryManager* geo_mgr)
    : Module(std::move(config)), geo_mgr_(geo_mgr) {
    // Bind to PixelHitMessage
    messenger->bindMulti(this, &RCEWriterModule::pixel_hit_messages_);

    config_.setDefault("file_name", "rce-data.root");
    config_.setDefault("geometry_file", "rce-geo.toml");
}

void RCEWriterModule::init() {
    // We need a sorted list of names to assign monotonic, numeric ids
    std::vector<std::string> detector_names;
    for(const auto& detector : geo_mgr_->getDetectors())
        detector_names.push_back(detector->getName());
    std::sort(detector_names.begin(), detector_names.end());

    // Open output data file
    std::string path_data = createOutputFile(add_file_extension(config_.get<std::string>("file_name"), "root"));
    output_file_ = std::make_unique<TFile>(path_data.c_str(), "RECREATE");
    output_file_->cd();

    // Initialize the events tree
    event_tree_ = new TTree("Event", "");
    event_tree_->Branch("TimeStamp", &timestamp_);
    event_tree_->Branch("FrameNumber", &frame_number_);
    event_tree_->Branch("TriggerTime", &trigger_time_);
    event_tree_->Branch("TriggerOffset", &trigger_offset_);
    event_tree_->Branch("TriggerInfo", &trigger_info_);
    event_tree_->Branch("Invalid", &invalid_);

    // For each detector name, initialize an instance of SensorData
    int det_index = 0;
    for(const auto& detector_name : detector_names) {
        auto& sensor = sensors_[detector_name];
        // Create directories for each detector
        std::string det_dir_name = "Plane" + std::to_string(det_index);
        TDirectory* detector = output_file_->mkdir(det_dir_name.c_str());
        detector->cd();
        det_index += 1;

        // Initialize the struct for each detector
        sensor.tree = new TTree("Hits", "");
        LOG(TRACE) << "Detector name is: " << detector_name;
        // initialze tree branches for each instance of the sensorData
        sensor.tree->Branch("NHits", &sensor.nhits_);
        sensor.tree->Branch("PixX", &sensor.pix_x_, "PixX[NHits]/I");
        sensor.tree->Branch("PixY", &sensor.pix_y_, "PixY[NHits]/I");
        sensor.tree->Branch("Value", &sensor.value_, "Value[NHits]/I");
        sensor.tree->Branch("Timing", &sensor.timing_, "Timing[NHits]/I");
        sensor.tree->Branch("HitInCluster", &sensor.hit_in_cluster_, "HitInCluster[NHits]/I");
    }

    // Write proteus geometry file
    std::string path_geo = createOutputFile(add_file_extension(config_.get<std::string>("geometry_file"), "toml"));
    std::ofstream geo_file(path_geo);
    print_geo(geo_file, detector_names, geo_mgr_);
}

void RCEWriterModule::run(unsigned int event_id) {
    // fill per-event data
    timestamp_ = 0;
    frame_number_ = event_id;
    trigger_time_ = 0;
    trigger_offset_ = 0;
    trigger_info_ = 0;
    invalid_ = false;

    LOG(TRACE) << "Writing new objects to the Events tree";
    // Fill the events tree
    event_tree_->Fill();

    // reset all per-sensor trees
    for(auto& item : sensors_)
        item.second.nhits_ = 0;

    // Loop over the pixel hit messages
    for(const auto& hit_msg : pixel_hit_messages_) {

        std::string detector_name = hit_msg->getDetector()->getName();
        auto& sensor = sensors_[detector_name];

        // Loop over all the hits
        for(const auto& hit : hit_msg->getData()) {
            int i = sensor.nhits_;

            if(sensor.kMaxHits <= sensor.nhits_) {
                LOG(ERROR) << "More than " << sensor.kMaxHits << " in detector " << detector_name << " for RCEWriter";
                continue;
            }

            // Fill the tree with received messages
            sensor.nhits_ += 1;
            sensor.pix_x_[i] = static_cast<Int_t>(hit.getPixel().getIndex().x()); // NOLINT
            sensor.pix_y_[i] = static_cast<Int_t>(hit.getPixel().getIndex().y()); // NOLINT
            sensor.value_[i] = static_cast<Int_t>(hit.getSignal());               // NOLINT
            // Set the  Timing and HitInCluster for each sesnor_tree (= 0 for now)
            sensor.timing_[i] = 0;         // NOLINT
            sensor.hit_in_cluster_[i] = 0; // NOLINT

            LOG(TRACE) << "Detector Name: " << detector_name << ", X: " << hit.getPixel().getIndex().x()
                       << ", Y:" << hit.getPixel().getIndex().y() << ", Signal: " << hit.getSignal();
        }
    }

    // Loop over all the detectors to fill all corresponding sensor trees
    for(auto& item : sensors_) {
        LOG(TRACE) << "Writing new objects to the Sensor Tree for " << item.first;
        item.second.tree->Fill();
    }
}

void RCEWriterModule::finalize() {
    LOG(TRACE) << "Writing objects to file";
    // Finish writing to the output file
    output_file_->Write();
}
<|endoftext|>


<commit_before>/******************************************************************************\
* File:          app.cpp
* Purpose:       Implementation of class 'App'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/cmdline.h> // for wxCmdLineParser
#include <wx/extension/filename.h>
#include <wx/extension/util.h>
#include "app.h"
#include "frame.h"

wxIMPLEMENT_APP(App);

#ifdef __WXOSX__
void App::MacOpenFile(const wxString& fileName)
{
  Frame* frame = (Frame*)GetTopWindow();
  frame->OpenFile(wxExFileName(fileName));
}
#endif

bool App::OnCmdLineParsed(wxCmdLineParser& parser)
{
  for (size_t i = 0; i < parser.GetParamCount(); i++)
  {
    m_Files.Add(parser.GetParam(i));
  }

  return wxApp::OnCmdLineParsed(parser);
}

bool App::OnInit()
{
  // This must be the first statement, other methods might use the name.
  SetAppName("syncped");

  if (!wxExApp::OnInit())
  {
    return false;
  }

  Frame* frame = new Frame(m_Files.Count() == 0);
  frame->Show();

  wxExOpenFiles(frame, m_Files, 0, wxDIR_FILES); // only files in this dir

  return true;
}

void App::OnInitCmdLine(wxCmdLineParser& parser)
{
  wxApp::OnInitCmdLine(parser);

  parser.AddParam(
    "input file:line number",
    wxCMD_LINE_VAL_STRING,
    wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
}
<commit_msg>follow mac guidelines<commit_after>/******************************************************************************\
* File:          app.cpp
* Purpose:       Implementation of class 'App'
* Author:        Anton van Wezenbeek
* RCS-ID:        $Id$
*
* Copyright (c) 1998-2009 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/

#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/cmdline.h> // for wxCmdLineParser
#include <wx/extension/filename.h>
#include <wx/extension/util.h>
#include "app.h"
#include "frame.h"

wxIMPLEMENT_APP(App);

#ifdef __WXOSX__
void App::MacOpenFile(const wxString& fileName)
{
  Frame* frame = (Frame*)GetTopWindow();
  frame->OpenFile(wxExFileName(fileName));
}
#endif

bool App::OnCmdLineParsed(wxCmdLineParser& parser)
{
  for (size_t i = 0; i < parser.GetParamCount(); i++)
  {
    m_Files.Add(parser.GetParam(i));
  }

  return wxApp::OnCmdLineParsed(parser);
}

bool App::OnInit()
{
  // This must be the first statement, other methods might use the name.
  SetAppName("syncped");

  if (!wxExApp::OnInit())
  {
    return false;
  }

#ifdef __WXOSX__
  wxApp::SetExitOnFrameDelete(false);
#endif

  Frame* frame = new Frame(m_Files.Count() == 0);
  frame->Show();

  wxExOpenFiles(frame, m_Files, 0, wxDIR_FILES); // only files in this dir

  return true;
}

void App::OnInitCmdLine(wxCmdLineParser& parser)
{
  wxApp::OnInitCmdLine(parser);

  parser.AddParam(
    "input file:line number",
    wxCMD_LINE_VAL_STRING,
    wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE);
}
<|endoftext|>


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

#ifndef _CAIROCANVAS_SPRITECANVAS_HXX_
#define _CAIROCANVAS_SPRITECANVAS_HXX_

#include <rtl/ref.hxx>

#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XServiceName.hpp>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/util/XUpdatable.hpp>
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>
#include <com/sun/star/rendering/XBufferController.hpp>
#include <com/sun/star/rendering/XColorSpace.hpp>
#include <com/sun/star/rendering/XParametricPolyPolygon2DFactory.hpp>

#include <cppuhelper/compbase10.hxx>
#include <comphelper/uno3.hxx>

#include <canvas/base/spritecanvasbase.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/windowgraphicdevicebase.hxx>

#include <basegfx/vector/b2isize.hxx>

#include "cairo_devicehelper.hxx"
#include "cairo_repainttarget.hxx"
#include "cairo_spritecanvashelper.hxx"

namespace cairocanvas
{
    typedef ::cppu::WeakComponentImplHelper10< ::com::sun::star::rendering::XSpriteCanvas,
                                                ::com::sun::star::rendering::XIntegerBitmap,
                                                ::com::sun::star::rendering::XGraphicDevice,
                                               ::com::sun::star::rendering::XParametricPolyPolygon2DFactory,
                                               ::com::sun::star::rendering::XBufferController,
                                               ::com::sun::star::rendering::XColorSpace,
                                               ::com::sun::star::awt::XWindowListener,
                                               ::com::sun::star::util::XUpdatable,
                                               ::com::sun::star::beans::XPropertySet,
                                               ::com::sun::star::lang::XServiceName >   WindowGraphicDeviceBase_Base;
    typedef ::canvas::WindowGraphicDeviceBase< ::canvas::BaseMutexHelper< WindowGraphicDeviceBase_Base >,
                                               DeviceHelper,
                                               ::osl::MutexGuard,
                                               ::cppu::OWeakObject >    SpriteCanvasBase_Base;
    /** Mixin SpriteSurface

        Have to mixin the SpriteSurface before deriving from
        ::canvas::SpriteCanvasBase, as this template should already
        implement some of those interface methods.

        The reason why this appears kinda convoluted is the fact that
        we cannot specify non-IDL types as WeakComponentImplHelperN
        template args, and furthermore, don't want to derive
        ::canvas::SpriteCanvasBase directly from
        ::canvas::SpriteSurface (because derivees of
        ::canvas::SpriteCanvasBase have to explicitely forward the
        XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
        anyway). Basically, ::canvas::CanvasCustomSpriteBase should
        remain a base class that provides implementation, not to
        enforce any specific interface on its derivees.
     */
    class SpriteCanvasBaseSpriteSurface_Base : public SpriteCanvasBase_Base,
                                               public ::canvas::SpriteSurface
    {
    };

    typedef ::canvas::SpriteCanvasBase< SpriteCanvasBaseSpriteSurface_Base,
                                        SpriteCanvasHelper,
                                        ::osl::MutexGuard,
                                        ::cppu::OWeakObject >           SpriteCanvasBaseT;

    /** Product of this component's factory.

        The SpriteCanvas object combines the actual Window canvas with
        the XGraphicDevice interface. This is because there's a
        one-to-one relation between them, anyway, since each window
        can have exactly one canvas and one associated
        XGraphicDevice. And to avoid messing around with circular
        references, this is implemented as one single object.
     */
    class SpriteCanvas : public SpriteCanvasBaseT,
                         public RepaintTarget
    {
    public:
        SpriteCanvas( const ::com::sun::star::uno::Sequence<
                            ::com::sun::star::uno::Any >&               aArguments,
                      const ::com::sun::star::uno::Reference<
                            ::com::sun::star::uno::XComponentContext >& rxContext );

        void initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );

#if defined __SUNPRO_CC
        using SpriteCanvasBaseT::disposing;
#endif

        /// Dispose all internal references
        virtual void SAL_CALL disposing();

        // Forwarding the XComponent implementation to the
        // cppu::ImplHelper templated base
        //                                    Classname     Base doing refcounting        Base implementing the XComponent interface
        //                                       |                 |                            |
        //                                       V                 V                            V
        DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( SpriteCanvas, WindowGraphicDeviceBase_Base, ::cppu::WeakComponentImplHelperBase );

        // XBufferController (partial)
        virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);

        // XSpriteCanvas (partial)
        virtual sal_Bool SAL_CALL updateScreen( sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceName
        virtual ::rtl::OUString SAL_CALL getServiceName(  ) throw (::com::sun::star::uno::RuntimeException);

        ::cairo::Surface* getSurface( const ::basegfx::B2ISize& rSize, ::cairo::Content aContent = CAIRO_CONTENT_COLOR_ALPHA );
        ::cairo::Surface* getSurface( ::cairo::Content aContent = CAIRO_CONTENT_COLOR_ALPHA );
        ::cairo::Surface* getSurface( Bitmap& rBitmap );
        ::cairo::Surface* getBufferSurface();
        ::cairo::Surface* getWindowSurface();
        ::cairo::Surface* getBackgroundSurface();
        const ::basegfx::B2ISize& getSizePixel();
        void setSizePixel( const ::basegfx::B2ISize& rSize );
        void flush();

        Window* getOutputWindow()
        {
            return maDeviceHelper.getOuputWindow();
        }

        // RepaintTarget
        virtual bool repaint( ::cairo::Surface* pSurface,
                  const ::com::sun::star::rendering::ViewState& viewState,
                  const ::com::sun::star::rendering::RenderState&   renderState );

     private:
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxComponentContext;

        ::cairo::Surface* mpBackgroundSurface;
        ::cairo::Cairo*   mpBackgroundCairo;
    };

    typedef ::rtl::Reference< SpriteCanvas > SpriteCanvasRef;
    typedef ::rtl::Reference< SpriteCanvas > DeviceRef;
}

#endif
<commit_msg>INTEGRATION: CWS canvas05 (1.3.56); FILE MERGED 2008/06/09 12:51:47 thb 1.3.56.7: #i88081# Join from CWS impress144 (fixing the dxcanvas crash), extended for the other canvas impls 2008/05/13 14:51:48 thb 1.3.56.6: removed redundant extra surface from spritecanvas; removed silly conditional that always resolved to true from X11Surface ctor 2008/04/21 07:31:37 thb 1.3.56.5: RESYNC: (1.4-1.5); FILE MERGED 2008/04/07 14:33:49 thb 1.3.56.4: RESYNC: (1.3-1.4); FILE MERGED 2008/04/02 22:56:28 thb 1.3.56.3: Reworked Surface class to abstract interface; changed all manual refcount handling to RAII 2008/03/18 22:00:57 thb 1.3.56.2: Implementing non-backbuffered canvas for cairocanvas as well - reworked to share most of the code 2007/12/20 22:18:56 thb 1.3.56.1: #i81092# #i78888# #i78925# #i79258# #i79437# #i84784# Large canvas rework, completing various areas such as color spaces, bitmap data access, true sprite and non-sprite implementations, and upstreaming the canvas parts of rodos emf+ rendering<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cairo_spritecanvas.hxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CAIROCANVAS_SPRITECANVAS_HXX_
#define _CAIROCANVAS_SPRITECANVAS_HXX_

#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XServiceName.hpp>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/util/XUpdatable.hpp>
#include <com/sun/star/rendering/XSpriteCanvas.hpp>
#include <com/sun/star/rendering/XIntegerBitmap.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>
#include <com/sun/star/rendering/XBufferController.hpp>
#include <com/sun/star/rendering/XParametricPolyPolygon2DFactory.hpp>

#include <cppuhelper/compbase9.hxx>
#include <comphelper/uno3.hxx>

#include <canvas/base/spritecanvasbase.hxx>
#include <canvas/base/basemutexhelper.hxx>
#include <canvas/base/bufferedgraphicdevicebase.hxx>

#include <basegfx/vector/b2isize.hxx>

#include "cairo_spritedevicehelper.hxx"
#include "cairo_repainttarget.hxx"
#include "cairo_surfaceprovider.hxx"
#include "cairo_spritecanvashelper.hxx"

#define SPRITECANVAS_SERVICE_NAME        "com.sun.star.rendering.SpriteCanvas.Cairo"
#define SPRITECANVAS_IMPLEMENTATION_NAME "com.sun.star.comp.rendering.SpriteCanvas.Cairo"

namespace cairocanvas
{
    typedef ::cppu::WeakComponentImplHelper9< ::com::sun::star::rendering::XSpriteCanvas,
                                                ::com::sun::star::rendering::XIntegerBitmap,
                                                ::com::sun::star::rendering::XGraphicDevice,
                                                ::com::sun::star::rendering::XParametricPolyPolygon2DFactory,
                                                ::com::sun::star::rendering::XBufferController,
                                                ::com::sun::star::awt::XWindowListener,
                                                ::com::sun::star::util::XUpdatable,
                                                ::com::sun::star::beans::XPropertySet,
                                                ::com::sun::star::lang::XServiceName >  WindowGraphicDeviceBase_Base;
    typedef ::canvas::BufferedGraphicDeviceBase< ::canvas::BaseMutexHelper< WindowGraphicDeviceBase_Base >,
                                                 SpriteDeviceHelper,
                                                 ::osl::MutexGuard,
                                                 ::cppu::OWeakObject > SpriteCanvasBase_Base;
    /** Mixin SpriteSurface

        Have to mixin the SpriteSurface before deriving from
        ::canvas::SpriteCanvasBase, as this template should already
        implement some of those interface methods.

        The reason why this appears kinda convoluted is the fact that
        we cannot specify non-IDL types as WeakComponentImplHelperN
        template args, and furthermore, don't want to derive
        ::canvas::SpriteCanvasBase directly from
        ::canvas::SpriteSurface (because derivees of
        ::canvas::SpriteCanvasBase have to explicitely forward the
        XInterface methods (e.g. via DECLARE_UNO3_AGG_DEFAULTS)
        anyway). Basically, ::canvas::CanvasCustomSpriteBase should
        remain a base class that provides implementation, not to
        enforce any specific interface on its derivees.
     */
    class SpriteCanvasBaseSpriteSurface_Base : public SpriteCanvasBase_Base,
                                               public ::canvas::SpriteSurface,
                                               public SurfaceProvider
    {
    };

    typedef ::canvas::SpriteCanvasBase< SpriteCanvasBaseSpriteSurface_Base,
                                        SpriteCanvasHelper,
                                        ::osl::MutexGuard,
                                        ::cppu::OWeakObject >           SpriteCanvasBaseT;

    /** Product of this component's factory.

        The SpriteCanvas object combines the actual Window canvas with
        the XGraphicDevice interface. This is because there's a
        one-to-one relation between them, anyway, since each window
        can have exactly one canvas and one associated
        XGraphicDevice. And to avoid messing around with circular
        references, this is implemented as one single object.
     */
    class SpriteCanvas : public SpriteCanvasBaseT,
                         public RepaintTarget
    {
    public:
        SpriteCanvas( const ::com::sun::star::uno::Sequence<
                            ::com::sun::star::uno::Any >&               aArguments,
                      const ::com::sun::star::uno::Reference<
                            ::com::sun::star::uno::XComponentContext >& rxContext );

        void initialize();

#if defined __SUNPRO_CC
        using SpriteCanvasBaseT::disposing;
#endif

        /// Dispose all internal references
        virtual void SAL_CALL disposing();

        // Forwarding the XComponent implementation to the
        // cppu::ImplHelper templated base
        //                                    Classname     Base doing refcounting        Base implementing the XComponent interface
        //                                       |                 |                            |
        //                                       V                 V                            V
        DECLARE_UNO3_XCOMPONENT_AGG_DEFAULTS( SpriteCanvas, WindowGraphicDeviceBase_Base, ::cppu::WeakComponentImplHelperBase );

        // XBufferController (partial)
        virtual ::sal_Bool SAL_CALL showBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::sal_Bool SAL_CALL switchBuffer( ::sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);

        // XSpriteCanvas (partial)
        virtual sal_Bool SAL_CALL updateScreen( sal_Bool bUpdateAll ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceName
        virtual ::rtl::OUString SAL_CALL getServiceName(  ) throw (::com::sun::star::uno::RuntimeException);

        // SurfaceProvider
        virtual SurfaceSharedPtr getSurface();
        virtual SurfaceSharedPtr createSurface( const ::basegfx::B2ISize& rSize, Content aContent = CAIRO_CONTENT_COLOR_ALPHA );
        virtual SurfaceSharedPtr createSurface( ::Bitmap& rBitmap );
        virtual SurfaceSharedPtr changeSurface( bool bHasAlpha, bool bCopyContent );
        virtual OutputDevice* getOutputDevice();

        // RepaintTarget
        virtual bool repaint( const ::cairo::SurfaceSharedPtr&                pSurface,
                              const ::com::sun::star::rendering::ViewState&   viewState,
                              const ::com::sun::star::rendering::RenderState& renderState );

        SurfaceSharedPtr getWindowSurface();
        SurfaceSharedPtr getBufferSurface();

        const ::basegfx::B2ISize& getSizePixel();
        void setSizePixel( const ::basegfx::B2ISize& rSize );
        void flush();

     private:
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > maArguments;
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > mxComponentContext;
    };

    typedef ::rtl::Reference< SpriteCanvas > SpriteCanvasRef;
}

#endif
<|endoftext|>


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

#ifndef _CAIROCANVAS_SPRITEHELPER_HXX
#define _CAIROCANVAS_SPRITEHELPER_HXX

#include <com/sun/star/rendering/XCustomSprite.hpp>

#include <canvas/base/canvascustomspritehelper.hxx>

#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2isize.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>

#include "cairo_spritecanvas.hxx"

namespace cairocanvas
{
    /* Definition of SpriteHelper class */

    /** Helper class for canvas sprites.

        This class implements all sprite-related functionality, like
        that available on the XSprite interface.
     */
    class SpriteHelper : public ::canvas::CanvasCustomSpriteHelper
    {
    public:
        /** Create sprite helper
         */
        SpriteHelper();

        /** Late-init the sprite helper

            @param rSpriteSize
            Size of the sprite

            @param rSpriteCanvas
            Sprite canvas this sprite is part of. Object stores
            ref-counted reference to it, thus, don't forget to pass on
            disposing()!

            @param rDevice
            DX device to use

            @param rSpriteSurface
            The surface of the sprite (not the DX texture, but the
            persistent target of content rendering)

            @param bShowSpriteBounds
            When true, little debug bound rects for sprites are shown
         */
        void init( const ::com::sun::star::geometry::RealSize2D&    rSpriteSize,
                   const SpriteCanvasRef&                           rSpriteCanvas );

        void disposing();

        void setSurface( ::cairo::Surface* pBufferSurface );

        /** Repaint sprite content to associated sprite canvas

            @param rPos
            Output position (sprite's own position is disregarded)

            @param io_bSurfacesDirty
            When true, the referenced sprite surfaces (backBuffer and
            backBufferMask) have been modified since last call.

            @param bBufferedUpdate
            When true, the redraw does not happen directly on
            the front buffer, but within a VDev. Used to speed up
            drawing.
         */
        void redraw( ::cairo::Cairo*            pCairo,
                     const ::basegfx::B2DPoint& rPos,
                     bool&                      bSurfacesDirty,
                     bool                       bBufferedUpdate ) const;

    private:
        virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const;

        SpriteCanvasRef             mpSpriteCanvas;
        mutable bool                mbTextureDirty;  // when true, texture needs update

    ::cairo::Surface* mpBufferSurface;
    };
}

#endif /* _CAIROCANVAS_SPRITEHELPER_HXX */
<commit_msg>INTEGRATION: CWS canvas05 (1.3.26); FILE MERGED 2008/04/21 07:32:46 thb 1.3.26.3: RESYNC: (1.3-1.4); FILE MERGED 2008/04/02 22:56:28 thb 1.3.26.2: Reworked Surface class to abstract interface; changed all manual refcount handling to RAII 2008/03/18 22:00:57 thb 1.3.26.1: Implementing non-backbuffered canvas for cairocanvas as well - reworked to share most of the code<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: cairo_spritehelper.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _CAIROCANVAS_SPRITEHELPER_HXX
#define _CAIROCANVAS_SPRITEHELPER_HXX

#include <com/sun/star/rendering/XCustomSprite.hpp>

#include <canvas/base/canvascustomspritehelper.hxx>

#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/vector/b2isize.hxx>
#include <basegfx/matrix/b2dhommatrix.hxx>

#include "cairo_spritecanvas.hxx"

namespace cairocanvas
{
    /* Definition of SpriteHelper class */

    /** Helper class for canvas sprites.

        This class implements all sprite-related functionality, like
        that available on the XSprite interface.
     */
    class SpriteHelper : public ::canvas::CanvasCustomSpriteHelper
    {
    public:
        /** Create sprite helper
         */
        SpriteHelper();

        /** Late-init the sprite helper

            @param rSpriteSize
            Size of the sprite

            @param rSpriteCanvas
            Sprite canvas this sprite is part of. Object stores
            ref-counted reference to it, thus, don't forget to pass on
            disposing()!

            @param rDevice
            DX device to use

            @param rSpriteSurface
            The surface of the sprite (not the DX texture, but the
            persistent target of content rendering)

            @param bShowSpriteBounds
            When true, little debug bound rects for sprites are shown
         */
        void init( const ::com::sun::star::geometry::RealSize2D& rSpriteSize,
                   const SpriteCanvasRef&                        rSpriteCanvas );

        void disposing();

        void setSurface( const ::cairo::SurfaceSharedPtr& pBufferSurface );

        /** Repaint sprite content to associated sprite canvas

            @param rPos
            Output position (sprite's own position is disregarded)

            @param io_bSurfacesDirty
            When true, the referenced sprite surfaces (backBuffer and
            backBufferMask) have been modified since last call.

            @param bBufferedUpdate
            When true, the redraw does not happen directly on
            the front buffer, but within a VDev. Used to speed up
            drawing.
         */
        void redraw( const ::cairo::CairoSharedPtr& pCairo,
                     const ::basegfx::B2DPoint&     rPos,
                     bool&                          bSurfacesDirty,
                     bool                           bBufferedUpdate ) const;

    private:
        virtual ::basegfx::B2DPolyPolygon polyPolygonFromXPolyPolygon2D(
            ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XPolyPolygon2D >& xPoly ) const;

        SpriteCanvasRef           mpSpriteCanvas;
        ::cairo::SurfaceSharedPtr mpBufferSurface;
        mutable bool              mbTextureDirty;  // when true, texture needs update
    };
}

#endif /* _CAIROCANVAS_SPRITEHELPER_HXX */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: parser.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-03-29 11:50:54 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _PARSER_HXX
#define _PARSER_HXX

#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif

#include <vector>
typedef ::std::vector< String > IfaceVector;

struct SbiParseStack;

class SbiParser : public SbiTokenizer
{
    friend class SbiExpression;

    SbiParseStack* pStack;          // Block-Stack
    SbiProcDef* pProc;              // aktuelle Prozedur
    SbiExprNode*  pWithVar;         // aktuelle With-Variable
    SbiToken    eEndTok;            // das Ende-Token
    USHORT      nGblChain;          // Chainkette fuer globale DIMs
    BOOL        bGblDefs;           // TRUE globale Definitionen allgemein
    BOOL        bNewGblDefs;        // TRUE globale Definitionen vor Sub
    BOOL        bSingleLineIf;      // TRUE einzeiliges if-Statement

    SbiSymDef*  VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
    SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
    void DefStatic( BOOL bPrivate );
    void DefProc( BOOL bStatic, BOOL bPrivate ); // Prozedur einlesen
    void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
    void TypeDecl( SbiSymDef&, BOOL bAsNewAlreadyParsed=FALSE );    // AS-Deklaration
    void OpenBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseBlock();              // Block aufloesen
    BOOL Channel( BOOL=FALSE );     // Kanalnummer parsen
    void StmntBlock( SbiToken );    // Statement-Block abarbeiten
    void DefType( BOOL bPrivate );  // Parse type declaration
    void DefEnum( BOOL bPrivate );  // Parse enum declaration

public:
    SbxArrayRef   rTypeArray;       // das Type-Array
    SbxArrayRef   rEnumArray;       // Enum types
    SbiStringPool aGblStrings;      // der String-Pool
    SbiStringPool aLclStrings;      // der String-Pool
    SbiSymPool    aGlobals;         // globale Variable
    SbiSymPool    aPublics;         // modulglobale Variable
    SbiSymPool    aRtlSyms;         // Runtime-Library
    SbiCodeGen    aGen;             // Code-Generator
    StarBASIC*    pBasic;           // StarBASIC-Instanz
    SbiSymPool*   pPool;            // aktueller Pool
    SbiExprType   eCurExpr;         // aktueller Expr-Typ
    short         nBase;            // OPTION BASE-Wert
    BOOL          bText;            // OPTION COMPARE TEXT
    BOOL          bExplicit;        // TRUE: OPTION EXPLICIT
    BOOL          bClassModule;     // TRUE: OPTION ClassModule
    IfaceVector   aIfaceVector;     // Holds all interfaces implemented by a class module
    SbxDataType   eDefTypes[26];    // DEFxxx-Datentypen

    SbiParser( StarBASIC*, SbModule* );
    BOOL Parse();                   // die Aktion
    SbiExprNode* GetWithVar();      // Innerste With-Variable liefern

    // AB 31.3.1996, Symbol in Runtime-Library suchen
    SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );
    void AddConstants( void );

    BOOL HasGlobalCode();           // Globaler Code definiert?

    BOOL TestToken( SbiToken );     // bestimmtes TOken?
    BOOL TestSymbol( BOOL=FALSE );  // Symbol?
    BOOL TestComma();               // Komma oder EOLN?
    void TestEoln();                // EOLN?

    void Symbol();                  // Let oder Call
    void ErrorStmnt();              // ERROR n
    void NotImp();                  // nicht implementiert
    void BadBlock();                // LOOP/WEND/NEXT
    void BadSyntax();               // Falsches SbiToken
    void NoIf();                    // ELSE/ELSE IF ohne IF
    void Assign();                  // LET
    void Call();                    // CALL
    void Close();                   // CLOSE
    void Declare();                 // DECLARE
    void DefXXX();                  // DEFxxx
    void Dim();                     // DIM
    void ReDim();                   // ReDim();
    void Erase();                   // ERASE
    void Exit();                    // EXIT
    void For();                     // FOR...NEXT
    void Goto();                    // GOTO / GOSUB
    void If();                      // IF
    void Implements();              // IMPLEMENTS
    void Input();                   // INPUT, INPUT #
    void LineInput();               // LINE INPUT, LINE INPUT #
    void LSet();                    // LSET
    void Name();                    // NAME .. AS ..
    void On();                      // ON ERROR/variable
    void OnGoto();                  // ON...GOTO / GOSUB
    void Open();                    // OPEN
    void Option();                  // OPTION
    void Print();                   // PRINT, PRINT #
    void SubFunc();                 // SUB / FUNCTION
    void Resume();                  // RESUME
    void Return();                  // RETURN
    void RSet();                    // RSET
    void DoLoop();                  // DO...LOOP
    void Select();                  // SELECT ... CASE
    void Set();                     // SET
    void Static();                  // STATIC
    void Stop();                    // STOP/SYSTEM
    void Type();                    // TYPE...AS...END TYPE
    void Enum();                    // TYPE...END ENUM
    void While();                   // WHILE/WEND
    void With();                    // WITH
    void Write();                   // WRITE

    // JavaScript-Parsing
    void OpenJavaBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseJavaBlock();                                  // Block aufloesen
    void JavaStmntBlock( SbiToken );    // Statement-Block abarbeiten
    void JavaBreak();
    void JavaContinue();
    void JavaFor();
    void JavaFunction();
    void JavaIf();
    void JavaNew();
    void JavaReturn();
    void JavaThis();
    void JavaVar();
    void JavaWhile();
    void JavaWith();
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.56); FILE MERGED 2005/09/05 14:36:12 rt 1.5.56.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: parser.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:34:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _PARSER_HXX
#define _PARSER_HXX

#ifndef _EXPR_HXX
#include "expr.hxx"
#endif
#ifndef _CODEGEN_HXX
#include "codegen.hxx"
#endif
#ifndef _SYMTBL_HXX
#include "symtbl.hxx"
#endif

#include <vector>
typedef ::std::vector< String > IfaceVector;

struct SbiParseStack;

class SbiParser : public SbiTokenizer
{
    friend class SbiExpression;

    SbiParseStack* pStack;          // Block-Stack
    SbiProcDef* pProc;              // aktuelle Prozedur
    SbiExprNode*  pWithVar;         // aktuelle With-Variable
    SbiToken    eEndTok;            // das Ende-Token
    USHORT      nGblChain;          // Chainkette fuer globale DIMs
    BOOL        bGblDefs;           // TRUE globale Definitionen allgemein
    BOOL        bNewGblDefs;        // TRUE globale Definitionen vor Sub
    BOOL        bSingleLineIf;      // TRUE einzeiliges if-Statement

    SbiSymDef*  VarDecl( SbiDimList**,BOOL,BOOL );// Variablen-Deklaration
    SbiProcDef* ProcDecl(BOOL bDecl);// Prozedur-Deklaration
    void DefStatic( BOOL bPrivate );
    void DefProc( BOOL bStatic, BOOL bPrivate ); // Prozedur einlesen
    void DefVar( SbiOpcode eOp, BOOL bStatic ); // DIM/REDIM einlesen
    void TypeDecl( SbiSymDef&, BOOL bAsNewAlreadyParsed=FALSE );    // AS-Deklaration
    void OpenBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseBlock();              // Block aufloesen
    BOOL Channel( BOOL=FALSE );     // Kanalnummer parsen
    void StmntBlock( SbiToken );    // Statement-Block abarbeiten
    void DefType( BOOL bPrivate );  // Parse type declaration
    void DefEnum( BOOL bPrivate );  // Parse enum declaration

public:
    SbxArrayRef   rTypeArray;       // das Type-Array
    SbxArrayRef   rEnumArray;       // Enum types
    SbiStringPool aGblStrings;      // der String-Pool
    SbiStringPool aLclStrings;      // der String-Pool
    SbiSymPool    aGlobals;         // globale Variable
    SbiSymPool    aPublics;         // modulglobale Variable
    SbiSymPool    aRtlSyms;         // Runtime-Library
    SbiCodeGen    aGen;             // Code-Generator
    StarBASIC*    pBasic;           // StarBASIC-Instanz
    SbiSymPool*   pPool;            // aktueller Pool
    SbiExprType   eCurExpr;         // aktueller Expr-Typ
    short         nBase;            // OPTION BASE-Wert
    BOOL          bText;            // OPTION COMPARE TEXT
    BOOL          bExplicit;        // TRUE: OPTION EXPLICIT
    BOOL          bClassModule;     // TRUE: OPTION ClassModule
    IfaceVector   aIfaceVector;     // Holds all interfaces implemented by a class module
    SbxDataType   eDefTypes[26];    // DEFxxx-Datentypen

    SbiParser( StarBASIC*, SbModule* );
    BOOL Parse();                   // die Aktion
    SbiExprNode* GetWithVar();      // Innerste With-Variable liefern

    // AB 31.3.1996, Symbol in Runtime-Library suchen
    SbiSymDef* CheckRTLForSym( const String& rSym, SbxDataType eType );
    void AddConstants( void );

    BOOL HasGlobalCode();           // Globaler Code definiert?

    BOOL TestToken( SbiToken );     // bestimmtes TOken?
    BOOL TestSymbol( BOOL=FALSE );  // Symbol?
    BOOL TestComma();               // Komma oder EOLN?
    void TestEoln();                // EOLN?

    void Symbol();                  // Let oder Call
    void ErrorStmnt();              // ERROR n
    void NotImp();                  // nicht implementiert
    void BadBlock();                // LOOP/WEND/NEXT
    void BadSyntax();               // Falsches SbiToken
    void NoIf();                    // ELSE/ELSE IF ohne IF
    void Assign();                  // LET
    void Call();                    // CALL
    void Close();                   // CLOSE
    void Declare();                 // DECLARE
    void DefXXX();                  // DEFxxx
    void Dim();                     // DIM
    void ReDim();                   // ReDim();
    void Erase();                   // ERASE
    void Exit();                    // EXIT
    void For();                     // FOR...NEXT
    void Goto();                    // GOTO / GOSUB
    void If();                      // IF
    void Implements();              // IMPLEMENTS
    void Input();                   // INPUT, INPUT #
    void LineInput();               // LINE INPUT, LINE INPUT #
    void LSet();                    // LSET
    void Name();                    // NAME .. AS ..
    void On();                      // ON ERROR/variable
    void OnGoto();                  // ON...GOTO / GOSUB
    void Open();                    // OPEN
    void Option();                  // OPTION
    void Print();                   // PRINT, PRINT #
    void SubFunc();                 // SUB / FUNCTION
    void Resume();                  // RESUME
    void Return();                  // RETURN
    void RSet();                    // RSET
    void DoLoop();                  // DO...LOOP
    void Select();                  // SELECT ... CASE
    void Set();                     // SET
    void Static();                  // STATIC
    void Stop();                    // STOP/SYSTEM
    void Type();                    // TYPE...AS...END TYPE
    void Enum();                    // TYPE...END ENUM
    void While();                   // WHILE/WEND
    void With();                    // WITH
    void Write();                   // WRITE

    // JavaScript-Parsing
    void OpenJavaBlock( SbiToken, SbiExprNode* = NULL );    // Block oeffnen
    void CloseJavaBlock();                                  // Block aufloesen
    void JavaStmntBlock( SbiToken );    // Statement-Block abarbeiten
    void JavaBreak();
    void JavaContinue();
    void JavaFor();
    void JavaFunction();
    void JavaIf();
    void JavaNew();
    void JavaReturn();
    void JavaThis();
    void JavaVar();
    void JavaWhile();
    void JavaWith();
};

#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 "boost/python.hpp"

#include "IECore/CurvesPrimitiveEvaluator.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/bindings/CurvesPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/RefCountedBinding.h"

using namespace IECore;
using namespace boost::python;

namespace IECore
{

static bool pointAtV( const CurvesPrimitiveEvaluator &e, unsigned curveIndex, float v, const PrimitiveEvaluator::ResultPtr &r )
{
	e.validateResult( r );
	return e.pointAtV( curveIndex, v, r );
}

void bindCurvesPrimitiveEvaluator()
{
	scope s = RunTimeTypedClass<CurvesPrimitiveEvaluator>()
		.def( init<CurvesPrimitivePtr>() )
		.def( "pointAtV", &pointAtV )
		.def( "curveLength", &CurvesPrimitiveEvaluator::curveLength,
			(
				arg( "curveIndex" ),
				arg( "vStart" ) = 0.0f,
				arg( "vEnd" ) = 1.0f
			)
		)
	;

	RefCountedClass<CurvesPrimitiveEvaluator::Result, PrimitiveEvaluator::Result>( "Result" )
		.def( "curveIndex", &CurvesPrimitiveEvaluator::Result::curveIndex )
	;

}

}
<commit_msg>Gah! Added file missing from previous commit.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009, Image Engine Design Inc. 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 Image Engine Design nor the names of any
//       other contributors to this software 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 "boost/python.hpp"

#include "IECore/CurvesPrimitiveEvaluator.h"
#include "IECore/CurvesPrimitive.h"
#include "IECore/bindings/CurvesPrimitiveEvaluatorBinding.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/bindings/RefCountedBinding.h"

using namespace IECore;
using namespace boost::python;

namespace IECore
{

static bool pointAtV( const CurvesPrimitiveEvaluator &e, unsigned curveIndex, float v, const PrimitiveEvaluator::ResultPtr &r )
{
	e.validateResult( r );
	return e.pointAtV( curveIndex, v, r );
}

static IntVectorDataPtr verticesPerCurve( const CurvesPrimitiveEvaluator &e )
{
	return new IntVectorData( e.verticesPerCurve() );
}

static IntVectorDataPtr vertexDataOffsets( const CurvesPrimitiveEvaluator &e )
{
	return new IntVectorData( e.vertexDataOffsets() );
}

static IntVectorDataPtr varyingDataOffsets( const CurvesPrimitiveEvaluator &e )
{
	return new IntVectorData( e.varyingDataOffsets() );
}

void bindCurvesPrimitiveEvaluator()
{
	scope s = RunTimeTypedClass<CurvesPrimitiveEvaluator>()
		.def( init<CurvesPrimitivePtr>() )
		.def( "pointAtV", &pointAtV )
		.def( "curveLength", &CurvesPrimitiveEvaluator::curveLength,
			(
				arg( "curveIndex" ),
				arg( "vStart" ) = 0.0f,
				arg( "vEnd" ) = 1.0f
			)
		)
		.def( "verticesPerCurve", &verticesPerCurve )
		.def( "vertexDataOffsets", &vertexDataOffsets )
		.def( "varyingDataOffsets", &varyingDataOffsets )
	;

	RefCountedClass<CurvesPrimitiveEvaluator::Result, PrimitiveEvaluator::Result>( "Result" )
		.def( "curveIndex", &CurvesPrimitiveEvaluator::Result::curveIndex )
	;

}

}
<|endoftext|>


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

#include "cc/debug/rasterize_and_record_benchmark.h"

#include <algorithm>
#include <limits>
#include <string>

#include "base/basictypes.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "cc/debug/lap_timer.h"
#include "cc/debug/rasterize_and_record_benchmark_impl.h"
#include "cc/layers/content_layer_client.h"
#include "cc/layers/layer.h"
#include "cc/layers/picture_layer.h"
#include "cc/playback/display_item_list.h"
#include "cc/playback/picture_pile.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_host_common.h"
#include "third_party/skia/include/utils/SkPictureUtils.h"
#include "ui/gfx/geometry/rect.h"

namespace cc {

namespace {

const int kDefaultRecordRepeatCount = 100;

// Parameters for LapTimer.
const int kTimeLimitMillis = 1;
const int kWarmupRuns = 0;
const int kTimeCheckInterval = 1;

const char* kModeSuffixes[RecordingSource::RECORDING_MODE_COUNT] = {
    "",
    "_sk_null_canvas",
    "_painting_disabled",
    "_caching_disabled",
    "_construction_disabled"};

}  // namespace

RasterizeAndRecordBenchmark::RasterizeAndRecordBenchmark(
    scoped_ptr<base::Value> value,
    const MicroBenchmark::DoneCallback& callback)
    : MicroBenchmark(callback),
      record_repeat_count_(kDefaultRecordRepeatCount),
      settings_(value.Pass()),
      main_thread_benchmark_done_(false),
      host_(nullptr),
      weak_ptr_factory_(this) {
  base::DictionaryValue* settings = nullptr;
  settings_->GetAsDictionary(&settings);
  if (!settings)
    return;

  if (settings->HasKey("record_repeat_count"))
    settings->GetInteger("record_repeat_count", &record_repeat_count_);
}

RasterizeAndRecordBenchmark::~RasterizeAndRecordBenchmark() {
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void RasterizeAndRecordBenchmark::DidUpdateLayers(LayerTreeHost* host) {
  host_ = host;
  LayerTreeHostCommon::CallFunctionForSubtree(
      host->root_layer(),
      [this](Layer* layer) { layer->RunMicroBenchmark(this); });

  DCHECK(!results_.get());
  results_ = make_scoped_ptr(new base::DictionaryValue);
  results_->SetInteger("pixels_recorded", record_results_.pixels_recorded);
  results_->SetInteger("picture_memory_usage",
                       static_cast<int>(record_results_.bytes_used));

  for (int i = 0; i < RecordingSource::RECORDING_MODE_COUNT; i++) {
    std::string name = base::StringPrintf("record_time%s_ms", kModeSuffixes[i]);
    results_->SetDouble(name,
                        record_results_.total_best_time[i].InMillisecondsF());
  }
  main_thread_benchmark_done_ = true;
}

void RasterizeAndRecordBenchmark::RecordRasterResults(
    scoped_ptr<base::Value> results_value) {
  DCHECK(main_thread_benchmark_done_);

  base::DictionaryValue* results = nullptr;
  results_value->GetAsDictionary(&results);
  DCHECK(results);

  results_->MergeDictionary(results);

  NotifyDone(results_.Pass());
}

scoped_ptr<MicroBenchmarkImpl> RasterizeAndRecordBenchmark::CreateBenchmarkImpl(
    scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner) {
  return make_scoped_ptr(new RasterizeAndRecordBenchmarkImpl(
      origin_task_runner, settings_.get(),
      base::Bind(&RasterizeAndRecordBenchmark::RecordRasterResults,
                 weak_ptr_factory_.GetWeakPtr())));
}

void RasterizeAndRecordBenchmark::RunOnLayer(PictureLayer* layer) {
  DCHECK(host_);

  gfx::Rect visible_layer_rect = layer->visible_layer_rect();
  if (visible_layer_rect.IsEmpty())
    return;

  if (host_->settings().use_display_lists) {
    RunOnDisplayListLayer(layer, visible_layer_rect);
  } else {
    RunOnPictureLayer(layer, visible_layer_rect);
  }
}

void RasterizeAndRecordBenchmark::RunOnPictureLayer(
    PictureLayer* layer,
    const gfx::Rect& visible_layer_rect) {
  ContentLayerClient* painter = layer->client();

  DCHECK(host_ && !host_->settings().use_display_lists);

  gfx::Size tile_grid_size = host_->settings().default_tile_size;

  for (int mode_index = 0; mode_index < RecordingSource::RECORDING_MODE_COUNT;
       mode_index++) {
    RecordingSource::RecordingMode mode =
        static_cast<RecordingSource::RecordingMode>(mode_index);

    // Not supported for SkPicture recording.
    if (mode == RecordingSource::RECORD_WITH_CONSTRUCTION_DISABLED)
      continue;

    base::TimeDelta min_time = base::TimeDelta::Max();
    size_t memory_used = 0;

    for (int i = 0; i < record_repeat_count_; ++i) {
      // Run for a minimum amount of time to avoid problems with timer
      // quantization when the layer is very small.
      LapTimer timer(kWarmupRuns,
                     base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
                     kTimeCheckInterval);
      scoped_refptr<Picture> picture;
      do {
        picture = Picture::Create(visible_layer_rect, painter, tile_grid_size,
                                  false, mode);
        if (memory_used) {
          // Verify we are recording the same thing each time.
          DCHECK(memory_used == picture->ApproximateMemoryUsage());
        } else {
          memory_used = picture->ApproximateMemoryUsage();
        }

        timer.NextLap();
      } while (!timer.HasTimeLimitExpired());
      base::TimeDelta duration =
          base::TimeDelta::FromMillisecondsD(timer.MsPerLap());
      if (duration < min_time)
        min_time = duration;
    }

    if (mode == RecordingSource::RECORD_NORMALLY) {
      record_results_.bytes_used += memory_used;
      record_results_.pixels_recorded +=
          visible_layer_rect.width() * visible_layer_rect.height();
    }
    record_results_.total_best_time[mode_index] += min_time;
  }
}

void RasterizeAndRecordBenchmark::RunOnDisplayListLayer(
    PictureLayer* layer,
    const gfx::Rect& visible_layer_rect) {
  ContentLayerClient* painter = layer->client();

  DCHECK(host_ && host_->settings().use_display_lists);

  for (int mode_index = 0; mode_index < RecordingSource::RECORDING_MODE_COUNT;
       mode_index++) {
    ContentLayerClient::PaintingControlSetting painting_control =
        ContentLayerClient::PAINTING_BEHAVIOR_NORMAL;
    switch (static_cast<RecordingSource::RecordingMode>(mode_index)) {
      case RecordingSource::RECORD_NORMALLY:
        // Already setup for normal recording.
        break;
      case RecordingSource::RECORD_WITH_SK_NULL_CANVAS:
        // Not supported for Display List recording.
        continue;
      case RecordingSource::RECORD_WITH_PAINTING_DISABLED:
        painting_control = ContentLayerClient::DISPLAY_LIST_PAINTING_DISABLED;
        break;
      case RecordingSource::RECORD_WITH_CACHING_DISABLED:
        painting_control = ContentLayerClient::DISPLAY_LIST_CACHING_DISABLED;
        break;
      case RecordingSource::RECORD_WITH_CONSTRUCTION_DISABLED:
        painting_control =
            ContentLayerClient::DISPLAY_LIST_CONSTRUCTION_DISABLED;
        break;
      default:
        NOTREACHED();
    }
    base::TimeDelta min_time = base::TimeDelta::Max();
    size_t memory_used = 0;

    scoped_refptr<DisplayItemList> display_list;
    for (int i = 0; i < record_repeat_count_; ++i) {
      // Run for a minimum amount of time to avoid problems with timer
      // quantization when the layer is very small.
      LapTimer timer(kWarmupRuns,
                     base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
                     kTimeCheckInterval);

      do {
        display_list = painter->PaintContentsToDisplayList(visible_layer_rect,
                                                           painting_control);

        if (memory_used) {
          // Verify we are recording the same thing each time.
          DCHECK_EQ(memory_used, display_list->ApproximateMemoryUsage());
        } else {
          memory_used = display_list->ApproximateMemoryUsage();
        }

        timer.NextLap();
      } while (!timer.HasTimeLimitExpired());
      base::TimeDelta duration =
          base::TimeDelta::FromMillisecondsD(timer.MsPerLap());
      if (duration < min_time)
        min_time = duration;
    }

    if (mode_index == RecordingSource::RECORD_NORMALLY) {
      record_results_.bytes_used += memory_used;
      record_results_.pixels_recorded +=
          visible_layer_rect.width() * visible_layer_rect.height();
    }
    record_results_.total_best_time[mode_index] += min_time;
  }
}

RasterizeAndRecordBenchmark::RecordResults::RecordResults()
    : pixels_recorded(0), bytes_used(0) {
}

RasterizeAndRecordBenchmark::RecordResults::~RecordResults() {}

}  // namespace cc
<commit_msg>cc: Include Blink's display list memory usage in rasterize_and_record_micro results.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "cc/debug/rasterize_and_record_benchmark.h"

#include <algorithm>
#include <limits>
#include <string>

#include "base/basictypes.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "cc/debug/lap_timer.h"
#include "cc/debug/rasterize_and_record_benchmark_impl.h"
#include "cc/layers/content_layer_client.h"
#include "cc/layers/layer.h"
#include "cc/layers/picture_layer.h"
#include "cc/playback/display_item_list.h"
#include "cc/playback/picture_pile.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/layer_tree_host_common.h"
#include "third_party/skia/include/utils/SkPictureUtils.h"
#include "ui/gfx/geometry/rect.h"

namespace cc {

namespace {

const int kDefaultRecordRepeatCount = 100;

// Parameters for LapTimer.
const int kTimeLimitMillis = 1;
const int kWarmupRuns = 0;
const int kTimeCheckInterval = 1;

const char* kModeSuffixes[RecordingSource::RECORDING_MODE_COUNT] = {
    "",
    "_sk_null_canvas",
    "_painting_disabled",
    "_caching_disabled",
    "_construction_disabled"};

}  // namespace

RasterizeAndRecordBenchmark::RasterizeAndRecordBenchmark(
    scoped_ptr<base::Value> value,
    const MicroBenchmark::DoneCallback& callback)
    : MicroBenchmark(callback),
      record_repeat_count_(kDefaultRecordRepeatCount),
      settings_(value.Pass()),
      main_thread_benchmark_done_(false),
      host_(nullptr),
      weak_ptr_factory_(this) {
  base::DictionaryValue* settings = nullptr;
  settings_->GetAsDictionary(&settings);
  if (!settings)
    return;

  if (settings->HasKey("record_repeat_count"))
    settings->GetInteger("record_repeat_count", &record_repeat_count_);
}

RasterizeAndRecordBenchmark::~RasterizeAndRecordBenchmark() {
  weak_ptr_factory_.InvalidateWeakPtrs();
}

void RasterizeAndRecordBenchmark::DidUpdateLayers(LayerTreeHost* host) {
  host_ = host;
  LayerTreeHostCommon::CallFunctionForSubtree(
      host->root_layer(),
      [this](Layer* layer) { layer->RunMicroBenchmark(this); });

  DCHECK(!results_.get());
  results_ = make_scoped_ptr(new base::DictionaryValue);
  results_->SetInteger("pixels_recorded", record_results_.pixels_recorded);
  results_->SetInteger("picture_memory_usage",
                       static_cast<int>(record_results_.bytes_used));

  for (int i = 0; i < RecordingSource::RECORDING_MODE_COUNT; i++) {
    std::string name = base::StringPrintf("record_time%s_ms", kModeSuffixes[i]);
    results_->SetDouble(name,
                        record_results_.total_best_time[i].InMillisecondsF());
  }
  main_thread_benchmark_done_ = true;
}

void RasterizeAndRecordBenchmark::RecordRasterResults(
    scoped_ptr<base::Value> results_value) {
  DCHECK(main_thread_benchmark_done_);

  base::DictionaryValue* results = nullptr;
  results_value->GetAsDictionary(&results);
  DCHECK(results);

  results_->MergeDictionary(results);

  NotifyDone(results_.Pass());
}

scoped_ptr<MicroBenchmarkImpl> RasterizeAndRecordBenchmark::CreateBenchmarkImpl(
    scoped_refptr<base::SingleThreadTaskRunner> origin_task_runner) {
  return make_scoped_ptr(new RasterizeAndRecordBenchmarkImpl(
      origin_task_runner, settings_.get(),
      base::Bind(&RasterizeAndRecordBenchmark::RecordRasterResults,
                 weak_ptr_factory_.GetWeakPtr())));
}

void RasterizeAndRecordBenchmark::RunOnLayer(PictureLayer* layer) {
  DCHECK(host_);

  gfx::Rect visible_layer_rect = layer->visible_layer_rect();
  if (visible_layer_rect.IsEmpty())
    return;

  if (host_->settings().use_display_lists) {
    RunOnDisplayListLayer(layer, visible_layer_rect);
  } else {
    RunOnPictureLayer(layer, visible_layer_rect);
  }
}

void RasterizeAndRecordBenchmark::RunOnPictureLayer(
    PictureLayer* layer,
    const gfx::Rect& visible_layer_rect) {
  ContentLayerClient* painter = layer->client();

  DCHECK(host_ && !host_->settings().use_display_lists);

  gfx::Size tile_grid_size = host_->settings().default_tile_size;

  for (int mode_index = 0; mode_index < RecordingSource::RECORDING_MODE_COUNT;
       mode_index++) {
    RecordingSource::RecordingMode mode =
        static_cast<RecordingSource::RecordingMode>(mode_index);

    // Not supported for SkPicture recording.
    if (mode == RecordingSource::RECORD_WITH_CONSTRUCTION_DISABLED)
      continue;

    base::TimeDelta min_time = base::TimeDelta::Max();
    size_t memory_used = 0;

    for (int i = 0; i < record_repeat_count_; ++i) {
      // Run for a minimum amount of time to avoid problems with timer
      // quantization when the layer is very small.
      LapTimer timer(kWarmupRuns,
                     base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
                     kTimeCheckInterval);
      scoped_refptr<Picture> picture;
      do {
        picture = Picture::Create(visible_layer_rect, painter, tile_grid_size,
                                  false, mode);
        if (memory_used) {
          // Verify we are recording the same thing each time.
          DCHECK(memory_used == picture->ApproximateMemoryUsage());
        } else {
          memory_used = picture->ApproximateMemoryUsage();
        }

        timer.NextLap();
      } while (!timer.HasTimeLimitExpired());
      base::TimeDelta duration =
          base::TimeDelta::FromMillisecondsD(timer.MsPerLap());
      if (duration < min_time)
        min_time = duration;
    }

    if (mode == RecordingSource::RECORD_NORMALLY) {
      record_results_.bytes_used += memory_used;
      record_results_.pixels_recorded +=
          visible_layer_rect.width() * visible_layer_rect.height();
    }
    record_results_.total_best_time[mode_index] += min_time;
  }
}

void RasterizeAndRecordBenchmark::RunOnDisplayListLayer(
    PictureLayer* layer,
    const gfx::Rect& visible_layer_rect) {
  ContentLayerClient* painter = layer->client();

  DCHECK(host_ && host_->settings().use_display_lists);

  for (int mode_index = 0; mode_index < RecordingSource::RECORDING_MODE_COUNT;
       mode_index++) {
    ContentLayerClient::PaintingControlSetting painting_control =
        ContentLayerClient::PAINTING_BEHAVIOR_NORMAL;
    switch (static_cast<RecordingSource::RecordingMode>(mode_index)) {
      case RecordingSource::RECORD_NORMALLY:
        // Already setup for normal recording.
        break;
      case RecordingSource::RECORD_WITH_SK_NULL_CANVAS:
        // Not supported for Display List recording.
        continue;
      case RecordingSource::RECORD_WITH_PAINTING_DISABLED:
        painting_control = ContentLayerClient::DISPLAY_LIST_PAINTING_DISABLED;
        break;
      case RecordingSource::RECORD_WITH_CACHING_DISABLED:
        painting_control = ContentLayerClient::DISPLAY_LIST_CACHING_DISABLED;
        break;
      case RecordingSource::RECORD_WITH_CONSTRUCTION_DISABLED:
        painting_control =
            ContentLayerClient::DISPLAY_LIST_CONSTRUCTION_DISABLED;
        break;
      default:
        NOTREACHED();
    }
    base::TimeDelta min_time = base::TimeDelta::Max();
    size_t memory_used = 0;

    scoped_refptr<DisplayItemList> display_list;
    for (int i = 0; i < record_repeat_count_; ++i) {
      // Run for a minimum amount of time to avoid problems with timer
      // quantization when the layer is very small.
      LapTimer timer(kWarmupRuns,
                     base::TimeDelta::FromMilliseconds(kTimeLimitMillis),
                     kTimeCheckInterval);

      do {
        display_list = painter->PaintContentsToDisplayList(visible_layer_rect,
                                                           painting_control);

        if (memory_used) {
          // Verify we are recording the same thing each time.
          DCHECK_EQ(memory_used, display_list->ApproximateMemoryUsage());
        } else {
          memory_used = display_list->ApproximateMemoryUsage();
        }

        timer.NextLap();
      } while (!timer.HasTimeLimitExpired());
      base::TimeDelta duration =
          base::TimeDelta::FromMillisecondsD(timer.MsPerLap());
      if (duration < min_time)
        min_time = duration;
    }

    if (mode_index == RecordingSource::RECORD_NORMALLY) {
      record_results_.bytes_used +=
          memory_used + painter->GetApproximateUnsharedMemoryUsage();
      record_results_.pixels_recorded +=
          visible_layer_rect.width() * visible_layer_rect.height();
    }
    record_results_.total_best_time[mode_index] += min_time;
  }
}

RasterizeAndRecordBenchmark::RecordResults::RecordResults()
    : pixels_recorded(0), bytes_used(0) {
}

RasterizeAndRecordBenchmark::RecordResults::~RecordResults() {}

}  // namespace cc
<|endoftext|>