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

#include "android_webview/browser/aw_browser_main_parts.h"

#include "android_webview/browser/aw_browser_context.h"
#include "android_webview/browser/aw_result_codes.h"
#include "base/android/build_info.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/result_codes.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace android_webview {

AwBrowserMainParts::AwBrowserMainParts(AwBrowserContext* browser_context)
    : browser_context_(browser_context) {
}

AwBrowserMainParts::~AwBrowserMainParts() {
}

void AwBrowserMainParts::PreEarlyInitialization() {
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());
  content::Compositor::InitializeWithFlags(
      content::Compositor::DIRECT_CONTEXT_ON_DRAW_THREAD);

  // Android WebView does not use default MessageLoop. It has its own
  // Android specific MessageLoop. Also see MainMessageLoopRun.
  DCHECK(!main_message_loop_.get());
  main_message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_UI));
  base::MessageLoopForUI::current()->Start();
}

int AwBrowserMainParts::PreCreateThreads() {
  browser_context_->InitializeBeforeThreadCreation();

  ui::ResourceBundle::InitSharedInstanceLocaleOnly(
      l10n_util::GetDefaultLocale(), NULL);

  base::FilePath pak_path;
  PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &pak_path);

  ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
      pak_path.AppendASCII("webviewchromium.pak"),
      ui::SCALE_FACTOR_NONE);

  return content::RESULT_CODE_NORMAL_EXIT;
}

void AwBrowserMainParts::PreMainMessageLoopRun() {
  browser_context_->PreMainMessageLoopRun();
}

bool AwBrowserMainParts::MainMessageLoopRun(int* result_code) {
  // Android WebView does not use default MessageLoop. It has its own
  // Android specific MessageLoop.
  return true;
}

}  // namespace android_webview
<commit_msg>am 58b78f98: Cherry-pick: [Android WebView] Hook up MemoryPressureListener<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "android_webview/browser/aw_browser_main_parts.h"

#include "android_webview/browser/aw_browser_context.h"
#include "android_webview/browser/aw_result_codes.h"
#include "base/android/build_info.h"
#include "base/android/memory_pressure_listener_android.h"
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "content/public/browser/android/compositor.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/common/content_client.h"
#include "content/public/common/result_codes.h"
#include "net/android/network_change_notifier_factory_android.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/l10n/l10n_util_android.h"
#include "ui/base/layout.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_paths.h"

namespace android_webview {

AwBrowserMainParts::AwBrowserMainParts(AwBrowserContext* browser_context)
    : browser_context_(browser_context) {
}

AwBrowserMainParts::~AwBrowserMainParts() {
}

void AwBrowserMainParts::PreEarlyInitialization() {
  net::NetworkChangeNotifier::SetFactory(
      new net::NetworkChangeNotifierFactoryAndroid());
  content::Compositor::InitializeWithFlags(
      content::Compositor::DIRECT_CONTEXT_ON_DRAW_THREAD);

  // Android WebView does not use default MessageLoop. It has its own
  // Android specific MessageLoop. Also see MainMessageLoopRun.
  DCHECK(!main_message_loop_.get());
  main_message_loop_.reset(new base::MessageLoop(base::MessageLoop::TYPE_UI));
  base::MessageLoopForUI::current()->Start();
}

int AwBrowserMainParts::PreCreateThreads() {
  browser_context_->InitializeBeforeThreadCreation();

  ui::ResourceBundle::InitSharedInstanceLocaleOnly(
      l10n_util::GetDefaultLocale(), NULL);

  base::FilePath pak_path;
  PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &pak_path);

  ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
      pak_path.AppendASCII("webviewchromium.pak"),
      ui::SCALE_FACTOR_NONE);

  base::android::MemoryPressureListenerAndroid::RegisterSystemCallback(
      base::android::AttachCurrentThread());

  return content::RESULT_CODE_NORMAL_EXIT;
}

void AwBrowserMainParts::PreMainMessageLoopRun() {
  browser_context_->PreMainMessageLoopRun();
}

bool AwBrowserMainParts::MainMessageLoopRun(int* result_code) {
  // Android WebView does not use default MessageLoop. It has its own
  // Android specific MessageLoop.
  return true;
}

}  // namespace android_webview
<|endoftext|>


<commit_before>/*
    Copyright (c) 2005-2022 Intel Corporation

    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 "common/test.h"

#include <stdio.h>
#include "tbb/parallel_for.h"
#include "tbb/global_control.h"
#include "tbb/enumerable_thread_specific.h"

#include "common/config.h"
#include "common/utils.h"
#include "common/utils_concurrency_limit.h"
#include "common/utils_report.h"
#include "common/vector_types.h"
#include "common/cpu_usertime.h"
#include "common/spin_barrier.h"
#include "common/exception_handling.h"
#include "common/concepts_common.h"
#include "test_partitioner.h"

#include <cstddef>
#include <vector>

//! \file test_numa_dist.cpp
//! \brief Test for [internal] functionality
#if _MSC_VER
#pragma warning (push)
// Suppress conditional expression is constant
#pragma warning (disable: 4127)
#if __TBB_MSVC_UNREACHABLE_CODE_IGNORED
    // Suppress pointless "unreachable code" warning.
    #pragma warning (disable: 4702)
#endif
#if defined(_Wp64)
    // Workaround for overzealous compiler warnings in /Wp64 mode
    #pragma warning (disable: 4267)
#endif
#define _SCL_SECURE_NO_WARNINGS
#endif //#if _MSC_VER

struct numa {
    WORD processorGroupCount;
    std::vector<DWORD> numaProcessors;
    DWORD maxProcessors;
    numa() : processorGroupCount(GetMaximumProcessorGroupCount()), maxProcessors(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)){
        numaProcessors.resize(processorGroupCount);
       for (WORD i = 0; i < processorGroupCount; i++) {
            this->numaProcessors[i] = GetActiveProcessorCount((i));
        }
    }
};

int TestNumaDistribution(std::vector<DWORD> &validateProcgrp, int additionalParallelism, bool allThreads){
    validateProcgrp.resize(GetMaximumProcessorGroupCount());
    PROCESSOR_NUMBER proc;
    struct numa nodes;
    GetThreadIdealProcessorEx(GetCurrentThread(), &proc);
    int master_thread_proc_grp = proc.Group;
    int requested_parallelism;
    if (allThreads)
        requested_parallelism = additionalParallelism;
    else
        requested_parallelism = nodes.numaProcessors.at(master_thread_proc_grp) + additionalParallelism;
    tbb::global_control global_limit(oneapi::tbb::global_control::max_allowed_parallelism, 1024);
    tbb::enumerable_thread_specific< std::pair<int, int> > tls;
    tbb::enumerable_thread_specific< double > tls_dummy;
    tbb::static_partitioner s;

    utils::SpinBarrier sb(requested_parallelism);
    oneapi::tbb::task_arena limited(requested_parallelism);
    limited.execute([&]() {

        tbb::parallel_for(0, requested_parallelism, [&](int)
            {
                PROCESSOR_NUMBER proc;
                if (GetThreadIdealProcessorEx(GetCurrentThread(), &proc))
                {
                    tls.local() = std::pair<int, int>(proc.Group, proc.Number);
                    sb.wait();
                }
            }, s);
        for (const auto it : tls) {
           validateProcgrp[it.first]++;
        }
      });

    return master_thread_proc_grp;
}

//! Testing Numa Thread Distribution
//! \brief \ref number of processor in Numa node of master thread

TEST_CASE("Numa stability for the same node") {
    numa example;
    std::vector<DWORD> validateProcgrp;

    int numaGrp = TestNumaDistribution(validateProcgrp,0, 0);
    std::vector<DWORD> result(GetMaximumProcessorGroupCount(), 0);
    result[numaGrp] = example.numaProcessors[numaGrp];
    REQUIRE(validateProcgrp == result);
}

TEST_CASE("Numa overflow") {
    numa example;
    std::vector<DWORD> validateProcgrp;

    int numaGrp = TestNumaDistribution(validateProcgrp, 1, 0);
    std::vector<DWORD> result(GetMaximumProcessorGroupCount(), 0);
    if (example.processorGroupCount <= 1) { // for single Numa node
       result[numaGrp] = example.numaProcessors[numaGrp] + 1;
    } else {
       result[numaGrp] = example.numaProcessors[numaGrp];
       result[(numaGrp+1)% GetMaximumProcessorGroupCount()] = 1;
    }
    REQUIRE(validateProcgrp == result);
}

TEST_CASE("Numa all threads") {
    numa example;
    std::vector<DWORD> validateProcgrp;
    TestNumaDistribution(validateProcgrp, example.maxProcessors, 1);
    REQUIRE(validateProcgrp == example.numaProcessors);
}

TEST_CASE("Double threads") {
    numa example;
    std::vector<DWORD> validateProcgrp;
    std::vector<DWORD> result(example.numaProcessors.size(), 0);
    for (int i = 0; i < example.numaProcessors.size(); i++) result[i] = 2 * example.numaProcessors[i];
    TestNumaDistribution(validateProcgrp, example.maxProcessors * 2, 1);
    REQUIRE(validateProcgrp == result);
}

#if _MSC_VER
#pragma warning (pop)
#endif
<commit_msg>Fix signed/unsigned compare. (#849)<commit_after>/*
    Copyright (c) 2005-2022 Intel Corporation

    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 "common/test.h"

#include <stdio.h>
#include "tbb/parallel_for.h"
#include "tbb/global_control.h"
#include "tbb/enumerable_thread_specific.h"

#include "common/config.h"
#include "common/utils.h"
#include "common/utils_concurrency_limit.h"
#include "common/utils_report.h"
#include "common/vector_types.h"
#include "common/cpu_usertime.h"
#include "common/spin_barrier.h"
#include "common/exception_handling.h"
#include "common/concepts_common.h"
#include "test_partitioner.h"

#include <cstddef>
#include <vector>

//! \file test_numa_dist.cpp
//! \brief Test for [internal] functionality
#if _MSC_VER
#pragma warning (push)
// Suppress conditional expression is constant
#pragma warning (disable: 4127)
#if __TBB_MSVC_UNREACHABLE_CODE_IGNORED
    // Suppress pointless "unreachable code" warning.
    #pragma warning (disable: 4702)
#endif
#if defined(_Wp64)
    // Workaround for overzealous compiler warnings in /Wp64 mode
    #pragma warning (disable: 4267)
#endif
#define _SCL_SECURE_NO_WARNINGS
#endif //#if _MSC_VER

struct numa {
    WORD processorGroupCount;
    std::vector<DWORD> numaProcessors;
    DWORD maxProcessors;
    numa() : processorGroupCount(GetMaximumProcessorGroupCount()), maxProcessors(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)){
        numaProcessors.resize(processorGroupCount);
       for (WORD i = 0; i < processorGroupCount; i++) {
            this->numaProcessors[i] = GetActiveProcessorCount((i));
        }
    }
};

int TestNumaDistribution(std::vector<DWORD> &validateProcgrp, int additionalParallelism, bool allThreads){
    validateProcgrp.resize(GetMaximumProcessorGroupCount());
    PROCESSOR_NUMBER proc;
    struct numa nodes;
    GetThreadIdealProcessorEx(GetCurrentThread(), &proc);
    int master_thread_proc_grp = proc.Group;
    int requested_parallelism;
    if (allThreads)
        requested_parallelism = additionalParallelism;
    else
        requested_parallelism = nodes.numaProcessors.at(master_thread_proc_grp) + additionalParallelism;
    tbb::global_control global_limit(oneapi::tbb::global_control::max_allowed_parallelism, 1024);
    tbb::enumerable_thread_specific< std::pair<int, int> > tls;
    tbb::enumerable_thread_specific< double > tls_dummy;
    tbb::static_partitioner s;

    utils::SpinBarrier sb(requested_parallelism);
    oneapi::tbb::task_arena limited(requested_parallelism);
    limited.execute([&]() {

        tbb::parallel_for(0, requested_parallelism, [&](int)
            {
                PROCESSOR_NUMBER proc;
                if (GetThreadIdealProcessorEx(GetCurrentThread(), &proc))
                {
                    tls.local() = std::pair<int, int>(proc.Group, proc.Number);
                    sb.wait();
                }
            }, s);
        for (const auto it : tls) {
           validateProcgrp[it.first]++;
        }
      });

    return master_thread_proc_grp;
}

//! Testing Numa Thread Distribution
//! \brief \ref number of processor in Numa node of master thread

TEST_CASE("Numa stability for the same node") {
    numa example;
    std::vector<DWORD> validateProcgrp;

    int numaGrp = TestNumaDistribution(validateProcgrp,0, 0);
    std::vector<DWORD> result(GetMaximumProcessorGroupCount(), 0);
    result[numaGrp] = example.numaProcessors[numaGrp];
    REQUIRE(validateProcgrp == result);
}

TEST_CASE("Numa overflow") {
    numa example;
    std::vector<DWORD> validateProcgrp;

    int numaGrp = TestNumaDistribution(validateProcgrp, 1, 0);
    std::vector<DWORD> result(GetMaximumProcessorGroupCount(), 0);
    if (example.processorGroupCount <= 1) { // for single Numa node
       result[numaGrp] = example.numaProcessors[numaGrp] + 1;
    } else {
       result[numaGrp] = example.numaProcessors[numaGrp];
       result[(numaGrp+1)% GetMaximumProcessorGroupCount()] = 1;
    }
    REQUIRE(validateProcgrp == result);
}

TEST_CASE("Numa all threads") {
    numa example;
    std::vector<DWORD> validateProcgrp;
    TestNumaDistribution(validateProcgrp, example.maxProcessors, 1);
    REQUIRE(validateProcgrp == example.numaProcessors);
}

TEST_CASE("Double threads") {
    numa example;
    std::vector<DWORD> validateProcgrp;
    std::vector<DWORD> result(example.numaProcessors.size(), 0);
    for (size_t i = 0; i < example.numaProcessors.size(); i++) result[i] = 2 * example.numaProcessors[i];
    TestNumaDistribution(validateProcgrp, example.maxProcessors * 2, 1);
    REQUIRE(validateProcgrp == result);
}

#if _MSC_VER
#pragma warning (pop)
#endif
<|endoftext|>


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

#include <cassert>

#include "maya/MFnNumericAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MTime.h"
#include "maya/MGlobal.h"

#include "typeIds/TypeIds.h"

#include "IECore/Exception.h"
#include "IECore/OversamplesCalculator.h"
#include "IECoreMaya/CacheSet.h"
#include "IECoreMaya/MayaTime.h"

using namespace IECore;
using namespace IECoreMaya;

MObject CacheSet::aActive;
MObject CacheSet::aFrameRate;
MObject CacheSet::aOversamples;
MObject CacheSet::aActualOversamples;
MObject CacheSet::aOutFrameMel;

MTypeId CacheSet::id( CacheSetId );

CacheSet::CacheSet()
{
}

CacheSet::~CacheSet()
{
}

void *CacheSet::creator()
{
	return new CacheSet;
}

bool CacheSet::isAbstractClass() const
{
	return true;
}

MStatus CacheSet::initialize()
{
	MStatus s;
	MFnNumericAttribute nAttr;
	MFnTypedAttribute tAttr;

	aActive = nAttr.create("active", "a", MFnNumericData::kBoolean, true, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setKeyable(true);

	aFrameRate = nAttr.create("frameRate", "fr", MFnNumericData::kDouble, 24.0, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setMin(1.0);

	aOversamples = nAttr.create("oversamples", "os", MFnNumericData::kInt, 1, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setMin(1);

	aActualOversamples = nAttr.create("actualOversamples", "aos", MFnNumericData::kInt, 1, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(false);
	nAttr.setStorable(true);

	aOutFrameMel = tAttr.create("outFrameMel", "ofc", MFnData::kString);
	tAttr.setWritable(false);
	tAttr.setReadable(true);

	s = addAttribute(aActive);
	assert(s);

	s = addAttribute(aFrameRate);
	assert(s);

	s = addAttribute(aOversamples);
	assert(s);

	s = addAttribute(aActualOversamples);
	assert(s);

	s = addAttribute(aOutFrameMel);
	assert(s);

	s = attributeAffects(aActive, aOutFrameMel);
	assert(s);

	s = attributeAffects(aFrameRate, aActualOversamples);
	assert(s);

	s = attributeAffects(aOversamples, aActualOversamples);
	assert(s);

	return MS::kSuccess;
}

MStatus CacheSet::compute(const MPlug &plug, MDataBlock &block)
{
	if (plug != aActualOversamples)
	{
		return MS::kUnknownParameter;
	}

	MStatus s;

	MDataHandle frameRateH = block.inputValue( aFrameRate );
	double frameRate = frameRateH.asDouble();

	MDataHandle oversamplesH = block.inputValue( aOversamples );
	int oversamples = oversamplesH.asInt();

	MDataHandle actualOversamplesH = block.outputValue( aActualOversamples, &s );

	// frameRate should match UI time units,
	// so we can use the mel command currentTime for caching very easily.
	if (frameRate != MayaTime::fps( MTime::uiUnit() ) )
	{
		MGlobal::displayError( "The frame rate attribute does not match current time unit. Caching will not save the expected frames." );
		return MS::kFailure;
	}

	try {
		OversamplesCalculator6kFPS oversamplesCalc( frameRate, oversamples );
		oversamples = oversamplesCalc.actualOversamples();
		actualOversamplesH.set( oversamples );
		s = MStatus::kSuccess;
	}
	catch (IECore::Exception &e)
	{
		MString err = e.type();
		err += ": ";
		err += e.what();

		MGlobal::displayError(err);
		return MS::kFailure;
	}
	catch (...)
	{
		MString err = "Unknown error computing actual oversamples.";

		MGlobal::displayError(err);
		return MS::kFailure;
	}

	return s;
}

MString CacheSet::melFromStringArray(const MStringArray &a) const
{
	MString mel = "{";
	for (unsigned i = 0; i < a.length(); i++)
	{
		if (i != 0)
		{
			mel += ", ";
		}
		mel += "\"";
		mel += a[i];
		mel += "\"";
	}
	mel += "}";

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

#include <cassert>

#include "maya/MFnNumericAttribute.h"
#include "maya/MFnTypedAttribute.h"
#include "maya/MTime.h"
#include "maya/MGlobal.h"

#include "IECore/Exception.h"
#include "IECore/OversamplesCalculator.h"
#include "IECoreMaya/CacheSet.h"
#include "IECoreMaya/MayaTime.h"
#include "IECoreMaya/MayaTypeIds.h"

using namespace IECore;
using namespace IECoreMaya;

MObject CacheSet::aActive;
MObject CacheSet::aFrameRate;
MObject CacheSet::aOversamples;
MObject CacheSet::aActualOversamples;
MObject CacheSet::aOutFrameMel;

MTypeId CacheSet::id( CacheSetId );

CacheSet::CacheSet()
{
}

CacheSet::~CacheSet()
{
}

void *CacheSet::creator()
{
	return new CacheSet;
}

bool CacheSet::isAbstractClass() const
{
	return true;
}

MStatus CacheSet::initialize()
{
	MStatus s;
	MFnNumericAttribute nAttr;
	MFnTypedAttribute tAttr;

	aActive = nAttr.create("active", "a", MFnNumericData::kBoolean, true, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setKeyable(true);

	aFrameRate = nAttr.create("frameRate", "fr", MFnNumericData::kDouble, 24.0, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setMin(1.0);

	aOversamples = nAttr.create("oversamples", "os", MFnNumericData::kInt, 1, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(true);
	nAttr.setStorable(true);
	nAttr.setMin(1);

	aActualOversamples = nAttr.create("actualOversamples", "aos", MFnNumericData::kInt, 1, &s);
	nAttr.setReadable(true);
	nAttr.setWritable(false);
	nAttr.setStorable(true);

	aOutFrameMel = tAttr.create("outFrameMel", "ofc", MFnData::kString);
	tAttr.setWritable(false);
	tAttr.setReadable(true);

	s = addAttribute(aActive);
	assert(s);

	s = addAttribute(aFrameRate);
	assert(s);

	s = addAttribute(aOversamples);
	assert(s);

	s = addAttribute(aActualOversamples);
	assert(s);

	s = addAttribute(aOutFrameMel);
	assert(s);

	s = attributeAffects(aActive, aOutFrameMel);
	assert(s);

	s = attributeAffects(aFrameRate, aActualOversamples);
	assert(s);

	s = attributeAffects(aOversamples, aActualOversamples);
	assert(s);

	return MS::kSuccess;
}

MStatus CacheSet::compute(const MPlug &plug, MDataBlock &block)
{
	if (plug != aActualOversamples)
	{
		return MS::kUnknownParameter;
	}

	MStatus s;

	MDataHandle frameRateH = block.inputValue( aFrameRate );
	double frameRate = frameRateH.asDouble();

	MDataHandle oversamplesH = block.inputValue( aOversamples );
	int oversamples = oversamplesH.asInt();

	MDataHandle actualOversamplesH = block.outputValue( aActualOversamples, &s );

	// frameRate should match UI time units,
	// so we can use the mel command currentTime for caching very easily.
	if (frameRate != MayaTime::fps( MTime::uiUnit() ) )
	{
		MGlobal::displayError( "The frame rate attribute does not match current time unit. Caching will not save the expected frames." );
		return MS::kFailure;
	}

	try {
		OversamplesCalculator6kFPS oversamplesCalc( frameRate, oversamples );
		oversamples = oversamplesCalc.actualOversamples();
		actualOversamplesH.set( oversamples );
		s = MStatus::kSuccess;
	}
	catch (IECore::Exception &e)
	{
		MString err = e.type();
		err += ": ";
		err += e.what();

		MGlobal::displayError(err);
		return MS::kFailure;
	}
	catch (...)
	{
		MString err = "Unknown error computing actual oversamples.";

		MGlobal::displayError(err);
		return MS::kFailure;
	}

	return s;
}

MString CacheSet::melFromStringArray(const MStringArray &a) const
{
	MString mel = "{";
	for (unsigned i = 0; i < a.length(); i++)
	{
		if (i != 0)
		{
			mel += ", ";
		}
		mel += "\"";
		mel += a[i];
		mel += "\"";
	}
	mel += "}";

	return mel;
}
<|endoftext|>


<commit_before>// 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 <gtest/gtest.h>

#include <gmock/gmock.h>

#include <stout/duration.hpp>
#include <stout/gtest.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>

TEST(DurationTest, Comparison)
{
  EXPECT_EQ(Duration::zero(), Seconds(0));
  EXPECT_EQ(Minutes(180), Hours(3));
  EXPECT_EQ(Seconds(10800), Hours(3));
  EXPECT_EQ(Milliseconds(10800000), Hours(3));

  EXPECT_EQ(Milliseconds(1), Microseconds(1000));
  EXPECT_EQ(Milliseconds(1000), Seconds(1));

  EXPECT_GT(Weeks(1), Days(6));

  EXPECT_LT(Hours(23), Days(1));

  EXPECT_LE(Hours(24), Days(1));
  EXPECT_GE(Hours(24), Days(1));

  EXPECT_NE(Minutes(59), Hours(1));

  // Maintains precision for a 100 year duration.
  EXPECT_GT(Weeks(5217) + Nanoseconds(1), Weeks(5217));
  EXPECT_LT(Weeks(5217) - Nanoseconds(1), Weeks(5217));
}

TEST(DurationTest, ParseAndTry)
{
  EXPECT_SOME_EQ(Hours(3), Duration::parse("3hrs"));
  EXPECT_SOME_EQ(Hours(3) + Minutes(30), Duration::parse("3.5hrs"));

  EXPECT_SOME_EQ(Nanoseconds(3141592653), Duration::create(3.141592653));
  // Duration can hold only 9.22337e9 seconds.
  EXPECT_ERROR(Duration::create(10 * 1e9));
  EXPECT_ERROR(Duration::create(-10 * 1e9));
}

TEST(DurationTest, Arithmetic)
{
  Duration d = Seconds(11);
  d += Seconds(9);
  EXPECT_EQ(Seconds(20), d);

  d = Seconds(11);
  d -= Seconds(21);
  EXPECT_EQ(Seconds(-10), d);

  d = Seconds(10);
  d *= 2;
  EXPECT_EQ(Seconds(20), d);

  d = Seconds(10);
  d /= 2.5;
  EXPECT_EQ(Seconds(4), d);

  EXPECT_EQ(Seconds(20), Seconds(11) + Seconds(9));
  EXPECT_EQ(Seconds(-10), Seconds(11) - Seconds(21));
  EXPECT_EQ(Duration::create(3.3).get(), Seconds(10) * 0.33);
  EXPECT_EQ(Duration::create(1.25).get(), Seconds(10) / 8);

  EXPECT_EQ(Duration::create(Days(11).secs() + 9).get(), Days(11) + Seconds(9));
}

TEST(DurationTest, OutputFormat)
{
  EXPECT_EQ("1ns", stringify(Nanoseconds(1)));
  EXPECT_EQ("2ns", stringify(Nanoseconds(2)));

  // Truncated. Seconds in 15 digits of precision, max of double
  // type's precise digits.
  EXPECT_EQ("3.141592653secs",
            stringify(Duration::create(3.14159265358979).get()));
  EXPECT_EQ("3140ms", stringify(Duration::create(3.14).get()));
  EXPECT_EQ("10hrs", stringify(Hours(10)));
  EXPECT_EQ("-10hrs", stringify(Hours(-10)));

  // "10days" reads better than "1.42857142857143weeks" so it is
  // printed out in the lower unit.
  EXPECT_EQ("10days", stringify(Days(10)));
  // We go one-level down and it is still not a whole number so we
  // print it out using the higher unit.
  EXPECT_EQ("1.1875days", stringify(Days(1) + Hours(4) + Minutes(30)));
  // "2weeks" reads better than "14days" so we use the higher unit
  // here.
  EXPECT_EQ("2weeks", stringify(Days(14)));

  // Boundary cases.
  EXPECT_EQ("0ns", stringify(Duration::zero()));
  EXPECT_EQ("15250.2844524715weeks", stringify(Duration::max()));
  EXPECT_EQ("-15250.2844524715weeks", stringify(Duration::min()));
}

TEST(DurationTest, Timeval)
{
  EXPECT_EQ(Duration(timeval{10, 0}), Seconds(10));
  EXPECT_EQ(Duration(timeval{0, 7}), Microseconds(7));
  EXPECT_EQ(Duration(timeval{2, 123}), Seconds(2) + Microseconds(123));

  timeval t{2, 123};
  Duration d(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  t.tv_usec = 0;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  // Negative times.
  t.tv_sec = 0;
  t.tv_usec = -1;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  d = Microseconds(-1);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  t.tv_sec = -1;
  t.tv_usec = -30;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);
}
<commit_msg>Used only exactly representable floats in test calculation.<commit_after>// 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 <gtest/gtest.h>

#include <gmock/gmock.h>

#include <stout/duration.hpp>
#include <stout/gtest.hpp>
#include <stout/stringify.hpp>
#include <stout/try.hpp>

TEST(DurationTest, Comparison)
{
  EXPECT_EQ(Duration::zero(), Seconds(0));
  EXPECT_EQ(Minutes(180), Hours(3));
  EXPECT_EQ(Seconds(10800), Hours(3));
  EXPECT_EQ(Milliseconds(10800000), Hours(3));

  EXPECT_EQ(Milliseconds(1), Microseconds(1000));
  EXPECT_EQ(Milliseconds(1000), Seconds(1));

  EXPECT_GT(Weeks(1), Days(6));

  EXPECT_LT(Hours(23), Days(1));

  EXPECT_LE(Hours(24), Days(1));
  EXPECT_GE(Hours(24), Days(1));

  EXPECT_NE(Minutes(59), Hours(1));

  // Maintains precision for a 100 year duration.
  EXPECT_GT(Weeks(5217) + Nanoseconds(1), Weeks(5217));
  EXPECT_LT(Weeks(5217) - Nanoseconds(1), Weeks(5217));
}

TEST(DurationTest, ParseAndTry)
{
  EXPECT_SOME_EQ(Hours(3), Duration::parse("3hrs"));
  EXPECT_SOME_EQ(Hours(3) + Minutes(30), Duration::parse("3.5hrs"));

  EXPECT_SOME_EQ(Nanoseconds(3141592653), Duration::create(3.141592653));
  // Duration can hold only 9.22337e9 seconds.
  EXPECT_ERROR(Duration::create(10 * 1e9));
  EXPECT_ERROR(Duration::create(-10 * 1e9));
}

TEST(DurationTest, Arithmetic)
{
  Duration d = Seconds(11);
  d += Seconds(9);
  EXPECT_EQ(Seconds(20), d);

  d = Seconds(11);
  d -= Seconds(21);
  EXPECT_EQ(Seconds(-10), d);

  d = Seconds(10);
  d *= 2;
  EXPECT_EQ(Seconds(20), d);

  d = Seconds(10);
  d /= 2.5;
  EXPECT_EQ(Seconds(4), d);

  EXPECT_EQ(Seconds(20), Seconds(11) + Seconds(9));
  EXPECT_EQ(Seconds(-10), Seconds(11) - Seconds(21));
  EXPECT_EQ(Duration::create(2.5).get(), Seconds(10) * 0.25);
  EXPECT_EQ(Duration::create(1.25).get(), Seconds(10) / 8);

  EXPECT_EQ(Duration::create(Days(11).secs() + 9).get(), Days(11) + Seconds(9));
}

TEST(DurationTest, OutputFormat)
{
  EXPECT_EQ("1ns", stringify(Nanoseconds(1)));
  EXPECT_EQ("2ns", stringify(Nanoseconds(2)));

  // Truncated. Seconds in 15 digits of precision, max of double
  // type's precise digits.
  EXPECT_EQ("3.141592653secs",
            stringify(Duration::create(3.14159265358979).get()));
  EXPECT_EQ("3140ms", stringify(Duration::create(3.14).get()));
  EXPECT_EQ("10hrs", stringify(Hours(10)));
  EXPECT_EQ("-10hrs", stringify(Hours(-10)));

  // "10days" reads better than "1.42857142857143weeks" so it is
  // printed out in the lower unit.
  EXPECT_EQ("10days", stringify(Days(10)));
  // We go one-level down and it is still not a whole number so we
  // print it out using the higher unit.
  EXPECT_EQ("1.1875days", stringify(Days(1) + Hours(4) + Minutes(30)));
  // "2weeks" reads better than "14days" so we use the higher unit
  // here.
  EXPECT_EQ("2weeks", stringify(Days(14)));

  // Boundary cases.
  EXPECT_EQ("0ns", stringify(Duration::zero()));
  EXPECT_EQ("15250.2844524715weeks", stringify(Duration::max()));
  EXPECT_EQ("-15250.2844524715weeks", stringify(Duration::min()));
}

TEST(DurationTest, Timeval)
{
  EXPECT_EQ(Duration(timeval{10, 0}), Seconds(10));
  EXPECT_EQ(Duration(timeval{0, 7}), Microseconds(7));
  EXPECT_EQ(Duration(timeval{2, 123}), Seconds(2) + Microseconds(123));

  timeval t{2, 123};
  Duration d(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  t.tv_usec = 0;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  // Negative times.
  t.tv_sec = 0;
  t.tv_usec = -1;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  d = Microseconds(-1);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);

  t.tv_sec = -1;
  t.tv_usec = -30;
  d = Duration(t);
  EXPECT_EQ(d.timeval().tv_sec, t.tv_sec);
  EXPECT_EQ(d.timeval().tv_usec, t.tv_usec);
}
<|endoftext|>


<commit_before>// Copyright 2013 Sean McKenna
//
//    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.
//

// a ray tracer in C++

// libraries, namespace
#include <fstream>
#include "xmlload.cpp"
#include "scene.cpp"
using namespace std;

// variables for ray tracing
int w;
int h;
int size;
Color24 white = {237, 237, 237};
Color24 black = {27, 27, 27};
Color24* img;

// variables for camera ray generation
void cameraRayVars();
Point3 *imageTopLeftV;
Point3 *dXV;
Point3 *dYV;
Point3 firstPixel;
Point3 cameraRay(int pX, int pY);

// trace a ray against all objects
void objectIntersection(Node &n, Ray r, int pixel);

// ray tracer
int main(){

  // load scene: root node, camera, image
  LoadScene("scenes/prj0.xml");

  // variables for ray tracing
  w = renderImage.GetWidth();
  h = renderImage.GetHeight();
  size = w * h;
  img = renderImage.GetPixels();

  // variables for generating camera rays
  cameraRayVars();

  // ray-tracing loop, per pixel
  for(int i = 0; i < size; i++){

    // establish pixel location
    int pX = i % w;
    int pY = i / w;

    // compute current ray (in camera space)
    Point3 rayPos = camera.pos;
    Point3 rayDir = cameraRay(pX, pY);

    // transform ray into world space
    Transformation* world = new Transformation();
    world->Translate(rayPos);
    rayDir=world->VectorTransformFrom(rayDir);
    Ray *curr = new Ray(rayPos, rayDir);

    // traverse through scene DOM
    // transform rays into model space
    // detect ray intersections ---> update pixel
    objectIntersection(rootNode, *curr, i);
  }

  // output ray-traced image & z-buffer
  renderImage.SaveImage("images/image.ppm");
  //renderImage.SaveZImage("images/z-image.ppm");
}

// create variables for camera ray generation
void cameraRayVars(){
  float fov = camera.fov;
  float aspectRatio = (float) w / (float) h;
  float imageDistance = 1;
  float imageTipY = imageDistance * tan(fov / 2.0 * M_PI / 180.0);
  float imageTipX = imageTipY * aspectRatio;
  float dX = (2.0 * imageTipX) / w;
  float dY = (2.0 * imageTipY) / h;
  imageTopLeftV = new Point3(-imageTipX, imageTipY, -imageDistance);
  dXV = new Point3(dX, 0.0, 0.0);
  dYV = new Point3(0.0, -dY, 0.0);
  firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
}

// compute camera rays
Point3 cameraRay(int pX, int pY){
 Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);
 ray.Normalize();
 return ray;
}

// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){

  // loop on child nodes
  int j = 0;
  int numChild = n.GetNumChild();
  while(j < numChild){

    // grab child node
    Node *child = n.GetChild(j);
    Object *obj = child->GetObject();

    // transform rays into model space (or local space)
    Ray r2 = child->ToNodeCoords(r);

    // compute ray intersections
    HitInfo h = HitInfo();
    bool hit = obj->IntersectRay(r2, h);

    // check the ray computation, update pixels
    if(hit)
      img[pixel] = white;
    else
      img[pixel] = black;

    // recursively check this child's children
    objectIntersection(*child, r2, pixel);
    j++;
  }
}
<commit_msg>add non-working ray tracer, bug with rays somewhere<commit_after>// Copyright 2013 Sean McKenna
//
//    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.
//

// a ray tracer in C++

// libraries, namespace
#include <fstream>
#include "xmlload.cpp"
#include "scene.cpp"
using namespace std;

// variables for ray tracing
int w;
int h;
int size;
Color24 white = {237, 237, 237};
Color24 black = {27, 27, 27};
Color24* img;

// variables for camera ray generation
void cameraRayVars();
Point3 *imageTopLeftV;
Point3 *dXV;
Point3 *dYV;
Point3 firstPixel;
Point3 cameraRay(int pX, int pY);

// trace a ray against all objects
void objectIntersection(Node &n, Ray r, int pixel);

// ray tracer
int main(){

  // load scene: root node, camera, image
  LoadScene("scenes/prj0.xml");

  // variables for ray tracing
  w = renderImage.GetWidth();
  h = renderImage.GetHeight();
  size = w * h;
  img = renderImage.GetPixels();

  // variables for generating camera rays
  cameraRayVars();

  // ray-tracing loop, per pixel
  for(int i = 0; i < size; i++){

    // establish pixel location
    int pX = i % w;
    int pY = i / w;

    // compute current ray (in camera space)
    Point3 rayPos = camera.pos;
    Point3 rayDir = cameraRay(pX, pY);

    // transform ray into world space
    Transformation* world = new Transformation();
    //world->Translate(rayPos);
    Ray *curr = new Ray();
    curr->p = world->TransformTo(rayPos);
    curr->dir = world->TransformTo(rayPos + rayDir) - curr->p;
    //curr->Normalize();
    //rayDir=world->VectorTransformFrom(rayDir);
    //Ray *curr = new Ray(rayPos, rayDir);

    // traverse through scene DOM
    // transform rays into model space
    // detect ray intersections ---> update pixel
    objectIntersection(rootNode, *curr, i);
  }

  // output ray-traced image & z-buffer
  renderImage.SaveImage("images/image.ppm");
  //renderImage.SaveZImage("images/z-image.ppm");
}

// create variables for camera ray generation
void cameraRayVars(){
  float fov = camera.fov;
  float aspectRatio = (float) w / (float) h;
  float imageDistance = 1;
  float imageTipY = imageDistance * tan(fov / 2.0 * M_PI / 180.0);
  float imageTipX = imageTipY * aspectRatio;
  float dX = (2.0 * imageTipX) / w;
  float dY = (2.0 * imageTipY) / h;
  imageTopLeftV = new Point3(-imageTipX, imageTipY, imageDistance);
  dXV = new Point3(dX, 0.0, 0.0);
  dYV = new Point3(0.0, -dY, 0.0);
  firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5);
}

// compute camera rays
Point3 cameraRay(int pX, int pY){
  Point3 ray = firstPixel + (*dXV * pX) + (*dYV * pY);
  ray.Normalize();
  return ray;
}

// recursive object intersection through all scene objects
void objectIntersection(Node &n, Ray r, int pixel){

  // loop on child nodes
  int j = 0;
  int numChild = n.GetNumChild();
  while(j < numChild){

    // grab child node
    Node *child = n.GetChild(j);
    Object *obj = child->GetObject();

    // transform rays into model space (or local space)
    Ray r2 = child->ToNodeCoords(r);

    // compute ray intersections
    HitInfo h = HitInfo();
    bool hit = obj->IntersectRay(r2, h);

    // check the ray computation, update pixels
    if(hit)
      img[pixel] = white;

    // need to update background pixels?

    // recursively check this child's children
    objectIntersection(*child, r2, pixel);
    j++;
  }
}
<|endoftext|>


<commit_before>#ifndef PIXELBOOST_DISABLE_BOX2D

#include "Box2D/Box2D.h"

#include "pixelboost/graphics/renderer/box2d/box2dRenderer.h"
#include "pixelboost/logic/component/physics/physics.h"
#include "pixelboost/logic/message/physics/collision.h"
#include "pixelboost/logic/system/physics/2d/physics.h"
#include "pixelboost/logic/scene.h"

using namespace pb;

PhysicsSystem2D::PhysicsSystem2D(glm::vec2 gravity)
    : _DebugRender(false)
    , _PositionIterations(3)
    , _VelocityIterations(3)
{
    _World = new b2World(b2Vec2(gravity.x, gravity.y));

    _World->SetContactListener(this);

    _DebugRenderer = new Box2dRenderer();
    _World->SetDebugDraw(_DebugRenderer);
}

PhysicsSystem2D::~PhysicsSystem2D()
{
    delete _World;
    delete _DebugRenderer;
}

pb::Uid PhysicsSystem2D::GetType() const
{
    return PhysicsSystem2D::GetStaticType();
}

pb::Uid PhysicsSystem2D::GetStaticType()
{
    return pb::TypeHash("pb::PhysicsSystem2D");
}

void PhysicsSystem2D::Update(Scene* scene, float totalTime, float gameTime)
{
    _World->Step(gameTime, _VelocityIterations, _PositionIterations);

    if (_DebugRender)
    {
        _DebugRenderer->SetScene(scene);
        _World->DrawDebugData();
    }
}

void PhysicsSystem2D::Render(Scene* scene, Viewport* viewport, RenderPass renderPass)
{

}

b2World* PhysicsSystem2D::GetPhysicsWorld()
{
    return _World;
}

void PhysicsSystem2D::SetDebugRender(bool debugRender, int layer, int flags)
{
    _DebugRender = debugRender;
    _DebugRenderer->SetLayer(layer);
    _DebugRenderer->SetFlags(flags);
}

void PhysicsSystem2D::BeginContact(b2Contact* contact)
{
    b2Body* a = contact->GetFixtureA()->GetBody();
    b2Body* b = contact->GetFixtureB()->GetBody();

    pb::PhysicsComponent* actorA = static_cast<pb::PhysicsComponent*>(a->GetUserData());
    pb::PhysicsComponent* actorB = static_cast<pb::PhysicsComponent*>(b->GetUserData());

    b2WorldManifold worldManifold;
    contact->GetWorldManifold(&worldManifold);

    glm::vec2 position(worldManifold.points[0].x, worldManifold.points[0].y);
    glm::vec2 normal(worldManifold.normal.x, worldManifold.normal.y);

    pb::Scene* scene = actorA->GetScene();

    scene->SendMessage(actorA->GetEntityUid(), PhysicsCollisionStartMessage(actorB, position, normal));
    scene->SendMessage(actorB->GetEntityUid(), PhysicsCollisionStartMessage(actorA, position, -normal));
}

void PhysicsSystem2D::EndContact(b2Contact* contact)
{
    b2Body* a = contact->GetFixtureA()->GetBody();
    b2Body* b = contact->GetFixtureB()->GetBody();

    pb::PhysicsComponent* actorA = static_cast<pb::PhysicsComponent*>(a->GetUserData());
    pb::PhysicsComponent* actorB = static_cast<pb::PhysicsComponent*>(b->GetUserData());

    b2WorldManifold worldManifold;
    contact->GetWorldManifold(&worldManifold);

    glm::vec2 position(worldManifold.points[0].x, worldManifold.points[0].y);
    glm::vec2 normal(worldManifold.normal.x, worldManifold.normal.y);

    pb::Scene* scene = actorA->GetScene();

    scene->SendMessage(actorA->GetEntityUid(), PhysicsCollisionEndMessage(actorB, position, normal));
    scene->SendMessage(actorB->GetEntityUid(), PhysicsCollisionEndMessage(actorA, position, -normal));
}

void PhysicsSystem2D::PreSolve(b2Contact *contact, const b2Manifold *oldManifold)
{
    contact->ResetFriction();
}

#endif
<commit_msg>Return approximate collision points for sensors<commit_after>#ifndef PIXELBOOST_DISABLE_BOX2D

#include "Box2D/Box2D.h"

#include "pixelboost/graphics/renderer/box2d/box2dRenderer.h"
#include "pixelboost/logic/component/physics/physics.h"
#include "pixelboost/logic/message/physics/collision.h"
#include "pixelboost/logic/system/physics/2d/physics.h"
#include "pixelboost/logic/scene.h"

using namespace pb;

PhysicsSystem2D::PhysicsSystem2D(glm::vec2 gravity)
    : _DebugRender(false)
    , _PositionIterations(3)
    , _VelocityIterations(3)
{
    _World = new b2World(b2Vec2(gravity.x, gravity.y));

    _World->SetContactListener(this);

    _DebugRenderer = new Box2dRenderer();
    _World->SetDebugDraw(_DebugRenderer);
}

PhysicsSystem2D::~PhysicsSystem2D()
{
    delete _World;
    delete _DebugRenderer;
}

pb::Uid PhysicsSystem2D::GetType() const
{
    return PhysicsSystem2D::GetStaticType();
}

pb::Uid PhysicsSystem2D::GetStaticType()
{
    return pb::TypeHash("pb::PhysicsSystem2D");
}

void PhysicsSystem2D::Update(Scene* scene, float totalTime, float gameTime)
{
    _World->Step(gameTime, _VelocityIterations, _PositionIterations);

    if (_DebugRender)
    {
        _DebugRenderer->SetScene(scene);
        _World->DrawDebugData();
    }
}

void PhysicsSystem2D::Render(Scene* scene, Viewport* viewport, RenderPass renderPass)
{

}

b2World* PhysicsSystem2D::GetPhysicsWorld()
{
    return _World;
}

void PhysicsSystem2D::SetDebugRender(bool debugRender, int layer, int flags)
{
    _DebugRender = debugRender;
    _DebugRenderer->SetLayer(layer);
    _DebugRenderer->SetFlags(flags);
}

void PhysicsSystem2D::BeginContact(b2Contact* contact)
{
    b2Body* a = contact->GetFixtureA()->GetBody();
    b2Body* b = contact->GetFixtureB()->GetBody();

    pb::PhysicsComponent* actorA = static_cast<pb::PhysicsComponent*>(a->GetUserData());
    pb::PhysicsComponent* actorB = static_cast<pb::PhysicsComponent*>(b->GetUserData());

    glm::vec2 position;
    glm::vec2 normal;

    if (contact->GetManifold()->pointCount)
    {
        b2WorldManifold worldManifold;
        contact->GetWorldManifold(&worldManifold);

        for (int i=0; i<contact->GetManifold()->pointCount; i++)
        {
            position += glm::vec2(worldManifold.points[i].x, worldManifold.points[i].y);
        }
        position /= contact->GetManifold()->pointCount;

        normal = glm::vec2(worldManifold.normal.x, worldManifold.normal.y);
    } else {
        // If there are no manifold points (because one of the items is a sensor), use the average of the distance between the two items as a collision point
        position = (glm::vec2(a->GetTransform().p.x, a->GetTransform().p.y) + glm::vec2(b->GetTransform().p.x, b->GetTransform().p.y))/2.f;
    }

    pb::Scene* scene = actorA->GetScene();

    scene->SendMessage(actorA->GetEntityUid(), PhysicsCollisionStartMessage(actorB, position, normal));
    scene->SendMessage(actorB->GetEntityUid(), PhysicsCollisionStartMessage(actorA, position, -normal));
}

void PhysicsSystem2D::EndContact(b2Contact* contact)
{
    b2Body* a = contact->GetFixtureA()->GetBody();
    b2Body* b = contact->GetFixtureB()->GetBody();

    pb::PhysicsComponent* actorA = static_cast<pb::PhysicsComponent*>(a->GetUserData());
    pb::PhysicsComponent* actorB = static_cast<pb::PhysicsComponent*>(b->GetUserData());

    b2WorldManifold worldManifold;
    contact->GetWorldManifold(&worldManifold);

    glm::vec2 position(worldManifold.points[0].x, worldManifold.points[0].y);
    glm::vec2 normal(worldManifold.normal.x, worldManifold.normal.y);

    pb::Scene* scene = actorA->GetScene();

    scene->SendMessage(actorA->GetEntityUid(), PhysicsCollisionEndMessage(actorB, position, normal));
    scene->SendMessage(actorB->GetEntityUid(), PhysicsCollisionEndMessage(actorA, position, -normal));
}

void PhysicsSystem2D::PreSolve(b2Contact *contact, const b2Manifold *oldManifold)
{
    contact->ResetFriction();
}

#endif
<|endoftext|>


<commit_before>#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>

#include "gui/buttongroup.hpp"
#include "gui/button.hpp"

#define BUTTONCOUNT 3

class ButtonGroupTest : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(ButtonGroupTest);
	CPPUNIT_TEST(activateTest);
	CPPUNIT_TEST_SUITE_END();

	public:
		void setUp()
		{
			group = new qrw::ButtonGroup();
			for(int i = 0; i < BUTTONCOUNT; ++i)
			{
				buttons[i] = new qrw::Button();
				group->addButton(buttons[i]);
			}
		}

		void tearDown()
		{
			delete group;
			for(int i = 0; i < BUTTONCOUNT; ++i)
				delete buttons[i];
		}

		void activateTest()
		{
			for(int i = 0; i < BUTTONCOUNT; ++i)
				CPPUNIT_ASSERT(buttons[i]->getState() == qrw::Button::ES_INACTIVE);
			group->activateButton(buttons[0]);
			CPPUNIT_ASSERT(buttons[0]->getState() == qrw::Button::ES_ACTIVE);
			CPPUNIT_ASSERT(buttons[1]->getState() == qrw::Button::ES_INACTIVE);
			group->activateButton(buttons[2]);
			CPPUNIT_ASSERT(buttons[0]->getState() == qrw::Button::ES_INACTIVE);
			CPPUNIT_ASSERT(buttons[1]->getState() == qrw::Button::ES_INACTIVE);
			CPPUNIT_ASSERT(buttons[2]->getState() == qrw::Button::ES_ACTIVE);
		}

	private:
		qrw::ButtonGroup* group;
		qrw::Button* buttons[BUTTONCOUNT];
};

CPPUNIT_TEST_SUITE_REGISTRATION(ButtonGroupTest);<commit_msg>Fixed bad constructor call in ButtonGroupTest.<commit_after>#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>

#include "gui/buttongroup.hpp"
#include "gui/button.hpp"

#define BUTTONCOUNT 3

class ButtonGroupTest : public CppUnit::TestFixture
{
	CPPUNIT_TEST_SUITE(ButtonGroupTest);
	CPPUNIT_TEST(activateTest);
	CPPUNIT_TEST_SUITE_END();

	public:
		void setUp()
		{
			group = new qrw::ButtonGroup();
			for(int i = 0; i < BUTTONCOUNT; ++i)
			{
				buttons[i] = new qrw::Button(NULL);
				group->addButton(buttons[i]);
			}
		}

		void tearDown()
		{
			delete group;
			for(int i = 0; i < BUTTONCOUNT; ++i)
				delete buttons[i];
		}

		void activateTest()
		{
			for(int i = 0; i < BUTTONCOUNT; ++i)
				CPPUNIT_ASSERT(buttons[i]->getState() == qrw::Button::ES_INACTIVE);
			group->activateButton(buttons[0]);
			CPPUNIT_ASSERT(buttons[0]->getState() == qrw::Button::ES_ACTIVE);
			CPPUNIT_ASSERT(buttons[1]->getState() == qrw::Button::ES_INACTIVE);
			group->activateButton(buttons[2]);
			CPPUNIT_ASSERT(buttons[0]->getState() == qrw::Button::ES_INACTIVE);
			CPPUNIT_ASSERT(buttons[1]->getState() == qrw::Button::ES_INACTIVE);
			CPPUNIT_ASSERT(buttons[2]->getState() == qrw::Button::ES_ACTIVE);
		}

	private:
		qrw::ButtonGroup* group;
		qrw::Button* buttons[BUTTONCOUNT];
};

CPPUNIT_TEST_SUITE_REGISTRATION(ButtonGroupTest);<|endoftext|>


<commit_before>/*
 * tests/embodiment/Control/OperationalAvatarController/OACMock.cc
 *
 * @author Zhenhua Cai <czhedu@gmail.com>
 * @date   2011-06-14
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "OACMock.h"
#include <opencog/embodiment/Control/MessagingSystem/MessageFactory.h>

void OACMock::setConfig()
{
    // Set arguments used by OAC::init
    // You can easily get these arguments by set MANUAL_OAC_LAUNCH true in
    // config file, run the embodiment system and copy the command of
    // running OAC in console.
    agentBrainId = "123456";
    ownerId = "290";
    agentType = "pet";
    agentTrait = "Maxie";
    networkElementPort = "16326";
    cogServerShellPort = "17002";
    zmqPublishPort = "18002";

    // Set logger level
    logger().setLevel(Logger::FINE);
    logger().setPrintToStdoutFlag(true);

    // Load config file and reset some configurations
    config(opencog::control::EmbodimentConfig::embodimentCreateInstance, true);

    if ( fileExists(config().get("CONFIG_FILE").c_str()) ) {
        config().load(config().get("CONFIG_FILE").c_str());
    }

    config().set("EXTERNAL_TICK_MODE", "true");
    config().set("SERVER_PORT", cogServerShellPort);
    config().set("ZMQ_PUBLISH_PORT", zmqPublishPort);

    config().set("MODULES", "libquery.so, libbuiltinreqs.so, \
                             libscheme-shell.so, libpersist.so");

    config().set("RUN_OAC_DEBUGGER", "false");
    config().set("MANUAL_OAC_LAUNCH", "false");
    config().set("ENABLE_UNITY_CONNECTOR", "false");
    //config().set("USE_3D_MAP", "false");

    // Put the log file in the current directory -- also print log
    // location to the screen.
    config().set("LOG_DIR", ".");
    config().set("PRINT_LOG_TO_STDOUT", "true");

    // Disable opencog::spatial::MapExplorerServer, which raises
    // 'bad file descriptor' error during unit test
    config().set("VISUAL_DEBUGGER_ACTIVE", "false");
};

OAC & OACMock::createOAC()
{
    // Create an instance of OAC
    server(OAC::createInstance);
    this->oac = & static_cast<OAC&>(server());

    // Open database *before* loading modules, since the modules
    // might create atoms, and we can't have that happen until
    // storage is open, as otherwise, there will be handle conflicts.
    oac->openDatabase();

    // Load modules specified in config
    oac->loadModules();

    const char* config_path[] = {"."};
    oac->loadSCMModules(config_path);

    // Initialize OAC
    //
    // OAC::loadSCMModules should be called before calling OAC::init,
    // because OAC::loadSCMModules will load 'rules_core.scm',  which should be loaded
    // before loading Psi Rules ('xxx_rules.scm') and
    // OAC::init is responsible for loading Psi Rules via OAC::addRulesToAtomSpace
    int portNumber = boost::lexical_cast<int>(networkElementPort);
    oac->init(
        agentBrainId,       // agent-brain-id, i.e., id of OAC
        "127.0.0.1",        // NetworkElement ip
        portNumber,         // NetworkElement port number
        zmqPublishPort,     // ZeroMQ port used by subscribers to get messages
        PAIUtils::getInternalId(agentBrainId.c_str()), // pet id
        PAIUtils::getInternalId(ownerId.c_str()),      // owner id
        agentType,  // agent type
        agentTrait  // agent traits
    );

    // enable the network server
    oac->enableNetworkServer();

    // Return the reference of newly created OAC
    return *(this->oac);
}

Message * OACMock::createMessageFromFile(const std::string & from,
                                         const std::string & to,
                                         int msgType,
                                         const char * fileName)
{
    Message * p_message = NULL;

    std::ifstream in(fileName);

    if ( in.good() ) {
        std::istreambuf_iterator<char> beg(in), end;
        std::string msgContent(beg, end);
        p_message = messageFactory(from, to, msgType, msgContent);
    }
    else {
        logger().error("OACMock::%s - Fail to create message from file '%s'",
                       __FUNCTION__,
                       fileName
                      );
    }

    in.close();

    return p_message;
}

<commit_msg>Add explicit locations to the modules to be loaded.<commit_after>/*
 * tests/embodiment/Control/OperationalAvatarController/OACMock.cc
 *
 * @author Zhenhua Cai <czhedu@gmail.com>
 * @date   2011-06-14
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License v3 as
 * published by the Free Software Foundation and including the exceptions
 * at http://opencog.org/wiki/Licenses
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, write to:
 * Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "OACMock.h"
#include <opencog/embodiment/Control/MessagingSystem/MessageFactory.h>

void OACMock::setConfig()
{
    // Set arguments used by OAC::init
    // You can easily get these arguments by set MANUAL_OAC_LAUNCH true in
    // config file, run the embodiment system and copy the command of
    // running OAC in console.
    agentBrainId = "123456";
    ownerId = "290";
    agentType = "pet";
    agentTrait = "Maxie";
    networkElementPort = "16326";
    cogServerShellPort = "17002";
    zmqPublishPort = "18002";

    // Set logger level
    logger().setLevel(Logger::FINE);
    logger().setPrintToStdoutFlag(true);

    // Load config file and reset some configurations
    config(opencog::control::EmbodimentConfig::embodimentCreateInstance, true);

    if ( fileExists(config().get("CONFIG_FILE").c_str()) ) {
        config().load(config().get("CONFIG_FILE").c_str());
    }

    config().set("EXTERNAL_TICK_MODE", "true");
    config().set("SERVER_PORT", cogServerShellPort);
    config().set("ZMQ_PUBLISH_PORT", zmqPublishPort);

    // XXX FIXME: at this time, we need to specify explicit paths to
    // to the modules that need to be loaded. I don't know why.
    config().set("MODULES", "opencog/query/libquery.so, "
                            "opencog/server/libbuiltinreqs.so, "
                            "opencog/shell/libscheme-shell.so, "
                            "opencog/persist/sql/libpersist.so");

    config().set("RUN_OAC_DEBUGGER", "false");
    config().set("MANUAL_OAC_LAUNCH", "false");
    config().set("ENABLE_UNITY_CONNECTOR", "false");
    //config().set("USE_3D_MAP", "false");

    // Put the log file in the current directory -- also print log
    // location to the screen.
    config().set("LOG_DIR", ".");
    config().set("PRINT_LOG_TO_STDOUT", "true");

    // Disable opencog::spatial::MapExplorerServer, which raises
    // 'bad file descriptor' error during unit test
    config().set("VISUAL_DEBUGGER_ACTIVE", "false");
};

OAC & OACMock::createOAC()
{
    // Create an instance of OAC
    server(OAC::createInstance);
    this->oac = & static_cast<OAC&>(server());

    // Open database *before* loading modules, since the modules
    // might create atoms, and we can't have that happen until
    // storage is open, as otherwise, there will be handle conflicts.
    oac->openDatabase();

    // Load modules specified in config
    oac->loadModules();

    const char* config_path[] = {"."};
    oac->loadSCMModules(config_path);

    // Initialize OAC
    //
    // OAC::loadSCMModules should be called before calling OAC::init,
    // because OAC::loadSCMModules will load 'rules_core.scm',  which should be loaded
    // before loading Psi Rules ('xxx_rules.scm') and
    // OAC::init is responsible for loading Psi Rules via OAC::addRulesToAtomSpace
    int portNumber = boost::lexical_cast<int>(networkElementPort);
    oac->init(
        agentBrainId,       // agent-brain-id, i.e., id of OAC
        "127.0.0.1",        // NetworkElement ip
        portNumber,         // NetworkElement port number
        zmqPublishPort,     // ZeroMQ port used by subscribers to get messages
        PAIUtils::getInternalId(agentBrainId.c_str()), // pet id
        PAIUtils::getInternalId(ownerId.c_str()),      // owner id
        agentType,  // agent type
        agentTrait  // agent traits
    );

    // enable the network server
    oac->enableNetworkServer();

    // Return the reference of newly created OAC
    return *(this->oac);
}

Message * OACMock::createMessageFromFile(const std::string & from,
                                         const std::string & to,
                                         int msgType,
                                         const char * fileName)
{
    Message * p_message = NULL;

    std::ifstream in(fileName);

    if ( in.good() ) {
        std::istreambuf_iterator<char> beg(in), end;
        std::string msgContent(beg, end);
        p_message = messageFactory(from, to, msgType, msgContent);
    }
    else {
        logger().error("OACMock::%s - Fail to create message from file '%s'",
                       __FUNCTION__,
                       fileName
                      );
    }

    in.close();

    return p_message;
}

<|endoftext|>


<commit_before>//===-- MachineFunction.cpp -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect native machine code information for a function.  This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
using namespace llvm;

static AnnotationID MF_AID(
                 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));

namespace {
  struct Printer : public MachineFunctionPass {
    std::ostream *OS;
    const std::string Banner;

    Printer (std::ostream *_OS, const std::string &_Banner) :
      OS (_OS), Banner (_Banner) { }

    const char *getPassName() const { return "MachineFunction Printer"; }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }

    bool runOnMachineFunction(MachineFunction &MF) {
      (*OS) << Banner;
      MF.print (*OS);
      return false;
    }
  };
}

/// Returns a newly-created MachineFunction Printer pass. The default output
/// stream is std::cerr; the default banner is empty.
///
FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
                                                     const std::string &Banner) {
  return new Printer(OS, Banner);
}

namespace {
  struct Deleter : public MachineFunctionPass {
    const char *getPassName() const { return "Machine Code Deleter"; }

    bool runOnMachineFunction(MachineFunction &MF) {
      // Delete the annotation from the function now.
      MachineFunction::destruct(MF.getFunction());
      return true;
    }
  };
}

/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
/// the current function, which should happen after the function has been
/// emitted to a .s file or to memory.
FunctionPass *llvm::createMachineCodeDeleter() {
  return new Deleter();
}

//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//

MachineFunction::MachineFunction(const Function *F,
                                 const TargetMachine &TM)
  : Annotation(MF_AID), Fn(F), Target(TM) {
  SSARegMapping = new SSARegMap();
  MFInfo = new MachineFunctionInfo(*this);
  FrameInfo = new MachineFrameInfo();
  ConstantPool = new MachineConstantPool();
}

MachineFunction::~MachineFunction() {
  delete SSARegMapping;
  delete MFInfo;
  delete FrameInfo;
  delete ConstantPool;
}

void MachineFunction::dump() const { print(std::cerr); }

void MachineFunction::print(std::ostream &OS) const {
  OS << "# Machine code for " << Fn->getName () << "():\n";

  // Print Frame Information
  getFrameInfo()->print(*this, OS);

  // Print Constant Pool
  getConstantPool()->print(OS);

  for (const_iterator BB = begin(); BB != end(); ++BB)
    BB->print(OS);

  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
}

// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get()       -- Returns a handle to the object.
//                This should not be called before "construct()"
//                for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
  assert(Fn->getAnnotation(MF_AID) == 0 &&
         "Object already exists for this function!");
  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
  Fn->addAnnotation(mcInfo);
  return *mcInfo;
}

void MachineFunction::destruct(const Function *Fn) {
  bool Deleted = Fn->deleteAnnotation(MF_AID);
  assert(Deleted && "Machine code did not exist for function!");
}

MachineFunction& MachineFunction::get(const Function *F)
{
  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
  assert(mc && "Call construct() method first to allocate the object");
  return *mc;
}

void MachineFunction::clearSSARegMap() {
  delete SSARegMapping;
  SSARegMapping = 0;
}

//===----------------------------------------------------------------------===//
//  MachineFrameInfo implementation
//===----------------------------------------------------------------------===//

/// CreateStackObject - Create a stack object for a value of the specified type.
///
int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
}

int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
  return CreateStackObject(RC->getSize(), RC->getAlignment());
}

void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
  int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea();

  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
    const StackObject &SO = Objects[i];
    OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
    if (SO.Size == 0)
      OS << "variable sized";
    else
      OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");

    if (i < NumFixedObjects)
      OS << " fixed";
    if (i < NumFixedObjects || SO.SPOffset != -1) {
      int Off = SO.SPOffset + ValOffset;
      OS << " at location [SP";
      if (Off > 0)
	OS << "+" << Off;
      else if (Off < 0)
	OS << Off;
      OS << "]";
    }
    OS << "\n";
  }

  if (HasVarSizedObjects)
    OS << "  Stack frame contains variable sized objects\n";
}

void MachineFrameInfo::dump(const MachineFunction &MF) const {
  print(MF, std::cerr);
}

//===----------------------------------------------------------------------===//
//  MachineConstantPool implementation
//===----------------------------------------------------------------------===//

void MachineConstantPool::print(std::ostream &OS) const {
  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
    OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
}

void MachineConstantPool::dump() const { print(std::cerr); }

//===----------------------------------------------------------------------===//
//  MachineFunctionInfo implementation
//===----------------------------------------------------------------------===//

static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
                           unsigned &maxOptionalNumArgs)
{
  const TargetFrameInfo &frameInfo = target.getFrameInfo();

  unsigned maxSize = 0;

  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      if (const CallInst *callInst = dyn_cast<CallInst>(I))
        {
          unsigned numOperands = callInst->getNumOperands() - 1;
          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
          if (numExtra <= 0)
            continue;

          unsigned sizeForThisCall;
          if (frameInfo.argsOnStackHaveFixedSize())
            {
              int argSize = frameInfo.getSizeOfEachArgOnStack();
              sizeForThisCall = numExtra * (unsigned) argSize;
            }
          else
            {
              assert(0 && "UNTESTED CODE: Size per stack argument is not "
                     "fixed on this architecture: use actual arg sizes to "
                     "compute MaxOptionalArgsSize");
              sizeForThisCall = 0;
              for (unsigned i = 0; i < numOperands; ++i)
                sizeForThisCall += target.getTargetData().getTypeSize(callInst->
                                              getOperand(i)->getType());
            }

          if (maxSize < sizeForThisCall)
            maxSize = sizeForThisCall;

          if ((int)maxOptionalNumArgs < numExtra)
            maxOptionalNumArgs = (unsigned) numExtra;
        }

  return maxSize;
}

// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated.  This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned
SizeToAlignment(unsigned size, const TargetMachine& target)
{
  const unsigned short cacheLineSize = 16;
  if (size > (unsigned) cacheLineSize / 2)
    return cacheLineSize;
  else
    for (unsigned sz=1; /*no condition*/; sz *= 2)
      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
        return sz;
}

void MachineFunctionInfo::CalculateArgSize() {
  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
						   MF.getFunction(),
                                                   maxOptionalNumArgs);
  staticStackSize = maxOptionalArgsSize
    + MF.getTarget().getFrameInfo().getMinStackFrameSize();
}

int
MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
					      unsigned &getPaddedSize,
					      unsigned  sizeToUse)
{
  if (sizeToUse == 0)
    sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
									     growUp);
  int offset = growUp? firstOffset + getAutomaticVarsSize()
                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
  getPaddedSize = sizeToUse + abs(aligned - offset);

  return aligned;
}

int MachineFunctionInfo::allocateLocalVar(const Value* val,
                                          unsigned sizeToUse) {
  assert(! automaticVarsAreaFrozen &&
         "Size of auto vars area has been used to compute an offset so "
         "no more automatic vars should be allocated!");

  // Check if we've allocated a stack slot for this value already
  //
  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
  if (pair != offsets.end())
    return pair->second;

  unsigned getPaddedSize;
  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
  offsets[val] = offset;
  incrementAutomaticVarsSize(getPaddedSize);
  return offset;
}

int
MachineFunctionInfo::allocateSpilledValue(const Type* type)
{
  assert(! spillsAreaFrozen &&
         "Size of reg spills area has been used to compute an offset so "
         "no more register spill slots should be allocated!");

  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + getRegSpillsSize()
                     : firstOffset - (getRegSpillsSize() + size);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementRegSpillsSize(size);  // update size of reg. spills area

  return aligned;
}

int
MachineFunctionInfo::pushTempValue(unsigned size)
{
  unsigned align = SizeToAlignment(size, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + currentTmpValuesSize
                     : firstOffset - (currentTmpValuesSize + size);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
							      align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementTmpAreaSize(size);    // update "current" size of tmp area

  return aligned;
}

void MachineFunctionInfo::popAllTempValues() {
  resetTmpAreaSize();            // clear tmp area to reuse
}

<commit_msg>Start NextMBBNumber out at zero.<commit_after>//===-- MachineFunction.cpp -----------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Collect native machine code information for a function.  This allows
// target-specific information about the generated code to be stored with each
// function.
//
//===----------------------------------------------------------------------===//

#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/MachineFunctionInfo.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetFrameInfo.h"
#include "llvm/Function.h"
#include "llvm/iOther.h"
using namespace llvm;

static AnnotationID MF_AID(
                 AnnotationManager::getID("CodeGen::MachineCodeForFunction"));

namespace {
  struct Printer : public MachineFunctionPass {
    std::ostream *OS;
    const std::string Banner;

    Printer (std::ostream *_OS, const std::string &_Banner) :
      OS (_OS), Banner (_Banner) { }

    const char *getPassName() const { return "MachineFunction Printer"; }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AU.setPreservesAll();
    }

    bool runOnMachineFunction(MachineFunction &MF) {
      (*OS) << Banner;
      MF.print (*OS);
      return false;
    }
  };
}

/// Returns a newly-created MachineFunction Printer pass. The default output
/// stream is std::cerr; the default banner is empty.
///
FunctionPass *llvm::createMachineFunctionPrinterPass(std::ostream *OS,
                                                     const std::string &Banner) {
  return new Printer(OS, Banner);
}

namespace {
  struct Deleter : public MachineFunctionPass {
    const char *getPassName() const { return "Machine Code Deleter"; }

    bool runOnMachineFunction(MachineFunction &MF) {
      // Delete the annotation from the function now.
      MachineFunction::destruct(MF.getFunction());
      return true;
    }
  };
}

/// MachineCodeDeletion Pass - This pass deletes all of the machine code for
/// the current function, which should happen after the function has been
/// emitted to a .s file or to memory.
FunctionPass *llvm::createMachineCodeDeleter() {
  return new Deleter();
}

//===---------------------------------------------------------------------===//
// MachineFunction implementation
//===---------------------------------------------------------------------===//

MachineFunction::MachineFunction(const Function *F,
                                 const TargetMachine &TM)
  : Annotation(MF_AID), Fn(F), Target(TM), NextMBBNumber(0) {
  SSARegMapping = new SSARegMap();
  MFInfo = new MachineFunctionInfo(*this);
  FrameInfo = new MachineFrameInfo();
  ConstantPool = new MachineConstantPool();
}

MachineFunction::~MachineFunction() {
  delete SSARegMapping;
  delete MFInfo;
  delete FrameInfo;
  delete ConstantPool;
}

void MachineFunction::dump() const { print(std::cerr); }

void MachineFunction::print(std::ostream &OS) const {
  OS << "# Machine code for " << Fn->getName () << "():\n";

  // Print Frame Information
  getFrameInfo()->print(*this, OS);

  // Print Constant Pool
  getConstantPool()->print(OS);

  for (const_iterator BB = begin(); BB != end(); ++BB)
    BB->print(OS);

  OS << "\n# End machine code for " << Fn->getName () << "().\n\n";
}

// The next two methods are used to construct and to retrieve
// the MachineCodeForFunction object for the given function.
// construct() -- Allocates and initializes for a given function and target
// get()       -- Returns a handle to the object.
//                This should not be called before "construct()"
//                for a given Function.
//
MachineFunction&
MachineFunction::construct(const Function *Fn, const TargetMachine &Tar)
{
  assert(Fn->getAnnotation(MF_AID) == 0 &&
         "Object already exists for this function!");
  MachineFunction* mcInfo = new MachineFunction(Fn, Tar);
  Fn->addAnnotation(mcInfo);
  return *mcInfo;
}

void MachineFunction::destruct(const Function *Fn) {
  bool Deleted = Fn->deleteAnnotation(MF_AID);
  assert(Deleted && "Machine code did not exist for function!");
}

MachineFunction& MachineFunction::get(const Function *F)
{
  MachineFunction *mc = (MachineFunction*)F->getAnnotation(MF_AID);
  assert(mc && "Call construct() method first to allocate the object");
  return *mc;
}

void MachineFunction::clearSSARegMap() {
  delete SSARegMapping;
  SSARegMapping = 0;
}

//===----------------------------------------------------------------------===//
//  MachineFrameInfo implementation
//===----------------------------------------------------------------------===//

/// CreateStackObject - Create a stack object for a value of the specified type.
///
int MachineFrameInfo::CreateStackObject(const Type *Ty, const TargetData &TD) {
  return CreateStackObject(TD.getTypeSize(Ty), TD.getTypeAlignment(Ty));
}

int MachineFrameInfo::CreateStackObject(const TargetRegisterClass *RC) {
  return CreateStackObject(RC->getSize(), RC->getAlignment());
}

void MachineFrameInfo::print(const MachineFunction &MF, std::ostream &OS) const{
  int ValOffset = MF.getTarget().getFrameInfo().getOffsetOfLocalArea();

  for (unsigned i = 0, e = Objects.size(); i != e; ++i) {
    const StackObject &SO = Objects[i];
    OS << "  <fi #" << (int)(i-NumFixedObjects) << "> is ";
    if (SO.Size == 0)
      OS << "variable sized";
    else
      OS << SO.Size << " byte" << (SO.Size != 1 ? "s" : " ");

    if (i < NumFixedObjects)
      OS << " fixed";
    if (i < NumFixedObjects || SO.SPOffset != -1) {
      int Off = SO.SPOffset + ValOffset;
      OS << " at location [SP";
      if (Off > 0)
	OS << "+" << Off;
      else if (Off < 0)
	OS << Off;
      OS << "]";
    }
    OS << "\n";
  }

  if (HasVarSizedObjects)
    OS << "  Stack frame contains variable sized objects\n";
}

void MachineFrameInfo::dump(const MachineFunction &MF) const {
  print(MF, std::cerr);
}

//===----------------------------------------------------------------------===//
//  MachineConstantPool implementation
//===----------------------------------------------------------------------===//

void MachineConstantPool::print(std::ostream &OS) const {
  for (unsigned i = 0, e = Constants.size(); i != e; ++i)
    OS << "  <cp #" << i << "> is" << *(Value*)Constants[i] << "\n";
}

void MachineConstantPool::dump() const { print(std::cerr); }

//===----------------------------------------------------------------------===//
//  MachineFunctionInfo implementation
//===----------------------------------------------------------------------===//

static unsigned
ComputeMaxOptionalArgsSize(const TargetMachine& target, const Function *F,
                           unsigned &maxOptionalNumArgs)
{
  const TargetFrameInfo &frameInfo = target.getFrameInfo();

  unsigned maxSize = 0;

  for (Function::const_iterator BB = F->begin(), BBE = F->end(); BB !=BBE; ++BB)
    for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I)
      if (const CallInst *callInst = dyn_cast<CallInst>(I))
        {
          unsigned numOperands = callInst->getNumOperands() - 1;
          int numExtra = (int)numOperands-frameInfo.getNumFixedOutgoingArgs();
          if (numExtra <= 0)
            continue;

          unsigned sizeForThisCall;
          if (frameInfo.argsOnStackHaveFixedSize())
            {
              int argSize = frameInfo.getSizeOfEachArgOnStack();
              sizeForThisCall = numExtra * (unsigned) argSize;
            }
          else
            {
              assert(0 && "UNTESTED CODE: Size per stack argument is not "
                     "fixed on this architecture: use actual arg sizes to "
                     "compute MaxOptionalArgsSize");
              sizeForThisCall = 0;
              for (unsigned i = 0; i < numOperands; ++i)
                sizeForThisCall += target.getTargetData().getTypeSize(callInst->
                                              getOperand(i)->getType());
            }

          if (maxSize < sizeForThisCall)
            maxSize = sizeForThisCall;

          if ((int)maxOptionalNumArgs < numExtra)
            maxOptionalNumArgs = (unsigned) numExtra;
        }

  return maxSize;
}

// Align data larger than one L1 cache line on L1 cache line boundaries.
// Align all smaller data on the next higher 2^x boundary (4, 8, ...),
// but not higher than the alignment of the largest type we support
// (currently a double word). -- see class TargetData).
//
// This function is similar to the corresponding function in EmitAssembly.cpp
// but they are unrelated.  This one does not align at more than a
// double-word boundary whereas that one might.
//
inline unsigned
SizeToAlignment(unsigned size, const TargetMachine& target)
{
  const unsigned short cacheLineSize = 16;
  if (size > (unsigned) cacheLineSize / 2)
    return cacheLineSize;
  else
    for (unsigned sz=1; /*no condition*/; sz *= 2)
      if (sz >= size || sz >= target.getTargetData().getDoubleAlignment())
        return sz;
}

void MachineFunctionInfo::CalculateArgSize() {
  maxOptionalArgsSize = ComputeMaxOptionalArgsSize(MF.getTarget(),
						   MF.getFunction(),
                                                   maxOptionalNumArgs);
  staticStackSize = maxOptionalArgsSize
    + MF.getTarget().getFrameInfo().getMinStackFrameSize();
}

int
MachineFunctionInfo::computeOffsetforLocalVar(const Value* val,
					      unsigned &getPaddedSize,
					      unsigned  sizeToUse)
{
  if (sizeToUse == 0)
    sizeToUse = MF.getTarget().findOptimalStorageSize(val->getType());
  unsigned align = SizeToAlignment(sizeToUse, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getFirstAutomaticVarOffset(MF,
									     growUp);
  int offset = growUp? firstOffset + getAutomaticVarsSize()
                     : firstOffset - (getAutomaticVarsSize() + sizeToUse);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
  getPaddedSize = sizeToUse + abs(aligned - offset);

  return aligned;
}

int MachineFunctionInfo::allocateLocalVar(const Value* val,
                                          unsigned sizeToUse) {
  assert(! automaticVarsAreaFrozen &&
         "Size of auto vars area has been used to compute an offset so "
         "no more automatic vars should be allocated!");

  // Check if we've allocated a stack slot for this value already
  //
  hash_map<const Value*, int>::const_iterator pair = offsets.find(val);
  if (pair != offsets.end())
    return pair->second;

  unsigned getPaddedSize;
  unsigned offset = computeOffsetforLocalVar(val, getPaddedSize, sizeToUse);
  offsets[val] = offset;
  incrementAutomaticVarsSize(getPaddedSize);
  return offset;
}

int
MachineFunctionInfo::allocateSpilledValue(const Type* type)
{
  assert(! spillsAreaFrozen &&
         "Size of reg spills area has been used to compute an offset so "
         "no more register spill slots should be allocated!");

  unsigned size  = MF.getTarget().getTargetData().getTypeSize(type);
  unsigned char align = MF.getTarget().getTargetData().getTypeAlignment(type);

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getRegSpillAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + getRegSpillsSize()
                     : firstOffset - (getRegSpillsSize() + size);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp, align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementRegSpillsSize(size);  // update size of reg. spills area

  return aligned;
}

int
MachineFunctionInfo::pushTempValue(unsigned size)
{
  unsigned align = SizeToAlignment(size, MF.getTarget());

  bool growUp;
  int firstOffset = MF.getTarget().getFrameInfo().getTmpAreaOffset(MF, growUp);

  int offset = growUp? firstOffset + currentTmpValuesSize
                     : firstOffset - (currentTmpValuesSize + size);

  int aligned = MF.getTarget().getFrameInfo().adjustAlignment(offset, growUp,
							      align);
  size += abs(aligned - offset); // include alignment padding in size

  incrementTmpAreaSize(size);    // update "current" size of tmp area

  return aligned;
}

void MachineFunctionInfo::popAllTempValues() {
  resetTmpAreaSize();            // clear tmp area to reuse
}

<|endoftext|>


<commit_before>//===-- DWARFTypeUnit.cpp -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "DWARFTypeUnit.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

bool DWARFTypeUnit::extractImpl(DataExtractor debug_info,
                                uint32_t *offset_ptr) {
  if (!DWARFUnit::extractImpl(debug_info, offset_ptr))
    return false;
  TypeHash = debug_info.getU64(offset_ptr);
  TypeOffset = debug_info.getU32(offset_ptr);
  return TypeOffset < getLength();
}

void DWARFTypeUnit::dump(raw_ostream &OS) {
  OS << format("0x%08x", getOffset()) << ": Type Unit:"
     << " length = " << format("0x%08x", getLength())
     << " version = " << format("0x%04x", getVersion())
     << " abbr_offset = " << format("0x%04x", getAbbreviations()->getOffset())
     << " addr_size = " << format("0x%02x", getAddressByteSize())
     << " type_signature = " << format("0x%16lx", TypeHash)
     << " type_offset = " << format("0x%04x", TypeOffset)
     << " (next unit at " << format("0x%08x", getNextUnitOffset())
     << ")\n";

  const DWARFDebugInfoEntryMinimal *CU = getCompileUnitDIE(false);
  assert(CU && "Null Compile Unit?");
  CU->dump(OS, this, -1U);
}
<commit_msg>DWARFTypeUnit::dump(): Use PRIx64 to format uint64_t.<commit_after>//===-- DWARFTypeUnit.cpp -------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "DWARFTypeUnit.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"

using namespace llvm;

bool DWARFTypeUnit::extractImpl(DataExtractor debug_info,
                                uint32_t *offset_ptr) {
  if (!DWARFUnit::extractImpl(debug_info, offset_ptr))
    return false;
  TypeHash = debug_info.getU64(offset_ptr);
  TypeOffset = debug_info.getU32(offset_ptr);
  return TypeOffset < getLength();
}

void DWARFTypeUnit::dump(raw_ostream &OS) {
  OS << format("0x%08x", getOffset()) << ": Type Unit:"
     << " length = " << format("0x%08x", getLength())
     << " version = " << format("0x%04x", getVersion())
     << " abbr_offset = " << format("0x%04x", getAbbreviations()->getOffset())
     << " addr_size = " << format("0x%02x", getAddressByteSize())
     << " type_signature = " << format("0x%16" PRIx64, TypeHash)
     << " type_offset = " << format("0x%04x", TypeOffset)
     << " (next unit at " << format("0x%08x", getNextUnitOffset())
     << ")\n";

  const DWARFDebugInfoEntryMinimal *CU = getCompileUnitDIE(false);
  assert(CU && "Null Compile Unit?");
  CU->dump(OS, this, -1U);
}
<|endoftext|>


<commit_before>#include <iostream>

#include "matrix.h"
#include "checks.h"

template<std::size_t NumberOfRows, std::size_t NumberOfCulomns, std::size_t NumberOfSecondRows>
int TestMatrixProduct() {
	std::cout << "Testing A(" << NumberOfRows << "," << NumberOfCulomns << ") X B(" <<  NumberOfCulomns << "," << NumberOfSecondRows << ") ";
	AMatrix::Matrix<double, NumberOfRows,NumberOfCulomns> a_matrix;
	AMatrix::Matrix<double, NumberOfCulomns,NumberOfSecondRows> b_matrix;
	AMatrix::Matrix<double, NumberOfRows,NumberOfSecondRows> c_matrix;
	for (int i = 0; i < a_matrix.size1(); i++)
		for (int j = 0; j < a_matrix.size2(); j++)
			if(i == j)
				a_matrix(i, j) = 2.33*(i+1);
			else
			 	a_matrix(i,j) = 0.00;

	for (int i = 0; i < b_matrix.size1(); i++)
		for (int j = 0; j < b_matrix.size2(); j++)
			b_matrix(i, j) = i + j + 1;

	c_matrix = a_matrix * b_matrix;

	std::cout << std::endl;
	std::cout << a_matrix << std::endl;
	std::cout << b_matrix << std::endl;
	std::cout << c_matrix << std::endl;

	for (int i = 0; i < c_matrix.size1(); i++)
		for (int j = 0; j < c_matrix.size2(); j++)
				if(static_cast<std::size_t>(i) < NumberOfCulomns)
					AMATRIX_CHECK_EQUAL(c_matrix(i,j), b_matrix(i,j)*(i+1)*2.33);

	std::cout << "OK" << std::endl;
	return 0; // not failed
}

int main()
{
	int number_of_failed_tests = 0;
	number_of_failed_tests += TestMatrixProduct<1,1,1>();

	number_of_failed_tests += TestMatrixProduct<1,1,2>();
	number_of_failed_tests += TestMatrixProduct<2,1,1>();
	number_of_failed_tests += TestMatrixProduct<2,1,2>();

	number_of_failed_tests += TestMatrixProduct<3,1,1>();
	number_of_failed_tests += TestMatrixProduct<3,1,2>();
	number_of_failed_tests += TestMatrixProduct<3,1,3>();
	number_of_failed_tests += TestMatrixProduct<1,1,3>();
	number_of_failed_tests += TestMatrixProduct<2,1,3>();
	number_of_failed_tests += TestMatrixProduct<3,1,3>();

	number_of_failed_tests += TestMatrixProduct<1,2,1>();

	number_of_failed_tests += TestMatrixProduct<1,2,2>();
	number_of_failed_tests += TestMatrixProduct<2,2,1>();
	number_of_failed_tests += TestMatrixProduct<2,2,2>();

	number_of_failed_tests += TestMatrixProduct<3,2,1>();
	number_of_failed_tests += TestMatrixProduct<3,2,2>();
	number_of_failed_tests += TestMatrixProduct<3,2,3>();
	number_of_failed_tests += TestMatrixProduct<1,2,3>();
	number_of_failed_tests += TestMatrixProduct<2,2,3>();
	number_of_failed_tests += TestMatrixProduct<3,2,3>();

	number_of_failed_tests += TestMatrixProduct<1,3,1>();

	number_of_failed_tests += TestMatrixProduct<1,3,2>();
	number_of_failed_tests += TestMatrixProduct<2,3,1>();
	number_of_failed_tests += TestMatrixProduct<2,3,2>();

	number_of_failed_tests += TestMatrixProduct<3,3,1>();
	number_of_failed_tests += TestMatrixProduct<3,3,2>();
	number_of_failed_tests += TestMatrixProduct<3,3,3>();
	number_of_failed_tests += TestMatrixProduct<1,3,3>();
	number_of_failed_tests += TestMatrixProduct<2,3,3>();
	number_of_failed_tests += TestMatrixProduct<3,3,3>();

	std::cout << number_of_failed_tests << " tests failed" << std::endl;

	return number_of_failed_tests;
}

<commit_msg>Adding scalar multiplication test<commit_after>#include <iostream>

#include "matrix.h"
#include "checks.h"

template <std::size_t NumberOfRows, std::size_t NumberOfCulomns>
int TestMatrixScalarProduct() {
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> a_matrix;
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> b_matrix;
    for (int i = 0; i < a_matrix.size1(); i++)
        for (int j = 0; j < a_matrix.size2(); j++)
            a_matrix(i, j) = 2.33 * i - 4.52 * j;

    b_matrix = 1.3 * a_matrix * 0.34;
    b_matrix = 2 * b_matrix;

    for (int i = 0; i < a_matrix.size1(); i++)
        for (int j = 0; j < a_matrix.size2(); j++)
            AMATRIX_CHECK_EQUAL(b_matrix(i, j), 2 * 1.3 * (2.33 * i - 4.52 * j) * 0.34);

    return 0;  // not failed
}

template <std::size_t NumberOfRows, std::size_t NumberOfCulomns,
    std::size_t NumberOfSecondRows>
int TestMatrixProduct() {
    std::cout << "Testing A(" << NumberOfRows << "," << NumberOfCulomns
              << ") X B(" << NumberOfCulomns << "," << NumberOfSecondRows
              << ") ";
    AMatrix::Matrix<double, NumberOfRows, NumberOfCulomns> a_matrix;
    AMatrix::Matrix<double, NumberOfCulomns, NumberOfSecondRows> b_matrix;
    AMatrix::Matrix<double, NumberOfRows, NumberOfSecondRows> c_matrix;
    for (int i = 0; i < a_matrix.size1(); i++)
        for (int j = 0; j < a_matrix.size2(); j++)
            if (i == j)
                a_matrix(i, j) = 2.33 * (i + 1);
            else
                a_matrix(i, j) = 0.00;

    for (int i = 0; i < b_matrix.size1(); i++)
        for (int j = 0; j < b_matrix.size2(); j++)
            b_matrix(i, j) = i + j + 1;

    c_matrix = a_matrix * b_matrix;

    for (int i = 0; i < c_matrix.size1(); i++)
        for (int j = 0; j < c_matrix.size2(); j++)
            if (static_cast<std::size_t>(i) < NumberOfCulomns)
                AMATRIX_CHECK_EQUAL(
                    c_matrix(i, j), b_matrix(i, j) * (i + 1) * 2.33);

    std::cout << "OK" << std::endl;
    return 0;  // not failed
}

int main() {
    int number_of_failed_tests = 0;

    // scalar product test
    number_of_failed_tests += TestMatrixScalarProduct<1, 1>();

    number_of_failed_tests += TestMatrixScalarProduct<1, 2>();
    number_of_failed_tests += TestMatrixScalarProduct<2, 1>();
    number_of_failed_tests += TestMatrixScalarProduct<2, 2>();

    number_of_failed_tests += TestMatrixScalarProduct<3, 1>();
    number_of_failed_tests += TestMatrixScalarProduct<3, 2>();
    number_of_failed_tests += TestMatrixScalarProduct<3, 3>();
    number_of_failed_tests += TestMatrixScalarProduct<1, 3>();
    number_of_failed_tests += TestMatrixScalarProduct<2, 3>();
    number_of_failed_tests += TestMatrixScalarProduct<3, 3>();

    // matrix product test
    number_of_failed_tests += TestMatrixProduct<1, 1, 1>();

    number_of_failed_tests += TestMatrixProduct<1, 1, 2>();
    number_of_failed_tests += TestMatrixProduct<2, 1, 1>();
    number_of_failed_tests += TestMatrixProduct<2, 1, 2>();

    number_of_failed_tests += TestMatrixProduct<3, 1, 1>();
    number_of_failed_tests += TestMatrixProduct<3, 1, 2>();
    number_of_failed_tests += TestMatrixProduct<3, 1, 3>();
    number_of_failed_tests += TestMatrixProduct<1, 1, 3>();
    number_of_failed_tests += TestMatrixProduct<2, 1, 3>();
    number_of_failed_tests += TestMatrixProduct<3, 1, 3>();

    number_of_failed_tests += TestMatrixProduct<1, 2, 1>();

    number_of_failed_tests += TestMatrixProduct<1, 2, 2>();
    number_of_failed_tests += TestMatrixProduct<2, 2, 1>();
    number_of_failed_tests += TestMatrixProduct<2, 2, 2>();

    number_of_failed_tests += TestMatrixProduct<3, 2, 1>();
    number_of_failed_tests += TestMatrixProduct<3, 2, 2>();
    number_of_failed_tests += TestMatrixProduct<3, 2, 3>();
    number_of_failed_tests += TestMatrixProduct<1, 2, 3>();
    number_of_failed_tests += TestMatrixProduct<2, 2, 3>();
    number_of_failed_tests += TestMatrixProduct<3, 2, 3>();

    number_of_failed_tests += TestMatrixProduct<1, 3, 1>();

    number_of_failed_tests += TestMatrixProduct<1, 3, 2>();
    number_of_failed_tests += TestMatrixProduct<2, 3, 1>();
    number_of_failed_tests += TestMatrixProduct<2, 3, 2>();

    number_of_failed_tests += TestMatrixProduct<3, 3, 1>();
    number_of_failed_tests += TestMatrixProduct<3, 3, 2>();
    number_of_failed_tests += TestMatrixProduct<3, 3, 3>();
    number_of_failed_tests += TestMatrixProduct<1, 3, 3>();
    number_of_failed_tests += TestMatrixProduct<2, 3, 3>();
    number_of_failed_tests += TestMatrixProduct<3, 3, 3>();

    std::cout << number_of_failed_tests << " tests failed" << std::endl;

    return number_of_failed_tests;
}
<|endoftext|>