<commit_before>/*
 * SessionPanmirrorPandoc.cpp
 *
 * Copyright (C) 2009-16 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPanmirrorPandoc.hpp"

#include <shared_core/Error.hpp>

#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Process.hpp>

#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace pandoc {

namespace {

Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
   for(json::Array::Iterator
         it = options.begin();
         it != options.end();
         ++it)
   {
      if ((*it).getType() != json::Type::STRING)
         return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);

      std::string option = (*it).getString();
      pOptions->push_back(option);
   }
   return Success();
}

void endAstToMarkdown(const json::JsonRpcFunctionContinuation& cont,
                      const core::system::ProcessResult& result)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      response.setResult(result.stdOut);
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
   }
   cont(Success(), &response);
}

void pandocAstToMarkdown(const json::JsonRpcRequest& request,
                         const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract params
   json::Object jsonAst;
   std::string format;
   json::Array jsonOptions;
   Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back("json");
   args.push_back("--to");
   args.push_back(format);
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc (async)
   error = module_context::runPandocAsync(args, jsonAst.write(), boost::bind(endAstToMarkdown, cont, _1));
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
   }
}

void endHeadingIds(json::Object astJson,
                   const core::system::ProcessResult& result,
                   const json::JsonRpcFunctionContinuation& cont)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      std::vector<std::string> lines;
      boost::algorithm::split(lines, result.stdOut, boost::algorithm::is_any_of("\n\r"));
      json::Array jsonHeadingsIds;
      std::for_each(lines.begin(), lines.end(), [&jsonHeadingsIds](std::string line) {
         boost::algorithm::trim(line);
         if (!line.empty())
            jsonHeadingsIds.push_back(line);
      });
      astJson["heading_ids"] = jsonHeadingsIds;
      response.setResult(astJson);
      cont(Success(), &response);
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
      cont(Success(), &response);
   }
}

void endMarkdownToAst(std::string markdown,
                      std::string format,
                      const core::system::ProcessResult& result,
                      const json::JsonRpcFunctionContinuation& cont)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      json::Object jsonObject;
      if (json::parseJsonForResponse(result.stdOut, &jsonObject, &response))
      {
         // got ast, now extract heading ids

         // disable auto identifiers so we can discover *only* explicit ids
         format += "-auto_identifiers-gfm_auto_identifiers";

         // path to lua filter
         FilePath resPath = session::options().rResourcesPath();
         FilePath headingIdsLuaPath = resPath.completePath("heading_ids.lua");
         std::string headingIdsLua = string_utils::utf8ToSystem(headingIdsLuaPath.getAbsolutePath());

         // build args
         std::vector<std::string> args;
         args.push_back("--from");
         args.push_back(format);
         args.push_back("--to");
         args.push_back(headingIdsLua);

         // run pandoc
         core::system::ProcessResult result;
         Error error = module_context::runPandocAsync(args, markdown, boost::bind(endHeadingIds, jsonObject, _1, cont));
         if (error)
         {
            json::setErrorResponse(error, &response);
            cont(Success(), &response);
         }
      }
      else
      {
         cont(Success(), &response);
      }
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
      cont(Success(), &response);
   }

}

void pandocMarkdownToAst(const json::JsonRpcRequest& request,
                         const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract params
   json::Array jsonOptions;
   std::string markdown, format;
   Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back(format);
   args.push_back("--to");
   args.push_back("json");
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = module_context::runPandocAsync(args, markdown, boost::bind(endMarkdownToAst, markdown, format, _1, cont));
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }
}

bool pandocCaptureOutput(const std::vector<std::string>& args,
                         const std::string& input,
                         std::string* pOutput,
                         json::JsonRpcResponse* pResponse)
{
   // run pandoc
   core::system::ProcessResult result;
   Error error = module_context::runPandoc(args, input, &result);
   if (error)
   {
      json::setErrorResponse(error, pResponse);
      return false;
   }
   else if (result.exitStatus != EXIT_SUCCESS)
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, pResponse);
      return false;
   }
   else
   {
      *pOutput = result.stdOut;
      return true;
   }
}

bool pandocCaptureOutput(const std::string& arg, std::string* pOutput, json::JsonRpcResponse* pResponse)
{
   std::vector<std::string> args;
   args.push_back(arg);
   return pandocCaptureOutput(args, "", pOutput, pResponse);
}

void pandocGetCapabilities(const json::JsonRpcRequest&,
                           const json::JsonRpcFunctionContinuation& cont)
{

   // response object
   json::JsonRpcResponse response;

   // version
   std::string version;
   if (!pandocCaptureOutput("--version", &version, &response))
   {
      cont(Success(), &response);
      return;
   }

   // try for hit from cache of capabilities by version
   static std::map<std::string,json::Object> s_capabilitiesCache;
   std::map<std::string,json::Object>::const_iterator it = s_capabilitiesCache.find(version);
   if (it != s_capabilitiesCache.end())
   {
      response.setResult(it->second);
      cont(Success(), &response);
      return;
   }

   // api version
   std::vector<std::string> apiArgs;
   apiArgs.push_back("--to");
   apiArgs.push_back("json");
   std::string apiOutput;
   if (!pandocCaptureOutput(apiArgs, " ", &apiOutput, &response))
   {
      cont(Success(), &response);
      return;
   }
   json::Object jsonAst;
   if (!json::parseJsonForResponse(apiOutput, &jsonAst, &response))
   {
      cont(Success(), &response);
      return;
   }

   // output formats
   json::Array apiVersion = jsonAst["pandoc-api-version"].getArray();
   std::string outputFormats;
   if (!pandocCaptureOutput("--list-output-formats", &outputFormats, &response))
   {
      cont(Success(), &response);
      return;
   }

   // highlight languages
   std::string highlightLanguages;
   if (!pandocCaptureOutput("--list-highlight-languages", &highlightLanguages, &response))
   {
      cont(Success(), &response);
      return;
   }

   // build capabilities response
   json::Object capabilities;
   capabilities["version"] = version;
   capabilities["api_version"] = apiVersion;
   capabilities["output_formats"] = outputFormats;
   capabilities["highlight_languages"] = highlightLanguages;

   // cache by version
   s_capabilitiesCache[version] = capabilities;

   // set response
   response.setResult(capabilities);
   cont(Success(), &response);
}

void pandocListExtensions(const json::JsonRpcRequest& request,
                          const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract format
   std::string format;
   Error error = json::readParams(request.params, &format);
   if (error)
   {
     json::setErrorResponse(error, &response);
     cont(Success(), &response);
     return;
   }

   // build arg
   std::string arg =  "--list-extensions";
   if (!format.empty())
      arg += ('=' + format);

   std::string extensions;
   if (pandocCaptureOutput(arg, &extensions, &response))
   {
      response.setResult(extensions);
      cont(Success(), &response);
   }

}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_get_capabilities", pandocGetCapabilities))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_list_extensions", pandocListExtensions))
   ;
   return initBlock.execute();
}

} // end namespace pandoc
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>Pass through error calling pandoc<commit_after>/*
 * SessionPanmirrorPandoc.cpp
 *
 * Copyright (C) 2009-16 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SessionPanmirrorPandoc.hpp"

#include <shared_core/Error.hpp>

#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Process.hpp>

#include <session/SessionModuleContext.hpp>

using namespace rstudio::core;

namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace pandoc {

namespace {

Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
   for(json::Array::Iterator
         it = options.begin();
         it != options.end();
         ++it)
   {
      if ((*it).getType() != json::Type::STRING)
         return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);

      std::string option = (*it).getString();
      pOptions->push_back(option);
   }
   return Success();
}

void endAstToMarkdown(const json::JsonRpcFunctionContinuation& cont,
                      const core::system::ProcessResult& result)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      response.setResult(result.stdOut);
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
   }
   cont(Success(), &response);
}

void pandocAstToMarkdown(const json::JsonRpcRequest& request,
                         const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract params
   json::Object jsonAst;
   std::string format;
   json::Array jsonOptions;
   Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back("json");
   args.push_back("--to");
   args.push_back(format);
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc (async)
   error = module_context::runPandocAsync(args, jsonAst.write(), boost::bind(endAstToMarkdown, cont, _1));
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
   }
}

void endHeadingIds(json::Object astJson,
                   const core::system::ProcessResult& result,
                   const json::JsonRpcFunctionContinuation& cont)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      std::vector<std::string> lines;
      boost::algorithm::split(lines, result.stdOut, boost::algorithm::is_any_of("\n\r"));
      json::Array jsonHeadingsIds;
      std::for_each(lines.begin(), lines.end(), [&jsonHeadingsIds](std::string line) {
         boost::algorithm::trim(line);
         if (!line.empty())
            jsonHeadingsIds.push_back(line);
      });
      astJson["heading_ids"] = jsonHeadingsIds;
      response.setResult(astJson);
      cont(Success(), &response);
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
      cont(Success(), &response);
   }
}

void endMarkdownToAst(std::string markdown,
                      std::string format,
                      const core::system::ProcessResult& result,
                      const json::JsonRpcFunctionContinuation& cont)
{
   json::JsonRpcResponse response;
   if (result.exitStatus == EXIT_SUCCESS)
   {
      json::Object jsonObject;
      if (json::parseJsonForResponse(result.stdOut, &jsonObject, &response))
      {
         // got ast, now extract heading ids

         // disable auto identifiers so we can discover *only* explicit ids
         format += "-auto_identifiers-gfm_auto_identifiers";

         // path to lua filter
         FilePath resPath = session::options().rResourcesPath();
         FilePath headingIdsLuaPath = resPath.completePath("heading_ids.lua");
         std::string headingIdsLua = string_utils::utf8ToSystem(headingIdsLuaPath.getAbsolutePath());

         // build args
         std::vector<std::string> args;
         args.push_back("--from");
         args.push_back(format);
         args.push_back("--to");
         args.push_back(headingIdsLua);

         // run pandoc
         core::system::ProcessResult result;
         Error error = module_context::runPandocAsync(args, markdown, boost::bind(endHeadingIds, jsonObject, _1, cont));
         if (error)
         {
            json::setErrorResponse(error, &response);
            cont(Success(), &response);
         }
      }
      else
      {
         cont(Success(), &response);
      }
   }
   else
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
      cont(Success(), &response);
   }

}

void pandocMarkdownToAst(const json::JsonRpcRequest& request,
                         const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract params
   json::Array jsonOptions;
   std::string markdown, format;
   Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }
   std::vector<std::string> options;
   error = readOptionsParam(jsonOptions, &options);
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }

   // build args
   std::vector<std::string> args;
   args.push_back("--from");
   args.push_back(format);
   args.push_back("--to");
   args.push_back("json");
   std::copy(options.begin(), options.end(), std::back_inserter(args));

   // run pandoc
   core::system::ProcessResult result;
   error = module_context::runPandocAsync(args, markdown, boost::bind(endMarkdownToAst, markdown, format, _1, cont));
   if (error)
   {
      json::setErrorResponse(error, &response);
      cont(Success(), &response);
      return;
   }
}

bool pandocCaptureOutput(const std::vector<std::string>& args,
                         const std::string& input,
                         std::string* pOutput,
                         json::JsonRpcResponse* pResponse)
{
   // run pandoc
   core::system::ProcessResult result;
   Error error = module_context::runPandoc(args, input, &result);
   if (error)
   {
      json::setErrorResponse(error, pResponse);
      return false;
   }
   else if (result.exitStatus != EXIT_SUCCESS)
   {
      json::setProcessErrorResponse(result, ERROR_LOCATION, pResponse);
      return false;
   }
   else
   {
      *pOutput = result.stdOut;
      return true;
   }
}

bool pandocCaptureOutput(const std::string& arg, std::string* pOutput, json::JsonRpcResponse* pResponse)
{
   std::vector<std::string> args;
   args.push_back(arg);
   return pandocCaptureOutput(args, "", pOutput, pResponse);
}

void pandocGetCapabilities(const json::JsonRpcRequest&,
                           const json::JsonRpcFunctionContinuation& cont)
{

   // response object
   json::JsonRpcResponse response;

   // version
   std::string version;
   if (!pandocCaptureOutput("--version", &version, &response))
   {
      cont(Success(), &response);
      return;
   }

   // try for hit from cache of capabilities by version
   static std::map<std::string,json::Object> s_capabilitiesCache;
   std::map<std::string,json::Object>::const_iterator it = s_capabilitiesCache.find(version);
   if (it != s_capabilitiesCache.end())
   {
      response.setResult(it->second);
      cont(Success(), &response);
      return;
   }

   // api version
   std::vector<std::string> apiArgs;
   apiArgs.push_back("--to");
   apiArgs.push_back("json");
   std::string apiOutput;
   if (!pandocCaptureOutput(apiArgs, " ", &apiOutput, &response))
   {
      cont(Success(), &response);
      return;
   }
   json::Object jsonAst;
   if (!json::parseJsonForResponse(apiOutput, &jsonAst, &response))
   {
      cont(Success(), &response);
      return;
   }

   // output formats
   json::Array apiVersion = jsonAst["pandoc-api-version"].getArray();
   std::string outputFormats;
   if (!pandocCaptureOutput("--list-output-formats", &outputFormats, &response))
   {
      cont(Success(), &response);
      return;
   }

   // highlight languages
   std::string highlightLanguages;
   if (!pandocCaptureOutput("--list-highlight-languages", &highlightLanguages, &response))
   {
      cont(Success(), &response);
      return;
   }

   // build capabilities response
   json::Object capabilities;
   capabilities["version"] = version;
   capabilities["api_version"] = apiVersion;
   capabilities["output_formats"] = outputFormats;
   capabilities["highlight_languages"] = highlightLanguages;

   // cache by version
   s_capabilitiesCache[version] = capabilities;

   // set response
   response.setResult(capabilities);
   cont(Success(), &response);
}

void pandocListExtensions(const json::JsonRpcRequest& request,
                          const json::JsonRpcFunctionContinuation& cont)
{
   // response object
   json::JsonRpcResponse response;

   // extract format
   std::string format;
   Error error = json::readParams(request.params, &format);
   if (error)
   {
     json::setErrorResponse(error, &response);
     cont(Success(), &response);
     return;
   }

   // build arg
   std::string arg =  "--list-extensions";
   if (!format.empty())
      arg += ('=' + format);

   std::string extensions;
   if (pandocCaptureOutput(arg, &extensions, &response))
   {
      response.setResult(extensions);
      cont(Success(), &response);
   }
   else
   {
       // Pandoc failed for some reason
       cont(Error(), &response);
   }

}

} // end anonymous namespace

Error initialize()
{
   ExecBlock initBlock;
   initBlock.addFunctions()
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_get_capabilities", pandocGetCapabilities))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
      (boost::bind(module_context::registerAsyncRpcMethod, "pandoc_list_extensions", pandocListExtensions))
   ;
   return initBlock.execute();
}

} // end namespace pandoc
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "ModularGapConductanceConstraint.h"
#include "GapFluxModelBase.h"

registerMooseObject("HeatConductionApp", ModularGapConductanceConstraint);

InputParameters
ModularGapConductanceConstraint::validParams()
{
  InputParameters params = ADMortarConstraint::validParams();
  params.addClassDescription(
      "Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' "
      "implementation of the thermal contact problem. For more information, see the "
      "detailed description here: http://tinyurl.com/gmmhbe9");
  params.addParam<std::vector<UserObjectName>>("gap_flux_models",
                                               "List of GapFluxModel user objects");
  params.addCoupledVar("displacements", "Displacement variables");
  return params;
}

ModularGapConductanceConstraint::ModularGapConductanceConstraint(const InputParameters & parameters)
  : ADMortarConstraint(parameters),
    _gap_flux_model_names(getParam<std::vector<UserObjectName>>("gap_flux_models")),
    _disp_name(parameters.getVecMooseType("displacements")),
    _n_disp(_disp_name.size()),
    _disp_secondary(_n_disp),
    _disp_primary(_n_disp)
{
  for (unsigned int i = 0; i < _n_disp; ++i)
  {
    auto & disp_var = _subproblem.getStandardVariable(_tid, _disp_name[i]);
    _disp_secondary[i] = &disp_var.adSln();
    _disp_primary[i] = &disp_var.adSlnNeighbor();
  }

  for (const auto & name : _gap_flux_model_names)
  {
    const auto & gap_model = getUserObjectByName<GapFluxModelBase>(name);

    // pass variable dependencies through
    const auto & var_dependencies = gap_model.getMooseVariableDependencies();
    for (const auto & var : var_dependencies)
      addMooseVariableDependency(var);

    // add gap model to list
    _gap_flux_models.push_back(&gap_model);
  }
}

ADReal
ModularGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)
{
  switch (mortar_type)
  {
    case Moose::MortarType::Primary:
      return _lambda[_qp] * _test_primary[_i][_qp];
    case Moose::MortarType::Secondary:
      return -_lambda[_qp] * _test_secondary[_i][_qp];
    case Moose::MortarType::Lower:
    {
      // we are creating an AD version of phys points primary and secondary here...
      ADRealVectorValue ad_phys_points_primary = _phys_points_primary[_qp];
      ADRealVectorValue ad_phys_points_secondary = _phys_points_secondary[_qp];

      // ...which uses the derivative vector of the primary and secondary displacements as
      // an approximation of the true phys points derivatives when the mesh is displacing
      if (_displaced)
        for (unsigned int i = 0; i < _n_disp; ++i)
        {
          ad_phys_points_primary(i).derivatives() = (*_disp_primary[i])[_qp].derivatives();
          ad_phys_points_secondary(i).derivatives() = (*_disp_secondary[i])[_qp].derivatives();
        }

      const auto gap_width = (ad_phys_points_primary - ad_phys_points_secondary) * _normals[_qp];
      ADReal flux = 0.0;
      for (auto & model : _gap_flux_models)
        flux += model->computeFlux(gap_width, _qp);

      return (_lambda[_qp] - flux) * _test[_i][_qp];
    }

    default:
      return 0;
  }
}
<commit_msg>Add material dependencies (#19229)<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "ModularGapConductanceConstraint.h"
#include "GapFluxModelBase.h"

registerMooseObject("HeatConductionApp", ModularGapConductanceConstraint);

InputParameters
ModularGapConductanceConstraint::validParams()
{
  InputParameters params = ADMortarConstraint::validParams();
  params.addClassDescription(
      "Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' "
      "implementation of the thermal contact problem. For more information, see the "
      "detailed description here: http://tinyurl.com/gmmhbe9");
  params.addParam<std::vector<UserObjectName>>("gap_flux_models",
                                               "List of GapFluxModel user objects");
  params.addCoupledVar("displacements", "Displacement variables");
  return params;
}

ModularGapConductanceConstraint::ModularGapConductanceConstraint(const InputParameters & parameters)
  : ADMortarConstraint(parameters),
    _gap_flux_model_names(getParam<std::vector<UserObjectName>>("gap_flux_models")),
    _disp_name(parameters.getVecMooseType("displacements")),
    _n_disp(_disp_name.size()),
    _disp_secondary(_n_disp),
    _disp_primary(_n_disp)
{
  for (unsigned int i = 0; i < _n_disp; ++i)
  {
    auto & disp_var = _subproblem.getStandardVariable(_tid, _disp_name[i]);
    _disp_secondary[i] = &disp_var.adSln();
    _disp_primary[i] = &disp_var.adSlnNeighbor();
  }

  for (const auto & name : _gap_flux_model_names)
  {
    const auto & gap_model = getUserObjectByName<GapFluxModelBase>(name);

    // pass variable dependencies through
    const auto & var_dependencies = gap_model.getMooseVariableDependencies();
    for (const auto & var : var_dependencies)
      addMooseVariableDependency(var);

    // pass material property dependencies through
    const auto & mat_dependencies = gap_model.getMatPropDependencies();
    _material_property_dependencies.insert(mat_dependencies.begin(), mat_dependencies.end());

    // add gap model to list
    _gap_flux_models.push_back(&gap_model);
  }
}

ADReal
ModularGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)
{
  switch (mortar_type)
  {
    case Moose::MortarType::Primary:
      return _lambda[_qp] * _test_primary[_i][_qp];
    case Moose::MortarType::Secondary:
      return -_lambda[_qp] * _test_secondary[_i][_qp];
    case Moose::MortarType::Lower:
    {
      // we are creating an AD version of phys points primary and secondary here...
      ADRealVectorValue ad_phys_points_primary = _phys_points_primary[_qp];
      ADRealVectorValue ad_phys_points_secondary = _phys_points_secondary[_qp];

      // ...which uses the derivative vector of the primary and secondary displacements as
      // an approximation of the true phys points derivatives when the mesh is displacing
      if (_displaced)
        for (unsigned int i = 0; i < _n_disp; ++i)
        {
          ad_phys_points_primary(i).derivatives() = (*_disp_primary[i])[_qp].derivatives();
          ad_phys_points_secondary(i).derivatives() = (*_disp_secondary[i])[_qp].derivatives();
        }

      const auto gap_width = (ad_phys_points_primary - ad_phys_points_secondary) * _normals[_qp];
      ADReal flux = 0.0;
      for (auto & model : _gap_flux_models)
        flux += model->computeFlux(gap_width, _qp);

      return (_lambda[_qp] - flux) * _test[_i][_qp];
    }

    default:
      return 0;
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-------------------------------------------------------------------------
//                Implementation of the AliKalmanTrack class
//   that is the base for AliTPCtrack, AliITStrackV2 and AliTRDtrack
//        Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include <TGeoManager.h>

#include "AliKalmanTrack.h"

ClassImp(AliKalmanTrack)

//_______________________________________________________________________
  AliKalmanTrack::AliKalmanTrack():AliExternalTrackParam(),
  fFakeRatio(0),
  fChi2(0),
  fMass(AliPID::ParticleMass(AliPID::kPion)),
  fLab(-3141593),
  fN(0),
  fStartTimeIntegral(kFALSE),
  fIntegratedLength(0)
{
  //
  // Default constructor
  //

  for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
}

AliKalmanTrack::AliKalmanTrack(const AliKalmanTrack &t):
  AliExternalTrackParam(t),
  fFakeRatio(t.fFakeRatio),
  fChi2(t.fChi2),
  fMass(t.fMass),
  fLab(t.fLab),
  fN(t.fN),
  fStartTimeIntegral(t.fStartTimeIntegral),
  fIntegratedLength(t.fIntegratedLength)
{
  //
  // Copy constructor
  //

  for (Int_t i=0; i<AliPID::kSPECIES; i++)
      fIntegratedTime[i] = t.fIntegratedTime[i];
}

AliKalmanTrack& AliKalmanTrack::operator=(const AliKalmanTrack&o){
  if(this!=&o){
    AliExternalTrackParam::operator=(o);
    fLab = o.fLab;
    fFakeRatio = o.fFakeRatio;
    fChi2 = o.fChi2;
    fMass = o.fMass;
    fN = o.fN;
    fStartTimeIntegral = o.fStartTimeIntegral;
    for(Int_t i = 0;i<AliPID::kSPECIES;++i)fIntegratedTime[i] = o.fIntegratedTime[i];
    fIntegratedLength = o.fIntegratedLength;
  }
  return *this;
}

//_______________________________________________________________________
void AliKalmanTrack::StartTimeIntegral()
{
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //
  // Start time integration
  // To be called at Vertex by ITS tracker
  //

  //if (fStartTimeIntegral)
  //  AliWarning("Reseting Recorded Time.");

  fStartTimeIntegral = kTRUE;
  for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
  fIntegratedLength = 0;
}

//_______________________________________________________________________
void AliKalmanTrack:: AddTimeStep(Double_t length)
{
  //
  // Add step to integrated time
  // this method should be called by a sublasses at the end
  // of the PropagateTo function or by a tracker
  // each time step is made.
  //
  // If integration not started function does nothing
  //
  // Formula
  // dt = dl * sqrt(p^2 + m^2) / p
  // p = pT * (1 + tg^2 (lambda) )
  //
  // pt = 1/external parameter [4]
  // tg lambda = external parameter [3]
  //
  //
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //

  static const Double_t kcc = 2.99792458e-2;

  if (!fStartTimeIntegral) return;

  fIntegratedLength += length;

  Double_t xr, param[5];
  Double_t pt, tgl;

  GetExternalParameters(xr, param);
  pt =  1/param[4] ;
  tgl = param[3];

  Double_t p = TMath::Abs(pt * TMath::Sqrt(1+tgl*tgl));

  if (length > 100) return;

  for (Int_t i=0; i<AliPID::kSPECIES; i++) {

    Double_t mass = AliPID::ParticleMass(i);
    Double_t correction = TMath::Sqrt( pt*pt * (1 + tgl*tgl) + mass * mass ) / p;
    Double_t time = length * correction / kcc;

    fIntegratedTime[i] += time;
  }
}

//_______________________________________________________________________
Double_t AliKalmanTrack::GetIntegratedTime(Int_t pdg) const
{
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //
  // Return integrated time hypothesis for a given particle
  // type assumption.
  //
  // Input parameter:
  // pdg - Pdg code of a particle type
  //

  if (!fStartTimeIntegral) {
    AliWarning("Time integration not started");
    return 0.;
  }

  for (Int_t i=0; i<AliPID::kSPECIES; i++)
    if (AliPID::ParticleCode(i) == TMath::Abs(pdg)) return fIntegratedTime[i];

  AliWarning(Form("Particle type [%d] not found", pdg));
  return 0;
}

void AliKalmanTrack::GetIntegratedTimes(Double_t *times) const {
  for (Int_t i=0; i<AliPID::kSPECIES; i++) times[i]=fIntegratedTime[i];
}

void AliKalmanTrack::SetIntegratedTimes(const Double_t *times) {
  for (Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i]=times[i];
}

<commit_msg>AddTimeStamp was always increasing track length but accounting  corresponding tof only for steps<100 cm. Commented out this condition<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

//-------------------------------------------------------------------------
//                Implementation of the AliKalmanTrack class
//   that is the base for AliTPCtrack, AliITStrackV2 and AliTRDtrack
//        Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch
//-------------------------------------------------------------------------
#include <TGeoManager.h>

#include "AliKalmanTrack.h"

ClassImp(AliKalmanTrack)

//_______________________________________________________________________
  AliKalmanTrack::AliKalmanTrack():AliExternalTrackParam(),
  fFakeRatio(0),
  fChi2(0),
  fMass(AliPID::ParticleMass(AliPID::kPion)),
  fLab(-3141593),
  fN(0),
  fStartTimeIntegral(kFALSE),
  fIntegratedLength(0)
{
  //
  // Default constructor
  //

  for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
}

AliKalmanTrack::AliKalmanTrack(const AliKalmanTrack &t):
  AliExternalTrackParam(t),
  fFakeRatio(t.fFakeRatio),
  fChi2(t.fChi2),
  fMass(t.fMass),
  fLab(t.fLab),
  fN(t.fN),
  fStartTimeIntegral(t.fStartTimeIntegral),
  fIntegratedLength(t.fIntegratedLength)
{
  //
  // Copy constructor
  //

  for (Int_t i=0; i<AliPID::kSPECIES; i++)
      fIntegratedTime[i] = t.fIntegratedTime[i];
}

AliKalmanTrack& AliKalmanTrack::operator=(const AliKalmanTrack&o){
  if(this!=&o){
    AliExternalTrackParam::operator=(o);
    fLab = o.fLab;
    fFakeRatio = o.fFakeRatio;
    fChi2 = o.fChi2;
    fMass = o.fMass;
    fN = o.fN;
    fStartTimeIntegral = o.fStartTimeIntegral;
    for(Int_t i = 0;i<AliPID::kSPECIES;++i)fIntegratedTime[i] = o.fIntegratedTime[i];
    fIntegratedLength = o.fIntegratedLength;
  }
  return *this;
}

//_______________________________________________________________________
void AliKalmanTrack::StartTimeIntegral()
{
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //
  // Start time integration
  // To be called at Vertex by ITS tracker
  //

  //if (fStartTimeIntegral)
  //  AliWarning("Reseting Recorded Time.");

  fStartTimeIntegral = kTRUE;
  for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
  fIntegratedLength = 0;
}

//_______________________________________________________________________
void AliKalmanTrack:: AddTimeStep(Double_t length)
{
  //
  // Add step to integrated time
  // this method should be called by a sublasses at the end
  // of the PropagateTo function or by a tracker
  // each time step is made.
  //
  // If integration not started function does nothing
  //
  // Formula
  // dt = dl * sqrt(p^2 + m^2) / p
  // p = pT * (1 + tg^2 (lambda) )
  //
  // pt = 1/external parameter [4]
  // tg lambda = external parameter [3]
  //
  //
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //

  static const Double_t kcc = 2.99792458e-2;

  if (!fStartTimeIntegral) return;

  fIntegratedLength += length;

  Double_t xr, param[5];
  Double_t pt, tgl;

  GetExternalParameters(xr, param);
  pt =  1/param[4] ;
  tgl = param[3];

  Double_t p = TMath::Abs(pt * TMath::Sqrt(1+tgl*tgl));

  //  if (length > 100) return;

  for (Int_t i=0; i<AliPID::kSPECIES; i++) {

    Double_t mass = AliPID::ParticleMass(i);
    Double_t correction = TMath::Sqrt( pt*pt * (1 + tgl*tgl) + mass * mass ) / p;
    Double_t time = length * correction / kcc;

    fIntegratedTime[i] += time;
  }
}

//_______________________________________________________________________
Double_t AliKalmanTrack::GetIntegratedTime(Int_t pdg) const
{
  // Sylwester Radomski, GSI
  // S.Radomski@gsi.de
  //
  // Return integrated time hypothesis for a given particle
  // type assumption.
  //
  // Input parameter:
  // pdg - Pdg code of a particle type
  //

  if (!fStartTimeIntegral) {
    AliWarning("Time integration not started");
    return 0.;
  }

  for (Int_t i=0; i<AliPID::kSPECIES; i++)
    if (AliPID::ParticleCode(i) == TMath::Abs(pdg)) return fIntegratedTime[i];

  AliWarning(Form("Particle type [%d] not found", pdg));
  return 0;
}

void AliKalmanTrack::GetIntegratedTimes(Double_t *times) const {
  for (Int_t i=0; i<AliPID::kSPECIES; i++) times[i]=fIntegratedTime[i];
}

void AliKalmanTrack::SetIntegratedTimes(const Double_t *times) {
  for (Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i]=times[i];
}

<|endoftext|>


<commit_before>/*The following code simulates the *Bounded* (single-single) Producer-Consumer problem using Standard Library threads. A producer thread produces a shared resource and then sleeps for a second.
The consumer thread consumes the resource and then sleeps for a second. How much of the resource is produced or consumed is dictated by a pseudo-random subroutine.*/
#include <iostream>
#include <thread>
#include <mutex>
#include <random>
#include <chrono>
#include <atomic>
#include <condition_variable>

const int MAXSIZE = 10;

std::mutex resourceMutex;
std::atomic<int> resource(1); // simulates the shared buffer of produced resource
std::condition_variable cv;

size_t getRandUnitSize(std::default_random_engine &seed)
{
	std::uniform_real_distribution<double> rnd(0.0, 1.0);
	double trial = rnd(seed);
	return static_cast<size_t>(trial * 10);
}

void produce()
{
	size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
	std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
	while (true)
	{
		std::unique_lock<std::mutex> lock(resourceMutex);
		std::cout << "Lock acquired by producer..." << std::endl;
		size_t units = 0;
		cv.wait(lock, [&]()
		{
			units = getRandUnitSize(seed);
			std::cout << "Available: " << resource << std::endl;
			std::cout << "Units to produce: " << units << std::endl;
			int newAmount = resource.load() + units;
			std::cout << "Projected amount after production: " << newAmount << std::endl;
			bool predicate = (newAmount <= MAXSIZE);
			if (!predicate)
			{
				std::cout << "Produced resource limit reached. Sleeping...\n\n" << std::endl;
				cv.notify_one();
			}
			return predicate;
		});

		resource += units;
		std::cout << "Produced " << units << " units." << std::endl;
		std::cout << "Total: " << resource << "\n\n" << std::endl;
		cv.notify_one();
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

void consume()
{
	size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
	std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
	while (true)
	{
		std::unique_lock<std::mutex> lock(resourceMutex);
		std::cout << "Lock acquired by consumer..." << std::endl;
		size_t units = 0;
		cv.wait(lock, [&]()
		{
			units = getRandUnitSize(seed);
			std::cout << "Available: " << resource << std::endl;
			std::cout << "Units to consume: " << units << std::endl;
			int newAmount = resource.load() - units;
			std::cout << "Projected amount after consumption: " << newAmount << std::endl;
			bool predicate = (newAmount >= 0);
			if (!predicate)
			{
				std::cout << "Not enough resources to consume. Sleeping...\n\n" << std::endl;
				cv.notify_one();
			}
			return predicate;
		});

		resource -= units;
		std::cout << "Consumed " << units << " units." << std::endl;
		std::cout << "Total: " << resource << "\n\n" << std::endl;
		cv.notify_one();
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	std::thread producer(produce);
	std::thread consumer(consume);

	producer.join();
	consumer.join();
}<commit_msg>Added support for multiple producers and consumers<commit_after>/*The following code simulates the *Bounded* Producer-Consumer (supporting arbitrary number of producers
and consumers) problem using Standard Library threads. A producer thread produces a shared resource and
then sleeps for a second. The consumer thread consumes the resource and then sleeps for a second. How
much of the resource is produced or consumed is dictated by a pseudo-random number generator subroutine.

Compile using flags to enable C++11 and link to pthread if necessary.
On GCC this is done using the flags -std=c++11 -pthread passed to the compiler*/

#include <iostream>
#include <thread>
#include <mutex>
#include <random>
#include <chrono>
#include <atomic>
#include <condition_variable>

const int nProd = 4;
const int nCon = 4;
const int MAXSIZE = 10;

std::mutex resourceMutex;
std::atomic<int> resource(1); // simulates the shared buffer of produced resource
std::condition_variable cv;

size_t getRandUnitSize(std::default_random_engine &seed)
{
	std::uniform_real_distribution<double> rnd(0.0, 1.0);
	double trial = rnd(seed);
	return static_cast<size_t>(trial * MAXSIZE);
}

void produce(int id)
{
	size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());

	// seeds the rng using the thread id and current time
	std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));

	while (true)
	{
		std::unique_lock<std::mutex> lock(resourceMutex);
		std::cout << "Lock acquired by producer " << id << " ... " << std::endl;
		size_t units = 0;

		cv.wait(lock, [&]()
		{
			units = getRandUnitSize(seed);
			std::cout << "Available: " << resource << std::endl;
			std::cout << "Units to produce: " << units << std::endl;
			int newAmount = resource.load() + units;
			std::cout << "Projected amount after production: " << newAmount << std::endl;
			bool predicate = (newAmount <= MAXSIZE);
			if (!predicate)
			{
				std::cout << "Produced resource limit reached. Sleeping...\n\n" << std::endl;
				cv.notify_one();
			}
			return predicate;
		});

		resource += units;
		std::cout << "Produced " << units << " units." << std::endl;
		std::cout << "Total: " << resource << "\n\n" << std::endl;
		cv.notify_one();
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

void consume(int id)
{
	size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());

	// seeds the rng using the thread id and current time
	std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));

	while (true)
	{
		std::unique_lock<std::mutex> lock(resourceMutex);
		std::cout << "Lock acquired by consumer " << id << " ... " << std::endl;
		size_t units = 0;

		cv.wait(lock, [&]()
		{
			units = getRandUnitSize(seed);
			std::cout << "Available: " << resource << std::endl;
			std::cout << "Units to consume: " << units << std::endl;
			int newAmount = resource.load() - units;
			std::cout << "Projected amount after consumption: " << newAmount << std::endl;
			bool predicate = (newAmount >= 0);
			if (!predicate)
			{
				std::cout << "Not enough resources to consume. Sleeping...\n\n" << std::endl;
				cv.notify_one();
			}
			return predicate;
		});

		resource -= units;
		std::cout << "Consumed " << units << " units." << std::endl;
		std::cout << "Total: " << resource << "\n\n" << std::endl;
		cv.notify_one();
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	std::thread producers[nProd];
	std::thread consumers[nCon];

	for (int i = 0; i < nProd; ++i)
		producers[i] = std::thread(produce, i);

	for (int i = 0; i < nProd; ++i)
		consumers[i] = std::thread(consume, i);

	for (int i = 0; i < nProd; ++i)
		producers[i].join();

	for (int i = 0; i < nProd; ++i)
		consumers[i].join();
}<|endoftext|>


<commit_before>#include "Scene.h"

Scene::Scene()
{
	//Generate the world on launch
	resetScene();
}

void Scene::resetScene()
{
	int count = PLANET_COUNT;
	bool hit = false;

	Planet* tempPlanet;

	while(count > 0)
	{
		--count;

		tempPlanet = new Planet( Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT) ), randomRange(100,250 ) ) ;

		//Check that the planet is not on top of other planes
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = tempPlanet->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			dist -= tempPlanet->size;

			if(dist < 0){
				//Hit! break from the loop
				hit = true;
			}
		}

		if(hit)
		{
			printf("planet collision!");
			delete tempPlanet;
		}
		else
		{
			printf("planet creation");
			planets.push_back(tempPlanet);
		}

		hit = false;
	}

	//Then add the pickups.
	count = SCENE_PICKUP_COUNT; //10 pickups

	hit = false;

	Entity *ent;

	while( count > 0 )
	{
		//Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_PICKUP);
		ent = new Entity();

		ent->position = Vector( (float)randomRange(0,WORLD_WIDTH), (float)randomRange(0,WORLD_HEIGHT));
		ent->type = ENTITYTYPE_PICKUP;

		printf("|%f %f|\n",ent->position.x,ent->position.y);

		//Check that the pickup is not inside a planet
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = ent->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			dist -= 150; //Some space between the planets and pickups...

			if(dist < 0){
				//Hit! break from the loop
				printf("planet collision!");
				hit = true;
			}
		}

		if(hit)
		{
			delete ent;
		}
		else
		{
			printf("|%f %f|\n",ent->position.x,ent->position.y);
			entities.push_back(ent);
			printf("|%f %f|\n",ent->position.x,ent->position.y);
		}
		printf("|%f %f|\n",ent->position.x,ent->position.y);

		--count;
		hit = false;
	}

	printf("entities.size() : %i \n", entities.size());

	count = SCENE_FUEL_COUNT; //5 fuel
	/*
	while( count > 0 )
	{
		Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_FUEL);

		//Check that the pickup is not inside a planet
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = ent->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			ent -= 150; //Some space between the planets and pickups...

			if(dist < 0){
				//Hit! break from the loop
				printf("planet collision!");
				delete ent;  //entity is not used
				break;
			}
		}

		entities.push_back(ent);

		--count;
	}
	*/

	printf("entities.size() : %i \n", entities.size());
}

void Scene::update()
{
	//calculate gravity from nearby planets

	for(int i = 0; i < planets.size(); ++i)
	{
		//get distance from player
		Vector vec = planets[i]->position - player.position;

		int dist = abs( vec.getLenght() );
		int radius = planets[i]->size;

		//#######################
		//Planets generate particles!
		//particleSystem.addParticles(1,4,planets[i]->position,0,0,-2,2,radius / 10,radius / 5 + radius / 2, sf::Color::Red,3);
		//Disabled because it would "eat" all the avaivable slots with current setup.
		//#######################

		//TODO: Kill player if it collides with a planet, fix the hit detection! the origin is invalid
		if(dist < radius)
			printf("KILL");

		//if distance is larger than the size, no gravity applies
		if(dist / GRAVITY_MULTIPLIER > radius)
			continue;

		dist -= radius / 2; //gravity "starts" from the surface, not center

		float str = dist / (1000000.f / 0.8);

		printf("# %f #\n",str);
		if(str < 0)
			continue;

		//apply force
		player.impulse(vec,str);
	}

	//Check the entities

	for ( int i = 0; i < entities.size(); ++i )
	{
		Vector vec = entities[i]->position - player.position;
		int dist = abs( vec.getLenght() );

		if(dist < 10)
		{
			//printf("PICKUP!");
			printf("dist: %i", dist);
		}
	}

	//get player input, apply velocity
	player.update();
}<commit_msg>Collecting entities is possible!<commit_after>#include "Scene.h"

Scene::Scene()
{
	//Generate the world on launch
	resetScene();
}

void Scene::resetScene()
{
	int count = PLANET_COUNT;
	bool hit = false;

	Planet* tempPlanet;

	while(count > 0)
	{
		--count;

		tempPlanet = new Planet( Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT) ), randomRange(100,250 ) ) ;

		//Check that the planet is not on top of other planes
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = tempPlanet->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			dist -= tempPlanet->size;

			if(dist < 0){
				//Hit! break from the loop
				hit = true;
			}
		}

		if(hit)
		{
			printf("planet collision!");
			delete tempPlanet;
		}
		else
		{
			printf("planet creation");
			planets.push_back(tempPlanet);
		}

		hit = false;
	}

	//Then add the pickups.
	count = SCENE_PICKUP_COUNT; //10 pickups

	hit = false;

	Entity *ent;

	while( count > 0 )
	{
		//Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_PICKUP);
		ent = new Entity();

		ent->position = Vector( (float)randomRange(0,WORLD_WIDTH), (float)randomRange(0,WORLD_HEIGHT));
		ent->type = ENTITYTYPE_PICKUP;

		printf("|%f %f|\n",ent->position.x,ent->position.y);

		//Check that the pickup is not inside a planet
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = ent->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			dist -= 150; //Some space between the planets and pickups...

			if(dist < 0){
				//Hit! break from the loop
				printf("planet collision!");
				hit = true;
			}
		}

		if(hit)
		{
			delete ent;
		}
		else
		{
			printf("|%f %f|\n",ent->position.x,ent->position.y);
			entities.push_back(ent);
			printf("|%f %f|\n",ent->position.x,ent->position.y);
		}
		printf("|%f %f|\n",ent->position.x,ent->position.y);

		--count;
		hit = false;
	}

	printf("entities.size() : %i \n", entities.size());

	count = SCENE_FUEL_COUNT; //5 fuel
	/*
	while( count > 0 )
	{
		Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_FUEL);

		//Check that the pickup is not inside a planet
		for( int i = 0; i < planets.size(); ++i)
		{
			Vector vec = ent->position - planets[i]->position;
			float dist = abs ( vec.getLenght() );

			dist -= planets[i]->size;
			ent -= 150; //Some space between the planets and pickups...

			if(dist < 0){
				//Hit! break from the loop
				printf("planet collision!");
				delete ent;  //entity is not used
				break;
			}
		}

		entities.push_back(ent);

		--count;
	}
	*/

	printf("entities.size() : %i \n", entities.size());
}

void Scene::update()
{
	//calculate gravity from nearby planets

	for(int i = 0; i < planets.size(); ++i)
	{
		//get distance from player
		Vector vec = planets[i]->position - player.position;

		int dist = abs( vec.getLenght() );
		int radius = planets[i]->size;

		//#######################
		//Planets generate particles!
		//particleSystem.addParticles(1,4,planets[i]->position,0,0,-2,2,radius / 10,radius / 5 + radius / 2, sf::Color::Red,3);
		//Disabled because it would "eat" all the avaivable slots with current setup.
		//#######################

		//TODO: Kill player if it collides with a planet, fix the hit detection! the origin is invalid
		if(dist < radius)
			printf("KILL");

		//if distance is larger than the size, no gravity applies
		if(dist / GRAVITY_MULTIPLIER > radius)
			continue;

		dist -= radius / 2; //gravity "starts" from the surface, not center

		float str = dist / (1000000.f / 0.8);

		printf("# %f #\n",str);
		if(str < 0)
			continue;

		//apply force
		player.impulse(vec,str);
	}

	//Check the entities

	for ( int i = 0; i < entities.size(); ++i )
	{
		Vector vec = entities[i]->position - player.position;
		int dist = abs( vec.getLenght() );

		if(dist < 40)
		{
			//printf("PICKUP!");
			printf("dist: %i", dist);
			particleSystem.addParticles(200, 200, entities[i]->position , Vector(0,1) ,360,30,50,50,100,sf::Color::Green,4);

			delete entities[i];
			entities.erase(entities.begin() + i);
			--i;
		}
	}

	//get player input, apply velocity
	player.update();
}<|endoftext|>


<commit_before><commit_msg>Fix MSVC build<commit_after><|endoftext|>


<commit_before>/*
Copyright 2017 creatorlxd

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

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

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

using namespace SpaceGameEngine;

REGISTERCOMPONENTCLASS(ConnectComponent);

SpaceGameEngine::ConnectComponent::ConnectComponent()
{
	m_TypeName = STRING(ConnectComponent);
	m_pFatherTransform = nullptr;
	m_pChildTransform = nullptr;
	m_IfInit = false;
}

void SpaceGameEngine::ConnectComponent::Run(float DeltaTime)
{
	if (m_IfInit == false)
		ThrowError("ConnectComponentҪSetTransform");
	else
	{
		if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::PositionChange) ||
			m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange) ||
			m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::ScaleChange))
		{
			m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(),Substract(m_pFatherTransform->GetPosition(),m_PositionBuffer)));
			m_pChildTransform->SetScale(Add(m_pChildTransform->GetScale(), Substract(m_pFatherTransform->GetScale(), m_ScaleBuffer)));
			if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange))
			{
				auto dis = Substract(m_pFatherTransform->GetPosition(), m_pChildTransform->GetPosition());
				auto angle = Substract(m_pFatherTransform->GetRotation(), m_RotationBuffer);
				dis = RotationVector(angle, dis);
				m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(), dis));
				m_pChildTransform->SetRotation(Add(m_pChildTransform->GetRotation(), angle));
			}
			m_PositionBuffer = m_pFatherTransform->GetPosition();
			m_RotationBuffer = m_pFatherTransform->GetRotation();
			m_ScaleBuffer = m_pFatherTransform->GetScale();
		}
	}
}

void SpaceGameEngine::ConnectComponent::SetTransform(TransformComponent * father, TransformComponent * child)
{
	m_pFatherTransform = father;
	m_pChildTransform = child;
	if (father)
	{
		m_PositionBuffer = father->GetPosition();
		m_RotationBuffer = father->GetRotation();
		m_ScaleBuffer = father->GetScale();
	}
	m_IfInit = true;
}

void SpaceGameEngine::ConnectObject(Object * father, Object * child)
{
	child->Attach(father);
	child->AddComponent(ConnectComponent::NewComponent());
	child->GetComponent<ConnectComponent>()->SetTransform(father->GetComponent<TransformComponent>(), child->GetComponent<TransformComponent>());
	if (child->GetRootComponent() != nullptr)
	{
		child->GetRootComponent()->Attach(child->GetComponent(STRING(ConnectComponent)));
		child->SetRootComponent(STRING(ConnectComponent));
	}
	else
		ThrowError("RootComponentΪnullptr");
}

void SpaceGameEngine::DisconObject(Object * child)
{
	if (child == nullptr)
	{
		ThrowError("childΪnullptr");
		return;
	}
	if (child->GetRootComponent()->GetTypeName() != STRING(ConnectComponent))
	{
		ThrowError("DisconObjectӦConnectObjectʹ||ʹConnectObjectĶRootComponentΪConnectComponent");
		return;
	}
	child->Discon();
	auto children_component = child->GetRootComponent()->GetChildrenComponent();
	if (children_component.size() >= 1)
	{
		child->SetRootComponent(children_component[0]->GetTypeName());
	}
	child->DeleteComponent(STRING(ConnectComponent));
}
<commit_msg>fix a bug in object connection<commit_after>/*
Copyright 2017 creatorlxd

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

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

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

using namespace SpaceGameEngine;

REGISTERCOMPONENTCLASS(ConnectComponent);

SpaceGameEngine::ConnectComponent::ConnectComponent()
{
	m_TypeName = STRING(ConnectComponent);
	m_pFatherTransform = nullptr;
	m_pChildTransform = nullptr;
	m_IfInit = false;
}

void SpaceGameEngine::ConnectComponent::Run(float DeltaTime)
{
	if (m_IfInit == false)
		ThrowError("ConnectComponentҪSetTransform");
	else
	{
		if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::PositionChange) ||
			m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange) ||
			m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::ScaleChange))
		{
			m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(), Substract(m_pFatherTransform->GetPosition(), m_PositionBuffer)));
			m_pChildTransform->SetScale(Add(m_pChildTransform->GetScale(), Substract(m_pFatherTransform->GetScale(), m_ScaleBuffer)));
			if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange))
			{
				auto dis = Substract(m_pChildTransform->GetPosition(), m_pFatherTransform->GetPosition());
				auto angle = Substract(m_pFatherTransform->GetRotation(), m_RotationBuffer);
				dis = RotationVector(angle, dis);
				m_pChildTransform->SetPosition(Add(dis,m_pFatherTransform->GetPosition()));
				m_pChildTransform->SetRotation(Add(m_pChildTransform->GetRotation(), angle));
			}
			m_PositionBuffer = m_pFatherTransform->GetPosition();
			m_RotationBuffer = m_pFatherTransform->GetRotation();
			m_ScaleBuffer = m_pFatherTransform->GetScale();
		}
	}
}

void SpaceGameEngine::ConnectComponent::SetTransform(TransformComponent * father, TransformComponent * child)
{
	m_pFatherTransform = father;
	m_pChildTransform = child;
	if (father)
	{
		m_PositionBuffer = father->GetPosition();
		m_RotationBuffer = father->GetRotation();
		m_ScaleBuffer = father->GetScale();
	}
	m_IfInit = true;
}

void SpaceGameEngine::ConnectObject(Object * father, Object * child)
{
	child->Attach(father);
	child->AddComponent(ConnectComponent::NewComponent());
	child->GetComponent<ConnectComponent>()->SetTransform(father->GetComponent<TransformComponent>(), child->GetComponent<TransformComponent>());
	if (child->GetRootComponent() != nullptr)
	{
		child->GetRootComponent()->Attach(child->GetComponent(STRING(ConnectComponent)));
		child->SetRootComponent(STRING(ConnectComponent));
	}
	else
		ThrowError("RootComponentΪnullptr");
}

void SpaceGameEngine::DisconObject(Object * child)
{
	if (child == nullptr)
	{
		ThrowError("childΪnullptr");
		return;
	}
	if (child->GetRootComponent()->GetTypeName() != STRING(ConnectComponent))
	{
		ThrowError("DisconObjectӦConnectObjectʹ||ʹConnectObjectĶRootComponentΪConnectComponent");
		return;
	}
	child->Discon();
	auto children_component = child->GetRootComponent()->GetChildrenComponent();
	if (children_component.size() >= 1)
	{
		child->SetRootComponent(children_component[0]->GetTypeName());
	}
	child->DeleteComponent(STRING(ConnectComponent));
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

/*****************************************************************************\
 *****************************************************************************
 **                                                                         **
 **                  This file is automatically generated.                  **
 **                                                                         **
 **          Any changes made to this file WILL be lost when it is          **
 **           regenerated, which can become necessary at any time.          **
 **                                                                         **
 **     Do not change this file, changes should be done in the derived      **
 **     class StageData!
 **                                                                         **
 *****************************************************************************
\*****************************************************************************/

OSG_BEGIN_NAMESPACE

//! access the type of the class
inline
OSG::FieldBundleType &StageDataBase::getClassType(void)
{
    return _type;
}

//! access the numerical type of the class
inline
OSG::UInt32 StageDataBase::getClassTypeId(void)
{
    return _type.getId();
}

inline
OSG::UInt16 StageDataBase::getClassGroupId(void)
{
    return _type.getGroupId();
}

/*------------------------------ get -----------------------------------*/

//! Get the value of the StageData::_sfPartitionRangeBegin field.

inline
Int32 &StageDataBase::editPartitionRangeBegin(void)
{
    editSField(PartitionRangeBeginFieldMask);

    return _sfPartitionRangeBegin.getValue();
}

//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
const Int32 &StageDataBase::getPartitionRangeBegin(void) const
{
    return _sfPartitionRangeBegin.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getPartitionRangeBegin(void)
{
    return this->editPartitionRangeBegin();
}
#endif

//! Set the value of the StageData::_sfPartitionRangeBegin field.
inline
void StageDataBase::setPartitionRangeBegin(const Int32 &value)
{
    editSField(PartitionRangeBeginFieldMask);

    _sfPartitionRangeBegin.setValue(value);
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.

inline
Int32 &StageDataBase::editPartitionRangeEnd(void)
{
    editSField(PartitionRangeEndFieldMask);

    return _sfPartitionRangeEnd.getValue();
}

//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
const Int32 &StageDataBase::getPartitionRangeEnd(void) const
{
    return _sfPartitionRangeEnd.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getPartitionRangeEnd(void)
{
    return this->editPartitionRangeEnd();
}
#endif

//! Set the value of the StageData::_sfPartitionRangeEnd field.
inline
void StageDataBase::setPartitionRangeEnd(const Int32 &value)
{
    editSField(PartitionRangeEndFieldMask);

    _sfPartitionRangeEnd.setValue(value);
}
//! Get the value of the StageData::_sfGroupMode field.

inline
Int32 &StageDataBase::editGroupMode(void)
{
    editSField(GroupModeFieldMask);

    return _sfGroupMode.getValue();
}

//! Get the value of the StageData::_sfGroupMode field.
inline
const Int32 &StageDataBase::getGroupMode(void) const
{
    return _sfGroupMode.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getGroupMode      (void)
{
    return this->editGroupMode      ();
}
#endif

//! Set the value of the StageData::_sfGroupMode field.
inline
void StageDataBase::setGroupMode(const Int32 &value)
{
    editSField(GroupModeFieldMask);

    _sfGroupMode.setValue(value);
}

//! create a new instance of the class
inline
StageDataP StageDataBase::create(void)
{
    StageDataP fc;

    if(getClassType().getPrototype() != NULL)
    {
        fc = dynamic_cast<StageData::ObjPtr>(
            getClassType().getPrototype()-> shallowCopy());
    }

    return fc;
}

inline
Char8 *StageDataBase::getClassname(void)
{
    return "StageData";
}

typedef BundlePointerBuilder<
    StageData>::ObjPtr          StageDataP;

typedef BundlePointerBuilder<
    StageData>::ObjPtrConst     StageDataPConst;

typedef BundlePointerBuilder<
    StageData>::ObjConstPtr     StageDataConstP;

typedef BundlePointerBuilder<
    StageData>::ObjPtrArg       StageDataPArg;

typedef BundlePointerBuilder<
    StageData>::ObjConstPtrArg  StageDataConstPArg;

typedef BundlePointerBuilder<
    StageData>::ObjPtrConstArg  StageDataPConstArg;

OSG_END_NAMESPACE

<commit_msg>Silence a compiler warning about a variable possibly being used without being initialized.<commit_after>/*---------------------------------------------------------------------------*\
 *                                OpenSG                                     *
 *                                                                           *
 *                                                                           *
 *               Copyright (C) 2000-2006 by the OpenSG Forum                 *
 *                                                                           *
 *   contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de          *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                License                                    *
 *                                                                           *
 * This library is free software; you can redistribute it and/or modify it   *
 * under the terms of the GNU Library General Public License as published    *
 * by the Free Software Foundation, version 2.                               *
 *                                                                           *
 * 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         *
 * Library General Public License for more details.                          *
 *                                                                           *
 * You should have received a copy of the GNU Library General Public         *
 * License along with this library; if not, write to the Free Software       *
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.                 *
 *                                                                           *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
 *                                Changes                                    *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
 *                                                                           *
\*---------------------------------------------------------------------------*/

/*****************************************************************************\
 *****************************************************************************
 **                                                                         **
 **                  This file is automatically generated.                  **
 **                                                                         **
 **          Any changes made to this file WILL be lost when it is          **
 **           regenerated, which can become necessary at any time.          **
 **                                                                         **
 **     Do not change this file, changes should be done in the derived      **
 **     class StageData!
 **                                                                         **
 *****************************************************************************
\*****************************************************************************/

OSG_BEGIN_NAMESPACE

//! access the type of the class
inline
OSG::FieldBundleType &StageDataBase::getClassType(void)
{
    return _type;
}

//! access the numerical type of the class
inline
OSG::UInt32 StageDataBase::getClassTypeId(void)
{
    return _type.getId();
}

inline
OSG::UInt16 StageDataBase::getClassGroupId(void)
{
    return _type.getGroupId();
}

/*------------------------------ get -----------------------------------*/

//! Get the value of the StageData::_sfPartitionRangeBegin field.

inline
Int32 &StageDataBase::editPartitionRangeBegin(void)
{
    editSField(PartitionRangeBeginFieldMask);

    return _sfPartitionRangeBegin.getValue();
}

//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
const Int32 &StageDataBase::getPartitionRangeBegin(void) const
{
    return _sfPartitionRangeBegin.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getPartitionRangeBegin(void)
{
    return this->editPartitionRangeBegin();
}
#endif

//! Set the value of the StageData::_sfPartitionRangeBegin field.
inline
void StageDataBase::setPartitionRangeBegin(const Int32 &value)
{
    editSField(PartitionRangeBeginFieldMask);

    _sfPartitionRangeBegin.setValue(value);
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.

inline
Int32 &StageDataBase::editPartitionRangeEnd(void)
{
    editSField(PartitionRangeEndFieldMask);

    return _sfPartitionRangeEnd.getValue();
}

//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
const Int32 &StageDataBase::getPartitionRangeEnd(void) const
{
    return _sfPartitionRangeEnd.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getPartitionRangeEnd(void)
{
    return this->editPartitionRangeEnd();
}
#endif

//! Set the value of the StageData::_sfPartitionRangeEnd field.
inline
void StageDataBase::setPartitionRangeEnd(const Int32 &value)
{
    editSField(PartitionRangeEndFieldMask);

    _sfPartitionRangeEnd.setValue(value);
}
//! Get the value of the StageData::_sfGroupMode field.

inline
Int32 &StageDataBase::editGroupMode(void)
{
    editSField(GroupModeFieldMask);

    return _sfGroupMode.getValue();
}

//! Get the value of the StageData::_sfGroupMode field.
inline
const Int32 &StageDataBase::getGroupMode(void) const
{
    return _sfGroupMode.getValue();
}

#ifdef OSG_1_COMPAT
inline
Int32               &StageDataBase::getGroupMode      (void)
{
    return this->editGroupMode      ();
}
#endif

//! Set the value of the StageData::_sfGroupMode field.
inline
void StageDataBase::setGroupMode(const Int32 &value)
{
    editSField(GroupModeFieldMask);

    _sfGroupMode.setValue(value);
}

//! create a new instance of the class
inline
StageDataP StageDataBase::create(void)
{
    StageDataP fc(NULL);

    if(getClassType().getPrototype() != NULL)
    {
        fc = dynamic_cast<StageData::ObjPtr>(
            getClassType().getPrototype()-> shallowCopy());
    }

    return fc;
}

inline
Char8 *StageDataBase::getClassname(void)
{
    return "StageData";
}

typedef BundlePointerBuilder<
    StageData>::ObjPtr          StageDataP;

typedef BundlePointerBuilder<
    StageData>::ObjPtrConst     StageDataPConst;

typedef BundlePointerBuilder<
    StageData>::ObjConstPtr     StageDataConstP;

typedef BundlePointerBuilder<
    StageData>::ObjPtrArg       StageDataPArg;

typedef BundlePointerBuilder<
    StageData>::ObjConstPtrArg  StageDataConstPArg;

typedef BundlePointerBuilder<
    StageData>::ObjPtrConstArg  StageDataPConstArg;

OSG_END_NAMESPACE

<|endoftext|>


<commit_before>//===- ObjCARCAliasAnalysis.cpp - ObjC ARC Optimization -*- mode: c++ -*---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "objc-arc-aa"

#include "ObjCARC.h"
#include "ObjCARCAliasAnalysis.h"
#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"

namespace llvm {
  class Function;
  class Value;
}

#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"

namespace llvm {
  class Function;
  class Value;
}

using namespace llvm;
using namespace llvm::objcarc;

// Register this pass...
char ObjCARCAliasAnalysis::ID = 0;
INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
                   "ObjC-ARC-Based Alias Analysis", false, true, false)

ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
  return new ObjCARCAliasAnalysis();
}

void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AliasAnalysis::getAnalysisUsage(AU);
}

AliasAnalysis::AliasResult
ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
  if (!EnableARCOpts)
    return AliasAnalysis::alias(LocA, LocB);

  // First, strip off no-ops, including ObjC-specific no-ops, and try making a
  // precise alias query.
  const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
  const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
  AliasResult Result =
    AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
                         Location(SB, LocB.Size, LocB.TBAATag));
  if (Result != MayAlias)
    return Result;

  // If that failed, climb to the underlying object, including climbing through
  // ObjC-specific no-ops, and try making an imprecise alias query.
  const Value *UA = GetUnderlyingObjCPtr(SA);
  const Value *UB = GetUnderlyingObjCPtr(SB);
  if (UA != SA || UB != SB) {
    Result = AliasAnalysis::alias(Location(UA), Location(UB));
    // We can't use MustAlias or PartialAlias results here because
    // GetUnderlyingObjCPtr may return an offsetted pointer value.
    if (Result == NoAlias)
      return NoAlias;
  }

  // If that failed, fail. We don't need to chain here, since that's covered
  // by the earlier precise query.
  return MayAlias;
}

bool
ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
                                             bool OrLocal) {
  if (!EnableARCOpts)
    return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);

  // First, strip off no-ops, including ObjC-specific no-ops, and try making
  // a precise alias query.
  const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
  if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
                                            OrLocal))
    return true;

  // If that failed, climb to the underlying object, including climbing through
  // ObjC-specific no-ops, and try making an imprecise alias query.
  const Value *U = GetUnderlyingObjCPtr(S);
  if (U != S)
    return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);

  // If that failed, fail. We don't need to chain here, since that's covered
  // by the earlier precise query.
  return false;
}

AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  // We have nothing to do. Just chain to the next AliasAnalysis.
  return AliasAnalysis::getModRefBehavior(CS);
}

AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
  if (!EnableARCOpts)
    return AliasAnalysis::getModRefBehavior(F);

  switch (GetFunctionClass(F)) {
  case IC_NoopCast:
    return DoesNotAccessMemory;
  default:
    break;
  }

  return AliasAnalysis::getModRefBehavior(F);
}

AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
  if (!EnableARCOpts)
    return AliasAnalysis::getModRefInfo(CS, Loc);

  switch (GetBasicInstructionClass(CS.getInstruction())) {
  case IC_Retain:
  case IC_RetainRV:
  case IC_Autorelease:
  case IC_AutoreleaseRV:
  case IC_NoopCast:
  case IC_AutoreleasepoolPush:
  case IC_FusedRetainAutorelease:
  case IC_FusedRetainAutoreleaseRV:
    // These functions don't access any memory visible to the compiler.
    // Note that this doesn't include objc_retainBlock, because it updates
    // pointers when it copies block data.
    return NoModRef;
  default:
    break;
  }

  return AliasAnalysis::getModRefInfo(CS, Loc);
}

AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
                                    ImmutableCallSite CS2) {
  // TODO: Theoretically we could check for dependencies between objc_* calls
  // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
  return AliasAnalysis::getModRefInfo(CS1, CS2);
}
<commit_msg>Removed some cruft from ObjCARCAliasAnalysis.cpp.<commit_after>//===- ObjCARCAliasAnalysis.cpp - ObjC ARC Optimization -*- mode: c++ -*---===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "objc-arc-aa"
#include "ObjCARC.h"
#include "ObjCARCAliasAnalysis.h"

#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"

namespace llvm {
  class Function;
  class Value;
}

using namespace llvm;
using namespace llvm::objcarc;

// Register this pass...
char ObjCARCAliasAnalysis::ID = 0;
INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
                   "ObjC-ARC-Based Alias Analysis", false, true, false)

ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
  return new ObjCARCAliasAnalysis();
}

void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AliasAnalysis::getAnalysisUsage(AU);
}

AliasAnalysis::AliasResult
ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
  if (!EnableARCOpts)
    return AliasAnalysis::alias(LocA, LocB);

  // First, strip off no-ops, including ObjC-specific no-ops, and try making a
  // precise alias query.
  const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
  const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
  AliasResult Result =
    AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
                         Location(SB, LocB.Size, LocB.TBAATag));
  if (Result != MayAlias)
    return Result;

  // If that failed, climb to the underlying object, including climbing through
  // ObjC-specific no-ops, and try making an imprecise alias query.
  const Value *UA = GetUnderlyingObjCPtr(SA);
  const Value *UB = GetUnderlyingObjCPtr(SB);
  if (UA != SA || UB != SB) {
    Result = AliasAnalysis::alias(Location(UA), Location(UB));
    // We can't use MustAlias or PartialAlias results here because
    // GetUnderlyingObjCPtr may return an offsetted pointer value.
    if (Result == NoAlias)
      return NoAlias;
  }

  // If that failed, fail. We don't need to chain here, since that's covered
  // by the earlier precise query.
  return MayAlias;
}

bool
ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
                                             bool OrLocal) {
  if (!EnableARCOpts)
    return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);

  // First, strip off no-ops, including ObjC-specific no-ops, and try making
  // a precise alias query.
  const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
  if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
                                            OrLocal))
    return true;

  // If that failed, climb to the underlying object, including climbing through
  // ObjC-specific no-ops, and try making an imprecise alias query.
  const Value *U = GetUnderlyingObjCPtr(S);
  if (U != S)
    return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);

  // If that failed, fail. We don't need to chain here, since that's covered
  // by the earlier precise query.
  return false;
}

AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
  // We have nothing to do. Just chain to the next AliasAnalysis.
  return AliasAnalysis::getModRefBehavior(CS);
}

AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
  if (!EnableARCOpts)
    return AliasAnalysis::getModRefBehavior(F);

  switch (GetFunctionClass(F)) {
  case IC_NoopCast:
    return DoesNotAccessMemory;
  default:
    break;
  }

  return AliasAnalysis::getModRefBehavior(F);
}

AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
  if (!EnableARCOpts)
    return AliasAnalysis::getModRefInfo(CS, Loc);

  switch (GetBasicInstructionClass(CS.getInstruction())) {
  case IC_Retain:
  case IC_RetainRV:
  case IC_Autorelease:
  case IC_AutoreleaseRV:
  case IC_NoopCast:
  case IC_AutoreleasepoolPush:
  case IC_FusedRetainAutorelease:
  case IC_FusedRetainAutoreleaseRV:
    // These functions don't access any memory visible to the compiler.
    // Note that this doesn't include objc_retainBlock, because it updates
    // pointers when it copies block data.
    return NoModRef;
  default:
    break;
  }

  return AliasAnalysis::getModRefInfo(CS, Loc);
}

AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
                                    ImmutableCallSite CS2) {
  // TODO: Theoretically we could check for dependencies between objc_* calls
  // and OnlyAccessesArgumentPointees calls or other well-behaved calls.
  return AliasAnalysis::getModRefInfo(CS1, CS2);
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

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

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"

int main ( int , char*  )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

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

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkNDimensionalSpatialObject.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"

int main ( int , char*  )
{

  return 0;
}

<|endoftext|>