<commit_before>// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Author: David Elder
//

#include "Stdafx.h"

#include "Texture12.h"

#include "CommandList12.h"
#include "DDSTextureLoader12.h"
#include "DXGIUtility.h"
#include "DeviceManager12.h"
#include "Format.h"
#include "Paths.h"
#include "RenderUtils.h"

using namespace Kodiak;
using namespace std;

namespace
{
map<string, shared_ptr<Texture>>	s_textureMap;

enum class TextureFormat : uint32_t
{
	None,
	DDS,

	NumFormats
};

const string s_formatString[] =
{
	"none",
	"dds",
};
} // anonymous namespace

shared_ptr<Texture> Texture::Load(const string& path, bool sRGB, bool asyncLoad)
{
	shared_ptr<Texture> texture;

	{
		static mutex textureMutex;
		lock_guard<mutex> CS(textureMutex);

		auto iter = s_textureMap.find(path);

		if (iter == s_textureMap.end())
		{
			texture = make_shared<Texture>();
			s_textureMap[path] = texture;

			if (asyncLoad)
			{
				// Non-blocking asynchronous load
				texture->loadTask = concurrency::create_task([texture, sRGB, path]()
				{
					LoadInternal(texture, sRGB, path);
				});
			}
			else
			{
				// Blocking synchronous create
				texture->loadTask = concurrency::create_task([] {});
				LoadInternal(texture, sRGB, path);
			}
		}
		else
		{
			texture = iter->second;
		}
	}

	return texture;
}

void Texture::Create(uint32_t width, uint32_t height, ColorFormat format, const void* initData)
{
	m_usageState = D3D12_RESOURCE_STATE_COMMON;

	DXGI_FORMAT dxgiFormat = DXGIUtility::ConvertToDXGI(format);

	D3D12_RESOURCE_DESC texDesc = {};
	texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
	texDesc.Width = width;
	texDesc.Height = (UINT)height;
	texDesc.DepthOrArraySize = 1;
	texDesc.MipLevels = 1;
	texDesc.Format = dxgiFormat;
	texDesc.SampleDesc.Count = 1;
	texDesc.SampleDesc.Quality = 0;
	texDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
	texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

	D3D12_HEAP_PROPERTIES HeapProps;
	HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
	HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
	HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
	HeapProps.CreationNodeMask = 1;
	HeapProps.VisibleNodeMask = 1;

	ThrowIfFailed(g_device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &texDesc,
		m_usageState, nullptr, IID_PPV_ARGS(m_resource.ReleaseAndGetAddressOf())));

	m_resource->SetName(L"Texture");

	D3D12_SUBRESOURCE_DATA texResource;
	texResource.pData = initData;
	texResource.RowPitch = width * DXGIUtility::BytesPerPixel(dxgiFormat);
	texResource.SlicePitch = texResource.RowPitch * height;

	CommandList::InitializeTexture(*this, 1, &texResource);

	if (m_cpuDescriptorHandle.ptr == D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN)
	{
		m_cpuDescriptorHandle = DeviceManager::GetInstance().AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
	}
	g_device->CreateShaderResourceView(m_resource.Get(), nullptr, m_cpuDescriptorHandle);
}

void Texture::LoadInternal(shared_ptr<Texture> texture, bool sRGB, const string& path)
{
	TextureFormat format = TextureFormat::None;

	string extension;
	bool appendExtension = false;

	auto sepIndex = path.rfind('.');
	if (sepIndex != string::npos)
	{
		string extension = path.substr(sepIndex + 1);
		transform(begin(extension), end(extension), begin(extension), ::tolower);

		for (uint32_t i = 0; i < static_cast<uint32_t>(TextureFormat::NumFormats); ++i)
		{
			if (extension == s_formatString[i])
			{
				format = static_cast<TextureFormat>(i);
				break;
			}
		}
	}
	else
	{
		// Assume .dds if there is no extension
		format = TextureFormat::DDS;
		extension = ".dds";
		appendExtension = true;
	}

	if (format != TextureFormat::None)
	{
		string fullPath = Paths::GetInstance().TextureDir() + path;
		if (appendExtension)
		{
			fullPath += extension;
		}

		switch (format)
		{
		case TextureFormat::DDS:

			texture->m_cpuDescriptorHandle = DeviceManager::GetInstance().AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);

			ThrowIfFailed(CreateDDSTextureFromFile(g_device,
				fullPath,
				0, // maxsize
				sRGB,
				texture->m_resource.GetAddressOf(),
				texture->m_cpuDescriptorHandle));
			break;
		}
	}
}<commit_msg>Fixed some bugs in DX12 texture loader.<commit_after>// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
// Author: David Elder
//

#include "Stdafx.h"

#include "Texture12.h"

#include "CommandList12.h"
#include "DDSTextureLoader12.h"
#include "DXGIUtility.h"
#include "DeviceManager12.h"
#include "Format.h"
#include "Paths.h"
#include "RenderUtils.h"

#include <Shlwapi.h>

using namespace Kodiak;
using namespace std;

namespace
{
map<string, shared_ptr<Texture>>	s_textureMap;

enum class TextureFormat : uint32_t
{
	None,
	DDS,

	NumFormats
};

const string s_formatString[] =
{
	"none",
	"dds",
};
} // anonymous namespace

shared_ptr<Texture> Texture::Load(const string& path, bool sRGB, bool asyncLoad)
{
	shared_ptr<Texture> texture;

	{
		static mutex textureMutex;
		lock_guard<mutex> CS(textureMutex);

		auto iter = s_textureMap.find(path);

		if (iter == s_textureMap.end())
		{
			if (!PathFileExistsA(path.c_str()))
			{
				return nullptr;
			}

			texture = make_shared<Texture>();
			s_textureMap[path] = texture;

			if (asyncLoad)
			{
				// Non-blocking asynchronous load
				texture->loadTask = concurrency::create_task([texture, sRGB, path]()
				{
					LoadInternal(texture, sRGB, path);
				});
			}
			else
			{
				// Blocking synchronous create
				texture->loadTask = concurrency::create_task([] {});
				LoadInternal(texture, sRGB, path);
			}
		}
		else
		{
			texture = iter->second;
		}
	}

	return texture;
}

void Texture::Create(uint32_t width, uint32_t height, ColorFormat format, const void* initData)
{
	m_usageState = D3D12_RESOURCE_STATE_COMMON;

	DXGI_FORMAT dxgiFormat = DXGIUtility::ConvertToDXGI(format);

	D3D12_RESOURCE_DESC texDesc = {};
	texDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
	texDesc.Width = width;
	texDesc.Height = (UINT)height;
	texDesc.DepthOrArraySize = 1;
	texDesc.MipLevels = 1;
	texDesc.Format = dxgiFormat;
	texDesc.SampleDesc.Count = 1;
	texDesc.SampleDesc.Quality = 0;
	texDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
	texDesc.Flags = D3D12_RESOURCE_FLAG_NONE;

	D3D12_HEAP_PROPERTIES HeapProps;
	HeapProps.Type = D3D12_HEAP_TYPE_DEFAULT;
	HeapProps.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
	HeapProps.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
	HeapProps.CreationNodeMask = 1;
	HeapProps.VisibleNodeMask = 1;

	ThrowIfFailed(g_device->CreateCommittedResource(&HeapProps, D3D12_HEAP_FLAG_NONE, &texDesc,
		m_usageState, nullptr, IID_PPV_ARGS(m_resource.ReleaseAndGetAddressOf())));

	m_resource->SetName(L"Texture");

	D3D12_SUBRESOURCE_DATA texResource;
	texResource.pData = initData;
	texResource.RowPitch = width * DXGIUtility::BytesPerPixel(dxgiFormat);
	texResource.SlicePitch = texResource.RowPitch * height;

	CommandList::InitializeTexture(*this, 1, &texResource);

	if (m_cpuDescriptorHandle.ptr == D3D12_GPU_VIRTUAL_ADDRESS_UNKNOWN)
	{
		m_cpuDescriptorHandle = DeviceManager::GetInstance().AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
	}
	g_device->CreateShaderResourceView(m_resource.Get(), nullptr, m_cpuDescriptorHandle);
}

void Texture::LoadInternal(shared_ptr<Texture> texture, bool sRGB, const string& path)
{
	TextureFormat format = TextureFormat::None;

	string extension;
	bool appendExtension = false;

	auto sepIndex = path.rfind('.');
	if (sepIndex != string::npos)
	{
		string extension = path.substr(sepIndex + 1);
		transform(begin(extension), end(extension), begin(extension), ::tolower);

		for (uint32_t i = 0; i < static_cast<uint32_t>(TextureFormat::NumFormats); ++i)
		{
			if (extension == s_formatString[i])
			{
				format = static_cast<TextureFormat>(i);
				break;
			}
		}
	}
	else
	{
		// Assume .dds if there is no extension
		format = TextureFormat::DDS;
		extension = ".dds";
		appendExtension = true;
	}

	if (format != TextureFormat::None)
	{
		switch (format)
		{
		case TextureFormat::DDS:

			texture->m_cpuDescriptorHandle = DeviceManager::GetInstance().AllocateDescriptor(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);

			ThrowIfFailed(CreateDDSTextureFromFile(g_device,
				path,
				0, // maxsize
				sRGB,
				texture->m_resource.GetAddressOf(),
				texture->m_cpuDescriptorHandle));
			break;
		}
	}
}<|endoftext|>


<commit_before>/* Copyright 2016 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 <stdio.h>
#include <set>

#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/tools/proto_text/gen_proto_text_functions_lib.h"

namespace tensorflow {

namespace {
class CrashOnErrorCollector
    : public tensorflow::protobuf::compiler::MultiFileErrorCollector {
 public:
  ~CrashOnErrorCollector() override {}

  void AddError(const string& filename, int line, int column,
                const string& message) override {
    LOG(FATAL) << "Unexpected error at " << filename << "@" << line << ":"
               << column << " - " << message;
  }
};

static const char kTensorFlowHeaderPrefix[] = "";

static const char kPlaceholderFile[] =
    "tensorflow/tools/proto_text/placeholder.txt";

bool IsPlaceholderFile(const char* s) {
  string ph(kPlaceholderFile);
  string str(s);
  return str.size() >= strlen(kPlaceholderFile) &&
         ph == str.substr(str.size() - ph.size());
}

}  // namespace

// Main program to take input protos and write output pb_text source files that
// contain generated proto text input and output functions.
//
// Main expects:
// - First argument is output path
// - Second argument is the relative path of the protos to the root. E.g.,
//   for protos built by a rule in tensorflow/core, this will be
//   tensorflow/core.
// - Then any number of source proto file names, plus one source name must be
//   placeholder.txt from this gen tool's package.  placeholder.txt is
//   ignored for proto resolution, but is used to determine the root at which
//   the build tool has placed the source proto files.
//
// Note that this code doesn't use tensorflow's command line parsing, because of
// circular dependencies between libraries if that were done.
//
// This is meant to be invoked by a genrule. See BUILD for more information.
int MainImpl(int argc, char** argv) {
  if (argc < 4) {
    LOG(ERROR) << "Pass output path, relative path, and at least proto file";
    return -1;
  }

  const string output_root = argv[1];
  const string output_relative_path = kTensorFlowHeaderPrefix + string(argv[2]);

  string src_relative_path;
  bool has_placeholder = false;
  for (int i = 3; i < argc; ++i) {
    if (IsPlaceholderFile(argv[i])) {
      const string s(argv[i]);
      src_relative_path = s.substr(0, s.size() - strlen(kPlaceholderFile));
      has_placeholder = true;
    }
  }
  if (!has_placeholder) {
    LOG(ERROR) << kPlaceholderFile << " must be passed";
    return -1;
  }

  tensorflow::protobuf::compiler::DiskSourceTree source_tree;

  source_tree.MapPath("", src_relative_path.empty() ? "." : src_relative_path);
  CrashOnErrorCollector crash_on_error;
  tensorflow::protobuf::compiler::Importer importer(&source_tree,
                                                    &crash_on_error);

  for (int i = 3; i < argc; i++) {
    if (IsPlaceholderFile(argv[i])) continue;
    const string proto_path = string(argv[i]).substr(src_relative_path.size());

    const tensorflow::protobuf::FileDescriptor* fd =
        importer.Import(proto_path);

    const int index = proto_path.find_last_of(".");
    string proto_path_no_suffix = proto_path.substr(0, index);

    proto_path_no_suffix =
        proto_path_no_suffix.substr(output_relative_path.size());

    const auto code =
        tensorflow::GetProtoTextFunctionCode(*fd, kTensorFlowHeaderPrefix);

    // Three passes, one for each output file.
    for (int pass = 0; pass < 3; ++pass) {
      string suffix;
      string data;
      if (pass == 0) {
        suffix = ".pb_text.h";
        data = code.header;
      } else if (pass == 1) {
        suffix = ".pb_text-impl.h";
        data = code.header_impl;
      } else {
        suffix = ".pb_text.cc";
        data = code.cc;
      }

      const string path = output_root + "/" + proto_path_no_suffix + suffix;
      FILE* f = fopen(path.c_str(), "w");
      if (fwrite(data.c_str(), 1, data.size(), f) != data.size()) {
        return -1;
      }
      if (fclose(f) != 0) {
        return -1;
      }
    }
  }
  return 0;
}

}  // namespace tensorflow

int main(int argc, char** argv) { return tensorflow::MainImpl(argc, argv); }
<commit_msg>Check the return value of fopen (#9964)<commit_after>/* Copyright 2016 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 <stdio.h>
#include <set>

#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/tools/proto_text/gen_proto_text_functions_lib.h"

namespace tensorflow {

namespace {
class CrashOnErrorCollector
    : public tensorflow::protobuf::compiler::MultiFileErrorCollector {
 public:
  ~CrashOnErrorCollector() override {}

  void AddError(const string& filename, int line, int column,
                const string& message) override {
    LOG(FATAL) << "Unexpected error at " << filename << "@" << line << ":"
               << column << " - " << message;
  }
};

static const char kTensorFlowHeaderPrefix[] = "";

static const char kPlaceholderFile[] =
    "tensorflow/tools/proto_text/placeholder.txt";

bool IsPlaceholderFile(const char* s) {
  string ph(kPlaceholderFile);
  string str(s);
  return str.size() >= strlen(kPlaceholderFile) &&
         ph == str.substr(str.size() - ph.size());
}

}  // namespace

// Main program to take input protos and write output pb_text source files that
// contain generated proto text input and output functions.
//
// Main expects:
// - First argument is output path
// - Second argument is the relative path of the protos to the root. E.g.,
//   for protos built by a rule in tensorflow/core, this will be
//   tensorflow/core.
// - Then any number of source proto file names, plus one source name must be
//   placeholder.txt from this gen tool's package.  placeholder.txt is
//   ignored for proto resolution, but is used to determine the root at which
//   the build tool has placed the source proto files.
//
// Note that this code doesn't use tensorflow's command line parsing, because of
// circular dependencies between libraries if that were done.
//
// This is meant to be invoked by a genrule. See BUILD for more information.
int MainImpl(int argc, char** argv) {
  if (argc < 4) {
    LOG(ERROR) << "Pass output path, relative path, and at least proto file";
    return -1;
  }

  const string output_root = argv[1];
  const string output_relative_path = kTensorFlowHeaderPrefix + string(argv[2]);

  string src_relative_path;
  bool has_placeholder = false;
  for (int i = 3; i < argc; ++i) {
    if (IsPlaceholderFile(argv[i])) {
      const string s(argv[i]);
      src_relative_path = s.substr(0, s.size() - strlen(kPlaceholderFile));
      has_placeholder = true;
    }
  }
  if (!has_placeholder) {
    LOG(ERROR) << kPlaceholderFile << " must be passed";
    return -1;
  }

  tensorflow::protobuf::compiler::DiskSourceTree source_tree;

  source_tree.MapPath("", src_relative_path.empty() ? "." : src_relative_path);
  CrashOnErrorCollector crash_on_error;
  tensorflow::protobuf::compiler::Importer importer(&source_tree,
                                                    &crash_on_error);

  for (int i = 3; i < argc; i++) {
    if (IsPlaceholderFile(argv[i])) continue;
    const string proto_path = string(argv[i]).substr(src_relative_path.size());

    const tensorflow::protobuf::FileDescriptor* fd =
        importer.Import(proto_path);

    const int index = proto_path.find_last_of(".");
    string proto_path_no_suffix = proto_path.substr(0, index);

    proto_path_no_suffix =
        proto_path_no_suffix.substr(output_relative_path.size());

    const auto code =
        tensorflow::GetProtoTextFunctionCode(*fd, kTensorFlowHeaderPrefix);

    // Three passes, one for each output file.
    for (int pass = 0; pass < 3; ++pass) {
      string suffix;
      string data;
      if (pass == 0) {
        suffix = ".pb_text.h";
        data = code.header;
      } else if (pass == 1) {
        suffix = ".pb_text-impl.h";
        data = code.header_impl;
      } else {
        suffix = ".pb_text.cc";
        data = code.cc;
      }

      const string path = output_root + "/" + proto_path_no_suffix + suffix;
      FILE* f = fopen(path.c_str(), "w");
      if (f == nullptr) return -1;
      if (fwrite(data.c_str(), 1, data.size(), f) != data.size()) {
        return -1;
      }
      if (fclose(f) != 0) {
        return -1;
      }
    }
  }
  return 0;
}

}  // namespace tensorflow

int main(int argc, char** argv) { return tensorflow::MainImpl(argc, argv); }
<|endoftext|>


<commit_before>#include "UnrealEnginePythonPrivatePCH.h"

static PyMethodDef ue_PyFTransform_methods[] = {

	{ NULL }  /* Sentinel */
};

static PyObject *py_ue_ftransform_get_translation(ue_PyFTransform *self, void *closure) {
	return py_ue_new_fvector(self->transform.GetTranslation());
}

static PyObject *py_ue_ftransform_get_scale(ue_PyFTransform *self, void *closure) {
	return py_ue_new_fvector(self->transform.GetScale3D());
}

static PyObject *py_ue_ftransform_get_rotation(ue_PyFTransform *self, void *closure) {
	return py_ue_new_frotator(self->transform.GetRotation().Rotator());
}

static int py_ue_ftransform_set_translation(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFVector *py_vec = py_ue_is_fvector(value)) {
		self->transform.SetLocation(py_vec->vec);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a vector");
	return -1;
}

static int py_ue_ftransform_set_rotation(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFRotator *py_rot = py_ue_is_frotator(value)) {
		self->transform.SetRotation(py_rot->rot.Quaternion());
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a rotator");
	return -1;
}

static int py_ue_ftransform_set_scale(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFVector *py_vec = py_ue_is_fvector(value)) {
		self->transform.SetScale3D(py_vec->vec);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a vector");
	return -1;
}

static PyGetSetDef ue_PyFTransform_getseters[] = {
	{(char *) "translation", (getter)py_ue_ftransform_get_translation, (setter)py_ue_ftransform_set_translation, (char *)"", NULL },
	{(char *) "scale", (getter)py_ue_ftransform_get_scale, (setter)py_ue_ftransform_set_scale, (char *)"", NULL },
	{(char *) "rotation", (getter)py_ue_ftransform_get_rotation, (setter)py_ue_ftransform_set_rotation, (char *)"", NULL },
	{ NULL }  /* Sentinel */
};

static PyTypeObject ue_PyFTransformType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.FTransform", /* tp_name */
	sizeof(ue_PyFTransform), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	0,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,        /* tp_flags */
	"Unreal Engine FTransform",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PyFTransform_methods,             /* tp_methods */
	0,
	ue_PyFTransform_getseters,
};

static int ue_py_ftransform_init(ue_PyFTransform *self, PyObject *args, PyObject *kwargs) {
	PyObject *py_translation = nullptr;
	PyObject *py_rotation = nullptr;
	PyObject *py_scale = nullptr;
	if (!PyArg_ParseTuple(args, "|OOO:__init__", &py_translation, &py_rotation, &py_scale)) {
		return -1;
	}

	if (py_translation) {
		if (ue_PyFVector *py_vec = py_ue_is_fvector(py_translation)) {
			self->transform.SetTranslation(py_vec->vec);
		}
	}

	if (py_rotation) {
		if (ue_PyFRotator *py_rot = py_ue_is_frotator(py_rotation)) {
			self->transform.SetRotation(py_rot->rot.Quaternion());
		}
	}

	// ensure scaling is set to 1,1,1
	FVector scale(1, 1, 1);

	if (py_scale) {
		if (ue_PyFVector *py_vec = py_ue_is_fvector(py_scale)) {
			scale = py_vec->vec;
		}
	}
	self->transform.SetScale3D(scale);
	return 0;
}

void ue_python_init_ftransform(PyObject *ue_module) {
	ue_PyFTransformType.tp_new = PyType_GenericNew;

	ue_PyFTransformType.tp_init = (initproc)ue_py_ftransform_init;

	if (PyType_Ready(&ue_PyFTransformType) < 0)
		return;

	Py_INCREF(&ue_PyFTransformType);
	PyModule_AddObject(ue_module, "FTransform", (PyObject *)&ue_PyFTransformType);
}

PyObject *py_ue_new_ftransform(FTransform transform) {
	ue_PyFTransform *ret = (ue_PyFTransform *)PyObject_New(ue_PyFTransform, &ue_PyFTransformType);
	ret->transform = transform;
	return (PyObject *)ret;
}

ue_PyFTransform *py_ue_is_ftransform(PyObject *obj) {
	if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFTransformType))
		return nullptr;
	return (ue_PyFTransform *)obj;
}

bool py_ue_transform_arg(PyObject *args, FTransform &t) {

	if (PyTuple_Size(args) == 1) {
		PyObject *arg = PyTuple_GetItem(args, 0);
		ue_PyFTransform *py_t = py_ue_is_ftransform(arg);
		if (!py_t) {
			PyErr_Format(PyExc_TypeError, "argument is not a FTransform");
			return false;
		}
		t = py_t->transform;
		return true;
	}

	float x, y, z;
	float roll, pitch, yaw;
	float sx, sy, sz;
	if (!PyArg_ParseTuple(args, "fffffffff", &x, &y, &z, &roll, &pitch, &yaw, &sx, &sy, &sz))
		return false;

	t.SetLocation(FVector(x, y, z));
	t.SetRotation(FRotator(pitch, yaw, roll).Quaternion());
	t.SetScale3D(FVector(sx, sy, sz));
	return true;
}<commit_msg>support Fquat in Ftransform<commit_after>#include "UnrealEnginePythonPrivatePCH.h"

static PyMethodDef ue_PyFTransform_methods[] = {

	{ NULL }  /* Sentinel */
};

static PyObject *py_ue_ftransform_get_translation(ue_PyFTransform *self, void *closure) {
	return py_ue_new_fvector(self->transform.GetTranslation());
}

static PyObject *py_ue_ftransform_get_scale(ue_PyFTransform *self, void *closure) {
	return py_ue_new_fvector(self->transform.GetScale3D());
}

static PyObject *py_ue_ftransform_get_rotation(ue_PyFTransform *self, void *closure) {
	return py_ue_new_frotator(self->transform.GetRotation().Rotator());
}

static int py_ue_ftransform_set_translation(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFVector *py_vec = py_ue_is_fvector(value)) {
		self->transform.SetLocation(py_vec->vec);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a vector");
	return -1;
}

static int py_ue_ftransform_set_rotation(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFRotator *py_rot = py_ue_is_frotator(value)) {
		self->transform.SetRotation(py_rot->rot.Quaternion());
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a rotator");
	return -1;
}

static int py_ue_ftransform_set_scale(ue_PyFTransform *self, PyObject *value, void *closure) {
	if (ue_PyFVector *py_vec = py_ue_is_fvector(value)) {
		self->transform.SetScale3D(py_vec->vec);
		return 0;
	}
	PyErr_SetString(PyExc_TypeError, "value is not a vector");
	return -1;
}

static PyGetSetDef ue_PyFTransform_getseters[] = {
	{(char *) "translation", (getter)py_ue_ftransform_get_translation, (setter)py_ue_ftransform_set_translation, (char *)"", NULL },
	{(char *) "scale", (getter)py_ue_ftransform_get_scale, (setter)py_ue_ftransform_set_scale, (char *)"", NULL },
	{(char *) "rotation", (getter)py_ue_ftransform_get_rotation, (setter)py_ue_ftransform_set_rotation, (char *)"", NULL },
	{ NULL }  /* Sentinel */
};

static PyTypeObject ue_PyFTransformType = {
	PyVarObject_HEAD_INIT(NULL, 0)
	"unreal_engine.FTransform", /* tp_name */
	sizeof(ue_PyFTransform), /* tp_basicsize */
	0,                         /* tp_itemsize */
	0,       /* tp_dealloc */
	0,                         /* tp_print */
	0,                         /* tp_getattr */
	0,                         /* tp_setattr */
	0,                         /* tp_reserved */
	0,                         /* tp_repr */
	0,                         /* tp_as_number */
	0,                         /* tp_as_sequence */
	0,                         /* tp_as_mapping */
	0,                         /* tp_hash  */
	0,                         /* tp_call */
	0,                         /* tp_str */
	0,                         /* tp_getattro */
	0,                         /* tp_setattro */
	0,                         /* tp_as_buffer */
	Py_TPFLAGS_DEFAULT,        /* tp_flags */
	"Unreal Engine FTransform",           /* tp_doc */
	0,                         /* tp_traverse */
	0,                         /* tp_clear */
	0,                         /* tp_richcompare */
	0,                         /* tp_weaklistoffset */
	0,                         /* tp_iter */
	0,                         /* tp_iternext */
	ue_PyFTransform_methods,             /* tp_methods */
	0,
	ue_PyFTransform_getseters,
};

static int ue_py_ftransform_init(ue_PyFTransform *self, PyObject *args, PyObject *kwargs) {
	PyObject *py_translation = nullptr;
	PyObject *py_rotation = nullptr;
	PyObject *py_scale = nullptr;
	if (!PyArg_ParseTuple(args, "|OOO:__init__", &py_translation, &py_rotation, &py_scale)) {
		return -1;
	}

	if (py_translation) {
		if (ue_PyFVector *py_vec = py_ue_is_fvector(py_translation)) {
			self->transform.SetTranslation(py_vec->vec);
		}
		else {
			PyErr_SetString(PyExc_Exception, "argument is not a FVector");
			return -1;
		}
	}

	if (py_rotation) {
		if (ue_PyFRotator *py_rot = py_ue_is_frotator(py_rotation)) {
			self->transform.SetRotation(py_rot->rot.Quaternion());
		}
		else if (ue_PyFQuat *py_quat = py_ue_is_fquat(py_rotation)) {
			self->transform.SetRotation(py_quat->quat);
		}
		else {
			PyErr_SetString(PyExc_Exception, "argument is not a FRotator or a FQuat");
			return -1;
		}
	}

	// ensure scaling is set to 1,1,1
	FVector scale(1, 1, 1);

	if (py_scale) {
		if (ue_PyFVector *py_vec = py_ue_is_fvector(py_scale)) {
			scale = py_vec->vec;
		}
		else {
			PyErr_SetString(PyExc_Exception, "argument is not a FVector");
			return -1;
		}
	}
	self->transform.SetScale3D(scale);
	return 0;
}

void ue_python_init_ftransform(PyObject *ue_module) {
	ue_PyFTransformType.tp_new = PyType_GenericNew;

	ue_PyFTransformType.tp_init = (initproc)ue_py_ftransform_init;

	if (PyType_Ready(&ue_PyFTransformType) < 0)
		return;

	Py_INCREF(&ue_PyFTransformType);
	PyModule_AddObject(ue_module, "FTransform", (PyObject *)&ue_PyFTransformType);
}

PyObject *py_ue_new_ftransform(FTransform transform) {
	ue_PyFTransform *ret = (ue_PyFTransform *)PyObject_New(ue_PyFTransform, &ue_PyFTransformType);
	ret->transform = transform;
	return (PyObject *)ret;
}

ue_PyFTransform *py_ue_is_ftransform(PyObject *obj) {
	if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFTransformType))
		return nullptr;
	return (ue_PyFTransform *)obj;
}

bool py_ue_transform_arg(PyObject *args, FTransform &t) {

	if (PyTuple_Size(args) == 1) {
		PyObject *arg = PyTuple_GetItem(args, 0);
		ue_PyFTransform *py_t = py_ue_is_ftransform(arg);
		if (!py_t) {
			PyErr_Format(PyExc_TypeError, "argument is not a FTransform");
			return false;
		}
		t = py_t->transform;
		return true;
	}

	float x, y, z;
	float roll, pitch, yaw;
	float sx, sy, sz;
	if (!PyArg_ParseTuple(args, "fffffffff", &x, &y, &z, &roll, &pitch, &yaw, &sx, &sy, &sz))
		return false;

	t.SetLocation(FVector(x, y, z));
	t.SetRotation(FRotator(pitch, yaw, roll).Quaternion());
	t.SetScale3D(FVector(sx, sy, sz));
	return true;
}<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

/// @file Water.cpp
/// @brief Manages Water-related Rex logic.

#include "StableHeaders.h"
#include "Water.h"
#include "EnvironmentModule.h"

// Ogre renderer -specific.
#include <OgreManualObject.h>
#include <OgreSceneManager.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreIteratorWrappers.h>
#include <OgreTechnique.h>

#include "EC_OgrePlaceable.h"
#include "EC_WaterPlane.h"
#include "Renderer.h"
#include "OgreTextureResource.h"
#include "OgreMaterialUtils.h"
#include "SceneManager.h"

namespace Environment
{

Water::Water(EnvironmentModule *owner) :
    owner_(owner)
{
}

Water::~Water()
{
      owner_ = 0;
}

void Water::CreateWaterGeometry(float height, AttributeChange::Type type)
{
    // Is there entity

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
    {
         owner_->CreateEnvironmentEntity(EC_WaterPlane::TypeNameStatic());
         plane = GetEnvironmentWaterComponent();
         if ( plane == 0)
             return;
    }

    Vector3df vec = plane->positionAttr_.Get();
    vec.z = height;
    plane->positionAttr_.Set(vec, type);
    plane->ComponentChanged(type);

    //emit WaterCreated();

 }

void Water::RemoveWaterGeometry()
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if ( entity == 0)
        return;
    else
    {
        entity->RemoveComponent(entity->GetComponent(EC_WaterPlane::TypeNameStatic()),AttributeChange::Local);
    }

    //emit WaterRemoved();
}

void Water::Update()
{
    // This is a hack, because of enviroment entity comes after then RexWater- package. We create LocalEnviroment-entity.
    // Now we need to update scene, if there exist a real enviroment entity, so that we do not get two ocean water planes.

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane != 0)
    {
        emit ExistWater(true);
    }
    else
    {
        emit ExistWater(false);
    }
}

void Water::SetWaterHeight(float height, AttributeChange::Type type)
{

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return;

    Vector3df vec = plane->positionAttr_.Get();
    vec.z = height;
    plane->positionAttr_.Set(vec, type);
    plane->ComponentChanged(type);
    emit HeightChanged(static_cast<double>(height));

}

EC_WaterPlane* Water::GetEnvironmentWaterComponent()
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if ( entity == 0)
        entity = owner_->CreateEnvironmentEntity(EC_WaterPlane::TypeNameStatic()).get();
    else
        owner_->RemoveLocalEnvironment();

    EC_WaterPlane* plane = entity->GetComponent<EC_WaterPlane >().get();

    return plane;
}

bool Water::IsWaterPlane() const
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if ( entity == 0)
    {
        entity = active_scene->GetEntityByName("LocalEnvironment").get();
        if ( entity == 0)
            return false;
    }

    if (  entity->GetComponent<EC_WaterPlane >().get() != 0)
        return true;

    return false;
}

float Water::GetWaterHeight()
{
    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return 0.0;

    return plane->positionAttr_.Get().z;

}

void Water::SetWaterFog(float fogStart, float fogEnd, const QVector<float>& color)
{
    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     if ( plane == 0)
        return;

    plane->fogStartAttr_.Set(fogStart,AttributeChange::Local);
    plane->fogEndAttr_.Set(fogEnd, AttributeChange::Local);
    plane->fogColorAttr_.Set(Color(color[0], color[1], color[2],1.0), AttributeChange::Local);
    plane->ComponentChanged(AttributeChange::Local);

    emit WaterFogAdjusted(fogStart, fogEnd, color);

}

QVector<float> Water::GetFogWaterColor()
{

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     if ( plane == 0)
        return QVector<float>();

    Ogre::ColourValue color = plane->GetFogColorAsOgreValue();
    QVector<float> vec;
    vec<<color[0]<<color[1]<<color[2];
    return vec;

}

void Water::SetWaterFogColor(const QVector<float>& color)
{
   EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return;

   Color col(color[0], color[1], color[2],1.0);
   plane->fogColorAttr_.Set(col, AttributeChange::Local);
   plane->ComponentChanged(AttributeChange::Local);

}

void Water::SetWaterFogDistance(float fogStart, float fogEnd)
{
  EC_WaterPlane* plane = GetEnvironmentWaterComponent();
  if ( plane == 0)
        return;

  plane->fogStartAttr_.Set(fogStart, AttributeChange::Local);
  plane->fogEndAttr_.Set(fogEnd, AttributeChange::Local);
  plane->ComponentChanged(AttributeChange::Local);

}

float Water::GetWaterFogStartDistance()
{
  EC_WaterPlane* plane = GetEnvironmentWaterComponent();
  return plane->fogStartAttr_.Get();

}

float Water::GetWaterFogEndDistance()
{
     EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     return plane->fogEndAttr_.Get();

}

}
<commit_msg>Fixed a small bug in widget synchronization.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

/// @file Water.cpp
/// @brief Manages Water-related Rex logic.

#include "StableHeaders.h"
#include "Water.h"
#include "EnvironmentModule.h"

// Ogre renderer -specific.
#include <OgreManualObject.h>
#include <OgreSceneManager.h>
#include <OgreMaterialManager.h>
#include <OgreTextureManager.h>
#include <OgreIteratorWrappers.h>
#include <OgreTechnique.h>

#include "EC_OgrePlaceable.h"
#include "EC_WaterPlane.h"
#include "Renderer.h"
#include "OgreTextureResource.h"
#include "OgreMaterialUtils.h"
#include "SceneManager.h"

namespace Environment
{

Water::Water(EnvironmentModule *owner) :
    owner_(owner)
{
}

Water::~Water()
{
      owner_ = 0;
}

void Water::CreateWaterGeometry(float height, AttributeChange::Type type)
{
    // Is there entity

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
    {
         owner_->CreateEnvironmentEntity(EC_WaterPlane::TypeNameStatic());
         plane = GetEnvironmentWaterComponent();
         if ( plane == 0)
             return;
    }

    Vector3df vec = plane->positionAttr_.Get();
    vec.z = height;
    plane->positionAttr_.Set(vec, type);
    plane->ComponentChanged(type);

 }

void Water::RemoveWaterGeometry()
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if ( entity == 0)
    {
       entity = active_scene->GetEntityByName("LocalEnvironment").get();
       if ( entity == 0)
           return;
    }

    entity->RemoveComponent(entity->GetComponent(EC_WaterPlane::TypeNameStatic()),AttributeChange::Local);

}

void Water::Update()
{
    // This is a hack, because of enviroment entity comes after then RexWater- package. We create LocalEnviroment-entity.
    // Now we need to update scene, if there exist a real enviroment entity, so that we do not get two ocean water planes.

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( IsWaterPlane())
    {
        emit ExistWater(true);
    }
    else
    {
        emit ExistWater(false);
    }
}

void Water::SetWaterHeight(float height, AttributeChange::Type type)
{

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return;

    Vector3df vec = plane->positionAttr_.Get();
    vec.z = height;
    plane->positionAttr_.Set(vec, type);
    plane->ComponentChanged(type);
    emit HeightChanged(static_cast<double>(height));

}

EC_WaterPlane* Water::GetEnvironmentWaterComponent()
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if (entity != 0 )
        owner_->RemoveLocalEnvironment();
    else
    {
        entity =  active_scene->GetEntityByName("LocalEnvironment").get();
        if ( entity == 0)
            return 0;
    }

    EC_WaterPlane* plane = entity->GetComponent<EC_WaterPlane >().get();

    return plane;
}

bool Water::IsWaterPlane() const
{
    Scene::ScenePtr active_scene = owner_->GetFramework()->GetDefaultWorldScene();
    Scene::Entity* entity = active_scene->GetEntityByName("Environment").get();

    if ( entity == 0)
    {
        entity = active_scene->GetEntityByName("LocalEnvironment").get();
        if ( entity == 0)
            return false;
    }

    if (  entity->GetComponent<EC_WaterPlane >().get() != 0)
        return true;

    return false;
}

float Water::GetWaterHeight()
{
    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return 0.0;

    return plane->positionAttr_.Get().z;

}

void Water::SetWaterFog(float fogStart, float fogEnd, const QVector<float>& color)
{
    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     if ( plane == 0)
        return;

    plane->fogStartAttr_.Set(fogStart,AttributeChange::Local);
    plane->fogEndAttr_.Set(fogEnd, AttributeChange::Local);
    plane->fogColorAttr_.Set(Color(color[0], color[1], color[2],1.0), AttributeChange::Local);
    plane->ComponentChanged(AttributeChange::Local);

    emit WaterFogAdjusted(fogStart, fogEnd, color);

}

QVector<float> Water::GetFogWaterColor()
{

    EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     if ( plane == 0)
        return QVector<float>();

    Ogre::ColourValue color = plane->GetFogColorAsOgreValue();
    QVector<float> vec;
    vec<<color[0]<<color[1]<<color[2];
    return vec;

}

void Water::SetWaterFogColor(const QVector<float>& color)
{
   EC_WaterPlane* plane = GetEnvironmentWaterComponent();
    if ( plane == 0)
        return;

   Color col(color[0], color[1], color[2],1.0);
   plane->fogColorAttr_.Set(col, AttributeChange::Local);
   plane->ComponentChanged(AttributeChange::Local);

}

void Water::SetWaterFogDistance(float fogStart, float fogEnd)
{
  EC_WaterPlane* plane = GetEnvironmentWaterComponent();
  if ( plane == 0)
        return;

  plane->fogStartAttr_.Set(fogStart, AttributeChange::Local);
  plane->fogEndAttr_.Set(fogEnd, AttributeChange::Local);
  plane->ComponentChanged(AttributeChange::Local);

}

float Water::GetWaterFogStartDistance()
{
  EC_WaterPlane* plane = GetEnvironmentWaterComponent();
  return plane->fogStartAttr_.Get();

}

float Water::GetWaterFogEndDistance()
{
     EC_WaterPlane* plane = GetEnvironmentWaterComponent();
     return plane->fogEndAttr_.Get();

}

}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageRegistrationMethodTest_15.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"

#include "itkTextOutput.h"
#include "itkImageRegionIterator.h"
#include "itkCommandIterationUpdate.h"

namespace
{

double F( itk::Vector<double,3> & v );
}

/**
 *  This program test one instantiation of the itk::ImageRegistrationMethod class
 *
 *  This file tests the combination of:
 *   - MattesMutualInformation
 *   - AffineTransform
 *   - GradientDescentOptimizer
 *   - BSplineInterpolateImageFunction
 *
 *  The test image pattern consists of a 3D gaussian in the middle
 *  with some directional pattern on the outside.
 *  One image is scaled and shifted relative to the other.
 *
 * Notes:
 * =======
 * This example performs an affine registration
 * between a moving (source) and fixed (target) image using mutual information.
 * It uses a simple steepest descent optimizer to find the
 * best affine transform to register the moving image onto the fixed
 * image.
 *
 * The mutual information value and its derivatives are estimated
 * using spatial sampling.
 *
 * The registration uses a simple stochastic gradient ascent scheme. Steps
 * are repeatedly taken that are proportional to the approximate
 * deriviative of the mutual information with respect to the affine
 * transform parameters. The stepsize is governed by the LearningRate
 * parameter.
 *
 * Since the parameters of the linear part is different in magnitude
 * to the parameters in the offset part, scaling is required
 * to improve convergence. The scaling can set via the optimizer.
 *
 * In the optimizer's scale transform set the scaling for
 * all the translation parameters to TranslationScale^{-2}.
 * Set the scale for all other parameters to 1.0.
 *
 * Note: the optimization performance can be improved by
 * setting the image origin to center of mass of the image.
 *
 */
int itkImageRegistrationMethodTest_15(int, char* [] )
{

  itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());

  bool pass = true;

  const unsigned int dimension = 3;
  unsigned int j;

  typedef float  PixelType;

  // Fixed Image Type
  typedef itk::Image<PixelType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<PixelType,dimension>               MovingImageType;

  // Transform Type
  typedef itk::AffineTransform< double,dimension >  TransformType;

  // Optimizer Type
  typedef itk::GradientDescentOptimizer             OptimizerType;

  // Metric Type
  typedef itk::MattesMutualInformationImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: BSplineInterpolateImageFunction<
                                    MovingImageType,
                                    double          >    InterpolatorType;

  // Registration Method
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  MetricType::Pointer         metric        = MetricType::New();
  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  /*********************************************************
   * Set up the two input images.
   * One image scaled and shifted with respect to the other.
   **********************************************************/
  double displacement[dimension] = {3,1,1};
  double scale[dimension] = { 0.90, 1.0, 1.0 };

  FixedImageType::SizeType size = {{100,100,40}};
  FixedImageType::IndexType index = {{0,0,0}};
  FixedImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  fixedImage->SetLargestPossibleRegion( region );
  fixedImage->SetBufferedRegion( region );
  fixedImage->SetRequestedRegion( region );
  fixedImage->Allocate();

  movingImage->SetLargestPossibleRegion( region );
  movingImage->SetBufferedRegion( region );
  movingImage->SetRequestedRegion( region );
  movingImage->Allocate();

  typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator;
  typedef itk::ImageRegionIterator<FixedImageType> FixedImageIterator;

  itk::Point<double,dimension> center;
  for ( j = 0; j < dimension; j++ )
    {
    center[j] = 0.5 *  (double)region.GetSize()[j];
    }

  itk::Point<double,dimension> p;
  itk::Vector<double,dimension> d;

  MovingImageIterator mIter( movingImage, region );
  FixedImageIterator  fIter( fixedImage, region );

  while( !mIter.IsAtEnd() )
    {
    for ( j = 0; j < dimension; j++ )
      {
      p[j] = mIter.GetIndex()[j];
      }

    d = p - center;

    fIter.Set( (PixelType) F(d) );

    for ( j = 0; j < dimension; j++ )
      {
      d[j] = d[j] * scale[j] + displacement[j];
      }

    mIter.Set( (PixelType) F(d) );

    ++fIter;
    ++mIter;

    }

  // set the image origin to be center of the image
  double transCenter[dimension];
  for ( j = 0; j < dimension; j++ )
    {
    transCenter[j] = -0.5 * double(size[j]);
    }

  movingImage->SetOrigin( transCenter );
  fixedImage->SetOrigin( transCenter );

  /******************************************************************
   * Set up the optimizer.
   ******************************************************************/

  // set the translation scale
  typedef OptimizerType::ScalesType ScalesType;
  ScalesType parametersScales( transform->GetNumberOfParameters() );

  parametersScales.Fill( 1.0 );

  for ( j = 9; j < 12; j++ )
    {
    parametersScales[j] = 0.0001;
    }

  optimizer->SetScales( parametersScales );
  optimizer->MaximizeOff();

  /******************************************************************
   * Set up the optimizer observer
   ******************************************************************/
  typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType;
  CommandIterationType::Pointer iterationCommand =
    CommandIterationType::New();

  iterationCommand->SetOptimizer( optimizer );

  /******************************************************************
   * Set up the metric.
   ******************************************************************/
  metric->SetNumberOfSpatialSamples( static_cast<unsigned long>(
    0.01 * fixedImage->GetBufferedRegion().GetNumberOfPixels() ) );

  metric->SetNumberOfHistogramBins( 50 );

  for( unsigned int j = 0; j < dimension; j++ )
    {
    size[j] -= 4;
    index[j] += 2;
    }
  region.SetSize( size );
  region.SetIndex( index );
  metric->SetFixedImageRegion( region );

  /******************************************************************
   * Set up the registrator.
   ******************************************************************/

  // connect up the components
  registration->SetMetric( metric );
  registration->SetOptimizer( optimizer );
  registration->SetTransform( transform );
  registration->SetFixedImage( fixedImage );
  registration->SetMovingImage( movingImage );
  registration->SetInterpolator( interpolator );

  // set initial parameters to identity
  RegistrationType::ParametersType initialParameters(
    transform->GetNumberOfParameters() );

  initialParameters.Fill( 0.0 );
  initialParameters[0] = 1.0;
  initialParameters[4] = 1.0;
  initialParameters[8] = 1.0;

  /***********************************************************
   * Run the registration
   ************************************************************/
  const unsigned int numberOfLoops = 2;
  unsigned int iter[numberOfLoops] = { 50, 0 };
  double      rates[numberOfLoops] = { 1e-3, 5e-4 };

  for ( j = 0; j < numberOfLoops; j++ )
    {

    try
      {
        optimizer->SetNumberOfIterations( iter[j] );
        optimizer->SetLearningRate( rates[j] );
        registration->SetInitialTransformParameters( initialParameters );
        registration->StartRegistration();

        initialParameters = registration->GetLastTransformParameters();

      }
    catch( itk::ExceptionObject & e )
      {
      std::cout << "Registration failed" << std::endl;
      std::cout << "Reason " << e.GetDescription() << std::endl;
      return EXIT_FAILURE;
      }

    }

  /***********************************************************
   * Check the results
   ************************************************************/
  RegistrationType::ParametersType solution =
    registration->GetLastTransformParameters();

  std::cout << "Solution is: " << solution << std::endl;

  RegistrationType::ParametersType trueParameters(
    transform->GetNumberOfParameters() );
  trueParameters.Fill( 0.0 );
  trueParameters[ 0] = 1/scale[0];
  trueParameters[ 4] = 1/scale[1];
  trueParameters[ 8] = 1/scale[2];
  trueParameters[ 9] = - displacement[0]/scale[0];
  trueParameters[10] = - displacement[1]/scale[1];
  trueParameters[11] = - displacement[2]/scale[2];

  std::cout << "True solution is: " << trueParameters << std::endl;

  for( j = 0; j < 9; j++ )
    {
    if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.025 )
      {
      pass = false;
      }
    }
  for( j = 9; j < 12; j++ )
    {
    if( vnl_math_abs( solution[j] - trueParameters[j] ) > 1.0 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}
namespace
{

/**
 * This function defines the test image pattern.
 * The pattern is a 3D gaussian in the middle
 * and some directional pattern on the outside.
 */
double F( itk::Vector<double,3> & v )
{
  double x = v[0];
  double y = v[1];
  double z = v[2];
  const double s = 50;
  double value = 200.0 * exp( - ( x*x + y*y + z*z )/(s*s) );
  x -= 8; y += 3; z += 0;
  double r = vcl_sqrt( x*x + y*y + z*z );
  if( r > 35 )
    {
    value = 2 * ( vnl_math_abs( x ) +
      0.8 * vnl_math_abs( y ) +
      0.5 * vnl_math_abs( z ) );
    }
  if( r < 4 )
    {
    value = 400;
    }

  return value;

}
}
<commit_msg><commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageRegistrationMethodTest_15.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include "itkImageRegistrationMethod.h"
#include "itkAffineTransform.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkGradientDescentOptimizer.h"

#include "itkTextOutput.h"
#include "itkImageRegionIterator.h"
#include "itkCommandIterationUpdate.h"

namespace
{

double F( itk::Vector<double,3> & v );
}

/**
 *  This program test one instantiation of the itk::ImageRegistrationMethod class
 *
 *  This file tests the combination of:
 *   - MattesMutualInformation
 *   - AffineTransform
 *   - GradientDescentOptimizer
 *   - BSplineInterpolateImageFunction
 *
 *  The test image pattern consists of a 3D gaussian in the middle
 *  with some directional pattern on the outside.
 *  One image is scaled and shifted relative to the other.
 *
 * Notes:
 * =======
 * This example performs an affine registration
 * between a moving (source) and fixed (target) image using mutual information.
 * It uses a simple steepest descent optimizer to find the
 * best affine transform to register the moving image onto the fixed
 * image.
 *
 * The mutual information value and its derivatives are estimated
 * using spatial sampling.
 *
 * The registration uses a simple stochastic gradient ascent scheme. Steps
 * are repeatedly taken that are proportional to the approximate
 * deriviative of the mutual information with respect to the affine
 * transform parameters. The stepsize is governed by the LearningRate
 * parameter.
 *
 * Since the parameters of the linear part is different in magnitude
 * to the parameters in the offset part, scaling is required
 * to improve convergence. The scaling can set via the optimizer.
 *
 * In the optimizer's scale transform set the scaling for
 * all the translation parameters to TranslationScale^{-2}.
 * Set the scale for all other parameters to 1.0.
 *
 * Note: the optimization performance can be improved by
 * setting the image origin to center of mass of the image.
 *
 */
int itkImageRegistrationMethodTest_15(int, char* [] )
{

  itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer());

/*==================================================*/
/**
 * Debugging vnl_sample
 */
  std::cout << "Debugging vnl_sample" << std::endl;

  #if VXL_STDLIB_HAS_DRAND48
  std::cout << "vxl stdlib has drand48" << std::endl;
  #else
  std::cout << "vxl stdlib does not have drand48" << std::endl;
  #endif

  std::cout << std::endl;
  std::cout << "printout 10 numbers with default seeds" << std::endl;

  for( int p = 0; p < 10; p++ )
    {
    double value = vnl_sample_uniform( 0, 100 );
    std::cout << p << "\t" << value << std::endl;
    }

  std::cout << "printout 10 numbers with seed 171219" << std::endl;
  vnl_sample_reseed( 171219 );

  for( int p = 0; p < 10; p++ )
    {
    double value = vnl_sample_uniform( 0, 100 );
    std::cout << p << "\t" << value << std::endl;
    }

/*==================================================*/

  bool pass = true;

  const unsigned int dimension = 3;
  unsigned int j;

  typedef float  PixelType;

  // Fixed Image Type
  typedef itk::Image<PixelType,dimension>               FixedImageType;

  // Moving Image Type
  typedef itk::Image<PixelType,dimension>               MovingImageType;

  // Transform Type
  typedef itk::AffineTransform< double,dimension >  TransformType;

  // Optimizer Type
  typedef itk::GradientDescentOptimizer             OptimizerType;

  // Metric Type
  typedef itk::MattesMutualInformationImageToImageMetric<
                                    FixedImageType,
                                    MovingImageType >    MetricType;

  // Interpolation technique
  typedef itk:: BSplineInterpolateImageFunction<
                                    MovingImageType,
                                    double          >    InterpolatorType;

  // Registration Method
  typedef itk::ImageRegistrationMethod<
                                    FixedImageType,
                                    MovingImageType >    RegistrationType;

  MetricType::Pointer         metric        = MetricType::New();
  TransformType::Pointer      transform     = TransformType::New();
  OptimizerType::Pointer      optimizer     = OptimizerType::New();
  FixedImageType::Pointer     fixedImage    = FixedImageType::New();
  MovingImageType::Pointer    movingImage   = MovingImageType::New();
  InterpolatorType::Pointer   interpolator  = InterpolatorType::New();
  RegistrationType::Pointer   registration  = RegistrationType::New();

  /*********************************************************
   * Set up the two input images.
   * One image scaled and shifted with respect to the other.
   **********************************************************/
  double displacement[dimension] = {3,1,1};
  double scale[dimension] = { 0.90, 1.0, 1.0 };

  FixedImageType::SizeType size = {{100,100,40}};
  FixedImageType::IndexType index = {{0,0,0}};
  FixedImageType::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );

  fixedImage->SetLargestPossibleRegion( region );
  fixedImage->SetBufferedRegion( region );
  fixedImage->SetRequestedRegion( region );
  fixedImage->Allocate();

  movingImage->SetLargestPossibleRegion( region );
  movingImage->SetBufferedRegion( region );
  movingImage->SetRequestedRegion( region );
  movingImage->Allocate();

  typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator;
  typedef itk::ImageRegionIterator<FixedImageType> FixedImageIterator;

  itk::Point<double,dimension> center;
  for ( j = 0; j < dimension; j++ )
    {
    center[j] = 0.5 *  (double)region.GetSize()[j];
    }

  itk::Point<double,dimension> p;
  itk::Vector<double,dimension> d;

  MovingImageIterator mIter( movingImage, region );
  FixedImageIterator  fIter( fixedImage, region );

  while( !mIter.IsAtEnd() )
    {
    for ( j = 0; j < dimension; j++ )
      {
      p[j] = mIter.GetIndex()[j];
      }

    d = p - center;

    fIter.Set( (PixelType) F(d) );

    for ( j = 0; j < dimension; j++ )
      {
      d[j] = d[j] * scale[j] + displacement[j];
      }

    mIter.Set( (PixelType) F(d) );

    ++fIter;
    ++mIter;

    }

  // set the image origin to be center of the image
  double transCenter[dimension];
  for ( j = 0; j < dimension; j++ )
    {
    transCenter[j] = -0.5 * double(size[j]);
    }

  movingImage->SetOrigin( transCenter );
  fixedImage->SetOrigin( transCenter );

  /******************************************************************
   * Set up the optimizer.
   ******************************************************************/

  // set the translation scale
  typedef OptimizerType::ScalesType ScalesType;
  ScalesType parametersScales( transform->GetNumberOfParameters() );

  parametersScales.Fill( 1.0 );

  for ( j = 9; j < 12; j++ )
    {
    parametersScales[j] = 0.0001;
    }

  optimizer->SetScales( parametersScales );
  optimizer->MaximizeOff();

  /******************************************************************
   * Set up the optimizer observer
   ******************************************************************/
  typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType;
  CommandIterationType::Pointer iterationCommand =
    CommandIterationType::New();

  iterationCommand->SetOptimizer( optimizer );

  /******************************************************************
   * Set up the metric.
   ******************************************************************/
  metric->SetNumberOfSpatialSamples( static_cast<unsigned long>(
    0.01 * fixedImage->GetBufferedRegion().GetNumberOfPixels() ) );

  metric->SetNumberOfHistogramBins( 50 );

  for( unsigned int j = 0; j < dimension; j++ )
    {
    size[j] -= 4;
    index[j] += 2;
    }
  region.SetSize( size );
  region.SetIndex( index );
  metric->SetFixedImageRegion( region );

  /******************************************************************
   * Set up the registrator.
   ******************************************************************/

  // connect up the components
  registration->SetMetric( metric );
  registration->SetOptimizer( optimizer );
  registration->SetTransform( transform );
  registration->SetFixedImage( fixedImage );
  registration->SetMovingImage( movingImage );
  registration->SetInterpolator( interpolator );

  // set initial parameters to identity
  RegistrationType::ParametersType initialParameters(
    transform->GetNumberOfParameters() );

  initialParameters.Fill( 0.0 );
  initialParameters[0] = 1.0;
  initialParameters[4] = 1.0;
  initialParameters[8] = 1.0;

  /***********************************************************
   * Run the registration
   ************************************************************/
  const unsigned int numberOfLoops = 2;
  unsigned int iter[numberOfLoops] = { 50, 0 };
  double      rates[numberOfLoops] = { 1e-3, 5e-4 };

  for ( j = 0; j < numberOfLoops; j++ )
    {

    try
      {
        optimizer->SetNumberOfIterations( iter[j] );
        optimizer->SetLearningRate( rates[j] );
        registration->SetInitialTransformParameters( initialParameters );
        registration->StartRegistration();

        initialParameters = registration->GetLastTransformParameters();

      }
    catch( itk::ExceptionObject & e )
      {
      std::cout << "Registration failed" << std::endl;
      std::cout << "Reason " << e.GetDescription() << std::endl;
      return EXIT_FAILURE;
      }

    }

  /***********************************************************
   * Check the results
   ************************************************************/
  RegistrationType::ParametersType solution =
    registration->GetLastTransformParameters();

  std::cout << "Solution is: " << solution << std::endl;

  RegistrationType::ParametersType trueParameters(
    transform->GetNumberOfParameters() );
  trueParameters.Fill( 0.0 );
  trueParameters[ 0] = 1/scale[0];
  trueParameters[ 4] = 1/scale[1];
  trueParameters[ 8] = 1/scale[2];
  trueParameters[ 9] = - displacement[0]/scale[0];
  trueParameters[10] = - displacement[1]/scale[1];
  trueParameters[11] = - displacement[2]/scale[2];

  std::cout << "True solution is: " << trueParameters << std::endl;

  for( j = 0; j < 9; j++ )
    {
    if( vnl_math_abs( solution[j] - trueParameters[j] ) > 0.025 )
      {
      pass = false;
      }
    }
  for( j = 9; j < 12; j++ )
    {
    if( vnl_math_abs( solution[j] - trueParameters[j] ) > 1.0 )
      {
      pass = false;
      }
    }

  if( !pass )
    {
    std::cout << "Test failed." << std::endl;
    return EXIT_FAILURE;
    }

  std::cout << "Test passed." << std::endl;
  return EXIT_SUCCESS;

}
namespace
{

/**
 * This function defines the test image pattern.
 * The pattern is a 3D gaussian in the middle
 * and some directional pattern on the outside.
 */
double F( itk::Vector<double,3> & v )
{
  double x = v[0];
  double y = v[1];
  double z = v[2];
  const double s = 50;
  double value = 200.0 * exp( - ( x*x + y*y + z*z )/(s*s) );
  x -= 8; y += 3; z += 0;
  double r = vcl_sqrt( x*x + y*y + z*z );
  if( r > 35 )
    {
    value = 2 * ( vnl_math_abs( x ) +
      0.8 * vnl_math_abs( y ) +
      0.5 * vnl_math_abs( z ) );
    }
  if( r < 4 )
    {
    value = 400;
    }

  return value;

}
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkHMaximaMinimaImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

#include "itkHMaximaImageFilter.h"
#include "itkHMinimaImageFilter.h"

int itkHMaximaMinimaImageFilterTest( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  ";
    std::cerr << " outputImageFile  height" << std::endl;
    return 1;
    }

  //
  //  The following code defines the input and output pixel types and their
  //  associated image types.
  //
  const unsigned int Dimension = 2;

  typedef unsigned char   InputPixelType;
  typedef unsigned char   OutputPixelType;
  typedef unsigned char    WritePixelType;

  typedef itk::Image< InputPixelType,  Dimension >   InputImageType;
  typedef itk::Image< OutputPixelType, Dimension >   OutputImageType;
  typedef itk::Image< WritePixelType, Dimension >    WriteImageType;

  // readers/writers
  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< WriteImageType >  WriterType;
  typedef itk::RescaleIntensityImageFilter<OutputImageType, WriteImageType>
    RescaleType;

  // define the hmaxima filter
  typedef itk::HMaximaImageFilter<
                            InputImageType,
                            OutputImageType >  HmaximaFilterType;
  // define the hminima filter
  typedef itk::HMinimaImageFilter<
                            InputImageType,
                            OutputImageType >  HminimaFilterType;

  // Creation of Reader and Writer filters
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer  = WriterType::New();
  RescaleType::Pointer rescaler = RescaleType::New();

  // Create the filters
  HmaximaFilterType::Pointer  hmaxima = HmaximaFilterType::New();
  HminimaFilterType::Pointer  hminima = HminimaFilterType::New();

  // Setup the input and output files
  reader->SetFileName( argv[1] );
  writer->SetFileName(  argv[2] );

  // Setup the hmaxima method
  hmaxima->SetInput(  reader->GetOutput() );
  hmaxima->SetHeight( atof(argv[3]) );

  // Setup the hminima method
  hminima->SetInput(  hmaxima->GetOutput() );
  hminima->SetHeight( atof(argv[3]) );

  // Run the filter
//   rescaler->SetInput( hmaxima->GetOutput() );
//   rescaler->SetOutputMinimum(   0 );
//   rescaler->SetOutputMaximum( 255 );
  writer->SetInput( hminima->GetOutput() );
  writer->Update();

  // Output the number of iterations used
  std::cout << "Hmaxima took " << hmaxima->GetNumberOfIterationsUsed() << " iterations." << std::endl;
  std::cout << "Hminima took " << hminima->GetNumberOfIterationsUsed() << " iterations." << std::endl;

  std::cout << "<DartMeasurement name=\"HMaximaNumberOfIterations\" type=\"numeric/integer\">" << hmaxima->GetNumberOfIterationsUsed() << "</DartMeasurement>" << std::endl;
  std::cout << "<DartMeasurement name=\"HMinimaNumberOfIterations\" type=\"numeric/integer\">" << hminima->GetNumberOfIterationsUsed() << "</DartMeasurement>" << std::endl;

  return 0;

}

<commit_msg>ERR: warnings.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkHMaximaMinimaImageFilterTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

//

#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"

#include "itkHMaximaImageFilter.h"
#include "itkHMinimaImageFilter.h"

int itkHMaximaMinimaImageFilterTest( int argc, char * argv[] )
{
  if( argc < 4 )
    {
    std::cerr << "Usage: " << std::endl;
    std::cerr << argv[0] << "  inputImageFile  ";
    std::cerr << " outputImageFile  height" << std::endl;
    return 1;
    }

  //
  //  The following code defines the input and output pixel types and their
  //  associated image types.
  //
  const unsigned int Dimension = 2;

  typedef unsigned char   InputPixelType;
  typedef unsigned char   OutputPixelType;
  typedef unsigned char    WritePixelType;

  typedef itk::Image< InputPixelType,  Dimension >   InputImageType;
  typedef itk::Image< OutputPixelType, Dimension >   OutputImageType;
  typedef itk::Image< WritePixelType, Dimension >    WriteImageType;

  // readers/writers
  typedef itk::ImageFileReader< InputImageType  >  ReaderType;
  typedef itk::ImageFileWriter< WriteImageType >  WriterType;
  typedef itk::RescaleIntensityImageFilter<OutputImageType, WriteImageType>
    RescaleType;

  // define the hmaxima filter
  typedef itk::HMaximaImageFilter<
                            InputImageType,
                            OutputImageType >  HmaximaFilterType;
  // define the hminima filter
  typedef itk::HMinimaImageFilter<
                            InputImageType,
                            OutputImageType >  HminimaFilterType;

  // Creation of Reader and Writer filters
  ReaderType::Pointer reader = ReaderType::New();
  WriterType::Pointer writer  = WriterType::New();
  RescaleType::Pointer rescaler = RescaleType::New();

  // Create the filters
  HmaximaFilterType::Pointer  hmaxima = HmaximaFilterType::New();
  HminimaFilterType::Pointer  hminima = HminimaFilterType::New();

  // Setup the input and output files
  reader->SetFileName( argv[1] );
  writer->SetFileName(  argv[2] );

  // Setup the hmaxima method
  hmaxima->SetInput(  reader->GetOutput() );
  hmaxima->SetHeight( static_cast<InputPixelType>(atof(argv[3])) );

  // Setup the hminima method
  hminima->SetInput(  hmaxima->GetOutput() );
  hminima->SetHeight( static_cast<InputPixelType>(atof(argv[3])) );

  // Run the filter
//   rescaler->SetInput( hmaxima->GetOutput() );
//   rescaler->SetOutputMinimum(   0 );
//   rescaler->SetOutputMaximum( 255 );
  writer->SetInput( hminima->GetOutput() );
  writer->Update();

  // Output the number of iterations used
  std::cout << "Hmaxima took " << hmaxima->GetNumberOfIterationsUsed() << " iterations." << std::endl;
  std::cout << "Hminima took " << hminima->GetNumberOfIterationsUsed() << " iterations." << std::endl;

  std::cout << "<DartMeasurement name=\"HMaximaNumberOfIterations\" type=\"numeric/integer\">" << hmaxima->GetNumberOfIterationsUsed() << "</DartMeasurement>" << std::endl;
  std::cout << "<DartMeasurement name=\"HMinimaNumberOfIterations\" type=\"numeric/integer\">" << hminima->GetNumberOfIterationsUsed() << "</DartMeasurement>" << std::endl;

  return 0;

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: functiondescription.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:02:47 $
 *
 *  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 "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<commit_msg>INTEGRATION: CWS warnings01 (1.3.52); FILE MERGED 2005/09/22 19:52:18 sb 1.3.52.2: RESYNC: (1.3-1.4); FILE MERGED 2005/09/19 15:23:56 sb 1.3.52.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: functiondescription.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 00:04:22 $
 *
 *  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 "functiondescription.hxx"

#include "com/sun/star/container/NoSuchElementException.hpp"
#include "com/sun/star/container/XHierarchicalNameAccess.hpp"
#include "com/sun/star/reflection/XCompoundTypeDescription.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/TypeClass.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/implbase1.hxx"
#include "osl/diagnose.h"
#include "osl/mutex.hxx"
#include "registry/reader.hxx"
#include "registry/version.h"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"

namespace css = com::sun::star;

using stoc::registry_tdprovider::FunctionDescription;

FunctionDescription::FunctionDescription(
    css::uno::Reference< css::container::XHierarchicalNameAccess > const &
        manager,
    com::sun::star::uno::Sequence< sal_Int8 > const & bytes,
    sal_uInt16 index):
    m_manager(manager), m_bytes(bytes), m_index(index), m_exceptionsInit(false)
{}

FunctionDescription::~FunctionDescription() {}

css::uno::Sequence<
    css::uno::Reference< css::reflection::XCompoundTypeDescription > >
FunctionDescription::getExceptions() const {
    {
        osl::MutexGuard guard(m_mutex);
        if (m_exceptionsInit) {
            return m_exceptions;
        }
    }
    typereg::Reader reader(getReader());
    sal_uInt16 n = reader.getMethodExceptionCount(m_index);
    css::uno::Sequence<
        css::uno::Reference< css::reflection::XCompoundTypeDescription > >
            exceptions(n);
    for (sal_uInt16 i = 0; i < n; ++i) {
        rtl::OUString name(
            reader.getMethodExceptionTypeName(m_index, i).replace('/', '.'));
        css::uno::Any any;
        try {
            any = m_manager->getByHierarchicalName(name);
        } catch (css::container::NoSuchElementException & e) {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM(
                        "com.sun.star.container.NoSuchElementException: "))
                 + e.Message),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        if (!(any >>= exceptions[i])
            || exceptions[i]->getTypeClass() != css::uno::TypeClass_EXCEPTION)
        {
            throw new css::uno::RuntimeException(
                (rtl::OUString(
                    RTL_CONSTASCII_USTRINGPARAM("not an exception type: "))
                 + name),
                css::uno::Reference< css::uno::XInterface >()); //TODO
        }
        OSL_ASSERT(exceptions[i].is());
    }
    osl::MutexGuard guard(m_mutex);
    if (!m_exceptionsInit) {
        m_exceptions = exceptions;
        m_exceptionsInit = true;
    }
    return m_exceptions;
}

typereg::Reader FunctionDescription::getReader() const {
    return typereg::Reader(
        m_bytes.getConstArray(), m_bytes.getLength(), false, TYPEREG_VERSION_1);
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "testbauhaus.h"

#include <QProcess>
#include <QFileInfo>
#include <QDir>
#include <QDebug>

TestBauhaus::TestBauhaus()
    : QObject()
{
    foreach (const QString &string, QProcess::systemEnvironment()) {
        if (string.contains("qtdir", Qt::CaseInsensitive)) {
            m_qtDir = string.split("=").last();
            break;
        }
    }
    Q_ASSERT(!m_qtDir.isEmpty());

    m_creatorDir = QString(WORKDIR) + "../../../../..";
#ifdef Q_OS_WIN
    m_executable = m_creatorDir + "/bin/qtcreator.exe";
#else
    m_executable = m_creatorDir + "/bin/qtcreator.bin";
#endif

    Q_ASSERT(QFileInfo(m_executable).exists());
}

bool TestBauhaus::loadFile(const QString &fileName)
{
    QProcess process;
    qDebug() << "starting: " << fileName;
    Q_ASSERT(QFileInfo(fileName).exists());

    process.start(m_executable, QStringList() << fileName);
    if (!process.waitForStarted())
        return false;
    if (!QProcess::Running == process.state()) {
        return false;
    }
    QTest::qWait(10000);
    if (!QProcess::Running == process.state()) {
        return false;
    }
    return true;
}

QStringList findAllQmlFiles(const QDir &dir)
{
    QStringList files;
    foreach (const QString &file, dir.entryList(QStringList() << "*.qml", QDir::Files)) {
        files += dir.absoluteFilePath(file);
    }

    foreach (const QString &directory, dir.entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot))
        files += findAllQmlFiles(QDir(dir.absoluteFilePath(directory)));
    return files;
}

void TestBauhaus::loadExamples_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_qtDir + "/examples/declarative"))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadExamples()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

void TestBauhaus::loadDemos_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_qtDir + "/demos/declarative"))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadDemos()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

void TestBauhaus::loadCreator_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_creatorDir))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadCreator()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

QTEST_MAIN(TestBauhaus);
<commit_msg>Make the bauhaust test find creator again.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "testbauhaus.h"

#include <QProcess>
#include <QFileInfo>
#include <QDir>
#include <QDebug>

TestBauhaus::TestBauhaus()
    : QObject()
{
    foreach (const QString &string, QProcess::systemEnvironment()) {
        if (string.contains("qtdir", Qt::CaseInsensitive)) {
            m_qtDir = string.split("=").last();
            break;
        }
    }
    Q_ASSERT(!m_qtDir.isEmpty());

    m_creatorDir = QString(WORKDIR) + "../../../../..";
#ifdef Q_OS_WIN
    m_executable = m_creatorDir + "/bin/qtcreator.exe";
#else
    m_executable = m_creatorDir + "/bin/qtcreator";
#endif

    Q_ASSERT(QFileInfo(m_executable).exists());
}

bool TestBauhaus::loadFile(const QString &fileName)
{
    QProcess process;
    qDebug() << "starting: " << fileName;
    Q_ASSERT(QFileInfo(fileName).exists());

    process.start(m_executable, QStringList() << fileName);
    if (!process.waitForStarted())
        return false;
    if (!QProcess::Running == process.state()) {
        return false;
    }
    QTest::qWait(10000);
    if (!QProcess::Running == process.state()) {
        return false;
    }
    return true;
}

QStringList findAllQmlFiles(const QDir &dir)
{
    QStringList files;
    foreach (const QString &file, dir.entryList(QStringList() << "*.qml", QDir::Files)) {
        files += dir.absoluteFilePath(file);
    }

    foreach (const QString &directory, dir.entryList(QStringList(), QDir::AllDirs | QDir::NoDotAndDotDot))
        files += findAllQmlFiles(QDir(dir.absoluteFilePath(directory)));
    return files;
}

void TestBauhaus::loadExamples_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_qtDir + "/examples/declarative"))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadExamples()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

void TestBauhaus::loadDemos_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_qtDir + "/demos/declarative"))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadDemos()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

void TestBauhaus::loadCreator_data()
{
    QTest::addColumn<QString>("filePath");
    foreach (const QString &file, findAllQmlFiles(QDir(m_creatorDir))) {
        QTest::newRow("file") << file;
    }
}

void TestBauhaus::loadCreator()
{
    QFETCH(QString, filePath);
    if (!loadFile(filePath))
        QFAIL(filePath.toAscii());
}

QTEST_MAIN(TestBauhaus);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <fstream>
#include <iostream>
#include <limits>
#include <vector>

#include "perfetto/base/logging.h"
#include "tools/trace_to_text/symbolize_profile.h"
#include "tools/trace_to_text/trace_to_json.h"
#include "tools/trace_to_text/trace_to_profile.h"
#include "tools/trace_to_text/trace_to_systrace.h"
#include "tools/trace_to_text/trace_to_text.h"

#if PERFETTO_BUILDFLAG(PERFETTO_VERSION_GEN)
#include "perfetto_version.gen.h"
#else
#define PERFETTO_GET_GIT_REVISION() "unknown"
#endif

namespace perfetto {
namespace trace_to_text {
namespace {

int Usage(const char* argv0) {
  printf(
      "Usage: %s systrace|json|ctrace|text|profile [--truncate start|end] "
      "[trace.pb] "
      "[trace.txt]\n",
      argv0);
  return 1;
}

int Main(int argc, char** argv) {
  std::vector<const char*> positional_args;
  Keep truncate_keep = Keep::kAll;
  for (int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
      printf("%s\n", PERFETTO_GET_GIT_REVISION());
      return 0;
    } else if (strcmp(argv[i], "-t") == 0 ||
               strcmp(argv[i], "--truncate") == 0) {
      i++;
      if (i <= argc && strcmp(argv[i], "start") == 0) {
        truncate_keep = Keep::kStart;
      } else if (i <= argc && strcmp(argv[i], "end") == 0) {
        truncate_keep = Keep::kEnd;
      } else {
        PERFETTO_ELOG(
            "--truncate must specify whether to keep the end or the "
            "start of the trace.");
        return Usage(argv[0]);
      }
    } else {
      positional_args.push_back(argv[i]);
    }
  }

  if (positional_args.size() < 1)
    return Usage(argv[0]);

  std::istream* input_stream;
  std::ifstream file_istream;
  if (positional_args.size() > 1) {
    const char* file_path = positional_args[1];
    file_istream.open(file_path, std::ios_base::in | std::ios_base::binary);
    if (!file_istream.is_open())
      PERFETTO_FATAL("Could not open %s", file_path);
    input_stream = &file_istream;
  } else {
    if (isatty(STDIN_FILENO)) {
      PERFETTO_ELOG("Reading from stdin but it's connected to a TTY");
      PERFETTO_LOG("It is unlikely that you want to type in some binary.");
      PERFETTO_LOG("Either pass a file path to the cmdline or pipe stdin");
      return Usage(argv[0]);
    }
    input_stream = &std::cin;
  }

  std::ostream* output_stream;
  std::ofstream file_ostream;
  if (positional_args.size() > 2) {
    const char* file_path = positional_args[2];
    file_ostream.open(file_path, std::ios_base::out | std::ios_base::trunc);
    if (!file_ostream.is_open())
      PERFETTO_FATAL("Could not open %s", file_path);
    output_stream = &file_ostream;
  } else {
    output_stream = &std::cout;
  }

  std::string format(positional_args[0]);

  if (format == "json")
    return TraceToJson(input_stream, output_stream, /*compress=*/false,
                       truncate_keep);

  if (format == "systrace")
    return TraceToSystrace(input_stream, output_stream, /*compress=*/false,
                           truncate_keep);

  if (format == "ctrace")
    return TraceToSystrace(input_stream, output_stream, /*compress=*/true,
                           truncate_keep);

  if (truncate_keep != Keep::kAll) {
    PERFETTO_ELOG(
        "--truncate is unsupported for text|profile|symbolize format.");
    return 1;
  }

  if (format == "text")
    return TraceToText(input_stream, output_stream);

  if (format == "profile")
    return TraceToProfile(input_stream, output_stream);

  if (format == "symbolize")
    return SymbolizeProfile(input_stream, output_stream);

  return Usage(argv[0]);
}

}  // namespace
}  // namespace trace_to_text
}  // namespace perfetto

int main(int argc, char** argv) {
  return perfetto::trace_to_text::Main(argc, argv);
}
<commit_msg>Fixing main.cc for support passing pid and timestamps to trace_to_profile<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 <fstream>
#include <iostream>
#include <limits>
#include <vector>

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/string_utils.h"
#include "tools/trace_to_text/symbolize_profile.h"
#include "tools/trace_to_text/trace_to_json.h"
#include "tools/trace_to_text/trace_to_profile.h"
#include "tools/trace_to_text/trace_to_systrace.h"
#include "tools/trace_to_text/trace_to_text.h"

#if PERFETTO_BUILDFLAG(PERFETTO_VERSION_GEN)
#include "perfetto_version.gen.h"
#else
#define PERFETTO_GET_GIT_REVISION() "unknown"
#endif

namespace perfetto {
namespace trace_to_text {
namespace {

int Usage(const char* argv0) {
  printf(
      "Usage: %s systrace|json|ctrace|text|profile [--pid PID] "
      "[--timestamps TIMESTAMP1,TIMESTAMP2,...] "
      "[--truncate start|end] "
      "[trace.pb] "
      "[trace.txt]\n"
      "\nProfile mode only:\n"
      "\t--timestamps TIMESTAMP1,TIMESTAMP2,... generate profiles "
      "only for these timestamps\n"
      "\t--pid PID generate profiles only for this process id\n",
      argv0);
  return 1;
}

uint64_t StringToUint64OrDie(const char* str) {
  char* end;
  uint64_t number = static_cast<uint64_t>(strtoll(str, &end, 10));
  if (*end != '\0') {
    PERFETTO_ELOG("Invalid %s. Expected decimal integer.", str);
    exit(1);
  }
  return number;
}

int Main(int argc, char** argv) {
  std::vector<const char*> positional_args;
  Keep truncate_keep = Keep::kAll;
  uint64_t pid = 0;
  std::vector<uint64_t> timestamps;
  for (int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
      printf("%s\n", PERFETTO_GET_GIT_REVISION());
      return 0;
    } else if (strcmp(argv[i], "-t") == 0 ||
               strcmp(argv[i], "--truncate") == 0) {
      i++;
      if (i <= argc && strcmp(argv[i], "start") == 0) {
        truncate_keep = Keep::kStart;
      } else if (i <= argc && strcmp(argv[i], "end") == 0) {
        truncate_keep = Keep::kEnd;
      } else {
        PERFETTO_ELOG(
            "--truncate must specify whether to keep the end or the "
            "start of the trace.");
        return Usage(argv[0]);
      }
    } else if (i <= argc && strcmp(argv[i], "--pid") == 0) {
      i++;
      pid = StringToUint64OrDie(argv[i]);
    } else if (i <= argc && strcmp(argv[i], "--timestamps") == 0) {
      i++;
      std::vector<std::string> ts_strings = base::SplitString(argv[i], ",");
      for (const std::string& ts : ts_strings) {
        timestamps.emplace_back(StringToUint64OrDie(ts.c_str()));
      }
    } else {
      positional_args.push_back(argv[i]);
    }
  }

  if (positional_args.size() < 1)
    return Usage(argv[0]);

  std::istream* input_stream;
  std::ifstream file_istream;
  if (positional_args.size() > 1) {
    const char* file_path = positional_args[1];
    file_istream.open(file_path, std::ios_base::in | std::ios_base::binary);
    if (!file_istream.is_open())
      PERFETTO_FATAL("Could not open %s", file_path);
    input_stream = &file_istream;
  } else {
    if (isatty(STDIN_FILENO)) {
      PERFETTO_ELOG("Reading from stdin but it's connected to a TTY");
      PERFETTO_LOG("It is unlikely that you want to type in some binary.");
      PERFETTO_LOG("Either pass a file path to the cmdline or pipe stdin");
      return Usage(argv[0]);
    }
    input_stream = &std::cin;
  }

  std::ostream* output_stream;
  std::ofstream file_ostream;
  if (positional_args.size() > 2) {
    const char* file_path = positional_args[2];
    file_ostream.open(file_path, std::ios_base::out | std::ios_base::trunc);
    if (!file_ostream.is_open())
      PERFETTO_FATAL("Could not open %s", file_path);
    output_stream = &file_ostream;
  } else {
    output_stream = &std::cout;
  }

  std::string format(positional_args[0]);

  if (format != "profile" && (pid != 0 || !timestamps.empty())) {
    PERFETTO_ELOG(
        "--pid and --timestamps are supported only for profile format.");
    return 1;
  }

  if (format == "json")
    return TraceToJson(input_stream, output_stream, /*compress=*/false,
                       truncate_keep);

  if (format == "systrace")
    return TraceToSystrace(input_stream, output_stream, /*compress=*/false,
                           truncate_keep);

  if (format == "ctrace")
    return TraceToSystrace(input_stream, output_stream, /*compress=*/true,
                           truncate_keep);

  if (truncate_keep != Keep::kAll) {
    PERFETTO_ELOG(
        "--truncate is unsupported for text|profile|symbolize format.");
    return 1;
  }

  if (format == "text")
    return TraceToText(input_stream, output_stream);

  if (format == "profile")
    return TraceToProfile(input_stream, output_stream, pid, timestamps);

  if (format == "symbolize")
    return SymbolizeProfile(input_stream, output_stream);

  return Usage(argv[0]);
}

}  // namespace
}  // namespace trace_to_text
}  // namespace perfetto

int main(int argc, char** argv) {
  return perfetto::trace_to_text::Main(argc, argv);
}
<|endoftext|>


<commit_before><commit_msg>Perception: simplify GetObjectSubType<commit_after><|endoftext|>