<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/jit/xla_launch_util.h"

#include <memory>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/util/stream_executor_util.h"

namespace tensorflow {
namespace {
using xla::ScopedShapedBuffer;
using xla::ShapedBuffer;
}  // anonymous namespace

std::map<int, OptionalTensor> SnapshotResourceVariables(
    OpKernelContext* ctx, const std::vector<int>& variables) {
  std::map<int, OptionalTensor> snapshot;
  for (int i : variables) {
    Var* variable = nullptr;
    ResourceHandle handle = HandleFromInput(ctx, i);
    OptionalTensor& tensor = snapshot[i];
    if (LookupResource(ctx, handle, &variable).ok()) {
      tf_shared_lock lock(*variable->mu());
      tensor.name = handle.name();
      tensor.present = true;
      tensor.value = *variable->tensor();
    }
  }
  return snapshot;
}

XlaAllocator::XlaAllocator(const se::Platform* platform, Allocator* wrapped)
    : xla::DeviceMemoryAllocator(platform), wrapped_(wrapped) {}

XlaAllocator::~XlaAllocator() {}

xla::StatusOr<xla::OwningDeviceMemory> XlaAllocator::Allocate(
    int device_ordinal, uint64 size, bool retry_on_failure) {
  AllocationAttributes attrs;
  attrs.no_retry_on_failure = !retry_on_failure;
  void* data = nullptr;
  if (size != 0) {
    data = wrapped_->AllocateRaw(Allocator::kAllocatorAlignment, size, attrs);
    if (data == nullptr) {
      return errors::ResourceExhausted(
          "Out of memory while trying to allocate ", size, " bytes.");
    }
  }
  return xla::OwningDeviceMemory(se::DeviceMemoryBase(data, size),
                                 device_ordinal, this);
}

Status XlaAllocator::Deallocate(int device_ordinal, se::DeviceMemoryBase mem) {
  wrapped_->DeallocateRaw(mem.opaque());
  return Status::OK();
}

namespace internal {
// Return the 'index''th subtree of the given ShapedBuffer as a
// ScopedShapedBuffer. The returned ScopedShapedBuffer takes ownership of the
// subtree, and sets the input's buffer pointers to nullptr for the subtree.
ScopedShapedBuffer ExtractSubShapedBuffer(
    ShapedBuffer* shaped_buffer, int index,
    xla::DeviceMemoryAllocator* allocator) {
  const xla::Shape& on_host_shape = xla::ShapeUtil::GetTupleElementShape(
      shaped_buffer->on_host_shape(), index);
  const xla::Shape& on_device_shape = xla::ShapeUtil::GetTupleElementShape(
      shaped_buffer->on_device_shape(), index);

  ShapedBuffer sub_shaped_buffer(on_host_shape, on_device_shape,
                                 shaped_buffer->platform(),
                                 shaped_buffer->device_ordinal());

  auto& shape_tree = shaped_buffer->buffers();
  auto& sub_shape_tree = sub_shaped_buffer.buffers();
  sub_shape_tree.CopySubtreeFrom(shape_tree,
                                 /*source_base_index=*/{index},
                                 /*target_base_index=*/{});
  shape_tree.ForEachMutableElement(
      [index](const xla::ShapeIndex& shape_index,
              tensorflow::se::DeviceMemoryBase* data) {
        // shape_index is empty for the root node. Ignore that.
        if (!shape_index.empty() && shape_index[0] == index) {
          *data = tensorflow::se::DeviceMemoryBase(nullptr, 0);
        }
      });
  return ScopedShapedBuffer(std::move(sub_shaped_buffer), allocator);
}
}  // namespace internal
using internal::ExtractSubShapedBuffer;

XlaComputationLaunchContext::XlaComputationLaunchContext(
    xla::LocalClient* client, xla::DeviceMemoryAllocator* xla_allocator,
    bool allocate_xla_tensors, bool use_multiple_streams)
    : client_(client),
      xla_allocator_(xla_allocator),
      allocate_xla_tensors_(allocate_xla_tensors),
      use_multiple_streams_(use_multiple_streams) {
  if (use_multiple_streams_) {
    CHECK(allocate_xla_tensors_) << "To use multiple streams correctly we must "
                                    "be allocating XLA tensors!";
  }
}

void XlaComputationLaunchContext::PopulateInputs(
    OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel,
    const std::map<int, OptionalTensor>& variables) {
  se::Stream* stream =
      ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr;
  // Build ShapedBuffers that point directly to the Tensor buffers.
  arg_buffers_.reserve(kernel->xla_input_shapes.size() + 1);
  arg_buffers_.resize(kernel->xla_input_shapes.size());
  arg_ptrs_ = std::vector<ShapedBuffer*>(arg_buffers_.size());

  // Pass remaining parameters.
  const Tensor* t;
  for (int i = 0; i < kernel->xla_input_shapes.size(); ++i) {
    int arg_num = kernel->input_mapping[i];
    const xla::Shape& shape = kernel->xla_input_shapes[i];
    if (variables.count(arg_num)) {
      t = &(variables.at(arg_num).value);
      CHECK(t);
    } else {
      t = &(ctx->input(arg_num));
    }

    if (use_multiple_streams_) {
      CHECK(stream) << "Must have a stream available when using XLA tensors!";
      XlaTensor* xla_tensor = XlaTensor::FromTensor(t);
      CHECK(xla_tensor);
      if (se::Event* event = xla_tensor->GetDefinitionEvent(stream)) {
        stream->ThenWaitFor(event);
        xla_tensor->SetDefinedOn(stream);
      }
    }

    const xla::Shape on_device_shape =
        client_->backend().transfer_manager()->HostShapeToDeviceShape(shape);
    if (xla::ShapeUtil::IsTuple(on_device_shape)) {
      const XlaTensor* xla_tensor = XlaTensor::FromTensor(t);
      CHECK(xla_tensor && xla_tensor->has_shaped_buffer());
      arg_ptrs_[i] = const_cast<ShapedBuffer*>(&xla_tensor->shaped_buffer());
    } else {
      CHECK(xla::ShapeUtil::Equal(shape, on_device_shape))
          << "On-device shape "
          << xla::ShapeUtil::HumanStringWithLayout(on_device_shape)
          << " not the same as on-host shape "
          << xla::ShapeUtil::HumanStringWithLayout(shape);
      se::DeviceMemoryBase dmem = XlaTensor::DeviceMemoryFromTensor(*t);
      arg_buffers_[i] = absl::make_unique<ShapedBuffer>(
          /*on_host_shape=*/shape, /*on_device_shape=*/shape,
          client_->platform(), client_->default_device_ordinal());
      arg_buffers_[i]->set_buffer(dmem, /*index=*/{});
      arg_ptrs_[i] = arg_buffers_[i].get();
    }
  }
}

Status XlaComputationLaunchContext::PopulateOutputs(
    OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel,
    ScopedShapedBuffer output) {
  se::Stream* stream =
      ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr;

  // Computation output should always be a tuple.
  if (VLOG_IS_ON(2)) {
    VLOG(2) << "Result tuple shape: " << output.on_host_shape().DebugString();
    VLOG(2) << "Result tuple shape (on device): "
            << output.on_device_shape().DebugString();
  }
  CHECK_EQ(ctx->num_outputs(), kernel->outputs.size());

  // If the on-host-shape isn't a tuple, create a new single-element tuple
  // buffer with a nullptr root index table. This allows the code below to treat
  // output as a tuple unconditionally.
  if (!xla::ShapeUtil::IsTuple(output.on_host_shape())) {
    ShapedBuffer nontuple_buffer = output.release();
    ShapedBuffer buffer(
        xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_host_shape()}),
        xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_device_shape()}),
        output.platform(), output.device_ordinal());
    buffer.buffers().CopySubtreeFrom(nontuple_buffer.buffers(),
                                     /*source_base_index=*/{},
                                     /*target_base_index=*/{0});
    output = ScopedShapedBuffer(std::move(buffer), output.memory_allocator());
  }

  std::shared_ptr<se::Event> definition_event;
  if (use_multiple_streams_) {
    definition_event = std::make_shared<se::Event>(stream->parent());
    if (!definition_event->Init()) {
      return errors::Internal("Failed to initialize tensor definition event.");
    }
    stream->ThenRecordEvent(definition_event.get());
  }

  // Copy XLA results to the OpOutputList.
  int output_num = 0;
  for (int i = 0; i < ctx->num_outputs(); ++i) {
    Allocator* allocator = ctx->device()->GetAllocator({});
    if (kernel->outputs[i].is_constant) {
      // Output is a constant.
      const Tensor& const_tensor = kernel->outputs[i].constant_value;
      Tensor* output_tensor;
      const size_t total_bytes = const_tensor.TotalBytes();
      if (stream && total_bytes > 0) {
        // Copy host -> device. (Empty tensors don't have backing buffers.)
        // Manually allocate memory using an XlaTensorBuffer so we can allocate
        // as much memory as the device requires (as given by
        // GetByteSizeRequirement). This avoids XlaTransferManager having to
        // reallocate the device buffer later.
        VLOG(1) << "Constant output tensor on device";

        TF_RETURN_IF_ERROR(
            ctx->allocate_output(i, const_tensor.shape(), &output_tensor));

        Device* device = dynamic_cast<Device*>(ctx->device());
        if (device == nullptr) {
          return errors::Internal("DeviceBase was not a Device.");
        }
        ctx->op_device_context()->CopyCPUTensorToDevice(
            &const_tensor, device, output_tensor,
            [&](Status status) { TF_CHECK_OK(status); });

        if (device->device_type() == DEVICE_GPU) {
          // The GPUDeviceContext enqueues the host->device transfer in a
          // separate stream from the main compute stream. We must ensure the
          // compute stream is synchronized with the host->device transfer
          // stream now otherwise we will create a race condition.
          auto* gpu_device_context =
              static_cast<GPUDeviceContext*>(ctx->op_device_context());
          gpu_device_context->stream()->ThenWaitFor(
              gpu_device_context->host_to_device_stream());
        }
      } else {
        // No copy required.
        ctx->set_output(i, const_tensor);
        output_tensor = ctx->mutable_output(i);
      }
      if (XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor)) {
        xla_tensor->set_host_tensor(const_tensor);
      }
    } else {
      const TensorShape& shape = kernel->outputs[i].shape;
      const DataType& type = kernel->outputs[i].type;
      VLOG(2) << "Retval " << i << " shape " << shape.DebugString() << " type "
              << DataTypeString(type);
      if (type == DT_RESOURCE) {
        ctx->set_output(i, ctx->input(kernel->outputs[i].input_index));
      } else {
        se::DeviceMemoryBase buffer = output.buffer({output_num});
        if (allocate_xla_tensors_) {
          Tensor* output_tensor;
          TF_RETURN_IF_ERROR(ctx->allocate_output(i, shape, &output_tensor));
          XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor);
          if (xla_tensor) {
            xla_tensor->set_shaped_buffer(ScopedShapedBuffer(
                ExtractSubShapedBuffer(&output, output_num, xla_allocator_)));
            if (use_multiple_streams_) {
              xla_tensor->SetDefinedOn(stream, definition_event);
            }
          } else {
            // xla_tensor wasn't valid, which must mean this is a zero-element
            // tensor.
            CHECK_EQ(output_tensor->TotalBytes(), 0);
          }
        } else {
          Tensor output_tensor = XlaTensorBuffer::MakeTensor(
              ctx->expected_output_dtype(i), shape, buffer, allocator);
          output.set_buffer(xla::OwningDeviceMemory(), {output_num});
          ctx->set_output(i, output_tensor);
        }
        ++output_num;
      }
    }

    if (VLOG_IS_ON(3)) {
      VLOG(3) << ctx->mutable_output(i)->DebugString();
    }
  }

  // Apply variable updates, if any.
  VLOG(2) << "Applying variable updates";
  for (int i = 0; i < kernel->resource_updates.size(); ++i) {
    Allocator* allocator = ctx->device()->GetAllocator({});
    const XlaCompiler::ResourceUpdate& write = kernel->resource_updates[i];
    if (write.input_index < 0 || write.input_index >= ctx->num_inputs()) {
      return errors::Internal("Invalid input index for variable write.");
    }

    se::DeviceMemoryBase buffer = output.buffer({output_num});

    Var* variable = nullptr;
    // TODO(b/35625933): tensorflow::Var should contain a PersistentTensor,
    // not a Tensor.
    TF_RETURN_IF_ERROR(LookupOrCreateResource<Var>(
        ctx, HandleFromInput(ctx, write.input_index), &variable,
        [&write](Var** ptr) {
          *ptr = new Var(write.type);
          return Status::OK();
        }));

    core::ScopedUnref s(variable);

    mutex_lock ml(*variable->mu());
    if (variable->tensor()->dtype() != write.type) {
      return errors::Internal("Mismatched type in variable write");
    }

    if (allocate_xla_tensors_) {
      Tensor output_tensor;
      TF_RETURN_IF_ERROR(
          ctx->allocate_temp(write.type, write.shape, &output_tensor));
      XlaTensor* xla_tensor = XlaTensor::FromTensor(&output_tensor);
      CHECK(xla_tensor);
      xla_tensor->set_shaped_buffer(
          ExtractSubShapedBuffer(&output, output_num, xla_allocator_));
      if (use_multiple_streams_) {
        xla_tensor->SetDefinedOn(stream, definition_event);
      }
      *variable->tensor() = output_tensor;
    } else {
      Tensor output_tensor = XlaTensorBuffer::MakeTensor(
          write.type, write.shape, buffer, allocator);
      output.set_buffer(xla::OwningDeviceMemory(), {output_num});
      *variable->tensor() = output_tensor;
    }
    ++output_num;
  }
  return Status::OK();
}

}  // namespace tensorflow
<commit_msg>Return error message with illegal input rather than check-failing in op_kernel.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/compiler/jit/xla_launch_util.h"

#include <memory>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/jit/defs.h"
#include "tensorflow/compiler/tf2xla/shape_util.h"
#include "tensorflow/compiler/tf2xla/xla_compiler.h"
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/core/common_runtime/dma_helper.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/util/stream_executor_util.h"

namespace tensorflow {
namespace {
using xla::ScopedShapedBuffer;
using xla::ShapedBuffer;
}  // anonymous namespace

std::map<int, OptionalTensor> SnapshotResourceVariables(
    OpKernelContext* ctx, const std::vector<int>& variables) {
  std::map<int, OptionalTensor> snapshot;
  for (int i : variables) {
    Var* variable = nullptr;
    ResourceHandle handle = HandleFromInput(ctx, i);
    OptionalTensor& tensor = snapshot[i];
    if (LookupResource(ctx, handle, &variable).ok()) {
      tf_shared_lock lock(*variable->mu());
      tensor.name = handle.name();
      tensor.present = true;
      tensor.value = *variable->tensor();
    }
  }
  return snapshot;
}

XlaAllocator::XlaAllocator(const se::Platform* platform, Allocator* wrapped)
    : xla::DeviceMemoryAllocator(platform), wrapped_(wrapped) {}

XlaAllocator::~XlaAllocator() {}

xla::StatusOr<xla::OwningDeviceMemory> XlaAllocator::Allocate(
    int device_ordinal, uint64 size, bool retry_on_failure) {
  AllocationAttributes attrs;
  attrs.no_retry_on_failure = !retry_on_failure;
  void* data = nullptr;
  if (size != 0) {
    data = wrapped_->AllocateRaw(Allocator::kAllocatorAlignment, size, attrs);
    if (data == nullptr) {
      return errors::ResourceExhausted(
          "Out of memory while trying to allocate ", size, " bytes.");
    }
  }
  return xla::OwningDeviceMemory(se::DeviceMemoryBase(data, size),
                                 device_ordinal, this);
}

Status XlaAllocator::Deallocate(int device_ordinal, se::DeviceMemoryBase mem) {
  wrapped_->DeallocateRaw(mem.opaque());
  return Status::OK();
}

namespace internal {
// Return the 'index''th subtree of the given ShapedBuffer as a
// ScopedShapedBuffer. The returned ScopedShapedBuffer takes ownership of the
// subtree, and sets the input's buffer pointers to nullptr for the subtree.
ScopedShapedBuffer ExtractSubShapedBuffer(
    ShapedBuffer* shaped_buffer, int index,
    xla::DeviceMemoryAllocator* allocator) {
  const xla::Shape& on_host_shape = xla::ShapeUtil::GetTupleElementShape(
      shaped_buffer->on_host_shape(), index);
  const xla::Shape& on_device_shape = xla::ShapeUtil::GetTupleElementShape(
      shaped_buffer->on_device_shape(), index);

  ShapedBuffer sub_shaped_buffer(on_host_shape, on_device_shape,
                                 shaped_buffer->platform(),
                                 shaped_buffer->device_ordinal());

  auto& shape_tree = shaped_buffer->buffers();
  auto& sub_shape_tree = sub_shaped_buffer.buffers();
  sub_shape_tree.CopySubtreeFrom(shape_tree,
                                 /*source_base_index=*/{index},
                                 /*target_base_index=*/{});
  shape_tree.ForEachMutableElement(
      [index](const xla::ShapeIndex& shape_index,
              tensorflow::se::DeviceMemoryBase* data) {
        // shape_index is empty for the root node. Ignore that.
        if (!shape_index.empty() && shape_index[0] == index) {
          *data = tensorflow::se::DeviceMemoryBase(nullptr, 0);
        }
      });
  return ScopedShapedBuffer(std::move(sub_shaped_buffer), allocator);
}
}  // namespace internal
using internal::ExtractSubShapedBuffer;

XlaComputationLaunchContext::XlaComputationLaunchContext(
    xla::LocalClient* client, xla::DeviceMemoryAllocator* xla_allocator,
    bool allocate_xla_tensors, bool use_multiple_streams)
    : client_(client),
      xla_allocator_(xla_allocator),
      allocate_xla_tensors_(allocate_xla_tensors),
      use_multiple_streams_(use_multiple_streams) {
  if (use_multiple_streams_) {
    CHECK(allocate_xla_tensors_) << "To use multiple streams correctly we must "
                                    "be allocating XLA tensors!";
  }
}

void XlaComputationLaunchContext::PopulateInputs(
    OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel,
    const std::map<int, OptionalTensor>& variables) {
  se::Stream* stream =
      ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr;
  // Build ShapedBuffers that point directly to the Tensor buffers.
  arg_buffers_.reserve(kernel->xla_input_shapes.size() + 1);
  arg_buffers_.resize(kernel->xla_input_shapes.size());
  arg_ptrs_ = std::vector<ShapedBuffer*>(arg_buffers_.size());

  // Pass remaining parameters.
  const Tensor* t;
  for (int i = 0; i < kernel->xla_input_shapes.size(); ++i) {
    int arg_num = kernel->input_mapping[i];
    const xla::Shape& shape = kernel->xla_input_shapes[i];
    if (variables.count(arg_num)) {
      t = &(variables.at(arg_num).value);
      CHECK(t);
    } else {
      t = &(ctx->input(arg_num));
    }

    if (use_multiple_streams_) {
      CHECK(stream) << "Must have a stream available when using XLA tensors!";
      XlaTensor* xla_tensor = XlaTensor::FromTensor(t);
      CHECK(xla_tensor);
      if (se::Event* event = xla_tensor->GetDefinitionEvent(stream)) {
        stream->ThenWaitFor(event);
        xla_tensor->SetDefinedOn(stream);
      }
    }

    const xla::Shape on_device_shape =
        client_->backend().transfer_manager()->HostShapeToDeviceShape(shape);
    if (xla::ShapeUtil::IsTuple(on_device_shape)) {
      const XlaTensor* xla_tensor = XlaTensor::FromTensor(t);
      CHECK(xla_tensor && xla_tensor->has_shaped_buffer());
      arg_ptrs_[i] = const_cast<ShapedBuffer*>(&xla_tensor->shaped_buffer());
    } else {
      CHECK(xla::ShapeUtil::Equal(shape, on_device_shape))
          << "On-device shape "
          << xla::ShapeUtil::HumanStringWithLayout(on_device_shape)
          << " not the same as on-host shape "
          << xla::ShapeUtil::HumanStringWithLayout(shape);
      se::DeviceMemoryBase dmem = XlaTensor::DeviceMemoryFromTensor(*t);
      arg_buffers_[i] = absl::make_unique<ShapedBuffer>(
          /*on_host_shape=*/shape, /*on_device_shape=*/shape,
          client_->platform(), client_->default_device_ordinal());
      arg_buffers_[i]->set_buffer(dmem, /*index=*/{});
      arg_ptrs_[i] = arg_buffers_[i].get();
    }
  }
}

Status XlaComputationLaunchContext::PopulateOutputs(
    OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel,
    ScopedShapedBuffer output) {
  se::Stream* stream =
      ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr;

  // Computation output should always be a tuple.
  if (VLOG_IS_ON(2)) {
    VLOG(2) << "Result tuple shape: " << output.on_host_shape().DebugString();
    VLOG(2) << "Result tuple shape (on device): "
            << output.on_device_shape().DebugString();
  }
  CHECK_EQ(ctx->num_outputs(), kernel->outputs.size());

  // If the on-host-shape isn't a tuple, create a new single-element tuple
  // buffer with a nullptr root index table. This allows the code below to treat
  // output as a tuple unconditionally.
  if (!xla::ShapeUtil::IsTuple(output.on_host_shape())) {
    ShapedBuffer nontuple_buffer = output.release();
    ShapedBuffer buffer(
        xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_host_shape()}),
        xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_device_shape()}),
        output.platform(), output.device_ordinal());
    buffer.buffers().CopySubtreeFrom(nontuple_buffer.buffers(),
                                     /*source_base_index=*/{},
                                     /*target_base_index=*/{0});
    output = ScopedShapedBuffer(std::move(buffer), output.memory_allocator());
  }

  std::shared_ptr<se::Event> definition_event;
  if (use_multiple_streams_) {
    definition_event = std::make_shared<se::Event>(stream->parent());
    if (!definition_event->Init()) {
      return errors::Internal("Failed to initialize tensor definition event.");
    }
    stream->ThenRecordEvent(definition_event.get());
  }

  // Copy XLA results to the OpOutputList.
  int output_num = 0;
  for (int i = 0; i < ctx->num_outputs(); ++i) {
    Allocator* allocator = ctx->device()->GetAllocator({});
    if (kernel->outputs[i].is_constant) {
      // Output is a constant.
      const Tensor& const_tensor = kernel->outputs[i].constant_value;
      Tensor* output_tensor;
      const size_t total_bytes = const_tensor.TotalBytes();
      if (stream && total_bytes > 0) {
        // Copy host -> device. (Empty tensors don't have backing buffers.)
        // Manually allocate memory using an XlaTensorBuffer so we can allocate
        // as much memory as the device requires (as given by
        // GetByteSizeRequirement). This avoids XlaTransferManager having to
        // reallocate the device buffer later.
        VLOG(1) << "Constant output tensor on device";

        TF_RETURN_IF_ERROR(
            ctx->allocate_output(i, const_tensor.shape(), &output_tensor));

        Device* device = dynamic_cast<Device*>(ctx->device());
        if (device == nullptr) {
          return errors::Internal("DeviceBase was not a Device.");
        }
        ctx->op_device_context()->CopyCPUTensorToDevice(
            &const_tensor, device, output_tensor,
            [&](Status status) { TF_CHECK_OK(status); });

        if (device->device_type() == DEVICE_GPU) {
          // The GPUDeviceContext enqueues the host->device transfer in a
          // separate stream from the main compute stream. We must ensure the
          // compute stream is synchronized with the host->device transfer
          // stream now otherwise we will create a race condition.
          auto* gpu_device_context =
              static_cast<GPUDeviceContext*>(ctx->op_device_context());
          gpu_device_context->stream()->ThenWaitFor(
              gpu_device_context->host_to_device_stream());
        }
      } else {
        // No copy required.
        ctx->set_output(i, const_tensor);
        output_tensor = ctx->mutable_output(i);
      }
      if (XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor)) {
        xla_tensor->set_host_tensor(const_tensor);
      }
    } else {
      const TensorShape& shape = kernel->outputs[i].shape;
      const DataType& type = kernel->outputs[i].type;
      VLOG(2) << "Retval " << i << " shape " << shape.DebugString() << " type "
              << DataTypeString(type);
      if (type == DT_RESOURCE) {
        TF_RET_CHECK(kernel->outputs[i].input_index >= 0)
            << "Invalid input for outputs " << i;
        ctx->set_output(i, ctx->input(kernel->outputs[i].input_index));
      } else {
        se::DeviceMemoryBase buffer = output.buffer({output_num});
        if (allocate_xla_tensors_) {
          Tensor* output_tensor;
          TF_RETURN_IF_ERROR(ctx->allocate_output(i, shape, &output_tensor));
          XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor);
          if (xla_tensor) {
            xla_tensor->set_shaped_buffer(ScopedShapedBuffer(
                ExtractSubShapedBuffer(&output, output_num, xla_allocator_)));
            if (use_multiple_streams_) {
              xla_tensor->SetDefinedOn(stream, definition_event);
            }
          } else {
            // xla_tensor wasn't valid, which must mean this is a zero-element
            // tensor.
            CHECK_EQ(output_tensor->TotalBytes(), 0);
          }
        } else {
          Tensor output_tensor = XlaTensorBuffer::MakeTensor(
              ctx->expected_output_dtype(i), shape, buffer, allocator);
          output.set_buffer(xla::OwningDeviceMemory(), {output_num});
          ctx->set_output(i, output_tensor);
        }
        ++output_num;
      }
    }

    if (VLOG_IS_ON(3)) {
      VLOG(3) << ctx->mutable_output(i)->DebugString();
    }
  }

  // Apply variable updates, if any.
  VLOG(2) << "Applying variable updates";
  for (int i = 0; i < kernel->resource_updates.size(); ++i) {
    Allocator* allocator = ctx->device()->GetAllocator({});
    const XlaCompiler::ResourceUpdate& write = kernel->resource_updates[i];
    if (write.input_index < 0 || write.input_index >= ctx->num_inputs()) {
      return errors::Internal("Invalid input index for variable write.");
    }

    se::DeviceMemoryBase buffer = output.buffer({output_num});

    Var* variable = nullptr;
    // TODO(b/35625933): tensorflow::Var should contain a PersistentTensor,
    // not a Tensor.
    TF_RETURN_IF_ERROR(LookupOrCreateResource<Var>(
        ctx, HandleFromInput(ctx, write.input_index), &variable,
        [&write](Var** ptr) {
          *ptr = new Var(write.type);
          return Status::OK();
        }));

    core::ScopedUnref s(variable);

    mutex_lock ml(*variable->mu());
    if (variable->tensor()->dtype() != write.type) {
      return errors::Internal("Mismatched type in variable write");
    }

    if (allocate_xla_tensors_) {
      Tensor output_tensor;
      TF_RETURN_IF_ERROR(
          ctx->allocate_temp(write.type, write.shape, &output_tensor));
      XlaTensor* xla_tensor = XlaTensor::FromTensor(&output_tensor);
      CHECK(xla_tensor);
      xla_tensor->set_shaped_buffer(
          ExtractSubShapedBuffer(&output, output_num, xla_allocator_));
      if (use_multiple_streams_) {
        xla_tensor->SetDefinedOn(stream, definition_event);
      }
      *variable->tensor() = output_tensor;
    } else {
      Tensor output_tensor = XlaTensorBuffer::MakeTensor(
          write.type, write.shape, buffer, allocator);
      output.set_buffer(xla::OwningDeviceMemory(), {output_num});
      *variable->tensor() = output_tensor;
    }
    ++output_num;
  }
  return Status::OK();
}

}  // namespace tensorflow
<|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetTreeHeader.cpp
 */

#include "JPetTreeHeader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include <sstream>

ClassImp(JPetTreeHeader);

JPetTreeHeader::JPetTreeHeader():
  fRunNo(-1),
  fBaseFilename("filename not set something"),
  fSourcePosition(-1),
  emptyStage({"module not set", "description not set", -1, "-1"})
{
}

JPetTreeHeader::JPetTreeHeader(int run):
  fRunNo(run),
  fBaseFilename("filename not set"),
  fSourcePosition(-1),
  emptyStage({"module not set", "description not set", -1, "-1"})
{
}

std::string JPetTreeHeader::stringify() const
{
  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n" ;
  tmp<<"------------------------- General Info --------------------------\n" ;
  tmp<<"-----------------------------------------------------------------\n" ;
  tmp<< "Run number              : " << JPetCommonTools::Itoa(fRunNo) <<"\n";
  tmp<< "Base file name          : "<<getBaseFileName()<<"\n";
  tmp<< "Source (if any) position: "<< Form("%lf",getSourcePosition())<<"\n";

tmp << stringifyHistory();
tmp << stringifyDictionary();

return tmp.str();
}

void JPetTreeHeader::addStageInfo(std::string p_name, std::string p_title, int p_version, std::string p_time_stamp )
{
  ProcessingStageInfo stage;
  stage.fModuleName = p_name;
  stage.fModuleDescription = p_title;
  stage.fModuleVersion = p_version;
  stage.fCreationTime = p_time_stamp;
  fStages.push_back( stage );
}

std::string JPetTreeHeader::stringifyDictionary() const {

  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n";
  tmp<<"--------------------- User-defined variables --------------------\n";
  tmp<<"-----------------------------------------------------------------\n";

  for(auto const &entry : fDictionary){
    tmp<<entry.first << "   =   " << entry.second <<"\n";
    tmp<<"-----------------------------------------------------------------\n";
  }
  return tmp.str();
}

std::string JPetTreeHeader::stringifyHistory() const {

  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n";
  tmp<<"-------------- Processing history (oldest first) ----------------\n";
  tmp<<"-----------------------------------------------------------------\n";

  for (int i = 0; i < getStagesNb(); i++ ) {
    const ProcessingStageInfo & info = getProcessingStageInfo(i);
    tmp<< "Module Name         : " << info.fModuleName<<"\n";
    tmp<< "Module desc.        : " << info.fModuleDescription<<"\n";
    tmp<< "Module version      : " << JPetCommonTools::Itoa( info.fModuleVersion ) <<"\n";
    tmp<< "Started processing  : " << info.fCreationTime <<"\n";
    tmp<<"-----------------------------------------------------------------\n";
  }
  return tmp.str();
}

/**
 * @brief Sets the textual value of an existing variable named 'name' or
 * creates such variable if it was nonexistent
 *
 * @param name name of the variable (existing or not)
 * @param value value of the variable
 *
 * Use this method to store any additional information in the TreeHeader.
 * All values must be encoded as text.
 *
 * Example:
 * header.setVariable("source position", "X=10cm; Y=2cm; Z=20cm")
 *
 */
void JPetTreeHeader::setVariable(std::string name, std::string value){
  fDictionary[name] = value;
}

/**
 * @brief Returns the textual value of a variable (see the setVariable method)
 *
 * @param name name of the variable
 *
 * Use this method to access any additional information previously stored
 * in the TreeHeader with the setVariable method. If a name of a non-existent variable
 * is provided, an empty string will be returned.
 *
 */
std::string JPetTreeHeader::getVariable(std::string name) const {
	if(fDictionary.find(name)!= fDictionary.end()) return fDictionary.at(name);
	else return "";
}
<commit_msg>ParseXML is working; back to previes, working code<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetTreeHeader.cpp
 */

#include "JPetTreeHeader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include <sstream>

ClassImp(JPetTreeHeader);

JPetTreeHeader::JPetTreeHeader():
  fRunNo(-1),
  fBaseFilename("filename not set"),
  fSourcePosition(-1),
  emptyStage({"module not set", "description not set", -1, "-1"})
{
}

JPetTreeHeader::JPetTreeHeader(int run):
  fRunNo(run),
  fBaseFilename("filename not set"),
  fSourcePosition(-1),
  emptyStage({"module not set", "description not set", -1, "-1"})
{
}

std::string JPetTreeHeader::stringify() const
{
  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n" ;
  tmp<<"------------------------- General Info --------------------------\n" ;
  tmp<<"-----------------------------------------------------------------\n" ;
  tmp<< "Run number              : " << JPetCommonTools::Itoa(fRunNo) <<"\n";
  tmp<< "Base file name          : "<<getBaseFileName()<<"\n";
  tmp<< "Source (if any) position: "<< Form("%lf",getSourcePosition())<<"\n";

tmp << stringifyHistory();
tmp << stringifyDictionary();

return tmp.str();
}

void JPetTreeHeader::addStageInfo(std::string p_name, std::string p_title, int p_version, std::string p_time_stamp )
{
  ProcessingStageInfo stage;
  stage.fModuleName = p_name;
  stage.fModuleDescription = p_title;
  stage.fModuleVersion = p_version;
  stage.fCreationTime = p_time_stamp;
  fStages.push_back( stage );
}

std::string JPetTreeHeader::stringifyDictionary() const {

  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n";
  tmp<<"--------------------- User-defined variables --------------------\n";
  tmp<<"-----------------------------------------------------------------\n";

  for(auto const &entry : fDictionary){
    tmp<<entry.first << "   =   " << entry.second <<"\n";
    tmp<<"-----------------------------------------------------------------\n";
  }
  return tmp.str();
}

std::string JPetTreeHeader::stringifyHistory() const {

  std::ostringstream tmp;
  tmp<<"-----------------------------------------------------------------\n";
  tmp<<"-------------- Processing history (oldest first) ----------------\n";
  tmp<<"-----------------------------------------------------------------\n";

  for (int i = 0; i < getStagesNb(); i++ ) {
    const ProcessingStageInfo & info = getProcessingStageInfo(i);
    tmp<< "Module Name         : " << info.fModuleName<<"\n";
    tmp<< "Module desc.        : " << info.fModuleDescription<<"\n";
    tmp<< "Module version      : " << JPetCommonTools::Itoa( info.fModuleVersion ) <<"\n";
    tmp<< "Started processing  : " << info.fCreationTime <<"\n";
    tmp<<"-----------------------------------------------------------------\n";
  }
  return tmp.str();
}

/**
 * @brief Sets the textual value of an existing variable named 'name' or
 * creates such variable if it was nonexistent
 *
 * @param name name of the variable (existing or not)
 * @param value value of the variable
 *
 * Use this method to store any additional information in the TreeHeader.
 * All values must be encoded as text.
 *
 * Example:
 * header.setVariable("source position", "X=10cm; Y=2cm; Z=20cm")
 *
 */
void JPetTreeHeader::setVariable(std::string name, std::string value){
  fDictionary[name] = value;
}

/**
 * @brief Returns the textual value of a variable (see the setVariable method)
 *
 * @param name name of the variable
 *
 * Use this method to access any additional information previously stored
 * in the TreeHeader with the setVariable method. If a name of a non-existent variable
 * is provided, an empty string will be returned.
 *
 */
std::string JPetTreeHeader::getVariable(std::string name) const {
	if(fDictionary.find(name)!= fDictionary.end()) return fDictionary.at(name);
	else return "";
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertyanimationnode.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2006-07-26 07:36:24 $
 *
 *  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
 *
 ************************************************************************/

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "propertyanimationnode.hxx"
#include "animationfactory.hxx"

using namespace com::sun::star;

namespace presentation {
namespace internal {

AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const
{
    // Create AnimationActivity from common XAnimate parameters:
    ActivitiesFactory::CommonParameters aParms( fillCommonParameters() );
    uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode();
    rtl::OUString const attrName( xAnimateNode->getAttributeName() );
    AttributableShapeSharedPtr const pShape( getShape() );

    switch (AnimationFactory::classifyAttributeName( attrName )) {
    default:
    case AnimationFactory::CLASS_UNKNOWN_PROPERTY:
        ENSURE_AND_THROW(
            false,
            "Unexpected attribute class (unknown or empty attribute name)" );
        break;

    case AnimationFactory::CLASS_NUMBER_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createNumberPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_ENUM_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createEnumPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_COLOR_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createColorPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_STRING_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createStringPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_BOOL_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createBoolPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );
    }

    return AnimationActivitySharedPtr();
}

} // namespace internal
} // namespace presentation

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.10); FILE MERGED 2006/09/01 17:39:39 kaib 1.4.10.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: propertyanimationnode.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:36: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
 *
 ************************************************************************/

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

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "propertyanimationnode.hxx"
#include "animationfactory.hxx"

using namespace com::sun::star;

namespace presentation {
namespace internal {

AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const
{
    // Create AnimationActivity from common XAnimate parameters:
    ActivitiesFactory::CommonParameters aParms( fillCommonParameters() );
    uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode();
    rtl::OUString const attrName( xAnimateNode->getAttributeName() );
    AttributableShapeSharedPtr const pShape( getShape() );

    switch (AnimationFactory::classifyAttributeName( attrName )) {
    default:
    case AnimationFactory::CLASS_UNKNOWN_PROPERTY:
        ENSURE_AND_THROW(
            false,
            "Unexpected attribute class (unknown or empty attribute name)" );
        break;

    case AnimationFactory::CLASS_NUMBER_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createNumberPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_ENUM_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createEnumPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_COLOR_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createColorPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_STRING_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createStringPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );

    case AnimationFactory::CLASS_BOOL_PROPERTY:
        return ActivitiesFactory::createAnimateActivity(
            aParms,
            AnimationFactory::createBoolPropertyAnimation(
                attrName,
                pShape,
                getContext().mpLayerManager ),
            xAnimateNode );
    }

    return AnimationActivitySharedPtr();
}

} // namespace internal
} // namespace presentation

<|endoftext|>


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

#include "checkinstall.hxx"

#ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_
#include <com/sun/star/beans/XExactName.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_
#include <com/sun/star/beans/XMaterialHolder.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;

namespace desktop
{

sal_Bool CheckInstallation( OUString& rTitle )
{
    Reference< XMultiServiceFactory > xSMgr = ::comphelper::getProcessServiceFactory();
    Reference< XExactName > xExactName( xSMgr->createInstance(
                                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.comp.desktop.Evaluation" ))),
                                UNO_QUERY );
    if ( xExactName.is() )
    {
        try
        {
            rTitle = xExactName->getExactName( rTitle );
            Reference< XMaterialHolder > xMaterialHolder( xExactName, UNO_QUERY );
            if ( xMaterialHolder.is() )
            {
                com::sun::star::util::Date aExpirationDate;
                Any a = xMaterialHolder->getMaterial();
                if ( a >>= aExpirationDate )
                {
                    Date aToday;
                    Date aTimeBombDate( aExpirationDate.Day, aExpirationDate.Month, aExpirationDate.Year );
                    if ( aToday > aTimeBombDate )
                    {
                        InfoBox aInfoBox( NULL, String::CreateFromAscii( "This version has expired" ) );
                        aInfoBox.Execute();
                        return sal_False;
                    }
                }

                return sal_True;
            }
            else
            {
                InfoBox aInfoBox( NULL, rTitle );
                aInfoBox.Execute();
                return sal_False;
            }
        }
        catch ( RuntimeException& )
        {
            // Evaluation version expired!
            return sal_False;
        }
    }
    else
    {
        Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY );
        if( rContent.is() )
        {
            OUString sEvalService = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.office.Evaluation" ) );
            Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sEvalService );
            if ( rEnum.is() )
            {
                InfoBox aInfoBox( NULL, rTitle );
                aInfoBox.Execute();
                return sal_False;
            }
        }
    }

    return sal_True;
}

} // namespace desktop
<commit_msg>INTEGRATION: CWS internatiodel (1.1.670); FILE MERGED 2006/01/19 17:52:07 er 1.1.670.2: RESYNC: (1.1-1.2); FILE MERGED 2005/06/29 11:14:33 er 1.1.670.1: #i50205# get rid of class International<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: checkinstall.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 14:43:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include "checkinstall.hxx"

#ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_
#include <com/sun/star/beans/XExactName.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_
#include <com/sun/star/beans/XMaterialHolder.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XContentEnumerationAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATE_HPP_
#include <com/sun/star/util/Date.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DATE_HXX
#include <tools/date.hxx>
#endif

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::beans;

namespace desktop
{

sal_Bool CheckInstallation( OUString& rTitle )
{
    Reference< XMultiServiceFactory > xSMgr = ::comphelper::getProcessServiceFactory();
    Reference< XExactName > xExactName( xSMgr->createInstance(
                                ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(
                                    "com.sun.star.comp.desktop.Evaluation" ))),
                                UNO_QUERY );
    if ( xExactName.is() )
    {
        try
        {
            rTitle = xExactName->getExactName( rTitle );
            Reference< XMaterialHolder > xMaterialHolder( xExactName, UNO_QUERY );
            if ( xMaterialHolder.is() )
            {
                com::sun::star::util::Date aExpirationDate;
                Any a = xMaterialHolder->getMaterial();
                if ( a >>= aExpirationDate )
                {
                    Date aToday;
                    Date aTimeBombDate( aExpirationDate.Day, aExpirationDate.Month, aExpirationDate.Year );
                    if ( aToday > aTimeBombDate )
                    {
                        InfoBox aInfoBox( NULL, String::CreateFromAscii( "This version has expired" ) );
                        aInfoBox.Execute();
                        return sal_False;
                    }
                }

                return sal_True;
            }
            else
            {
                InfoBox aInfoBox( NULL, rTitle );
                aInfoBox.Execute();
                return sal_False;
            }
        }
        catch ( RuntimeException& )
        {
            // Evaluation version expired!
            return sal_False;
        }
    }
    else
    {
        Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY );
        if( rContent.is() )
        {
            OUString sEvalService = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.office.Evaluation" ) );
            Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sEvalService );
            if ( rEnum.is() )
            {
                InfoBox aInfoBox( NULL, rTitle );
                aInfoBox.Execute();
                return sal_False;
            }
        }
    }

    return sal_True;
}

} // namespace desktop
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/boundary.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int    default_k = 0;
double default_radius = 0.0;
double default_angle  = M_PI/2.0;

Eigen::Vector4f    translation;
Eigen::Quaternionf orientation;

void
printHelp (int argc, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
  print_value ("%f", default_radius); print_info (")\n");
  print_info ("                     -k X      = use a fixed number of X-nearest neighbors around each point (default: ");
  print_value ("%d", default_k); print_info (")\n");
  print_info ("                     -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: ");
  print_value ("%f", default_angle); print_info (")\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud, translation, orientation) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  // Check if the dataset has normals
  if (pcl::getFieldIndex (cloud, "normal_x") == -1)
  {
    print_error ("The input dataset does not contain normal information!\n");
    return (false);
  }
  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         int k, double radius, double angle)
{
  // Convert data to PointCloud<T>
  PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>);
  fromROSMsg (*input, *xyznormals);

  // Estimate
  TicToc tt;
  tt.tic ();

  print_highlight (stderr, "Computing ");

  BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne;
  ne.setInputCloud (xyznormals);
  ne.setInputNormals (xyznormals);
  ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>));
  ne.setKSearch (k);
  ne.setRadiusSearch (radius);

  PointCloud<Boundary> boundaries;
  ne.compute (boundaries);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n");

  // Convert data back
  sensor_msgs::PointCloud2 output_boundaries;
  toROSMsg (boundaries, output_boundaries);
  concatenateFields (*input, output_boundaries, output);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output, translation, orientation, true);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]);
  bool help = false;
  parse_argument (argc, argv, "-h", help);
  if (argc < 3 || help)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  int k = default_k;
  double radius = default_radius;
  double angle  = default_angle;
  parse_argument (argc, argv, "-k", k);
  parse_argument (argc, argv, "-radius", radius);
  parse_argument (argc, argv, "-thresh", angle);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Perform the feature estimation
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, k, radius, angle);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

<commit_msg>save as ascii in an attempt to catch a bug<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/features/boundary.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

int    default_k = 0;
double default_radius = 0.0;
double default_angle  = M_PI/2.0;

Eigen::Vector4f    translation;
Eigen::Quaternionf orientation;

void
printHelp (int argc, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -radius X = use a radius of Xm around each point to determine the neighborhood (default: ");
  print_value ("%f", default_radius); print_info (")\n");
  print_info ("                     -k X      = use a fixed number of X-nearest neighbors around each point (default: ");
  print_value ("%d", default_k); print_info (")\n");
  print_info ("                     -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: ");
  print_value ("%f", default_angle); print_info (")\n");
}

bool
loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud, translation, orientation) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  // Check if the dataset has normals
  if (pcl::getFieldIndex (cloud, "normal_x") == -1)
  {
    print_error ("The input dataset does not contain normal information!\n");
    return (false);
  }
  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         int k, double radius, double angle)
{
  // Convert data to PointCloud<T>
  PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>);
  fromROSMsg (*input, *xyznormals);

  // Estimate
  TicToc tt;
  tt.tic ();

  print_highlight (stderr, "Computing ");

  BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne;
  ne.setInputCloud (xyznormals);
  ne.setInputNormals (xyznormals);
  ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>));
  ne.setKSearch (k);
  ne.setRadiusSearch (radius);

  PointCloud<Boundary> boundaries;
  ne.compute (boundaries);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n");

  // Convert data back
  sensor_msgs::PointCloud2 output_boundaries;
  toROSMsg (boundaries, output_boundaries);
  concatenateFields (*input, output_boundaries, output);
}

void
saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  pcl::io::savePCDFile (filename, output, translation, orientation, false);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]);
  bool help = false;
  parse_argument (argc, argv, "-h", help);
  if (argc < 3 || help)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  std::vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  int k = default_k;
  double radius = default_radius;
  double angle  = default_angle;
  parse_argument (argc, argv, "-k", k);
  parse_argument (argc, argv, "-radius", radius);
  parse_argument (argc, argv, "-thresh", angle);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Perform the feature estimation
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, k, radius, angle);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

<|endoftext|>


<commit_before>#include <KameMix.h>
#include <cmath>
#include <cassert>
#include <thread>
#include <chrono>
#include <iostream>

using namespace KameMix;
using std::cout;
using std::cerr;

void onSoundFinished(Sound *sound, void *udata)
{
  cout << "sound finished\n";
  assert(!sound->isPlaying());
}

void onStreamFinished(Stream *stream, void *udata)
{
  cout << "stream finished\n";
  assert(!stream->isPlaying());
}

int main(int argc, char *argv[])
{
  //OutAudioFormat format = OutFormat_S16;
  OutAudioFormat format = OutFormat_Float;
  if (!System::init(44100, 2048, format)) {
    cout << "System::init failed\n";
    return 1;
  }

  cout << "Initialized KameMix\n";

  System::setSoundFinished(onSoundFinished, nullptr);
  System::setStreamFinished(onStreamFinished, nullptr);

  assert(System::getMasterVolume() == 1.0);
  System::setMasterVolume(.5);
  assert(System::getMasterVolume() == .5);
  System::setMasterVolume(1.0);

  const char *file_path = "sound/spell1.wav";
  Stream spell1(file_path);
  if (!spell1.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  file_path = "sound/spell3.wav";
  Sound spell3(file_path);
  if (!spell3.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  file_path = "sound/cow.ogg";
  Sound cow(file_path);
  if (!cow.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  file_path = "sound/duck.ogg";
  Stream duck(file_path);
  if (!duck.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  file_path = "sound/dark fallout.ogg";
  Stream music1(file_path);
  if (!music1.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  file_path = "sound/a new beginning.ogg";
  Sound music2(file_path);
  if (!music2.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return EXIT_FAILURE;
  }

  int group1 = System::createGroup();
  System::setGroupVolume(group1, .75);
  assert(System::getGroupVolume(group1) == .75);

  spell1.play(6);
  spell1.setGroup(group1);
  assert(spell1.isPlaying());
  assert(spell1.getGroup() == group1);
  cout << "play spell1 7 times\n";

  spell3.play(6);
  assert(spell3.isPlaying());
  assert(spell3.getGroup() == -1);
  cout << "play spell3 7 times\n";

  cow.play(6);
  assert(cow.isPlaying());
  cout << "play cow 7 times\n";

  duck.play(6);
  assert(duck.isPlaying());
  duck.setVolume(1.25f);
  assert(duck.getVolume() == 1.25f);
  cout << "play duck 7 times\n";

  double time_ms = 0.0;
  int count = 0;
  const int frame_ms = 17;
  const double frames_per_sec = 1000.0/frame_ms;
  float listener_x = .5f;
  float listener_y = .5f;
  System::setListenerPos(listener_x, listener_y);
  {
    float a, b;
    System::getListenerPos(a, b);
    assert(a == listener_x && b == listener_y);
  }
  float x = listener_x;
  float y = .75f;
  bool going_left = true;

  while (true) {
    System::update();
    std::this_thread::sleep_for(std::chrono::milliseconds(frame_ms));
    time_ms += frame_ms;

    if (time_ms > 10000 && count == 0) {
      cout << "play music1 starting at 40sec for 10secs\n";
      time_ms = 0.0;
      count++;
      music1.playAt(40);
    } else if (time_ms > 10000 && count == 1) {
      cout << "Fadeout music1 over 10 secs\n";
      time_ms = 0.0;
      count++;
      music1.fadeout(10);
    } else if (time_ms > 10000 && count == 2) {
      cout << "Fadein music2 over 10 secs, pause after 5 secs\n";
      time_ms = 0.0;
      count++;
      music2.fadein(10.0);
    } else if (time_ms > 5000 && count == 3) {
      cout << "pause music2 for 3 secs\n";
      time_ms = 0.0;
      count++;
      music2.pause();
    } else if (time_ms > 3000 && count == 4) {
      cout << "unpause music2, and continue fadein over 5 secs\n";
      time_ms = 0.0;
      count++;
      music2.unpause();
    } else if (time_ms > 5000 && count == 5) {
      cout << "fadein complete, play for 5 secs and then stop\n";
      time_ms = 0.0;
      count++;
    } else if (time_ms > 5000 && count == 6) {
      cout << "stop music2\n";
      time_ms = 0.0;
      count++;
      music2.stop();
      cout << "play spell1 moving left to right and back for 20secs\n";
      spell1.setMaxDistance(1.0f);
      spell1.play(-1);
    } else if (count == 7) {
      spell1.setPos(x, y);
      // 1 cycle in 10 secs
      float dx = (float)(2*spell1.getMaxDistance() / 10 / frames_per_sec);
      if (going_left) {
        x -= dx;
      } else {
        x += dx;
      }
      if (std::abs(listener_x - x) >= spell1.getMaxDistance() * 1.05) {
        going_left = !going_left;
      }
      if (time_ms > 20000) {
        spell1.stop();
        count++;
      }
    } else if (count == 8) {
      if (System::numberPlaying() == 0) {
        cout << "Test complete\n";
        break;
      }
    }
  }

  System::shutdown();
  cout << "Shutdown KameMix\n";

  return 0;
}
<commit_msg>Improved and added more tests<commit_after>#include <KameMix.h>
#include <cmath>
#include <cassert>
#include <thread>
#include <chrono>
#include <iostream>

using namespace KameMix;
using std::cout;
using std::cerr;

void onSoundFinished(Sound *sound, void *udata)
{
  cout << "sound finished\n";
  assert(!sound->isPlaying());
}

void onStreamFinished(Stream *stream, void *udata)
{
  cout << "stream finished\n";
  assert(!stream->isPlaying());
}

Sound spell1;
Sound spell3;
Sound cow;
Stream duck;
Stream music1;
Sound music2;

const int frames_per_sec = 60;
const double frame_ms = 1000.0 / frames_per_sec;

double update_ms(double msec);
bool loadAudio();
void test1();
void test2();
void test3();
void test4();
void test5();

int main(int argc, char *argv[])
{
  //OutAudioFormat format = OutFormat_S16;
  OutAudioFormat format = OutFormat_Float;
  if (!System::init(44100, 2048, format)) {
    cout << "System::init failed\n";
    return 1;
  }

  cout << "Initialized KameMix\n";

  if (!loadAudio()) {
    return EXIT_FAILURE;
  }

  System::setSoundFinished(onSoundFinished, nullptr);
  System::setStreamFinished(onStreamFinished, nullptr);

  assert(System::getMasterVolume() == 1.0f);
  System::setMasterVolume(.5f);
  assert(System::getMasterVolume() == .5f);
  System::setMasterVolume(1.0f);

  {
    float a, b;
    System::getListenerPos(a, b);
    assert(a == 0 && b == 0);

    System::setListenerPos(.5f, .75f);
    System::getListenerPos(a, b);
    assert(a == .5f && b == .75f);
  }

  int group1 = System::createGroup();
  System::setGroupVolume(group1, .75f);
  assert(System::getGroupVolume(group1) == .75f);

  assert(spell1.getGroup() == -1);
  spell1.setGroup(group1);
  assert(spell1.getGroup() == group1);

  duck.setVolume(1.5);
  assert(duck.getVolume() == 1.5);

  //test1();
  //test2();
  //test3();
  //test4();
  test5();

  cout << "Test complete\n";

  System::shutdown();
  cout << "Shutdown KameMix\n";

  return 0;
}

bool loadAudio()
{
  const char *file_path = "sound/spell1.wav";
  spell1.load(file_path);
  if (!spell1.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  file_path = "sound/spell3.wav";
  spell3.load(file_path);
  if (!spell3.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  file_path = "sound/cow.ogg";
  cow.load(file_path);
  if (!cow.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  file_path = "sound/duck.ogg";
  duck.load(file_path);
  if (!duck.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  file_path = "sound/dark fallout.ogg";
  music1.load(file_path);
  if (!music1.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  file_path = "sound/a new beginning.ogg";
  music2.load(file_path);
  if (!music2.isLoaded()) {
    cerr << "Couldn't load " << file_path << "\n";
    return false;
  }

  return true;
}

double update_ms(double msec)
{
  const std::chrono::duration<double, std::milli> sleep_duration(frame_ms);
  double total_time = 0;
  while (true) {
    System::update();
    std::this_thread::sleep_for(sleep_duration);
    total_time += frame_ms;
    if (total_time >= msec) {
      break;
    }
  }
  return total_time;
}

void test1()
{
  cout << "play spell1 7 times\n";
  spell1.play(6);
  assert(spell1.isPlaying());

  cout << "play spell3 7 times\n";
  spell3.play(6);
  assert(spell3.isPlaying());

  cout << "play cow 7 times\n";
  cow.play(6);
  assert(cow.isPlaying());

  cout << "play duck 7 times\n";
  duck.play(6);
  assert(duck.isPlaying());

  while (true) {
    update_ms(1000);
    if (System::numberPlaying() == 0) {
      break;
    }
  }
}

void test2()
{
  cout << "Play music1 starting at 40sec for 10secs\n";
  music1.playAt(40);
  update_ms(10000);

  cout << "Fadeout music1 over 10 secs\n";
  music1.fadeout(10);
  update_ms(10000);

  cout << "Fadein music2 over 10 secs, pause after 5 secs\n";
  music2.fadein(10.0);
  update_ms(5000);

  cout << "Pause music2 for 3 secs\n";
  music2.pause();
  update_ms(3000);

  cout << "Unpause music2, and continue fadein over 5 secs\n";
  music2.unpause();
  update_ms(5000);

  cout << "Fadein complete, play for 5 secs and then stop\n";
  update_ms(5000);

  cout << "Stop music2\n";
  music2.stop();
}

void test3()
{
  float listener_x = .5f;
  float listener_y = .5f;
  System::setListenerPos(listener_x, listener_y);
  float x = listener_x;
  float y = listener_y + .25f;

  cout << "Play spell1 moving left to right and back for 20secs\n";
  spell1.setMaxDistance(1.0f);
  spell1.setPos(x, y);
  spell1.play(-1);

  bool going_left = true;
  double total_time = 0;

  while (true) {
    // 2 cycle in 10 secs
    float dx = (float)(4*spell1.getMaxDistance() / 10 / frames_per_sec);
    if (going_left) {
      x -= dx;
    } else {
      x += dx;
    }

    if (std::abs(listener_x - x) >= spell1.getMaxDistance() * 1.05) {
      going_left = !going_left;
    }

    total_time += update_ms(frame_ms);
    if (total_time > 20000) {
      spell1.stop();
      break;
    }

    spell1.setPos(x, y);
  }
}

void test4()
{
  float listener_x = .5f;
  float listener_y = .5f;
  System::setListenerPos(listener_x, listener_y);
  float lx = listener_x - .5f;
  float rx = listener_x + .5f;
  float y = listener_y;

  cout << "Play duck for 12 secs, swapping sides every 3 secs\n";
  duck.setMaxDistance(1.0f);
  duck.setPos(lx, y);
  duck.play(-1);
  update_ms(3000);

  duck.setPos(rx, y);
  update_ms(3000);

  duck.setPos(lx, y);
  update_ms(3000);

  duck.setPos(rx, y);
  update_ms(3000);

  duck.setPos(lx, y);
  update_ms(3000);

  cout << "Stop duck\n";
  duck.stop();
}

void test5()
{
  cout << "Play music1 for 5 secs at 100% volume\n";
  music1.setVolume(1.0f);
  music1.setGroup(-1);
  music1.play(-1);
  update_ms(5000);

  cout << "Set music1 volume to 0% for 3 secs\n";
  music1.setVolume(0);
  update_ms(3000);

  cout << "Set music1 volume to 100% for 5 secs\n";
  music1.setVolume(1.0f);
  update_ms(5000);

  cout << "Set music1 volume to 25% for 5 secs\n";
  music1.setVolume(.25f);
  update_ms(5000);

  cout << "Set music1 volume to 100% for 5 secs\n";
  music1.setVolume(1.0f);
  update_ms(5000);

  cout << "Stop music1\n";
  music1.stop();
}<|endoftext|>


<commit_before>//   Copyright 2015 Patrick Putnam
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#ifndef CLOTHO_SELECTION_GENERATOR_HPP_
#define CLOTHO_SELECTION_GENERATOR_HPP_

#include <boost/property_tree/ptree.hpp>

#include <boost/random/uniform_int_distribution.hpp>

#include <vector>

namespace clotho {
namespace genetics {

/**
 * Random selection
 */
template < class RNG, class GeneticSpaceType >
class SelectionGenerator {
public:
    typedef RNG                                                                 random_engine_type;
    typedef GeneticSpaceType                                                    genetic_space_type;
    typedef typename genetic_space_type::individual_id_type                     individual_id_type;

    typedef std::vector< std::pair< individual_id_type, individual_id_type > >  mate_pair_vector;
    typedef typename mate_pair_vector::iterator                                 parent_iterator;
    typedef typename mate_pair_vector::const_iterator                           const_parent_iterator;

    typedef typename genetic_space_type::fitness_score_type                     fitness_score_type;
    typedef typename genetic_space_type::fitness_scores                         fitness_scores;

    typedef boost::random::uniform_int_distribution< size_t >                   distribution_type;

    SelectionGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) :
        m_rand( rng )
    { }

    void update( genetic_space_type * parents, size_t count ) {
        // distribution generates numbers in range [0, N]
        // therefore N needs to be the maximum index (individual_count - 1)
        distribution_type dist( 0, parents->individual_count() - 1 );

        m_pairs.clear();

        while( count-- ) {
            individual_id_type  id0 = m_dist( *m_rand );
            individual_id_type  id1 = m_dist( *m_rand );

            m_pairs.push_back( std::make_pair( id0, id1 ) );
        }
    }

    parent_iterator begin() {
        return m_pairs.begin();
    }

    parent_iterator end() {
        return m_pairs.end();
    }

    const_parent_iterator begin() const {
        return m_pairs.begin();
    }

    const_parent_iterator end() const {
        return m_pairs.end();
    }

    mate_pair_vector & getMatePairs() {
        return m_pairs;
    }

    size_t  size() const {
        return m_pairs.size();
    }

    virtual ~SelectionGenerator() {}

protected:
    random_engine_type  * m_rand;
    mate_pair_vector    m_pairs;
};

}   // namespace genetics
}   // namespace clotho

#endif  // CLOTHO_SELECTION_GENERATOR_HPP_
<commit_msg>Fixed to use local variable<commit_after>//   Copyright 2015 Patrick Putnam
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
#ifndef CLOTHO_SELECTION_GENERATOR_HPP_
#define CLOTHO_SELECTION_GENERATOR_HPP_

#include <boost/property_tree/ptree.hpp>

#include <boost/random/uniform_int_distribution.hpp>

#include <vector>

namespace clotho {
namespace genetics {

/**
 * Random selection
 */
template < class RNG, class GeneticSpaceType >
class SelectionGenerator {
public:
    typedef RNG                                                                 random_engine_type;
    typedef GeneticSpaceType                                                    genetic_space_type;
    typedef typename genetic_space_type::individual_id_type                     individual_id_type;

    typedef std::vector< std::pair< individual_id_type, individual_id_type > >  mate_pair_vector;
    typedef typename mate_pair_vector::iterator                                 parent_iterator;
    typedef typename mate_pair_vector::const_iterator                           const_parent_iterator;

    typedef typename genetic_space_type::fitness_score_type                     fitness_score_type;
    typedef typename genetic_space_type::fitness_scores                         fitness_scores;

    typedef boost::random::uniform_int_distribution< size_t >                   distribution_type;

    SelectionGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) :
        m_rand( rng )
    { }

    void update( genetic_space_type * parents, size_t count ) {
        // distribution generates numbers in range [0, N]
        // therefore N needs to be the maximum index (individual_count - 1)
        distribution_type dist( 0, parents->individual_count() - 1 );

        m_pairs.clear();

        while( count-- ) {
            individual_id_type  id0 = dist( *m_rand );
            individual_id_type  id1 = dist( *m_rand );

            m_pairs.push_back( std::make_pair( id0, id1 ) );
        }
    }

    parent_iterator begin() {
        return m_pairs.begin();
    }

    parent_iterator end() {
        return m_pairs.end();
    }

    const_parent_iterator begin() const {
        return m_pairs.begin();
    }

    const_parent_iterator end() const {
        return m_pairs.end();
    }

    mate_pair_vector & getMatePairs() {
        return m_pairs;
    }

    size_t  size() const {
        return m_pairs.size();
    }

    virtual ~SelectionGenerator() {}

protected:
    random_engine_type  * m_rand;
    mate_pair_vector    m_pairs;
};

}   // namespace genetics
}   // namespace clotho

#endif  // CLOTHO_SELECTION_GENERATOR_HPP_
<|endoftext|>