<commit_before>/*************************************************************************
 *
 *  $RCSfile: globdoc.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:42:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWGLOBDOCSH_HXX
#define _SWGLOBDOCSH_HXX

#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#include "docsh.hxx"

class SwGlobalDocShell : public SwDocShell
{
public:

    SFX_DECL_OBJECTFACTORY(SwGlobalDocShell);
    TYPEINFO();

    SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    ~SwGlobalDocShell();

    virtual void    FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;
};

#endif

<commit_msg>INTEGRATION: CWS mav09 (1.4.242); FILE MERGED 2004/08/12 17:11:45 mav 1.4.242.2: #i27773# introduce version back 2004/05/18 16:43:03 mba 1.4.242.1: RESYNC to m39<commit_after>/*************************************************************************
 *
 *  $RCSfile: globdoc.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:58:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWGLOBDOCSH_HXX
#define _SWGLOBDOCSH_HXX

#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#include "docsh.hxx"

class SwGlobalDocShell : public SwDocShell
{
public:

    SFX_DECL_OBJECTFACTORY();
    TYPEINFO();

    SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    ~SwGlobalDocShell();

    virtual void    FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   sal_Int32 nFileFormat ) const;
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: globdoc.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: jp $ $Date: 2001-07-05 17:29:32 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWGLOBDOCSH_HXX
#define _SWGLOBDOCSH_HXX

#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#include "docsh.hxx"

class SwGlobalDocShell : public SwDocShell
{
public:

    SFX_DECL_OBJECTFACTORY_DLL(SwGlobalDocShell, SW_DLL());
    TYPEINFO();

    SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    ~SwGlobalDocShell();

    virtual void    FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;
};

#endif

<commit_msg>INTEGRATION: CWS fwkq1 (1.3.276); FILE MERGED 2003/07/15 06:35:53 mba 1.3.276.1: #110843#: get rid of factories<commit_after>/*************************************************************************
 *
 *  $RCSfile: globdoc.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2003-09-19 08:42:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SWGLOBDOCSH_HXX
#define _SWGLOBDOCSH_HXX

#ifndef SW_SWDLL_HXX
#include <swdll.hxx>
#endif
#include "docsh.hxx"

class SwGlobalDocShell : public SwDocShell
{
public:

    SFX_DECL_OBJECTFACTORY(SwGlobalDocShell);
    TYPEINFO();

    SwGlobalDocShell(SfxObjectCreateMode eMode = SFX_CREATE_MODE_EMBEDDED);
    ~SwGlobalDocShell();

    virtual void    FillClass( SvGlobalName * pClassName,
                                   ULONG * pClipFormat,
                                   String * pAppName,
                                   String * pLongUserName,
                                   String * pUserName,
                                   long nVersion = SOFFICE_FILEFORMAT_CURRENT ) const;
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_TEST_UTIL_TEST_PATH_HPP
#define REALM_TEST_UTIL_TEST_PATH_HPP

#include <string>

#include <realm/util/features.h>

#include "unit_test.hpp"

#define TEST_PATH_HELPER(class_name, var_name, suffix) \
    class_name var_name(realm::test_util::get_test_path(test_details, "." #var_name "." suffix))

#define TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "test");

#define GROUP_TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "realm");

#define SHARED_GROUP_TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::SharedGroupTestPathGuard, var_name, "realm");

namespace realm {
namespace test_util {

/// Disable removal of test files. If called, the call must complete
/// before any TestPathGuard object is created.
void keep_test_files();

/// By default, test files are placed in the current working
/// directory. Use this function to set a path prefix. The specified
/// prefix must contain a final `/`.
void set_test_path_prefix(const std::string&);
std::string get_test_path_prefix();

std::string get_test_path(const unit_test::TestDetails&, const std::string& suffix);

std::string get_test_resource_path();
void set_test_resource_path(const std::string&);

/// Constructor and destructor removes file if it exists.
class TestPathGuard {
public:
    TestPathGuard(const std::string& path);
    ~TestPathGuard() noexcept;
    operator std::string() const
    {
        return m_path;
    }
    const char* c_str() const
    {
        return m_path.c_str();
    }
protected:
    std::string m_path;
};

class SharedGroupTestPathGuard: public TestPathGuard {
public:
    SharedGroupTestPathGuard(const std::string& path);
    std::string get_lock_path() const
    {
        return m_path + ".lock";
    }
    ~SharedGroupTestPathGuard();
};

} // namespace test_util
} // namespace realm

#endif // REALM_TEST_UTIL_TEST_PATH_HPP
<commit_msg>Prevent copy of TestPathGuard as it has unfortunate side effects; such as deleting the associated Realm files<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_TEST_UTIL_TEST_PATH_HPP
#define REALM_TEST_UTIL_TEST_PATH_HPP

#include <string>

#include <realm/util/features.h>

#include "unit_test.hpp"

#define TEST_PATH_HELPER(class_name, var_name, suffix) \
    class_name var_name(realm::test_util::get_test_path(test_details, "." #var_name "." suffix))

#define TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "test");

#define GROUP_TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "realm");

#define SHARED_GROUP_TEST_PATH(var_name) \
    TEST_PATH_HELPER(realm::test_util::SharedGroupTestPathGuard, var_name, "realm");

namespace realm {
namespace test_util {

/// Disable removal of test files. If called, the call must complete
/// before any TestPathGuard object is created.
void keep_test_files();

/// By default, test files are placed in the current working
/// directory. Use this function to set a path prefix. The specified
/// prefix must contain a final `/`.
void set_test_path_prefix(const std::string&);
std::string get_test_path_prefix();

std::string get_test_path(const unit_test::TestDetails&, const std::string& suffix);

std::string get_test_resource_path();
void set_test_resource_path(const std::string&);

/// Constructor and destructor removes file if it exists.
class TestPathGuard {
public:
    TestPathGuard(const std::string& path);
    ~TestPathGuard() noexcept;
    operator std::string() const
    {
        return m_path;
    }
    const char* c_str() const
    {
        return m_path.c_str();
    }
    TestPathGuard(const TestPathGuard&) = delete;
    TestPathGuard& operator=(const TestPathGuard&) = delete;
protected:
    std::string m_path;
};

class SharedGroupTestPathGuard: public TestPathGuard {
public:
    SharedGroupTestPathGuard(const std::string& path);
    std::string get_lock_path() const
    {
        return m_path + ".lock";
    }
    ~SharedGroupTestPathGuard();
};

} // namespace test_util
} // namespace realm

#endif // REALM_TEST_UTIL_TEST_PATH_HPP
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <string>

#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/md5_helper.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vp9/decoder/vp9_thread.h"

namespace {

using std::string;

class VP9WorkerThreadTest : public ::testing::TestWithParam<bool> {
 protected:
  virtual ~VP9WorkerThreadTest() {}
  virtual void SetUp() {
    vp9_worker_init(&worker_);
  }

  virtual void TearDown() {
    vp9_worker_end(&worker_);
  }

  VP9Worker worker_;
};

int ThreadHook(void* data, void* return_value) {
  int* const hook_data = reinterpret_cast<int*>(data);
  *hook_data = 5;
  return *reinterpret_cast<int*>(return_value);
}

TEST_P(VP9WorkerThreadTest, HookSuccess) {
  EXPECT_NE(vp9_worker_sync(&worker_), 0);  // should be a no-op.

  for (int i = 0; i < 2; ++i) {
    EXPECT_NE(vp9_worker_reset(&worker_), 0);

    int hook_data = 0;
    int return_value = 1;  // return successfully from the hook
    worker_.hook = ThreadHook;
    worker_.data1 = &hook_data;
    worker_.data2 = &return_value;

    const bool synchronous = GetParam();
    if (synchronous) {
      vp9_worker_execute(&worker_);
    } else {
      vp9_worker_launch(&worker_);
    }
    EXPECT_NE(vp9_worker_sync(&worker_), 0);
    EXPECT_FALSE(worker_.had_error);
    EXPECT_EQ(5, hook_data);

    EXPECT_NE(vp9_worker_sync(&worker_), 0);  // should be a no-op.
  }
}

TEST_P(VP9WorkerThreadTest, HookFailure) {
  EXPECT_NE(vp9_worker_reset(&worker_), 0);

  int hook_data = 0;
  int return_value = 0;  // return failure from the hook
  worker_.hook = ThreadHook;
  worker_.data1 = &hook_data;
  worker_.data2 = &return_value;

  const bool synchronous = GetParam();
  if (synchronous) {
    vp9_worker_execute(&worker_);
  } else {
    vp9_worker_launch(&worker_);
  }
  EXPECT_FALSE(vp9_worker_sync(&worker_));
  EXPECT_EQ(1, worker_.had_error);

  // Ensure _reset() clears the error and _launch() can be called again.
  return_value = 1;
  EXPECT_NE(vp9_worker_reset(&worker_), 0);
  EXPECT_FALSE(worker_.had_error);
  vp9_worker_launch(&worker_);
  EXPECT_NE(vp9_worker_sync(&worker_), 0);
  EXPECT_FALSE(worker_.had_error);
}

// -----------------------------------------------------------------------------
// Multi-threaded decode tests

#if CONFIG_WEBM_IO
// Decodes |filename| with |num_threads|. Returns the md5 of the decoded frames.
string DecodeFile(const string& filename, int num_threads) {
  libvpx_test::WebMVideoSource video(filename);
  video.Init();

  vpx_codec_dec_cfg_t cfg = {0};
  cfg.threads = num_threads;
  libvpx_test::VP9Decoder decoder(cfg, 0);

  libvpx_test::MD5 md5;
  for (video.Begin(); video.cxdata(); video.Next()) {
    const vpx_codec_err_t res =
        decoder.DecodeFrame(video.cxdata(), video.frame_size());
    if (res != VPX_CODEC_OK) {
      EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();
      break;
    }

    libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();
    const vpx_image_t *img = NULL;

    // Get decompressed data
    while ((img = dec_iter.Next())) {
      md5.Add(img);
    }
  }
  return string(md5.Get());
}

TEST(VP9DecodeMTTest, MTDecode) {
  // no tiles or frame parallel; this exercises loop filter threading.
  EXPECT_STREQ("b35a1b707b28e82be025d960aba039bc",
               DecodeFile("vp90-2-03-size-226x226.webm", 2).c_str());
}

TEST(VP9DecodeMTTest, MTDecode2) {
  static const struct {
    const char *name;
    const char *expected_md5;
  } files[] = {
    { "vp90-2-08-tile_1x2_frame_parallel.webm",
      "68ede6abd66bae0a2edf2eb9232241b6" },
    { "vp90-2-08-tile_1x4_frame_parallel.webm",
      "368ebc6ebf3a5e478d85b2c3149b2848" },
    { "vp90-2-08-tile_1x8_frame_parallel.webm",
      "17e439da2388aff3a0f69cb22579c6c1" },
  };

  for (int i = 0; i < static_cast<int>(sizeof(files) / sizeof(files[0])); ++i) {
    for (int t = 2; t <= 8; ++t) {
      EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())
          << "threads = " << t;
    }
  }
}

// Test tile quantity changes within one file.
TEST(VP9DecodeMTTest, MTDecode3) {
  static const struct {
    const char *name;
    const char *expected_md5;
  } files[] = {
    { "vp90-2-14-resize-fp-tiles-1-16.webm",
      "0cd5e632c326297e975f38949c31ea94" },
    { "vp90-2-14-resize-fp-tiles-1-2-4-8-16.webm",
      "5c78a96a42e7f4a4f6b2edcdb791e44c" },
    { "vp90-2-14-resize-fp-tiles-1-2.webm",
      "e030450ae85c3277be2a418769df98e2" },
    { "vp90-2-14-resize-fp-tiles-1-4.webm",
      "312eed4e2b64eb7a4e7f18916606a430" },
    { "vp90-2-14-resize-fp-tiles-16-1.webm",
      "1755c16d8af16a9cb3fe7338d90abe52" },
    { "vp90-2-14-resize-fp-tiles-16-2.webm",
      "500300592d3fcb6f12fab25e48aaf4df" },
    { "vp90-2-14-resize-fp-tiles-16-4.webm",
      "47c48379fa6331215d91c67648e1af6e" },
    { "vp90-2-14-resize-fp-tiles-16-8-4-2-1.webm",
      "eecf17290739bc708506fa4827665989" },
    { "vp90-2-14-resize-fp-tiles-16-8.webm",
      "29b6bb54e4c26b5ca85d5de5fed94e76" },
    { "vp90-2-14-resize-fp-tiles-1-8.webm",
      "1b6f175e08cd82cf84bb800ac6d1caa3" },
    { "vp90-2-14-resize-fp-tiles-2-16.webm",
      "ca3b03e4197995d8d5444ede7a6c0804" },
    { "vp90-2-14-resize-fp-tiles-2-1.webm",
      "99aec065369d70bbb78ccdff65afed3f" },
    { "vp90-2-14-resize-fp-tiles-2-4.webm",
      "22d0ebdb49b87d2920a85aea32e1afd5" },
    { "vp90-2-14-resize-fp-tiles-2-8.webm",
      "c2115cf051c62e0f7db1d4a783831541" },
    { "vp90-2-14-resize-fp-tiles-4-16.webm",
      "c690d7e1719b31367564cac0af0939cb" },
    { "vp90-2-14-resize-fp-tiles-4-1.webm",
      "a926020b2cc3e15ad4cc271853a0ff26" },
    { "vp90-2-14-resize-fp-tiles-4-2.webm",
      "42699063d9e581f1993d0cf890c2be78" },
    { "vp90-2-14-resize-fp-tiles-4-8.webm",
      "7f76d96036382f45121e3d5aa6f8ec52" },
    { "vp90-2-14-resize-fp-tiles-8-16.webm",
      "76a43fcdd7e658542913ea43216ec55d" },
    { "vp90-2-14-resize-fp-tiles-8-1.webm",
      "8e3fbe89486ca60a59299dea9da91378" },
    { "vp90-2-14-resize-fp-tiles-8-2.webm",
      "ae96f21f21b6370cc0125621b441fc52" },
    { "vp90-2-14-resize-fp-tiles-8-4.webm",
      "3eb4f24f10640d42218f7fd7b9fd30d4" },
  };

  for (int i = 0; i < static_cast<int>(sizeof(files) / sizeof(files[0])); ++i) {
    for (int t = 2; t <= 8; ++t) {
      EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())
          << "threads = " << t;
    }
  }
}
#endif  // CONFIG_WEBM_IO

INSTANTIATE_TEST_CASE_P(Synchronous, VP9WorkerThreadTest, ::testing::Bool());

}  // namespace
<commit_msg>vp9_thread_test: add 'Thread' to test names<commit_after>/*
 *  Copyright (c) 2013 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <string>

#include "third_party/googletest/src/include/gtest/gtest.h"
#include "./vpx_config.h"
#include "test/codec_factory.h"
#include "test/decode_test_driver.h"
#include "test/md5_helper.h"
#if CONFIG_WEBM_IO
#include "test/webm_video_source.h"
#endif
#include "vp9/decoder/vp9_thread.h"

namespace {

using std::string;

class VP9WorkerThreadTest : public ::testing::TestWithParam<bool> {
 protected:
  virtual ~VP9WorkerThreadTest() {}
  virtual void SetUp() {
    vp9_worker_init(&worker_);
  }

  virtual void TearDown() {
    vp9_worker_end(&worker_);
  }

  VP9Worker worker_;
};

int ThreadHook(void* data, void* return_value) {
  int* const hook_data = reinterpret_cast<int*>(data);
  *hook_data = 5;
  return *reinterpret_cast<int*>(return_value);
}

TEST_P(VP9WorkerThreadTest, HookSuccess) {
  EXPECT_NE(vp9_worker_sync(&worker_), 0);  // should be a no-op.

  for (int i = 0; i < 2; ++i) {
    EXPECT_NE(vp9_worker_reset(&worker_), 0);

    int hook_data = 0;
    int return_value = 1;  // return successfully from the hook
    worker_.hook = ThreadHook;
    worker_.data1 = &hook_data;
    worker_.data2 = &return_value;

    const bool synchronous = GetParam();
    if (synchronous) {
      vp9_worker_execute(&worker_);
    } else {
      vp9_worker_launch(&worker_);
    }
    EXPECT_NE(vp9_worker_sync(&worker_), 0);
    EXPECT_FALSE(worker_.had_error);
    EXPECT_EQ(5, hook_data);

    EXPECT_NE(vp9_worker_sync(&worker_), 0);  // should be a no-op.
  }
}

TEST_P(VP9WorkerThreadTest, HookFailure) {
  EXPECT_NE(vp9_worker_reset(&worker_), 0);

  int hook_data = 0;
  int return_value = 0;  // return failure from the hook
  worker_.hook = ThreadHook;
  worker_.data1 = &hook_data;
  worker_.data2 = &return_value;

  const bool synchronous = GetParam();
  if (synchronous) {
    vp9_worker_execute(&worker_);
  } else {
    vp9_worker_launch(&worker_);
  }
  EXPECT_FALSE(vp9_worker_sync(&worker_));
  EXPECT_EQ(1, worker_.had_error);

  // Ensure _reset() clears the error and _launch() can be called again.
  return_value = 1;
  EXPECT_NE(vp9_worker_reset(&worker_), 0);
  EXPECT_FALSE(worker_.had_error);
  vp9_worker_launch(&worker_);
  EXPECT_NE(vp9_worker_sync(&worker_), 0);
  EXPECT_FALSE(worker_.had_error);
}

// -----------------------------------------------------------------------------
// Multi-threaded decode tests

#if CONFIG_WEBM_IO
// Decodes |filename| with |num_threads|. Returns the md5 of the decoded frames.
string DecodeFile(const string& filename, int num_threads) {
  libvpx_test::WebMVideoSource video(filename);
  video.Init();

  vpx_codec_dec_cfg_t cfg = {0};
  cfg.threads = num_threads;
  libvpx_test::VP9Decoder decoder(cfg, 0);

  libvpx_test::MD5 md5;
  for (video.Begin(); video.cxdata(); video.Next()) {
    const vpx_codec_err_t res =
        decoder.DecodeFrame(video.cxdata(), video.frame_size());
    if (res != VPX_CODEC_OK) {
      EXPECT_EQ(VPX_CODEC_OK, res) << decoder.DecodeError();
      break;
    }

    libvpx_test::DxDataIterator dec_iter = decoder.GetDxData();
    const vpx_image_t *img = NULL;

    // Get decompressed data
    while ((img = dec_iter.Next())) {
      md5.Add(img);
    }
  }
  return string(md5.Get());
}

TEST(VP9DecodeMultiThreadedTest, Decode) {
  // no tiles or frame parallel; this exercises loop filter threading.
  EXPECT_STREQ("b35a1b707b28e82be025d960aba039bc",
               DecodeFile("vp90-2-03-size-226x226.webm", 2).c_str());
}

TEST(VP9DecodeMultiThreadedTest, Decode2) {
  static const struct {
    const char *name;
    const char *expected_md5;
  } files[] = {
    { "vp90-2-08-tile_1x2_frame_parallel.webm",
      "68ede6abd66bae0a2edf2eb9232241b6" },
    { "vp90-2-08-tile_1x4_frame_parallel.webm",
      "368ebc6ebf3a5e478d85b2c3149b2848" },
    { "vp90-2-08-tile_1x8_frame_parallel.webm",
      "17e439da2388aff3a0f69cb22579c6c1" },
  };

  for (int i = 0; i < static_cast<int>(sizeof(files) / sizeof(files[0])); ++i) {
    for (int t = 2; t <= 8; ++t) {
      EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())
          << "threads = " << t;
    }
  }
}

// Test tile quantity changes within one file.
TEST(VP9DecodeMultiThreadedTest, Decode3) {
  static const struct {
    const char *name;
    const char *expected_md5;
  } files[] = {
    { "vp90-2-14-resize-fp-tiles-1-16.webm",
      "0cd5e632c326297e975f38949c31ea94" },
    { "vp90-2-14-resize-fp-tiles-1-2-4-8-16.webm",
      "5c78a96a42e7f4a4f6b2edcdb791e44c" },
    { "vp90-2-14-resize-fp-tiles-1-2.webm",
      "e030450ae85c3277be2a418769df98e2" },
    { "vp90-2-14-resize-fp-tiles-1-4.webm",
      "312eed4e2b64eb7a4e7f18916606a430" },
    { "vp90-2-14-resize-fp-tiles-16-1.webm",
      "1755c16d8af16a9cb3fe7338d90abe52" },
    { "vp90-2-14-resize-fp-tiles-16-2.webm",
      "500300592d3fcb6f12fab25e48aaf4df" },
    { "vp90-2-14-resize-fp-tiles-16-4.webm",
      "47c48379fa6331215d91c67648e1af6e" },
    { "vp90-2-14-resize-fp-tiles-16-8-4-2-1.webm",
      "eecf17290739bc708506fa4827665989" },
    { "vp90-2-14-resize-fp-tiles-16-8.webm",
      "29b6bb54e4c26b5ca85d5de5fed94e76" },
    { "vp90-2-14-resize-fp-tiles-1-8.webm",
      "1b6f175e08cd82cf84bb800ac6d1caa3" },
    { "vp90-2-14-resize-fp-tiles-2-16.webm",
      "ca3b03e4197995d8d5444ede7a6c0804" },
    { "vp90-2-14-resize-fp-tiles-2-1.webm",
      "99aec065369d70bbb78ccdff65afed3f" },
    { "vp90-2-14-resize-fp-tiles-2-4.webm",
      "22d0ebdb49b87d2920a85aea32e1afd5" },
    { "vp90-2-14-resize-fp-tiles-2-8.webm",
      "c2115cf051c62e0f7db1d4a783831541" },
    { "vp90-2-14-resize-fp-tiles-4-16.webm",
      "c690d7e1719b31367564cac0af0939cb" },
    { "vp90-2-14-resize-fp-tiles-4-1.webm",
      "a926020b2cc3e15ad4cc271853a0ff26" },
    { "vp90-2-14-resize-fp-tiles-4-2.webm",
      "42699063d9e581f1993d0cf890c2be78" },
    { "vp90-2-14-resize-fp-tiles-4-8.webm",
      "7f76d96036382f45121e3d5aa6f8ec52" },
    { "vp90-2-14-resize-fp-tiles-8-16.webm",
      "76a43fcdd7e658542913ea43216ec55d" },
    { "vp90-2-14-resize-fp-tiles-8-1.webm",
      "8e3fbe89486ca60a59299dea9da91378" },
    { "vp90-2-14-resize-fp-tiles-8-2.webm",
      "ae96f21f21b6370cc0125621b441fc52" },
    { "vp90-2-14-resize-fp-tiles-8-4.webm",
      "3eb4f24f10640d42218f7fd7b9fd30d4" },
  };

  for (int i = 0; i < static_cast<int>(sizeof(files) / sizeof(files[0])); ++i) {
    for (int t = 2; t <= 8; ++t) {
      EXPECT_STREQ(files[i].expected_md5, DecodeFile(files[i].name, t).c_str())
          << "threads = " << t;
    }
  }
}
#endif  // CONFIG_WEBM_IO

INSTANTIATE_TEST_CASE_P(Synchronous, VP9WorkerThreadTest, ::testing::Bool());

}  // namespace
<|endoftext|>


<commit_before>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.

#include <errno.h>
#include <pthread.h>
#include <iostream>

#include <hpp/util/debug.hh>
#include "hpp/corbaserver/server.hh"

#include "server-private.hh"

namespace hpp
{
  namespace corbaServer
  {
    using CORBA::Exception;
    using CORBA::Object_var;
    using CORBA::SystemException;
    using CORBA::ORB_init;
    using CORBA::PolicyList;
    using omniORB::fatalException;

    namespace
    {
      /// \brief Forward logging messages to hpp logging mechanism.
      /// If debug is disabled, CORBA logging will be disabled too.
      ///
      /// Tracing has to be enabled in your ``omniORB.cfg'' to use this
      /// feature.
      /// See ``omniORB configuration and API'' > ``Tracing options''
      /// section of omniORB manual for more information.
      void logFunction (const char* msg);

      void logFunction (const char* hppDebugStatement (msg))
      {
	hppDout (info, "omniORB: " << msg);
      }

      void usage (const char* app)
      {
        std::cerr << "Usage: " << app << " [options] ..." << '\n'
                  << "  --name <name>" << '\n'
                  << "  --help" << '\n'
                  << "  --single-thread" << '\n'
                  << "  --multi-thread"  << std::endl;
      }
    } // end of anonymous namespace.

    Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,
		   const char *argv[], bool inMultiThread) :
      multiThread_ (inMultiThread),
      problemSolverMap_ (new ProblemSolverMap (problemSolver))
    {
      // Register log function.
      omniORB::setLogFunction (&logFunction);

      private_ = new impl::Server;

      parseArguments (argc, argv);

      initORBandServers (argc, argv, multiThread_);
    }

    Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,
		   const char *argv[], bool inMultiThread) :
      multiThread_ (inMultiThread),
      problemSolverMap_ (problemSolverMap)
    {
      // Register log function.
      omniORB::setLogFunction (&logFunction);

      private_ = new impl::Server;

      parseArguments (argc, argv);

      initORBandServers (argc, argv, multiThread_);
    }

    /// \brief Shutdown CORBA server
    Server::~Server()
    {
      private_->deactivateAndDestroyServers();
      delete private_;
      private_ = NULL;
    }

    /// CORBA SERVER INITIALIZATION

    void Server::initORBandServers(int argc, const char* argv[],
				   bool inMultiThread)
    {
      Object_var obj;
      PortableServer::ThreadPolicy_var threadPolicy;
      PortableServer::POA_var rootPoa;

      /// ORB init
      private_->orb_ = ORB_init (argc, const_cast<char **> (argv));
      if (is_nil(private_->orb_)) {
	std::string msg ("failed to initialize ORB");
	hppDout (error, msg.c_str ());
	throw std::runtime_error (msg.c_str ());
      }
      /// ORB init
      obj = private_->orb_->resolve_initial_references("RootPOA");

      /// Create thread policy

      //
      // Make the CORBA object single-threaded to avoid GUI krash
      //
      // Create a sigle threaded policy object
      rootPoa = PortableServer::POA::_narrow(obj);

      if (inMultiThread) {
	threadPolicy = rootPoa->create_thread_policy
	  (PortableServer::ORB_CTRL_MODEL);
      }
      else {
	threadPolicy = rootPoa->create_thread_policy
	  (PortableServer::MAIN_THREAD_MODEL);
      }
      /// Duplicate thread policy
      PolicyList policyList;
      policyList.length(1);
      policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);

      try {
        private_->poa_ = rootPoa->create_POA
          ("child", PortableServer::POAManager::_nil(), policyList);
      } catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) {
        private_->poa_ = rootPoa->find_POA ("child", false);
      }

      // Destroy policy object
      threadPolicy->destroy();
      private_->createAndActivateServers(this);
    }

    void Server::parseArguments (int argc, const char* argv[])
    {
      mainContextId_ = "hpp";

      for (int i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "--name") == 0) {
          if (i < argc - 1) {
            mainContextId_.append(argv[i+1]);
            ++i;
          }
          else              usage(argv[0]);
          std::cout << "Server main context: " << mainContextId_;
        } else if (strcmp(argv[i], "--help") == 0) {
          usage(argv[0]);
        } else if (strcmp(argv[i], "--single-thread") == 0) {
          multiThread_ = false;
        } else if (strcmp(argv[i], "--multi-thread") == 0) {
          multiThread_ = true;
        }
      }
    }

    void Server::startCorbaServer()
    {
      // Obtain a reference to objects, and register them in
      // the naming service.
      Object_var robotObj = private_->robotServant_->_this();
      Object_var obstacleObj = private_->obstacleServant_->_this();
      Object_var problemObj = private_->problemServant_->_this();

      private_->createHppContext (mainContextId());
      // Bind robotObj with name Robot to the hppContext:
      CosNaming::Name objectName;
      objectName.length(1);
      objectName[0].id   = (const char*) "basic";   // string copied
      objectName[0].kind = (const char*) "robot"; // string copied

      private_->bindObjectToName(robotObj, objectName);
      private_->robotServant_->_remove_ref();

      // Bind obstacleObj with name Obstacle to the hppContext:
      objectName.length(1);
      objectName[0].id   = (const char*) "basic"; // string copied
      objectName[0].kind = (const char*) "obstacle";   // string copied

      private_->bindObjectToName(obstacleObj, objectName);
      private_->obstacleServant_->_remove_ref();

      // Bind problemObj with name Problem to the hppContext:
      objectName.length(1);
      objectName[0].id   = (const char*) "basic"; // string copied
      objectName[0].kind = (const char*) "problem";   // string copied

      private_->bindObjectToName(problemObj, objectName);
      private_->problemServant_->_remove_ref();

      PortableServer::POAManager_var pman = private_->poa_->the_POAManager();
      pman->activate();
    }

    core::ProblemSolverPtr_t Server::problemSolver ()
    {
      return problemSolverMap_->selected();
    }

    ProblemSolverMapPtr_t Server::problemSolverMap ()
    {
      return problemSolverMap_;
    }

    /// \brief If CORBA requests are pending, process them
    int Server::processRequest (bool loop)
    {
      if (loop)
	{
	  hppDout (info, "start processing CORBA requests for ever.");
	  private_->orb_->run();
	}
      else
	{
	  if (private_->orb_->work_pending())
	    private_->orb_->perform_work();
	}
      return 0;
    }

    void Server::requestShutdown (bool wait)
    {
      private_->orb_->shutdown (wait);
    }

  } // end of namespace corbaServer.
} // end of namespace hpp.
<commit_msg>Improve output when parsing arguments<commit_after>// Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.
//
// This file is part of the hpp-corbaserver.
//
// This software is provided "as is" without warranty of any kind,
// either expressed or implied, including but not limited to the
// implied warranties of fitness for a particular purpose.
//
// See the COPYING file for more information.

#include <errno.h>
#include <pthread.h>
#include <iostream>

#include <hpp/util/debug.hh>
#include "hpp/corbaserver/server.hh"

#include "server-private.hh"

namespace hpp
{
  namespace corbaServer
  {
    using CORBA::Exception;
    using CORBA::Object_var;
    using CORBA::SystemException;
    using CORBA::ORB_init;
    using CORBA::PolicyList;
    using omniORB::fatalException;

    namespace
    {
      /// \brief Forward logging messages to hpp logging mechanism.
      /// If debug is disabled, CORBA logging will be disabled too.
      ///
      /// Tracing has to be enabled in your ``omniORB.cfg'' to use this
      /// feature.
      /// See ``omniORB configuration and API'' > ``Tracing options''
      /// section of omniORB manual for more information.
      void logFunction (const char* msg);

      void logFunction (const char* hppDebugStatement (msg))
      {
	hppDout (info, "omniORB: " << msg);
      }

      void usage (const char* app)
      {
        std::cerr << "Usage: " << app << " [options] ..." << '\n'
                  << "  --name <name>" << '\n'
                  << "  --help" << '\n'
                  << "  --single-thread" << '\n'
                  << "  --multi-thread"  << std::endl;
      }
    } // end of anonymous namespace.

    Server::Server(core::ProblemSolverPtr_t problemSolver, int argc,
		   const char *argv[], bool inMultiThread) :
      multiThread_ (inMultiThread),
      problemSolverMap_ (new ProblemSolverMap (problemSolver))
    {
      // Register log function.
      omniORB::setLogFunction (&logFunction);

      private_ = new impl::Server;

      parseArguments (argc, argv);

      initORBandServers (argc, argv, multiThread_);
    }

    Server::Server(ProblemSolverMapPtr_t problemSolverMap, int argc,
		   const char *argv[], bool inMultiThread) :
      multiThread_ (inMultiThread),
      problemSolverMap_ (problemSolverMap)
    {
      // Register log function.
      omniORB::setLogFunction (&logFunction);

      private_ = new impl::Server;

      parseArguments (argc, argv);

      initORBandServers (argc, argv, multiThread_);
    }

    /// \brief Shutdown CORBA server
    Server::~Server()
    {
      private_->deactivateAndDestroyServers();
      delete private_;
      private_ = NULL;
    }

    /// CORBA SERVER INITIALIZATION

    void Server::initORBandServers(int argc, const char* argv[],
				   bool inMultiThread)
    {
      Object_var obj;
      PortableServer::ThreadPolicy_var threadPolicy;
      PortableServer::POA_var rootPoa;

      /// ORB init
      private_->orb_ = ORB_init (argc, const_cast<char **> (argv));
      if (is_nil(private_->orb_)) {
	std::string msg ("failed to initialize ORB");
	hppDout (error, msg.c_str ());
	throw std::runtime_error (msg.c_str ());
      }
      /// ORB init
      obj = private_->orb_->resolve_initial_references("RootPOA");

      /// Create thread policy

      //
      // Make the CORBA object single-threaded to avoid GUI krash
      //
      // Create a sigle threaded policy object
      rootPoa = PortableServer::POA::_narrow(obj);

      if (inMultiThread) {
	threadPolicy = rootPoa->create_thread_policy
	  (PortableServer::ORB_CTRL_MODEL);
      }
      else {
	threadPolicy = rootPoa->create_thread_policy
	  (PortableServer::MAIN_THREAD_MODEL);
      }
      /// Duplicate thread policy
      PolicyList policyList;
      policyList.length(1);
      policyList[0] = PortableServer::ThreadPolicy::_duplicate(threadPolicy);

      try {
        private_->poa_ = rootPoa->create_POA
          ("child", PortableServer::POAManager::_nil(), policyList);
      } catch (PortableServer::POA::AdapterAlreadyExists& /*e*/) {
        private_->poa_ = rootPoa->find_POA ("child", false);
      }

      // Destroy policy object
      threadPolicy->destroy();
      private_->createAndActivateServers(this);
    }

    void Server::parseArguments (int argc, const char* argv[])
    {
      mainContextId_ = "hpp";

      for (int i = 1; i < argc; ++i) {
        if (strcmp(argv[i], "--name") == 0) {
          if (i < argc - 1) {
            mainContextId_.append(argv[i+1]);
            ++i;
          }
          else              usage(argv[0]);
          std::cout << "Server main context: " << mainContextId_ << std::endl;
        } else if (strcmp(argv[i], "--help") == 0) {
          usage(argv[0]);
        } else if (strcmp(argv[i], "--single-thread") == 0) {
          multiThread_ = false;
          std::cout << "Switched to single thread mode." << std::endl;
        } else if (strcmp(argv[i], "--multi-thread") == 0) {
          std::cout << "Switched to multi-thread mode." << std::endl;
          multiThread_ = true;
        }
      }
    }

    void Server::startCorbaServer()
    {
      // Obtain a reference to objects, and register them in
      // the naming service.
      Object_var robotObj = private_->robotServant_->_this();
      Object_var obstacleObj = private_->obstacleServant_->_this();
      Object_var problemObj = private_->problemServant_->_this();

      private_->createHppContext (mainContextId());
      // Bind robotObj with name Robot to the hppContext:
      CosNaming::Name objectName;
      objectName.length(1);
      objectName[0].id   = (const char*) "basic";   // string copied
      objectName[0].kind = (const char*) "robot"; // string copied

      private_->bindObjectToName(robotObj, objectName);
      private_->robotServant_->_remove_ref();

      // Bind obstacleObj with name Obstacle to the hppContext:
      objectName.length(1);
      objectName[0].id   = (const char*) "basic"; // string copied
      objectName[0].kind = (const char*) "obstacle";   // string copied

      private_->bindObjectToName(obstacleObj, objectName);
      private_->obstacleServant_->_remove_ref();

      // Bind problemObj with name Problem to the hppContext:
      objectName.length(1);
      objectName[0].id   = (const char*) "basic"; // string copied
      objectName[0].kind = (const char*) "problem";   // string copied

      private_->bindObjectToName(problemObj, objectName);
      private_->problemServant_->_remove_ref();

      PortableServer::POAManager_var pman = private_->poa_->the_POAManager();
      pman->activate();
    }

    core::ProblemSolverPtr_t Server::problemSolver ()
    {
      return problemSolverMap_->selected();
    }

    ProblemSolverMapPtr_t Server::problemSolverMap ()
    {
      return problemSolverMap_;
    }

    /// \brief If CORBA requests are pending, process them
    int Server::processRequest (bool loop)
    {
      if (loop)
	{
	  hppDout (info, "start processing CORBA requests for ever.");
	  private_->orb_->run();
	}
      else
	{
	  if (private_->orb_->work_pending())
	    private_->orb_->perform_work();
	}
      return 0;
    }

    void Server::requestShutdown (bool wait)
    {
      private_->orb_->shutdown (wait);
    }

  } // end of namespace corbaServer.
} // end of namespace hpp.
<|endoftext|>


<commit_before>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"

//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
	virtual ~CSysControlLocal();

	virtual void Init();	//角色要初始化，着色器要初始化，
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//鼠标状态，键盘状态，人物状态，子弹状态等等。
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//设置是否显示鼠标
	virtual int GetMouseGrab();			//获取鼠标状态，是显示呢还是不显示的状态。

	virtual void SetControlMode(ControlMode mode);			//控制模式
	virtual ControlMode GetControlMode() const;				//获取控制模式

private:
	void Update_Mouse(float ifps);
	void Update_Keyboard(float ifps);
	void Update_XPad360(float ifps);

	CControlsApp        *m_pControlsApp;		//控制游戏中移动
	CControlsXPad360    *m_pControlsXPad360;
	ControlMode         m_nControlMode;			//控制模式

	int                 m_nOldMouseX;			//上一个鼠标坐标X
	int                 m_nOldMouseY;			//上一个鼠标坐标Y

	CObjectGui          *m_pTest3DUI;
	CWidgetLabel        *m_pTestMessageLabel;

};

CSysControlLocal::CSysControlLocal()
{

}
CSysControlLocal::~CSysControlLocal()
{

}

void CSysControlLocal::Init()
{
	m_pControlsApp = new CControlsApp;
	m_pControlsXPad360 = new CControlsXPad360(0);

	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);

	SetControlMode(CONTROL_KEYBORAD_MOUSE);

	m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
	m_pTest3DUI->SetMouseShow(0);
	m_pTest3DUI->SetBackground(1);
	m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));

	m_pTest3DUI->SetScreenSize(800, 400);
	m_pTest3DUI->SetControlDistance(1000.0f);
	m_pTest3DUI->CreateMaterial("gui_base");	 //show in game

	m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel->SetFontSize(80);		//设置字体大小
	m_pTestMessageLabel->SetFontOutline(1);		//设置字体轮廓
	m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");

	void CSysControlLocal::Update(float ifps)
	{
		Update_Mouse(ifps);
		Update_Keyboard(ifps);
		Update_XPad360(ifps);
	}

	m_nOldMouseX = 0;
	m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);
	delete m_pControlsApp;
	m_pControlsApp = NULL;
	delete m_pControlsXPad360;
	m_pControlsXPad360 = NULL;
	delete m_pTestMessageLabel;
	m_pTestMessageLabel = NULL;
	delete m_pTest3DUI;
	m_pTest3DUI = NULL;

}

int CSysControlLocal::GetState(int state)
{

	return m_pControlsApp->GetState(state);
}

int CSysControlLocal::ClearState(int state)
{
	return m_pControlsApp->ClearState(state);
}

float CSysControlLocal::GetMouseDX()
{
	return m_pControlsApp->GetMouseDX();
}

float CSysControlLocal::GetMouseDY()
{
	return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
	g_Engine.pApp->SetMouseGrab(g);
	g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
	return g_Engine.pApp->GetMouseGrab();
}

void CSysControlLocal::SetControlMode(ControlMode mode)
{
	m_nControlMode = mode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
	float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大，鼠标移动越快
	float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小，鼠标移动越慢

	m_pControlsApp->SetMouseDX(dx);
	m_pControlsApp->SetMouseDY(dy);

	if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
	{
		g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
	}

	m_nOldMouseX = g_Engine.pApp->GetMouseX();
	m_nOldMouseY = g_Engine.pApp->GetMouseY();
}

void CSysControlLocal::Update_Keyboard(float ifps)		//键盘按键响应wsad
{

	if (g_Engine.pInput->IsKeyDown('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	if (g_Engine.pInput->IsKeyDown('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	if (g_Engine.pInput->IsKeyDown('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	if (g_Engine.pInput->IsKeyDown('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);

	if (g_Engine.pInput->IsKeyUp('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
	else if (g_Engine.pInput->IsKeyUp('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);

	if (g_Engine.pInput->IsKeyUp('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
	else if (g_Engine.pInput->IsKeyUp('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	if (g_Engine.pInput->IsKeyDown(' '))		//空格跳跃
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
	m_pControlsXPad360->UpdateEvents();
	CUtilStr strMessage;
	strMessage = CUtilStr("测试3D UI\n"),
	strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";

	strMessage += CUtilStr::Format("\n手柄测试\n");
	strMessage += CUtilStr::Format("LeftX:  %5.2f\n", m_pControlsXPad360->GetLeftX());
	strMessage += CUtilStr::Format("LeftY:  %5.2f\n", m_pControlsXPad360->GetLeftY());
	strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
	strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
	strMessage += "\nTriggers:\n";
	strMessage += CUtilStr::Format("Left:   %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
	strMessage += CUtilStr::Format("Right:  %5.2f\n", m_pControlsXPad360->GetRightTrigger());

	strMessage += CUtilStr::Format("\nButtons:\n");
	for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
	{
		strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
	}
	m_pTestMessageLabel->SetText(strMessage.Get());

	const float fPadThreshold = 0.5f;
	if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
	else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	}
	if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
	}
	if (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
	//update jump
	// LT RT
	if (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)
	{
		m_pControlsApp->SetState(CControls::STATE_FIRE, 1);
		//震动
		m_pControlsXPad360->SetLeftMotor(0.3f);
		m_pControlsXPad360->SetRightMotor(0.3f);
	}
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "SysControl.h"
#include "ControlsApp.h"
#include "ControlsXPad360.h"
#include "Engine.h"
#include "App.h"
#include "Engine.h"
#include "App.h"
#include "Input.h"
#include "ObjectGui.h"
#include "WidgetLabel.h"

//解决跨平台字符集兼容问题
#ifdef _WIN32
#pragma execution_character_set("utf-8")
#endif

using namespace MathLib;

class CSysControlLocal : public CSysControl
{
public:
	CSysControlLocal();
	virtual ~CSysControlLocal();

	virtual void Init();	//角色要初始化，着色器要初始化，
	virtual void Update(float ifps);
	virtual void Shutdown();

	virtual int GetState(int state);		//鼠标状态，键盘状态，人物状态，子弹状态等等。
	virtual int ClearState(int state);

	virtual float GetMouseDX();
	virtual float GetMouseDY();

	virtual void SetMouseGrab(int g);		//设置是否显示鼠标
	virtual int GetMouseGrab();			//获取鼠标状态，是显示呢还是不显示的状态。

	virtual void SetControlMode(ControlMode mode);			//控制模式
	virtual ControlMode GetControlMode() const;				//获取控制模式

private:
	void Update_Mouse(float ifps);
	void Update_Keyboard(float ifps);
	void Update_XPad360(float ifps);

	CControlsApp        *m_pControlsApp;		//控制游戏中移动
	CControlsXPad360    *m_pControlsXPad360;
	ControlMode         m_nControlMode;			//控制模式

	int                 m_nOldMouseX;			//上一个鼠标坐标X
	int                 m_nOldMouseY;			//上一个鼠标坐标Y

	CObjectGui          *m_pTest3DUI;
	CWidgetLabel        *m_pTestMessageLabel;

};

CSysControlLocal::CSysControlLocal()
{

}
CSysControlLocal::~CSysControlLocal()
{

}

void CSysControlLocal::Init()
{
	m_pControlsApp = new CControlsApp;
	m_pControlsXPad360 = new CControlsXPad360(0);

	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);

	SetControlMode(CONTROL_KEYBORAD_MOUSE);

	m_pTest3DUI = new CObjectGui(2.0f, 1.0f, "data/core/gui/");
	m_pTest3DUI->SetMouseShow(0);
	m_pTest3DUI->SetBackground(1);
	m_pTest3DUI->SetBackgroundColor(vec4(1.0f, 0.0f, 0.0f, 1.0f));

	m_pTest3DUI->SetScreenSize(800, 400);
	m_pTest3DUI->SetControlDistance(1000.0f);
	m_pTest3DUI->CreateMaterial("gui_base");	 //show in game

	m_pTest3DUI->SetWorldTransform(Translate(0.0f, 0.0f, 2.0f) * MakeRotationFromZY(vec3(0.0f, -1.0f, 0.0f), vec3(0.0f, 0.0f, 1.0f)));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel = new CWidgetLabel(m_pTest3DUI->GetGui());	//初始化文字标签
	m_pTest3DUI->GetGui()->AddChild(m_pTestMessageLabel, CGui::ALIGN_CENTER);
	m_pTestMessageLabel->SetFontColor(vec4(0.0f, 0.0f, 0.0f, 1.0f));

	m_pTestMessageLabel->SetFontSize(80);		//设置字体大小
	m_pTestMessageLabel->SetFontOutline(1);		//设置字体轮廓
	m_pTestMessageLabel->SetText("两个黄鹂鸣翠柳\n一行白鹭上青天\n窗含西岭千秋雪\n门泊东吴万里船");

	void CSysControlLocal::Update(float ifps)
	{
		Update_Mouse(ifps);
		Update_Keyboard(ifps);
		Update_XPad360(ifps);
	}

	m_nOldMouseX = 0;
	m_nOldMouseY = 0;
}
void CSysControlLocal::Shutdown()
{
	g_Engine.pApp->SetMouseGrab(0);
	g_Engine.pApp->SetMouseShow(0);
	delete m_pControlsApp;
	m_pControlsApp = NULL;
	delete m_pControlsXPad360;
	m_pControlsXPad360 = NULL;
	delete m_pTestMessageLabel;
	m_pTestMessageLabel = NULL;
	delete m_pTest3DUI;
	m_pTest3DUI = NULL;

}

int CSysControlLocal::GetState(int state)
{

	return m_pControlsApp->GetState(state);
}

int CSysControlLocal::ClearState(int state)
{
	return m_pControlsApp->ClearState(state);
}

float CSysControlLocal::GetMouseDX()
{
	return m_pControlsApp->GetMouseDX();
}

float CSysControlLocal::GetMouseDY()
{
	return m_pControlsApp->GetMouseDY();
}
void CSysControlLocal::SetMouseGrab(int g)
{
	g_Engine.pApp->SetMouseGrab(g);
	g_Engine.pGui->SetMouseShow(!g);
}
int CSysControlLocal::GetMouseGrab()
{
	return g_Engine.pApp->GetMouseGrab();
}

void CSysControlLocal::SetControlMode(ControlMode mode)
{
	m_nControlMode = mode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}

CSysControl::ControlMode CSysControlLocal::GetControlMode() const
{
	return m_nControlMode;
}
void CSysControlLocal::Update_Mouse(float ifps)
{
	float dx = (g_Engine.pApp->GetMouseX() - m_nOldMouseX) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1f这个数值越大，鼠标移动越快
	float dy = (g_Engine.pApp->GetMouseY() - m_nOldMouseY) * g_Engine.pControls->GetMouseSensitivity() * 0.1f;//0.1这个数值越小，鼠标移动越慢

	m_pControlsApp->SetMouseDX(dx);
	m_pControlsApp->SetMouseDY(dy);

	if (g_Engine.pApp->GetMouseGrab() && g_Engine.pApp->GetActive())
	{
		g_Engine.pApp->SetMouse(g_Engine.pApp->GetWidth() / 2, g_Engine.pApp->GetHeight() / 2);
	}

	m_nOldMouseX = g_Engine.pApp->GetMouseX();
	m_nOldMouseY = g_Engine.pApp->GetMouseY();
}

void CSysControlLocal::Update_Keyboard(float ifps)		//键盘按键响应wsad
{

	if (g_Engine.pInput->IsKeyDown('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	if (g_Engine.pInput->IsKeyDown('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	if (g_Engine.pInput->IsKeyDown('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	if (g_Engine.pInput->IsKeyDown('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);

	if (g_Engine.pInput->IsKeyUp('w'))
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
	else if (g_Engine.pInput->IsKeyUp('s'))
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);

	if (g_Engine.pInput->IsKeyUp('a'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
	else if (g_Engine.pInput->IsKeyUp('d'))
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	if (g_Engine.pInput->IsKeyDown(' '))		//空格跳跃
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
}
void CSysControlLocal::Update_XPad360(float ifps)
{
	m_pControlsXPad360->UpdateEvents();
	CUtilStr strMessage;
	strMessage = CUtilStr("测试3D UI\n"),
	strMessage += CUtilStr(m_pControlsXPad360->GetName()) + "\n";

	strMessage += CUtilStr::Format("\n手柄测试\n");
	strMessage += CUtilStr::Format("LeftX:  %5.2f\n", m_pControlsXPad360->GetLeftX());
	strMessage += CUtilStr::Format("LeftY:  %5.2f\n", m_pControlsXPad360->GetLeftY());
	strMessage += CUtilStr::Format("RightX: %5.2f\n", m_pControlsXPad360->GetRightX());
	strMessage += CUtilStr::Format("RightY: %5.2f\n", m_pControlsXPad360->GetRightY());
	strMessage += "\nTriggers:\n";
	strMessage += CUtilStr::Format("Left:   %5.2f\n", m_pControlsXPad360->GetLeftTrigger());
	strMessage += CUtilStr::Format("Right:  %5.2f\n", m_pControlsXPad360->GetRightTrigger());

	strMessage += CUtilStr::Format("\nButtons:\n");
	for (int i = 0; i < CControlsXPad360::NUM_BUTTONS; ++i)
	{
		strMessage += CUtilStr::Format("%d ", m_pControlsXPad360->GetButton(i));
	}
	m_pTestMessageLabel->SetText(strMessage.Get());

	const float fPadThreshold = 0.5f;
	if (m_pControlsXPad360->GetLeftX() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 1);
	else if (m_pControlsXPad360->GetLeftX() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_MOVE_LEFT, 0);
		m_pControlsApp->SetState(CControls::STATE_MOVE_RIGHT, 0);
	}
	if (m_pControlsXPad360->GetLeftY() > fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 1);
	else if (m_pControlsXPad360->GetLeftY() < -fPadThreshold)
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 1);
	else
	{
		m_pControlsApp->SetState(CControls::STATE_FORWARD, 0);
		m_pControlsApp->SetState(CControls::STATE_BACKWARD, 0);
	}
	if (m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_LEFT) || m_pControlsXPad360->GetButton(CControlsXPad360::BUTTON_SHOULDER_RIGHT))
		m_pControlsApp->SetState(CControls::STATE_JUMP, 1);
	else
		m_pControlsApp->SetState(CControls::STATE_JUMP, 0);
	//update jump
	// LT RT
	if (m_pControlsXPad360->GetRightTrigger() > fPadThreshold || m_pControlsXPad360->GetLeftTrigger() > fPadThreshold)
	{
		m_pControlsApp->SetState(CControls::STATE_FIRE, 1);
		//震动
		m_pControlsXPad360->SetLeftMotor(0.3f);
		m_pControlsXPad360->SetRightMotor(0.3f);
	else if (m_pControlsXPad360->GetRightTrigger() < fPadThreshold && m_pControlsXPad360->GetLeftTrigger() < fPadThreshold)
	{
		m_pControlsApp->SetState(CControls::STATE_FIRE, 0);

		m_pControlsXPad360->SetLeftMotor(0.0f);
		m_pControlsXPad360->SetRightMotor(0.0f);
	}
	}
}<|endoftext|>


<commit_before>/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation,
 modification or redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject to these
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
 this original Apple software (the "Apple Software"), to use, reproduce, modify and
 redistribute the Apple Software, with or without modifications, in source and/or binary
 forms; provided that if you redistribute the Apple Software in its entirety and without
 modifications, you must retain this notice and the following text and disclaimers in all
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES,
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
          OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/tools/pepper_test_plugin/plugin_object.h"

#ifdef WIN32
#define NPAPI WINAPI
#else
#define NPAPI
#endif

namespace {

void Log(NPP instance, const char* format, ...) {
  va_list args;
  va_start(args, format);
  std::string message("PLUGIN: ");
  StringAppendV(&message, format, args);
  va_end(args);

  NPObject* window_object = 0;
  NPError error = browser->getvalue(instance, NPNVWindowNPObject,
                                    &window_object);
  if (error != NPERR_NO_ERROR) {
    LOG(ERROR) << "Failed to retrieve window object while logging: "
               << message;
    return;
  }

  NPVariant console_variant;
  if (!browser->getproperty(instance, window_object,
                            browser->getstringidentifier("console"),
                            &console_variant)) {
    LOG(ERROR) << "Failed to retrieve console object while logging: "
               << message;
    browser->releaseobject(window_object);
    return;
  }

  NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);

  NPVariant message_variant;
  STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);

  NPVariant result;
  if (!browser->invoke(instance, console_object,
                       browser->getstringidentifier("log"),
                       &message_variant, 1, &result)) {
    fprintf(stderr, "Failed to invoke console.log while logging: %s\n",
            message);
    browser->releaseobject(console_object);
    browser->releaseobject(window_object);
    return;
  }

  browser->releasevariantvalue(&result);
  browser->releaseobject(console_object);
  browser->releaseobject(window_object);
}

}  // namespace

// Plugin entry points
extern "C" {

#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
                            , NPPluginFuncs* plugin_funcs
#endif
                            );
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);

#if defined(OS_WIN)
//__declspec(dllexport)
#endif
void NPAPI NP_Shutdown() {
}

#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value);
const char* NP_GetMIMEDescription();
#endif

}  // extern "C"

// Plugin entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
                            , NPPluginFuncs* plugin_funcs
#endif
                            ) {
  browser = browser_funcs;
#if defined(OS_LINUX)
  return NP_GetEntryPoints(plugin_funcs);
#else
  return NPERR_NO_ERROR;
#endif
}

// Entrypoints -----------------------------------------------------------------

NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {
  plugin_funcs->version = 11;
  plugin_funcs->size = sizeof(plugin_funcs);
  plugin_funcs->newp = NPP_New;
  plugin_funcs->destroy = NPP_Destroy;
  plugin_funcs->setwindow = NPP_SetWindow;
  plugin_funcs->newstream = NPP_NewStream;
  plugin_funcs->destroystream = NPP_DestroyStream;
  plugin_funcs->asfile = NPP_StreamAsFile;
  plugin_funcs->writeready = NPP_WriteReady;
  plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;
  plugin_funcs->print = NPP_Print;
  plugin_funcs->event = NPP_HandleEvent;
  plugin_funcs->urlnotify = NPP_URLNotify;
  plugin_funcs->getvalue = NPP_GetValue;
  plugin_funcs->setvalue = NPP_SetValue;

  return NPERR_NO_ERROR;
}

NPError NPP_New(NPMIMEType pluginType,
                NPP instance,
                uint16 mode,
                int16 argc, char* argn[], char* argv[],
                NPSavedData* saved) {
  if (browser->version >= 14) {
    PluginObject* obj = reinterpret_cast<PluginObject*>(
        browser->createobject(instance, PluginObject::GetPluginClass()));
    instance->pdata = obj;
  }

  return NPERR_NO_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** save) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
  if (obj)
    browser->releaseobject(obj->header());

  fflush(stdout);
  return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
  if (obj)
    obj->SetWindow(*window);
  return NPERR_NO_ERROR;
}

NPError NPP_NewStream(NPP instance,
                      NPMIMEType type,
                      NPStream* stream,
                      NPBool seekable,
                      uint16* stype) {
  *stype = NP_ASFILEONLY;
  return NPERR_NO_ERROR;
}

NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {
  return NPERR_NO_ERROR;
}

void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
}

int32 NPP_Write(NPP instance,
                NPStream* stream,
                int32 offset,
                int32 len,
                void* buffer) {
  return 0;
}

int32 NPP_WriteReady(NPP instance, NPStream* stream) {
  return 0;
}

void NPP_Print(NPP instance, NPPrint* platformPrint) {
}

int16 NPP_HandleEvent(NPP instance, void* event) {
  return 0;
}

void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
                   void* notify_data) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {
  NPError err = NPERR_NO_ERROR;

  switch (variable) {
#if defined(OS_LINUX)
    case NPPVpluginNameString:
      *((const char**)value) = "Pepper Test PlugIn";
      break;
    case NPPVpluginDescriptionString:
      *((const char**)value) = "Simple Pepper plug-in for manual testing.";
      break;
    case NPPVpluginNeedsXEmbed:
      *((NPBool*)value) = TRUE;
      break;
#endif
    case NPPVpluginScriptableNPObject: {
      void** v = (void**)value;
      PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
      // Return value is expected to be retained
      browser->retainobject((NPObject*)obj);
      *v = obj;
      break;
    }
    default:
      fprintf(stderr, "Unhandled variable to NPP_GetValue\n");
      err = NPERR_GENERIC_ERROR;
      break;
  }

  return err;
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {
  return NPERR_GENERIC_ERROR;
}

#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {
  return NPP_GetValue(instance, variable, value);
}

const char* NP_GetMIMEDescription() {
  return "pepper-application/x-pepper-test-plugin pepper test;";
}
#endif
<commit_msg>Fix a compilation failure on Linux. It still doesn't link correctly yet on Linux.<commit_after>/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation,
 modification or redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject to these
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
 this original Apple software (the "Apple Software"), to use, reproduce, modify and
 redistribute the Apple Software, with or without modifications, in source and/or binary
 forms; provided that if you redistribute the Apple Software in its entirety and without
 modifications, you must retain this notice and the following text and disclaimers in all
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES,
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
          OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/tools/pepper_test_plugin/plugin_object.h"

#ifdef WIN32
#define NPAPI WINAPI
#else
#define NPAPI
#endif

namespace {

void Log(NPP instance, const char* format, ...) {
  va_list args;
  va_start(args, format);
  std::string message("PLUGIN: ");
  StringAppendV(&message, format, args);
  va_end(args);

  NPObject* window_object = 0;
  NPError error = browser->getvalue(instance, NPNVWindowNPObject,
                                    &window_object);
  if (error != NPERR_NO_ERROR) {
    LOG(ERROR) << "Failed to retrieve window object while logging: "
               << message;
    return;
  }

  NPVariant console_variant;
  if (!browser->getproperty(instance, window_object,
                            browser->getstringidentifier("console"),
                            &console_variant)) {
    LOG(ERROR) << "Failed to retrieve console object while logging: "
               << message;
    browser->releaseobject(window_object);
    return;
  }

  NPObject* console_object = NPVARIANT_TO_OBJECT(console_variant);

  NPVariant message_variant;
  STRINGZ_TO_NPVARIANT(message.c_str(), message_variant);

  NPVariant result;
  if (!browser->invoke(instance, console_object,
                       browser->getstringidentifier("log"),
                       &message_variant, 1, &result)) {
    fprintf(stderr, "Failed to invoke console.log while logging: %s\n",
            message.c_str());
    browser->releaseobject(console_object);
    browser->releaseobject(window_object);
    return;
  }

  browser->releasevariantvalue(&result);
  browser->releaseobject(console_object);
  browser->releaseobject(window_object);
}

}  // namespace

// Plugin entry points
extern "C" {

#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
                            , NPPluginFuncs* plugin_funcs
#endif
                            );
#if defined(OS_WIN)
//__declspec(dllexport)
#endif
NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs);

#if defined(OS_WIN)
//__declspec(dllexport)
#endif
void NPAPI NP_Shutdown() {
}

#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value);
const char* NP_GetMIMEDescription();
#endif

}  // extern "C"

// Plugin entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs* browser_funcs
#if defined(OS_LINUX)
                            , NPPluginFuncs* plugin_funcs
#endif
                            ) {
  browser = browser_funcs;
#if defined(OS_LINUX)
  return NP_GetEntryPoints(plugin_funcs);
#else
  return NPERR_NO_ERROR;
#endif
}

// Entrypoints -----------------------------------------------------------------

NPError NPAPI NP_GetEntryPoints(NPPluginFuncs* plugin_funcs) {
  plugin_funcs->version = 11;
  plugin_funcs->size = sizeof(plugin_funcs);
  plugin_funcs->newp = NPP_New;
  plugin_funcs->destroy = NPP_Destroy;
  plugin_funcs->setwindow = NPP_SetWindow;
  plugin_funcs->newstream = NPP_NewStream;
  plugin_funcs->destroystream = NPP_DestroyStream;
  plugin_funcs->asfile = NPP_StreamAsFile;
  plugin_funcs->writeready = NPP_WriteReady;
  plugin_funcs->write = (NPP_WriteProcPtr)NPP_Write;
  plugin_funcs->print = NPP_Print;
  plugin_funcs->event = NPP_HandleEvent;
  plugin_funcs->urlnotify = NPP_URLNotify;
  plugin_funcs->getvalue = NPP_GetValue;
  plugin_funcs->setvalue = NPP_SetValue;

  return NPERR_NO_ERROR;
}

NPError NPP_New(NPMIMEType pluginType,
                NPP instance,
                uint16 mode,
                int16 argc, char* argn[], char* argv[],
                NPSavedData* saved) {
  if (browser->version >= 14) {
    PluginObject* obj = reinterpret_cast<PluginObject*>(
        browser->createobject(instance, PluginObject::GetPluginClass()));
    instance->pdata = obj;
  }

  return NPERR_NO_ERROR;
}

NPError NPP_Destroy(NPP instance, NPSavedData** save) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
  if (obj)
    browser->releaseobject(obj->header());

  fflush(stdout);
  return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow* window) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
  if (obj)
    obj->SetWindow(*window);
  return NPERR_NO_ERROR;
}

NPError NPP_NewStream(NPP instance,
                      NPMIMEType type,
                      NPStream* stream,
                      NPBool seekable,
                      uint16* stype) {
  *stype = NP_ASFILEONLY;
  return NPERR_NO_ERROR;
}

NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) {
  return NPERR_NO_ERROR;
}

void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) {
}

int32 NPP_Write(NPP instance,
                NPStream* stream,
                int32 offset,
                int32 len,
                void* buffer) {
  return 0;
}

int32 NPP_WriteReady(NPP instance, NPStream* stream) {
  return 0;
}

void NPP_Print(NPP instance, NPPrint* platformPrint) {
}

int16 NPP_HandleEvent(NPP instance, void* event) {
  return 0;
}

void NPP_URLNotify(NPP instance, const char* url, NPReason reason,
                   void* notify_data) {
  PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) {
  NPError err = NPERR_NO_ERROR;

  switch (variable) {
#if defined(OS_LINUX)
    case NPPVpluginNameString:
      *((const char**)value) = "Pepper Test PlugIn";
      break;
    case NPPVpluginDescriptionString:
      *((const char**)value) = "Simple Pepper plug-in for manual testing.";
      break;
    case NPPVpluginNeedsXEmbed:
      *((NPBool*)value) = TRUE;
      break;
#endif
    case NPPVpluginScriptableNPObject: {
      void** v = (void**)value;
      PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
      // Return value is expected to be retained
      browser->retainobject((NPObject*)obj);
      *v = obj;
      break;
    }
    default:
      fprintf(stderr, "Unhandled variable to NPP_GetValue\n");
      err = NPERR_GENERIC_ERROR;
      break;
  }

  return err;
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) {
  return NPERR_GENERIC_ERROR;
}

#if defined(OS_LINUX)
NPError NP_GetValue(NPP instance, NPPVariable variable, void* value) {
  return NPP_GetValue(instance, variable, value);
}

const char* NP_GetMIMEDescription() {
  return "pepper-application/x-pepper-test-plugin pepper test;";
}
#endif
<|endoftext|>


<commit_before>#include <boost/test/unit_test.hpp>
#include <iostream>
#include "submodular-ibfs.hpp"
#include "higher-order.hpp"
#include "gen-random.hpp"
#include "QPBO.h"

typedef SubmodularIBFS::NodeId NodeId;
typedef SubmodularIBFS::CliqueId CliqueId;

/* Sets up a submodular flow problem with a single clique. The clique has 4
* nodes, and is equal to -1 when all 4 nodes are set to 1, 0 otherwise.
*/
void SetupMinimalFlow(SubmodularIBFS& sf) {

    sf.AddNode(4);

    std::vector<NodeId> nodes = {0, 1, 2, 3};
    const size_t numAssignments = 1 << 4;
    std::vector<REAL> energyTable(numAssignments, 0);
    energyTable[0xf] = -1;
    sf.AddClique(nodes, energyTable);
}

BOOST_AUTO_TEST_SUITE(ibfsSetupTests)

BOOST_AUTO_TEST_CASE(defaultConstructor) {
    SubmodularIBFS sf;

    BOOST_CHECK_EQUAL(sf.GetConstantTerm(), 0);
    BOOST_CHECK_EQUAL(sf.GetNumNodes(), 0);
    BOOST_CHECK_EQUAL(sf.GetC_si().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), 0);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 0);
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);
}

BOOST_AUTO_TEST_CASE(minimalFlowSetup) {
    SubmodularIBFS sf;
    SetupMinimalFlow(sf);

    BOOST_CHECK_EQUAL(sf.GetConstantTerm(), -1);
    BOOST_CHECK_EQUAL(sf.GetC_si().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), 1);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), 1);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 4);
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);

    std::vector<int>& labels = sf.GetLabels();
    const uint32_t max_assgn = 1 << 4;
    for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {
        for (NodeId i = 0; i < 4; ++i) {
            if (assgn & (1 << i))
                labels[i] = 1;
            else
                labels[i] = 0;
        }
        if (assgn == 0xf)
            BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);
        else
            BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);
    }
}

BOOST_AUTO_TEST_CASE(randomFlowSetup) {
    SubmodularIBFS sf;
    const size_t n = 100;
    const size_t k = 4;
    const size_t m = 100;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);

    BOOST_CHECK_EQUAL(sf.GetC_si().size(), n);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), n);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), n);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), n);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), n);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), m);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), m);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), n);

}

/* Check that for a clique c, the energy is always >= 0, and is equal to 0 at
* the all 0 and all 1 labelings.
*/
void CheckNormalized(const SubmodularIBFS::Clique& c, std::vector<int>& labels) {
    const size_t n = c.Nodes().size();
    BOOST_REQUIRE_LT(n, 32);
    const uint32_t max_assgn = 1 << n;
    for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {
        for (size_t i = 0; i < n; ++i) {
            if (assgn & (1 << i))
                labels[c.Nodes()[i]] = 1;
            else
                labels[c.Nodes()[i]] = 0;
        }
        if (assgn == 0)
            BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);
        else if (assgn == max_assgn - 1)
            BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);
        else
            BOOST_CHECK_GE(c.ComputeEnergy(labels), 0);
    }
}

/* Check that all source-sink capacities are >= 0, and that cliques
* are normalized (i.e., are >= 0 for all labelings)
*/
BOOST_AUTO_TEST_CASE(randomFlowNormalized) {
    SubmodularIBFS sf;
    const size_t n = 100;
    const size_t k = 4;
    const size_t m = 100;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);

    for (size_t i = 0; i < n; ++i) {
        BOOST_CHECK_GE(sf.GetC_si()[i], 0);
        BOOST_CHECK_GE(sf.GetC_it()[i], 0);
        BOOST_CHECK_EQUAL(sf.GetPhi_si()[i], 0);
        BOOST_CHECK_EQUAL(sf.GetPhi_it()[i], 0);
    }

    for (const SubmodularIBFS::CliquePtr& cp : sf.GetCliques()) {
        const SubmodularIBFS::Clique& c = *cp;
        BOOST_CHECK_EQUAL(c.Nodes().size(), 4);
        CheckNormalized(c, sf.GetLabels());
    }
}

BOOST_AUTO_TEST_SUITE_END()

//BOOST_AUTO_TEST_SUITE(flowInvariants)
//BOOST_AUTO_TEST_SUITE_END()

void CheckCut(SubmodularIBFS& sf) {
    auto& phi_si = sf.GetPhi_si();
    auto& phi_it = sf.GetPhi_it();
    auto& c_si = sf.GetC_si();
    auto& c_it = sf.GetC_it();
    auto& nodes = sf.GetNodes();
    for (SubmodularIBFS::NodeId i = 0; i < sf.GetNumNodes(); ++i) {
        int label = sf.GetLabel(i);
        if (label == 0) {
            BOOST_CHECK_EQUAL(phi_si[i], c_si[i]);
        } else {
            BOOST_CHECK_EQUAL(phi_it[i], c_it[i]);
        }
        for (auto arc : nodes[i].out_arcs) {
            auto j = arc.j;
            if (j >= sf.GetNumNodes())
                continue;
            int label_j = sf.GetLabel(j);
            if (label == 1 && label_j == 0) {
                BOOST_CHECK_EQUAL(sf.ResCap(arc), 0);
                if (sf.ResCap(arc) != 0)
                    std::cout << "Bad Arc: " << arc.i << ", " << arc.j << "\n";
            }
        }

    }
}

BOOST_AUTO_TEST_SUITE(ibfsFlowTests)

/* Sanity check to make sure basic flow computation working on a minimally
* sized graph.
*/
BOOST_AUTO_TEST_CASE(minimalFlow) {
    SubmodularIBFS sf;
    SetupMinimalFlow(sf);

    sf.Solve();
    CheckCut(sf);

    // Minimum energy is -1 with all 4 nodes labeled 1. Check that this
    // was the answer we found.
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);
    for (NodeId i = 0; i < 4; ++i) {
        BOOST_CHECK_EQUAL(sf.GetLabel(i), 1);
    }
}

BOOST_AUTO_TEST_CASE(makeSureToSearchSource) {
SubmodularIBFS crf;
crf.AddNode(3);
crf.AddUnaryTerm(0, 12, 6);
crf.AddUnaryTerm(1, 8, 8);
crf.AddUnaryTerm(2, 6, 12);
NodeId node_array[3] = {0, 1, 2};
std::vector<NodeId> node(node_array, node_array + 3);
REAL energy_array[8] = {0, 3, 1, 2, 0, 2, 0, 0};
std::vector<REAL> energy(energy_array, energy_array + 8);
crf.AddClique(node, energy);
crf.Solve();
    BOOST_CHECK_EQUAL(crf.GetLabel(0), 1);
    BOOST_CHECK_EQUAL(crf.GetLabel(1), 1);
    BOOST_CHECK_EQUAL(crf.GetLabel(2), 0);
    BOOST_CHECK_EQUAL(crf.ComputeEnergy(), 22);

    std::vector<int> label;
    label.push_back(1);
    label.push_back(0);
    label.push_back(0);
    BOOST_CHECK_EQUAL(crf.ComputeEnergy(label), 23);
}

/* More complicated test case on a larger graph.
*
* GenRandom generates a random submodular function that can be turned into
* a submodular quadratic function by HigherOrderEnergy. We generate the
* same energy function for both SubmodularIBFS and HigherOrderEnergy
* and then check that they give the same answer.
*/
BOOST_AUTO_TEST_CASE(identicalToHigherOrder) {
    SubmodularIBFS sf;
    HigherOrderEnergy<REAL, 4> ho;

    const size_t n = 2000;
    const size_t k = 4;
    const size_t m = 2000;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);
    GenRandom(ho, n, k, m, clique_range, unary_mean, unary_var, seed);

    sf.Solve();
    CheckCut(sf);

    QPBO<REAL> qr(n, 0);
    ho.ToQuadratic(qr);
    qr.Solve();

    std::vector<int> qr_labels;
    for (size_t i = 0; i < n; ++i)
        qr_labels.push_back(qr.GetLabel(i));

    // If this test fails, there's a problem in the higher-order code. Email me
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(qr_labels)*2, qr.ComputeTwiceEnergy());

    BOOST_CHECK_EQUAL(sf.ComputeEnergy()*2, qr.ComputeTwiceEnergy());
    for (size_t i = 0; i < n; ++i) {
        BOOST_REQUIRE(qr.GetLabel(i) >= 0);
        BOOST_WARN_EQUAL(sf.GetLabel(i), qr.GetLabel(i));
    }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fixing strange merge error<commit_after>#include <boost/test/unit_test.hpp>
#include <iostream>
#include "submodular-ibfs.hpp"
#include "higher-order.hpp"
#include "gen-random.hpp"
#include "QPBO.h"

typedef SubmodularIBFS::NodeId NodeId;
typedef SubmodularIBFS::CliqueId CliqueId;

/* Sets up a submodular flow problem with a single clique. The clique has 4
* nodes, and is equal to -1 when all 4 nodes are set to 1, 0 otherwise.
*/
void SetupMinimalFlow(SubmodularIBFS& sf) {

    sf.AddNode(4);

    std::vector<NodeId> nodes = {0, 1, 2, 3};
    const size_t numAssignments = 1 << 4;
    std::vector<REAL> energyTable(numAssignments, 0);
    energyTable[0xf] = -1;
    sf.AddClique(nodes, energyTable);
}

BOOST_AUTO_TEST_SUITE(ibfsSetupTests)

BOOST_AUTO_TEST_CASE(defaultConstructor) {
    SubmodularIBFS sf;

    BOOST_CHECK_EQUAL(sf.GetConstantTerm(), 0);
    BOOST_CHECK_EQUAL(sf.GetNumNodes(), 0);
    BOOST_CHECK_EQUAL(sf.GetC_si().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), 0);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), 0);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 0);
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);
}

BOOST_AUTO_TEST_CASE(minimalFlowSetup) {
    SubmodularIBFS sf;
    SetupMinimalFlow(sf);

    BOOST_CHECK_EQUAL(sf.GetConstantTerm(), -1);
    BOOST_CHECK_EQUAL(sf.GetC_si().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), 4);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), 1);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), 1);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), 4);
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);

    std::vector<int>& labels = sf.GetLabels();
    const uint32_t max_assgn = 1 << 4;
    for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {
        for (NodeId i = 0; i < 4; ++i) {
            if (assgn & (1 << i))
                labels[i] = 1;
            else
                labels[i] = 0;
        }
        if (assgn == 0xf)
            BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);
        else
            BOOST_CHECK_EQUAL(sf.ComputeEnergy(), 0);
    }
}

BOOST_AUTO_TEST_CASE(randomFlowSetup) {
    SubmodularIBFS sf;
    const size_t n = 100;
    const size_t k = 4;
    const size_t m = 100;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);

    BOOST_CHECK_EQUAL(sf.GetC_si().size(), n);
    BOOST_CHECK_EQUAL(sf.GetC_it().size(), n);
    BOOST_CHECK_EQUAL(sf.GetPhi_si().size(), n);
    BOOST_CHECK_EQUAL(sf.GetPhi_it().size(), n);
    BOOST_CHECK_EQUAL(sf.GetLabels().size(), n);
    BOOST_CHECK_EQUAL(sf.GetNumCliques(), m);
    BOOST_CHECK_EQUAL(sf.GetCliques().size(), m);
    BOOST_CHECK_EQUAL(sf.GetNeighbors().size(), n);

}

/* Check that for a clique c, the energy is always >= 0, and is equal to 0 at
* the all 0 and all 1 labelings.
*/
void CheckNormalized(const SubmodularIBFS::Clique& c, std::vector<int>& labels) {
    const size_t n = c.Nodes().size();
    BOOST_REQUIRE_LT(n, 32);
    const uint32_t max_assgn = 1 << n;
    for (uint32_t assgn = 0; assgn < max_assgn; ++assgn) {
        for (size_t i = 0; i < n; ++i) {
            if (assgn & (1 << i))
                labels[c.Nodes()[i]] = 1;
            else
                labels[c.Nodes()[i]] = 0;
        }
        if (assgn == 0)
            BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);
        else if (assgn == max_assgn - 1)
            BOOST_CHECK_EQUAL(c.ComputeEnergy(labels), 0);
        else
            BOOST_CHECK_GE(c.ComputeEnergy(labels), 0);
    }
}

/* Check that all source-sink capacities are >= 0, and that cliques
* are normalized (i.e., are >= 0 for all labelings)
*/
BOOST_AUTO_TEST_CASE(randomFlowNormalized) {
    SubmodularIBFS sf;
    const size_t n = 100;
    const size_t k = 4;
    const size_t m = 100;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);

    for (size_t i = 0; i < n; ++i) {
        BOOST_CHECK_GE(sf.GetC_si()[i], 0);
        BOOST_CHECK_GE(sf.GetC_it()[i], 0);
        BOOST_CHECK_EQUAL(sf.GetPhi_si()[i], 0);
        BOOST_CHECK_EQUAL(sf.GetPhi_it()[i], 0);
    }

    for (const SubmodularIBFS::CliquePtr& cp : sf.GetCliques()) {
        const SubmodularIBFS::Clique& c = *cp;
        BOOST_CHECK_EQUAL(c.Nodes().size(), 4);
        CheckNormalized(c, sf.GetLabels());
    }
}

BOOST_AUTO_TEST_SUITE_END()

//BOOST_AUTO_TEST_SUITE(flowInvariants)
//BOOST_AUTO_TEST_SUITE_END()

void CheckCut(SubmodularIBFS& sf) {
    auto& phi_si = sf.GetPhi_si();
    auto& phi_it = sf.GetPhi_it();
    auto& c_si = sf.GetC_si();
    auto& c_it = sf.GetC_it();
    auto& nodes = sf.GetNodes();
    for (SubmodularIBFS::NodeId i = 0; i < sf.GetNumNodes(); ++i) {
        int label = sf.GetLabel(i);
        if (label == 0) {
            BOOST_CHECK_EQUAL(phi_si[i], c_si[i]);
        } else {
            BOOST_CHECK_EQUAL(phi_it[i], c_it[i]);
        }
        for (auto arc : nodes[i].out_arcs) {
            auto j = arc.j;
            if (j >= sf.GetNumNodes())
                continue;
            int label_j = sf.GetLabel(j);
            if (label == 1 && label_j == 0) {
                BOOST_CHECK_EQUAL(sf.ResCap(arc), 0);
                if (sf.ResCap(arc) != 0)
                    std::cout << "Bad Arc: " << arc.i << ", " << arc.j << "\n";
            }
        }

    }
}

BOOST_AUTO_TEST_SUITE(ibfsFlowTests)

/* Sanity check to make sure basic flow computation working on a minimally
* sized graph.
*/
BOOST_AUTO_TEST_CASE(minimalFlow) {
    SubmodularIBFS sf;
    SetupMinimalFlow(sf);

    sf.Solve();
    CheckCut(sf);

    // Minimum energy is -1 with all 4 nodes labeled 1. Check that this
    // was the answer we found.
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(), -1);
    for (NodeId i = 0; i < 4; ++i) {
        BOOST_CHECK_EQUAL(sf.GetLabel(i), 1);
    }
}

BOOST_AUTO_TEST_CASE(makeSureToSearchSource) {
	SubmodularIBFS crf;
	crf.AddNode(3);
	crf.AddUnaryTerm(0, 12, 6);
	crf.AddUnaryTerm(1, 8, 8);
	crf.AddUnaryTerm(2, 6, 12);
	NodeId node_array[3] = {0, 1, 2};
	std::vector<NodeId> node(node_array, node_array + 3);
	REAL energy_array[8] = {0, 3, 1, 2, 0, 2, 0, 0};
	std::vector<REAL> energy(energy_array, energy_array + 8);
	crf.AddClique(node, energy);
	crf.Solve();
    BOOST_CHECK_EQUAL(crf.GetLabel(0), 1);
    BOOST_CHECK_EQUAL(crf.GetLabel(1), 1);
    BOOST_CHECK_EQUAL(crf.GetLabel(2), 0);
    BOOST_CHECK_EQUAL(crf.ComputeEnergy(), 22);

    std::vector<int> label;
    label.push_back(1);
    label.push_back(0);
    label.push_back(0);
    BOOST_CHECK_EQUAL(crf.ComputeEnergy(label), 23);
}

/* More complicated test case on a larger graph.
*
* GenRandom generates a random submodular function that can be turned into
* a submodular quadratic function by HigherOrderEnergy. We generate the
* same energy function for both SubmodularIBFS and HigherOrderEnergy
* and then check that they give the same answer.
*/
BOOST_AUTO_TEST_CASE(identicalToHigherOrder) {
    SubmodularIBFS sf;
    HigherOrderEnergy<REAL, 4> ho;

    const size_t n = 2000;
    const size_t k = 4;
    const size_t m = 2000;
    const REAL clique_range = 100;
    const REAL unary_mean = 800;
    const REAL unary_var = 1600;
    const unsigned int seed = 0;

    GenRandom(sf, n, k, m, clique_range, unary_mean, unary_var, seed);
    GenRandom(ho, n, k, m, clique_range, unary_mean, unary_var, seed);

    sf.Solve();
    CheckCut(sf);

    QPBO<REAL> qr(n, 0);
    ho.ToQuadratic(qr);
    qr.Solve();

    std::vector<int> qr_labels;
    for (size_t i = 0; i < n; ++i)
        qr_labels.push_back(qr.GetLabel(i));

    // If this test fails, there's a problem in the higher-order code. Email me
    BOOST_CHECK_EQUAL(sf.ComputeEnergy(qr_labels)*2, qr.ComputeTwiceEnergy());

    BOOST_CHECK_EQUAL(sf.ComputeEnergy()*2, qr.ComputeTwiceEnergy());
    for (size_t i = 0; i < n; ++i) {
        BOOST_REQUIRE(qr.GetLabel(i) >= 0);
        BOOST_WARN_EQUAL(sf.GetLabel(i), qr.GetLabel(i));
    }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>