<commit_before>/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * 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.
 */

#if !DEVICE_SLEEP
#error [NOT_SUPPORTED] sleep not supported for this target
#endif

#include "mbed.h"

#include "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"

#include "sleep_api_tests.h"

#define US_PER_S 1000000

using namespace utest::v1;

/* The following ticker frequencies are possible:
 * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us)
 * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)
 */

/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:
 * delta = default 10 us + worst ticker resolution + extra time for code execution */
static const uint32_t sleep_mode_delta_us = (10 + 4 + 5);

/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:
 * delta = default 10 ms + worst ticker resolution + extra time for code execution */
static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);

unsigned int ticks_to_us(unsigned int ticks, unsigned int freq)
{
    return (unsigned int)((unsigned long long)ticks * US_PER_S / freq);
}

unsigned int us_to_ticks(unsigned int us, unsigned int freq)
{
    return (unsigned int)((unsigned long long)us * freq / US_PER_S);
}

unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)
{
    unsigned int counter_mask = ((1 << ticker_width) - 1);

    return (timestamp & counter_mask);
}

bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)
{
    const unsigned int counter_mask = ((1 << ticker_width) - 1);

    const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);
    const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);

    if(lower_bound < upper_bound) {
        if (actual >= lower_bound && actual <= upper_bound) {
            return true;
        } else {
            return false;
        }
    } else {
        if ((actual >= lower_bound && actual <= counter_mask) ||
            (actual >= 0 && actual <= upper_bound)) {
            return true;
        } else {
            return false;
        }
    }
}

void us_ticker_isr(const ticker_data_t *const ticker_data)
{
    us_ticker_clear_interrupt();
}

#ifdef DEVICE_LOWPOWERTIMER
void lp_ticker_isr(const ticker_data_t *const ticker_data)
{
    lp_ticker_clear_interrupt();
}
#endif

/* Test that wake-up time from sleep should be less than 10 us and
 * high frequency ticker interrupt can wake-up target from sleep. */
void sleep_usticker_test()
{
    Timeout timeout;
    const ticker_data_t * ticker = get_us_ticker_data();
    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
    const unsigned int ticker_width = ticker->interface->get_info()->bits;

    const ticker_irq_handler_type  us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);

    /* Test only sleep functionality. */
    sleep_manager_lock_deep_sleep();
    TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked");

    /* Testing wake-up time 10 us. */
    for (timestamp_t i = 100; i < 1000; i += 100) {
        /* note: us_ticker_read() operates on ticks. */
        const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),
                ticker_width);

        us_ticker_set_interrupt(next_match_timestamp);

        sleep();

        const unsigned int wakeup_timestamp = us_ticker_read();

        TEST_ASSERT(
                compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,
                        wakeup_timestamp));
    }

    set_us_ticker_irq_handler(us_ticker_irq_handler_org);

    sleep_manager_unlock_deep_sleep();
    TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());
}

#ifdef DEVICE_LOWPOWERTIMER

/* Test that wake-up time from sleep should be less than 10 ms and
 * low power ticker interrupt can wake-up target from sleep. */
void deepsleep_lpticker_test()
{
    const ticker_data_t * ticker = get_lp_ticker_data();
    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
    const unsigned int ticker_width = ticker->interface->get_info()->bits;

    const ticker_irq_handler_type  lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);

    /* Give some time Green Tea to finish UART transmission before entering
     * deep-sleep mode.
     */
    wait_ms(10);

    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");

    /* Testing wake-up time 10 ms. */
    for (timestamp_t i = 20000; i < 200000; i += 20000) {
        /* note: lp_ticker_read() operates on ticks. */
        const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);

        lp_ticker_set_interrupt(next_match_timestamp);

        sleep();

        const timestamp_t wakeup_timestamp = lp_ticker_read();

        TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));
    }

    set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);

}

void deepsleep_high_speed_clocks_turned_off_test()
{
    const ticker_data_t * us_ticker = get_us_ticker_data();
    const ticker_data_t * lp_ticker = get_lp_ticker_data();
    const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;
    const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;
    const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;
    const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;
    const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);

    /* Give some time Green Tea to finish UART transmission before entering
     * deep-sleep mode.
     */
    wait_ms(10);

    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");

    const unsigned int us_ticks_before_sleep = us_ticker_read();

    const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);
    lp_ticker_set_interrupt(wakeup_time);

    sleep();

    const unsigned int us_ticks_after_sleep = us_ticker_read();
    const unsigned int lp_ticks_after_sleep = lp_ticker_read();

    /* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between
     * ticker reads before and after the sleep represents only code execution time between calls.
     * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not
     * exceed 1 ms.
     */
    const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);

    TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));

    /* Check if we have woken-up after expected time. */
    TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));
}

#endif

utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)
{
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_CONTINUE;
}

utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(60, "default_auto");
    us_ticker_init();
#if DEVICE_LOWPOWERTIMER
    lp_ticker_init();
#endif
    /* Suspend RTOS Kernel to enable sleep modes. */
    osKernelSuspend();
    return greentea_test_setup_handler(number_of_cases);
}

Case cases[] = {
    Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler),
#if DEVICE_LOWPOWERTIMER
    Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler),
    Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),
#endif
};

Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);

int main() {
    Harness::run(specification);
}
<commit_msg>tests-mbed_hal-sleep: remove unused variable.<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2017 ARM Limited
 *
 * 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.
 */

#if !DEVICE_SLEEP
#error [NOT_SUPPORTED] sleep not supported for this target
#endif

#include "mbed.h"

#include "utest/utest.h"
#include "unity/unity.h"
#include "greentea-client/test_env.h"

#include "sleep_api_tests.h"

#define US_PER_S 1000000

using namespace utest::v1;

/* The following ticker frequencies are possible:
 * high frequency ticker: 250 KHz (1 tick per 4 us) - 8 Mhz (1 tick per 1/8 us)
 * low power ticker: 8 KHz (1 tick per 125 us) - 64 KHz (1 tick per ~15.6 us)
 */

/* Used for regular sleep mode, a target should be awake within 10 us. Define us delta value as follows:
 * delta = default 10 us + worst ticker resolution + extra time for code execution */
static const uint32_t sleep_mode_delta_us = (10 + 4 + 5);

/* Used for deep-sleep mode, a target should be awake within 10 ms. Define us delta value as follows:
 * delta = default 10 ms + worst ticker resolution + extra time for code execution */
static const uint32_t deepsleep_mode_delta_us = (10000 + 125 + 5);

unsigned int ticks_to_us(unsigned int ticks, unsigned int freq)
{
    return (unsigned int)((unsigned long long)ticks * US_PER_S / freq);
}

unsigned int us_to_ticks(unsigned int us, unsigned int freq)
{
    return (unsigned int)((unsigned long long)us * freq / US_PER_S);
}

unsigned int overflow_protect(unsigned int timestamp, unsigned int ticker_width)
{
    unsigned int counter_mask = ((1 << ticker_width) - 1);

    return (timestamp & counter_mask);
}

bool compare_timestamps(unsigned int delta_ticks, unsigned int ticker_width, unsigned int expected, unsigned int actual)
{
    const unsigned int counter_mask = ((1 << ticker_width) - 1);

    const unsigned int lower_bound = ((expected - delta_ticks) & counter_mask);
    const unsigned int upper_bound = ((expected + delta_ticks) & counter_mask);

    if(lower_bound < upper_bound) {
        if (actual >= lower_bound && actual <= upper_bound) {
            return true;
        } else {
            return false;
        }
    } else {
        if ((actual >= lower_bound && actual <= counter_mask) ||
            (actual >= 0 && actual <= upper_bound)) {
            return true;
        } else {
            return false;
        }
    }
}

void us_ticker_isr(const ticker_data_t *const ticker_data)
{
    us_ticker_clear_interrupt();
}

#ifdef DEVICE_LOWPOWERTIMER
void lp_ticker_isr(const ticker_data_t *const ticker_data)
{
    lp_ticker_clear_interrupt();
}
#endif

/* Test that wake-up time from sleep should be less than 10 us and
 * high frequency ticker interrupt can wake-up target from sleep. */
void sleep_usticker_test()
{
    const ticker_data_t * ticker = get_us_ticker_data();
    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
    const unsigned int ticker_width = ticker->interface->get_info()->bits;

    const ticker_irq_handler_type  us_ticker_irq_handler_org = set_us_ticker_irq_handler(us_ticker_isr);

    /* Test only sleep functionality. */
    sleep_manager_lock_deep_sleep();
    TEST_ASSERT_FALSE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should be locked");

    /* Testing wake-up time 10 us. */
    for (timestamp_t i = 100; i < 1000; i += 100) {
        /* note: us_ticker_read() operates on ticks. */
        const timestamp_t next_match_timestamp = overflow_protect(us_ticker_read() + us_to_ticks(i, ticker_freq),
                ticker_width);

        us_ticker_set_interrupt(next_match_timestamp);

        sleep();

        const unsigned int wakeup_timestamp = us_ticker_read();

        TEST_ASSERT(
                compare_timestamps(us_to_ticks(sleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp,
                        wakeup_timestamp));
    }

    set_us_ticker_irq_handler(us_ticker_irq_handler_org);

    sleep_manager_unlock_deep_sleep();
    TEST_ASSERT_TRUE(sleep_manager_can_deep_sleep());
}

#ifdef DEVICE_LOWPOWERTIMER

/* Test that wake-up time from sleep should be less than 10 ms and
 * low power ticker interrupt can wake-up target from sleep. */
void deepsleep_lpticker_test()
{
    const ticker_data_t * ticker = get_lp_ticker_data();
    const unsigned int ticker_freq = ticker->interface->get_info()->frequency;
    const unsigned int ticker_width = ticker->interface->get_info()->bits;

    const ticker_irq_handler_type  lp_ticker_irq_handler_org = set_lp_ticker_irq_handler(lp_ticker_isr);

    /* Give some time Green Tea to finish UART transmission before entering
     * deep-sleep mode.
     */
    wait_ms(10);

    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");

    /* Testing wake-up time 10 ms. */
    for (timestamp_t i = 20000; i < 200000; i += 20000) {
        /* note: lp_ticker_read() operates on ticks. */
        const timestamp_t next_match_timestamp = overflow_protect(lp_ticker_read() + us_to_ticks(i, ticker_freq), ticker_width);

        lp_ticker_set_interrupt(next_match_timestamp);

        sleep();

        const timestamp_t wakeup_timestamp = lp_ticker_read();

        TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, ticker_freq), ticker_width, next_match_timestamp, wakeup_timestamp));
    }

    set_lp_ticker_irq_handler(lp_ticker_irq_handler_org);

}

void deepsleep_high_speed_clocks_turned_off_test()
{
    const ticker_data_t * us_ticker = get_us_ticker_data();
    const ticker_data_t * lp_ticker = get_lp_ticker_data();
    const unsigned int us_ticker_freq = us_ticker->interface->get_info()->frequency;
    const unsigned int lp_ticker_freq = lp_ticker->interface->get_info()->frequency;
    const unsigned int us_ticker_width = us_ticker->interface->get_info()->bits;
    const unsigned int lp_ticker_width = lp_ticker->interface->get_info()->bits;
    const unsigned int us_ticker_mask = ((1 << us_ticker_width) - 1);

    /* Give some time Green Tea to finish UART transmission before entering
     * deep-sleep mode.
     */
    wait_ms(10);

    TEST_ASSERT_TRUE_MESSAGE(sleep_manager_can_deep_sleep(), "deep sleep should not be locked");

    const unsigned int us_ticks_before_sleep = us_ticker_read();

    const timestamp_t wakeup_time = lp_ticker_read() + us_to_ticks(200000, lp_ticker_freq);
    lp_ticker_set_interrupt(wakeup_time);

    sleep();

    const unsigned int us_ticks_after_sleep = us_ticker_read();
    const unsigned int lp_ticks_after_sleep = lp_ticker_read();

    /* High freqency ticker should be disabled in deep-sleep mode. We expect that time difference between
     * ticker reads before and after the sleep represents only code execution time between calls.
     * Since we went to sleep for about 200 ms check if time counted by high frequency timer does not
     * exceed 1 ms.
     */
    const unsigned int us_ticks_diff = (us_ticks_before_sleep <= us_ticks_after_sleep) ? (us_ticks_after_sleep - us_ticks_before_sleep) : (us_ticker_mask - us_ticks_before_sleep + us_ticks_after_sleep + 1);

    TEST_ASSERT_UINT32_WITHIN(1000, 0, ticks_to_us(us_ticks_diff, us_ticker_freq));

    /* Check if we have woken-up after expected time. */
    TEST_ASSERT(compare_timestamps(us_to_ticks(deepsleep_mode_delta_us, lp_ticker_freq), lp_ticker_width, wakeup_time, lp_ticks_after_sleep));
}

#endif

utest::v1::status_t greentea_failure_handler(const Case * const source, const failure_t reason)
{
    greentea_case_failure_abort_handler(source, reason);
    return STATUS_CONTINUE;
}

utest::v1::status_t greentea_test_setup(const size_t number_of_cases)
{
    GREENTEA_SETUP(60, "default_auto");
    us_ticker_init();
#if DEVICE_LOWPOWERTIMER
    lp_ticker_init();
#endif
    /* Suspend RTOS Kernel to enable sleep modes. */
    osKernelSuspend();
    return greentea_test_setup_handler(number_of_cases);
}

Case cases[] = {
    Case("sleep - source of wake-up - us ticker", sleep_usticker_test, greentea_failure_handler),
#if DEVICE_LOWPOWERTIMER
    Case("deep-sleep - source of wake-up - lp ticker",deepsleep_lpticker_test, greentea_failure_handler),
    Case("deep-sleep - high-speed clocks are turned off",deepsleep_high_speed_clocks_turned_off_test, greentea_failure_handler),
#endif
};

Specification specification(greentea_test_setup, cases, greentea_test_teardown_handler);

int main() {
    Harness::run(specification);
}
<|endoftext|>


<commit_before>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//

#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <algorithm>
using namespace llvm;

// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
  EmitSourceFileHeader("Target Instruction Enum Values", OS);
  OS << "namespace llvm {\n\n";

  CodeGenTarget Target;

  // We must emit the PHI opcode first...
  std::string Namespace;
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
       E = Target.inst_end(); II != E; ++II) {
    if (II->second.Namespace != "TargetInstrInfo") {
      Namespace = II->second.Namespace;
      break;
    }
  }

  if (Namespace.empty()) {
    std::cerr << "No instructions defined!\n";
    exit(1);
  }

  std::vector<const CodeGenInstruction*> NumberedInstructions;
  Target.getInstructionsByEnumValue(NumberedInstructions);

  OS << "namespace " << Namespace << " {\n";
  OS << "  enum {\n";
  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
    OS << "    " << NumberedInstructions[i]->TheDef->getName()
       << "\t= " << i << ",\n";
  }
  OS << "    INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
  OS << "  };\n}\n";
  OS << "} // End llvm namespace \n";
}

void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
                                    unsigned Num, std::ostream &OS) const {
  OS << "static const unsigned ImplicitList" << Num << "[] = { ";
  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
    OS << getQualifiedName(Uses[i]) << ", ";
  OS << "0 };\n";
}

static std::vector<Record*> GetOperandInfo(const CodeGenInstruction &Inst) {
  std::vector<Record*> Result;
  for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
    if (Inst.OperandList[i].Rec->isSubClassOf("RegisterClass")) {
      Result.push_back(Inst.OperandList[i].Rec);
    } else {
      // This might be a multiple operand thing.
      // Targets like X86 have registers in their multi-operand operands.
      DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
      unsigned NumDefs = MIOI->getNumArgs();
      for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
        if (NumDefs <= j) {
          Result.push_back(0);
        } else {
          DefInit *Def = dynamic_cast<DefInit*>(MIOI->getArg(j));
          Result.push_back(Def ? Def->getDef() : 0);
        }
      }
    }
  }
  return Result;
}

// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
  GatherItinClasses();

  EmitSourceFileHeader("Target Instruction Descriptors", OS);
  OS << "namespace llvm {\n\n";

  CodeGenTarget Target;
  const std::string &TargetName = Target.getName();
  Record *InstrInfo = Target.getInstructionSet();

  // Emit empty implicit uses and defs lists
  OS << "static const unsigned EmptyImpList[] = { 0 };\n";

  // Keep track of all of the def lists we have emitted already.
  std::map<std::vector<Record*>, unsigned> EmittedLists;
  unsigned ListNumber = 0;

  // Emit all of the instruction's implicit uses and defs.
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
         E = Target.inst_end(); II != E; ++II) {
    Record *Inst = II->second.TheDef;
    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
    if (!Uses.empty()) {
      unsigned &IL = EmittedLists[Uses];
      if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
    }
    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
    if (!Defs.empty()) {
      unsigned &IL = EmittedLists[Defs];
      if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
    }
  }

  std::map<std::vector<Record*>, unsigned> OperandInfosEmitted;
  unsigned OperandListNum = 0;
  OperandInfosEmitted[std::vector<Record*>()] = ++OperandListNum;

  // Emit all of the operand info records.
  OS << "\n";
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
       E = Target.inst_end(); II != E; ++II) {
    std::vector<Record*> OperandInfo = GetOperandInfo(II->second);
    unsigned &N = OperandInfosEmitted[OperandInfo];
    if (N == 0) {
      N = ++OperandListNum;
      OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
      for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i) {
        Record *RC = OperandInfo[i];
        // FIXME: We only care about register operands for now.
        if (RC && RC->isSubClassOf("RegisterClass"))
          OS << "{ " << getQualifiedName(RC) << "RegClassID, 0 }, ";
        else if (RC && RC->getName() == "ptr_rc")
          // Ptr value whose register class is resolved via callback.
          OS << "{ 0, 1 }, ";
        else
          OS << "{ 0, 0 }, ";
      }
      OS << "};\n";
    }
  }

  // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
  //
  OS << "\nstatic const TargetInstrDescriptor " << TargetName
     << "Insts[] = {\n";
  std::vector<const CodeGenInstruction*> NumberedInstructions;
  Target.getInstructionsByEnumValue(NumberedInstructions);

  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
               OperandInfosEmitted, OS);
  OS << "};\n";
  OS << "} // End llvm namespace \n";
}

void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
                                  Record *InstrInfo,
                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
                               std::map<std::vector<Record*>, unsigned> &OpInfo,
                                  std::ostream &OS) {
  int MinOperands;
  if (!Inst.OperandList.empty())
    // Each logical operand can be multiple MI operands.
    MinOperands = Inst.OperandList.back().MIOperandNo +
                  Inst.OperandList.back().MINumOperands;
  else
    MinOperands = 0;

  OS << "  { \"";
  if (Inst.Name.empty())
    OS << Inst.TheDef->getName();
  else
    OS << Inst.Name;

  unsigned ItinClass = !IsItineraries ? 0 :
            ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());

  OS << "\",\t" << MinOperands << ", " << ItinClass
     << ", 0";

  // Try to determine (from the pattern), if the instruction is a store.
  bool isStore = false;
  if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
    ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
    if (LI && LI->getSize() > 0) {
      DagInit *Dag = (DagInit *)LI->getElement(0);
      DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
      if (OpDef) {
        Record *Operator = OpDef->getDef();
        if (Operator->isSubClassOf("SDNode")) {
          const std::string Opcode = Operator->getValueAsString("Opcode");
          if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
            isStore = true;
        }
      }
    }
  }

  // Emit all of the target indepedent flags...
  if (Inst.isReturn)     OS << "|M_RET_FLAG";
  if (Inst.isBranch)     OS << "|M_BRANCH_FLAG";
  if (Inst.isBarrier)    OS << "|M_BARRIER_FLAG";
  if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
  if (Inst.isCall)       OS << "|M_CALL_FLAG";
  if (Inst.isLoad)       OS << "|M_LOAD_FLAG";
  if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
  if (Inst.isTwoAddress) OS << "|M_2_ADDR_FLAG";
  if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
  if (Inst.isCommutable) OS << "|M_COMMUTABLE";
  if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
  if (Inst.usesCustomDAGSchedInserter)
    OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
  if (Inst.hasVariableNumberOfOperands)
    OS << "|M_VARIABLE_OPS";
  OS << ", 0";

  // Emit all of the target-specific flags...
  ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
  ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
  if (LI->getSize() != Shift->getSize())
    throw "Lengths of " + InstrInfo->getName() +
          ":(TargetInfoFields, TargetInfoPositions) must be equal!";

  for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
    emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
                     dynamic_cast<IntInit*>(Shift->getElement(i)), OS);

  OS << ", ";

  // Emit the implicit uses and defs lists...
  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
  if (UseList.empty())
    OS << "EmptyImpList, ";
  else
    OS << "ImplicitList" << EmittedLists[UseList] << ", ";

  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
  if (DefList.empty())
    OS << "EmptyImpList, ";
  else
    OS << "ImplicitList" << EmittedLists[DefList] << ", ";

  // Emit the operand info.
  std::vector<Record*> OperandInfo = GetOperandInfo(Inst);
  if (OperandInfo.empty())
    OS << "0";
  else
    OS << "OperandInfo" << OpInfo[OperandInfo];

  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}

struct LessRecord {
  bool operator()(const Record *Rec1, const Record *Rec2) const {
    return Rec1->getName() < Rec2->getName();
  }
};
void InstrInfoEmitter::GatherItinClasses() {
  std::vector<Record*> DefList =
                          Records.getAllDerivedDefinitions("InstrItinClass");
  IsItineraries = !DefList.empty();

  if (!IsItineraries) return;

  std::sort(DefList.begin(), DefList.end(), LessRecord());

  for (unsigned i = 0, N = DefList.size(); i < N; i++) {
    Record *Def = DefList[i];
    ItinClassMap[Def->getName()] = i;
  }
}

unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
  return ItinClassMap[ItinName];
}

void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
                                        IntInit *ShiftInt, std::ostream &OS) {
  if (Val == 0 || ShiftInt == 0)
    throw std::string("Illegal value or shift amount in TargetInfo*!");
  RecordVal *RV = R->getValue(Val->getValue());
  int Shift = ShiftInt->getValue();

  if (RV == 0 || RV->getValue() == 0) {
    // This isn't an error if this is a builtin instruction.
    if (R->getName() != "PHI" && R->getName() != "INLINEASM")
      throw R->getName() + " doesn't have a field named '" +
            Val->getValue() + "'!";
    return;
  }

  Init *Value = RV->getValue();
  if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
    if (BI->getValue()) OS << "|(1<<" << Shift << ")";
    return;
  } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
    // Convert the Bits to an integer to print...
    Init *I = BI->convertInitializerTo(new IntRecTy());
    if (I)
      if (IntInit *II = dynamic_cast<IntInit*>(I)) {
        if (II->getValue()) {
          if (Shift)
            OS << "|(" << II->getValue() << "<<" << Shift << ")";
          else
            OS << "|" << II->getValue();
        }
        return;
      }

  } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
    if (II->getValue()) {
      if (Shift)
        OS << "|(" << II->getValue() << "<<" << Shift << ")";
      else
        OS << II->getValue();
    }
    return;
  }

  std::cerr << "Unhandled initializer: " << *Val << "\n";
  throw "In record '" + R->getName() + "' for TSFlag emission.";
}

<commit_msg>Eliminate data relocations by using NULL instead of global empty list.<commit_after>//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tablegen backend is responsible for emitting a description of the target
// instruction set for the code generator.
//
//===----------------------------------------------------------------------===//

#include "InstrInfoEmitter.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include <algorithm>
using namespace llvm;

// runEnums - Print out enum values for all of the instructions.
void InstrInfoEmitter::runEnums(std::ostream &OS) {
  EmitSourceFileHeader("Target Instruction Enum Values", OS);
  OS << "namespace llvm {\n\n";

  CodeGenTarget Target;

  // We must emit the PHI opcode first...
  std::string Namespace;
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
       E = Target.inst_end(); II != E; ++II) {
    if (II->second.Namespace != "TargetInstrInfo") {
      Namespace = II->second.Namespace;
      break;
    }
  }

  if (Namespace.empty()) {
    std::cerr << "No instructions defined!\n";
    exit(1);
  }

  std::vector<const CodeGenInstruction*> NumberedInstructions;
  Target.getInstructionsByEnumValue(NumberedInstructions);

  OS << "namespace " << Namespace << " {\n";
  OS << "  enum {\n";
  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i) {
    OS << "    " << NumberedInstructions[i]->TheDef->getName()
       << "\t= " << i << ",\n";
  }
  OS << "    INSTRUCTION_LIST_END = " << NumberedInstructions.size() << "\n";
  OS << "  };\n}\n";
  OS << "} // End llvm namespace \n";
}

void InstrInfoEmitter::printDefList(const std::vector<Record*> &Uses,
                                    unsigned Num, std::ostream &OS) const {
  OS << "static const unsigned ImplicitList" << Num << "[] = { ";
  for (unsigned i = 0, e = Uses.size(); i != e; ++i)
    OS << getQualifiedName(Uses[i]) << ", ";
  OS << "0 };\n";
}

static std::vector<Record*> GetOperandInfo(const CodeGenInstruction &Inst) {
  std::vector<Record*> Result;
  for (unsigned i = 0, e = Inst.OperandList.size(); i != e; ++i) {
    if (Inst.OperandList[i].Rec->isSubClassOf("RegisterClass")) {
      Result.push_back(Inst.OperandList[i].Rec);
    } else {
      // This might be a multiple operand thing.
      // Targets like X86 have registers in their multi-operand operands.
      DagInit *MIOI = Inst.OperandList[i].MIOperandInfo;
      unsigned NumDefs = MIOI->getNumArgs();
      for (unsigned j = 0, e = Inst.OperandList[i].MINumOperands; j != e; ++j) {
        if (NumDefs <= j) {
          Result.push_back(0);
        } else {
          DefInit *Def = dynamic_cast<DefInit*>(MIOI->getArg(j));
          Result.push_back(Def ? Def->getDef() : 0);
        }
      }
    }
  }
  return Result;
}

// run - Emit the main instruction description records for the target...
void InstrInfoEmitter::run(std::ostream &OS) {
  GatherItinClasses();

  EmitSourceFileHeader("Target Instruction Descriptors", OS);
  OS << "namespace llvm {\n\n";

  CodeGenTarget Target;
  const std::string &TargetName = Target.getName();
  Record *InstrInfo = Target.getInstructionSet();

  // Keep track of all of the def lists we have emitted already.
  std::map<std::vector<Record*>, unsigned> EmittedLists;
  unsigned ListNumber = 0;

  // Emit all of the instruction's implicit uses and defs.
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
         E = Target.inst_end(); II != E; ++II) {
    Record *Inst = II->second.TheDef;
    std::vector<Record*> Uses = Inst->getValueAsListOfDefs("Uses");
    if (!Uses.empty()) {
      unsigned &IL = EmittedLists[Uses];
      if (!IL) printDefList(Uses, IL = ++ListNumber, OS);
    }
    std::vector<Record*> Defs = Inst->getValueAsListOfDefs("Defs");
    if (!Defs.empty()) {
      unsigned &IL = EmittedLists[Defs];
      if (!IL) printDefList(Defs, IL = ++ListNumber, OS);
    }
  }

  std::map<std::vector<Record*>, unsigned> OperandInfosEmitted;
  unsigned OperandListNum = 0;
  OperandInfosEmitted[std::vector<Record*>()] = ++OperandListNum;

  // Emit all of the operand info records.
  OS << "\n";
  for (CodeGenTarget::inst_iterator II = Target.inst_begin(),
       E = Target.inst_end(); II != E; ++II) {
    std::vector<Record*> OperandInfo = GetOperandInfo(II->second);
    unsigned &N = OperandInfosEmitted[OperandInfo];
    if (N == 0) {
      N = ++OperandListNum;
      OS << "static const TargetOperandInfo OperandInfo" << N << "[] = { ";
      for (unsigned i = 0, e = OperandInfo.size(); i != e; ++i) {
        Record *RC = OperandInfo[i];
        // FIXME: We only care about register operands for now.
        if (RC && RC->isSubClassOf("RegisterClass"))
          OS << "{ " << getQualifiedName(RC) << "RegClassID, 0 }, ";
        else if (RC && RC->getName() == "ptr_rc")
          // Ptr value whose register class is resolved via callback.
          OS << "{ 0, 1 }, ";
        else
          OS << "{ 0, 0 }, ";
      }
      OS << "};\n";
    }
  }

  // Emit all of the TargetInstrDescriptor records in their ENUM ordering.
  //
  OS << "\nstatic const TargetInstrDescriptor " << TargetName
     << "Insts[] = {\n";
  std::vector<const CodeGenInstruction*> NumberedInstructions;
  Target.getInstructionsByEnumValue(NumberedInstructions);

  for (unsigned i = 0, e = NumberedInstructions.size(); i != e; ++i)
    emitRecord(*NumberedInstructions[i], i, InstrInfo, EmittedLists,
               OperandInfosEmitted, OS);
  OS << "};\n";
  OS << "} // End llvm namespace \n";
}

void InstrInfoEmitter::emitRecord(const CodeGenInstruction &Inst, unsigned Num,
                                  Record *InstrInfo,
                         std::map<std::vector<Record*>, unsigned> &EmittedLists,
                               std::map<std::vector<Record*>, unsigned> &OpInfo,
                                  std::ostream &OS) {
  int MinOperands;
  if (!Inst.OperandList.empty())
    // Each logical operand can be multiple MI operands.
    MinOperands = Inst.OperandList.back().MIOperandNo +
                  Inst.OperandList.back().MINumOperands;
  else
    MinOperands = 0;

  OS << "  { \"";
  if (Inst.Name.empty())
    OS << Inst.TheDef->getName();
  else
    OS << Inst.Name;

  unsigned ItinClass = !IsItineraries ? 0 :
            ItinClassNumber(Inst.TheDef->getValueAsDef("Itinerary")->getName());

  OS << "\",\t" << MinOperands << ", " << ItinClass
     << ", 0";

  // Try to determine (from the pattern), if the instruction is a store.
  bool isStore = false;
  if (dynamic_cast<ListInit*>(Inst.TheDef->getValueInit("Pattern"))) {
    ListInit *LI = Inst.TheDef->getValueAsListInit("Pattern");
    if (LI && LI->getSize() > 0) {
      DagInit *Dag = (DagInit *)LI->getElement(0);
      DefInit *OpDef = dynamic_cast<DefInit*>(Dag->getOperator());
      if (OpDef) {
        Record *Operator = OpDef->getDef();
        if (Operator->isSubClassOf("SDNode")) {
          const std::string Opcode = Operator->getValueAsString("Opcode");
          if (Opcode == "ISD::STORE" || Opcode == "ISD::TRUNCSTORE")
            isStore = true;
        }
      }
    }
  }

  // Emit all of the target indepedent flags...
  if (Inst.isReturn)     OS << "|M_RET_FLAG";
  if (Inst.isBranch)     OS << "|M_BRANCH_FLAG";
  if (Inst.isBarrier)    OS << "|M_BARRIER_FLAG";
  if (Inst.hasDelaySlot) OS << "|M_DELAY_SLOT_FLAG";
  if (Inst.isCall)       OS << "|M_CALL_FLAG";
  if (Inst.isLoad)       OS << "|M_LOAD_FLAG";
  if (Inst.isStore || isStore) OS << "|M_STORE_FLAG";
  if (Inst.isTwoAddress) OS << "|M_2_ADDR_FLAG";
  if (Inst.isConvertibleToThreeAddress) OS << "|M_CONVERTIBLE_TO_3_ADDR";
  if (Inst.isCommutable) OS << "|M_COMMUTABLE";
  if (Inst.isTerminator) OS << "|M_TERMINATOR_FLAG";
  if (Inst.usesCustomDAGSchedInserter)
    OS << "|M_USES_CUSTOM_DAG_SCHED_INSERTION";
  if (Inst.hasVariableNumberOfOperands)
    OS << "|M_VARIABLE_OPS";
  OS << ", 0";

  // Emit all of the target-specific flags...
  ListInit *LI    = InstrInfo->getValueAsListInit("TSFlagsFields");
  ListInit *Shift = InstrInfo->getValueAsListInit("TSFlagsShifts");
  if (LI->getSize() != Shift->getSize())
    throw "Lengths of " + InstrInfo->getName() +
          ":(TargetInfoFields, TargetInfoPositions) must be equal!";

  for (unsigned i = 0, e = LI->getSize(); i != e; ++i)
    emitShiftedValue(Inst.TheDef, dynamic_cast<StringInit*>(LI->getElement(i)),
                     dynamic_cast<IntInit*>(Shift->getElement(i)), OS);

  OS << ", ";

  // Emit the implicit uses and defs lists...
  std::vector<Record*> UseList = Inst.TheDef->getValueAsListOfDefs("Uses");
  if (UseList.empty())
    OS << "NULL, ";
  else
    OS << "ImplicitList" << EmittedLists[UseList] << ", ";

  std::vector<Record*> DefList = Inst.TheDef->getValueAsListOfDefs("Defs");
  if (DefList.empty())
    OS << "NULL, ";
  else
    OS << "ImplicitList" << EmittedLists[DefList] << ", ";

  // Emit the operand info.
  std::vector<Record*> OperandInfo = GetOperandInfo(Inst);
  if (OperandInfo.empty())
    OS << "0";
  else
    OS << "OperandInfo" << OpInfo[OperandInfo];

  OS << " },  // Inst #" << Num << " = " << Inst.TheDef->getName() << "\n";
}

struct LessRecord {
  bool operator()(const Record *Rec1, const Record *Rec2) const {
    return Rec1->getName() < Rec2->getName();
  }
};
void InstrInfoEmitter::GatherItinClasses() {
  std::vector<Record*> DefList =
                          Records.getAllDerivedDefinitions("InstrItinClass");
  IsItineraries = !DefList.empty();

  if (!IsItineraries) return;

  std::sort(DefList.begin(), DefList.end(), LessRecord());

  for (unsigned i = 0, N = DefList.size(); i < N; i++) {
    Record *Def = DefList[i];
    ItinClassMap[Def->getName()] = i;
  }
}

unsigned InstrInfoEmitter::ItinClassNumber(std::string ItinName) {
  return ItinClassMap[ItinName];
}

void InstrInfoEmitter::emitShiftedValue(Record *R, StringInit *Val,
                                        IntInit *ShiftInt, std::ostream &OS) {
  if (Val == 0 || ShiftInt == 0)
    throw std::string("Illegal value or shift amount in TargetInfo*!");
  RecordVal *RV = R->getValue(Val->getValue());
  int Shift = ShiftInt->getValue();

  if (RV == 0 || RV->getValue() == 0) {
    // This isn't an error if this is a builtin instruction.
    if (R->getName() != "PHI" && R->getName() != "INLINEASM")
      throw R->getName() + " doesn't have a field named '" +
            Val->getValue() + "'!";
    return;
  }

  Init *Value = RV->getValue();
  if (BitInit *BI = dynamic_cast<BitInit*>(Value)) {
    if (BI->getValue()) OS << "|(1<<" << Shift << ")";
    return;
  } else if (BitsInit *BI = dynamic_cast<BitsInit*>(Value)) {
    // Convert the Bits to an integer to print...
    Init *I = BI->convertInitializerTo(new IntRecTy());
    if (I)
      if (IntInit *II = dynamic_cast<IntInit*>(I)) {
        if (II->getValue()) {
          if (Shift)
            OS << "|(" << II->getValue() << "<<" << Shift << ")";
          else
            OS << "|" << II->getValue();
        }
        return;
      }

  } else if (IntInit *II = dynamic_cast<IntInit*>(Value)) {
    if (II->getValue()) {
      if (Shift)
        OS << "|(" << II->getValue() << "<<" << Shift << ")";
      else
        OS << II->getValue();
    }
    return;
  }

  std::cerr << "Unhandled initializer: " << *Val << "\n";
  throw "In record '" + R->getName() + "' for TSFlag emission.";
}

<|endoftext|>


<commit_before>#ifndef __UTIL_SMARTBYTEARRAY_HPP__
#define __UTIL_SMARTBYTEARRAY_HPP__

#include <memory>

namespace FreshCask {

	class SmartByteArray
	{
	public:
		SmartByteArray() : data(nullptr), size(0) {}
		SmartByteArray(const uint32_t& size) : data(new Byte[size]), size(size) {}
		SmartByteArray(const std::string& str) : data(new Byte[str.length()]), size(str.length())
		{
			memcpy(Data(), &str[0], str.length());
		}
		SmartByteArray(const char* str) { new (this) SmartByteArray(std::string(str)); }
		SmartByteArray(const BytePtr ptr, const uint32_t& size) : data(ptr, senderAllocDeleter()), size(size) {}

		std::string ToString() const
		{
			if (Data() != nullptr)
				return std::string(reinterpret_cast<char*>(Data()), Size());
			else
				return std::string();
		}

		BytePtr Data() const { return data.get(); }
		uint32_t Size() const { return size; }

		bool IsNull() { return size == 0 || data == nullptr; }
		static SmartByteArray Null() { return SmartByteArray();  }

		friend bool operator<(const SmartByteArray& lhs, const SmartByteArray& rhs)
		{
			size_t len = min(lhs.Size(), rhs.Size());
			int cmp = memcmp(lhs.Data(), rhs.Data(), len);

			if (cmp != 0) return cmp < 0;
			else return lhs.Size() - rhs.Size() < 0;

			/*if (lhs.Size() < rhs.Size()) return true;
			else if (lhs.Size() > rhs.Size()) return false;
			else return memcmp(lhs.Data(), rhs.Data(), lhs.Size()) < 0;*/
		}

	private:
		struct senderAllocDeleter { // tricky, avoid being deleted by std::shared_ptr
			void operator()(BytePtr) { /* do nothing */ }
		};

	private:
		std::shared_ptr<Byte> data;
		uint32_t size;
	};

}	// namespace FreshCask

#endif // __UTIL_SMARTBYTEARRAY_HPP__<commit_msg>Roll back to ToString<commit_after>#ifndef __UTIL_SMARTBYTEARRAY_HPP__
#define __UTIL_SMARTBYTEARRAY_HPP__

#include <memory>

namespace FreshCask {

	class SmartByteArray
	{
	public:
		SmartByteArray() : data(nullptr), size(0) {}
		SmartByteArray(const uint32_t& size) : data(new Byte[size]), size(size) {}
		SmartByteArray(const std::string& str) : data(new Byte[str.length()]), size(str.length())
		{
			memcpy(Data(), &str[0], str.length());
		}
		SmartByteArray(const char* str) { new (this) SmartByteArray(std::string(str)); }
		SmartByteArray(const BytePtr ptr, const uint32_t& size) : data(ptr, senderAllocDeleter()), size(size) {}

		std::string ToString() const
		{
			if (Data() != nullptr)
				return std::string(reinterpret_cast<char*>(Data()), Size());
			else
				return std::string();
		}

		BytePtr Data() const { return data.get(); }
		uint32_t Size() const { return size; }

		bool IsNull() { return size == 0 || data == nullptr; }
		static SmartByteArray Null() { return SmartByteArray();  }

		friend bool operator<(const SmartByteArray& lhs, const SmartByteArray& rhs)
		{
			return lhs.ToString() < rhs.ToString();
		}

	private:
		struct senderAllocDeleter { // tricky, avoid being deleted by std::shared_ptr
			void operator()(BytePtr) { /* do nothing */ }
		};

	private:
		std::shared_ptr<Byte> data;
		uint32_t size;
	};

}	// namespace FreshCask

#endif // __UTIL_SMARTBYTEARRAY_HPP__<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                      OpenSim:  AbstractPathPoint.cpp                       *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "AbstractPathPoint.h"

//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
using SimTK::Transform;

const PhysicalFrame& AbstractPathPoint::getParentFrame() const
{
    return getSocket<PhysicalFrame>("parent_frame").getConnectee();
}

void AbstractPathPoint::setParentFrame(const OpenSim::PhysicalFrame& frame)
{
    connectSocket_parent_frame(frame);
}

const PhysicalFrame& AbstractPathPoint::getBody() const {
    return getParentFrame();
}

void AbstractPathPoint::setBody(const PhysicalFrame& body)
{
    setParentFrame(body);
}

const std::string& AbstractPathPoint::getBodyName() const {
    return getParentFrame().getName();
}

// PathPoint used to be the base class for all path points including
// MovingPathPoints, which was incorrect. AbstractPathPoint was added to
// the hierarchy to resolve that issue and since the updateFromXML code
// still pertains to all PathPoints was included here in AbstractPathPoint
// If derived classes have to override for future changes, do not
// forget to invoke Super::updateFromXMLNode.
void AbstractPathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode,
                                          int versionNumber)
{
    int documentVersion = versionNumber;
    if (documentVersion < XMLDocument::getLatestVersion()) {
        if (documentVersion < 30505) {
            // replace old properties with latest use of Connectors
            SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
            std::string bodyName("");
            if (bodyElement != aNode.element_end()) {
                bodyElement->getValueAs<std::string>(bodyName);
                // PathPoints in pre-4.0 models are necessarily 3 levels deep
                // (model, muscle, geometry path), and Bodies are
                // necessarily 1 levels deep; here we create the correct
                // relative path (accounting for sets being components).
                bodyName = XMLDocument::updateConnecteePath30517("bodyset",
                                                                 bodyName);
                XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_",
                    "parent_frame", bodyName);
            }
        }
    }

    Super::updateFromXMLNode(aNode, versionNumber);
}

<commit_msg>Changed "parent_frame" string literal for a std::string<commit_after>/* -------------------------------------------------------------------------- *
 *                      OpenSim:  AbstractPathPoint.cpp                       *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 *                                                                            *
 * 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.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "AbstractPathPoint.h"

//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;
using SimTK::Vec3;
using SimTK::Transform;

// here for perf reasons: many functions take a const reference to a
// std::string. Using a C string literal results in millions of temporary
// std::strings being constructed so, instead, pre-allocate it in static
// storage
static const std::string parentFrameKey{"parent_frame"};

const PhysicalFrame& AbstractPathPoint::getParentFrame() const
{
    return getSocket<PhysicalFrame>(parentFrameKey).getConnectee();
}

void AbstractPathPoint::setParentFrame(const OpenSim::PhysicalFrame& frame)
{
    connectSocket_parent_frame(frame);
}

const PhysicalFrame& AbstractPathPoint::getBody() const {
    return getParentFrame();
}

void AbstractPathPoint::setBody(const PhysicalFrame& body)
{
    setParentFrame(body);
}

const std::string& AbstractPathPoint::getBodyName() const {
    return getParentFrame().getName();
}

// PathPoint used to be the base class for all path points including
// MovingPathPoints, which was incorrect. AbstractPathPoint was added to
// the hierarchy to resolve that issue and since the updateFromXML code
// still pertains to all PathPoints was included here in AbstractPathPoint
// If derived classes have to override for future changes, do not
// forget to invoke Super::updateFromXMLNode.
void AbstractPathPoint::updateFromXMLNode(SimTK::Xml::Element& aNode,
                                          int versionNumber)
{
    int documentVersion = versionNumber;
    if (documentVersion < XMLDocument::getLatestVersion()) {
        if (documentVersion < 30505) {
            // replace old properties with latest use of Connectors
            SimTK::Xml::element_iterator bodyElement = aNode.element_begin("body");
            std::string bodyName("");
            if (bodyElement != aNode.element_end()) {
                bodyElement->getValueAs<std::string>(bodyName);
                // PathPoints in pre-4.0 models are necessarily 3 levels deep
                // (model, muscle, geometry path), and Bodies are
                // necessarily 1 levels deep; here we create the correct
                // relative path (accounting for sets being components).
                bodyName = XMLDocument::updateConnecteePath30517("bodyset",
                                                                 bodyName);
                XMLDocument::addConnector(aNode, "Connector_PhysicalFrame_",
                    parentFrameKey, bodyName);
            }
        }
    }

    Super::updateFromXMLNode(aNode, versionNumber);
}

<|endoftext|>


<commit_before>/* vim: set sw=4 ts=4: */
/*
 * BindingConverter.cpp
 * Implements an AST Consumer that outputs clay bindings
 *
 */

#include <iostream>
#include <vector>
using namespace std;

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "llvm/ADT/Triple.h"

#include "BindingsConverter.h"

using namespace clang;
using namespace llvm;

BindingsConverter::BindingsConverter(bool useCTypes, ostream& out)
    :useCTypes(useCTypes), out(out) {
    }

void BindingsConverter::printHeader()
{
    // Print header
    string header = "# Auto-Generated by BindingsGenerator\n";
    header += "import types.*;\n";
    header += "import operators.*;\n";
    header += "import numbers.*;\n";
    header += "import pointers.*;\n";

    out << header;
}

void BindingsConverter::printFooter()
{

}

// Print a variable in clay
void BindingsConverter::printVarDecl(const VarDecl*& D) {
    out << "external ";
    out << D->getNameAsString();
    QualType type = D->getType();       // The return value
    if(useCTypes) {
        out << " : " << type.getAsString() << ";\n";
    }
    else {
        out << " : " << printType(convert(type)) << ";\n";
    }
}

// Print a function in clay
void BindingsConverter::printFuncDecl(const FunctionDecl*& D) {
    out << "external ";
    out << D->getNameAsString() << " (\n";
    int numParams = D->param_size();
    for( int i = 0 ; i < numParams ; i ++ ) {
        const ParmVarDecl * param = D->getParamDecl(i);        // Parameter number i
        const string name = param -> getNameAsString();
        if(name != "")
            out << "\t" << name << " : ";
        else
            out << "\t" << "argument_" << i + 1<< " : ";
        QualType cType = param->getOriginalType();
        if(useCTypes) {
            out << cType.getAsString();
        }
        else {
            out << printType(convert(cType));
        }
        if (i+1 < numParams)
            out << ",";
        out << "\n";
    }
    QualType ret = D->getResultType();       // The return value
    if(useCTypes) {
        out << ") : " << ret.getAsString() << ";\n";
    }
    else {
        out << ") : " << printType(convert(ret)) << ";\n";
    }
}

// Print a enum in clay
void BindingsConverter::printEnumDecl(const EnumDecl*& D) {
    for(EnumDecl::enumerator_iterator it = D->enumerator_begin(); it != D->enumerator_end(); it++)
    {
        EnumConstantDecl* CD = *it;
        out << "static " << CD->getNameAsString() << " = " ;
        out << CD->getInitVal().getLimitedValue() << ";\n"; // XXX: Warning, this limits enum values to 64-bits which is safe, I think
    }
}

// Print a record in clay
void BindingsConverter::printRecordDecl(const RecordDecl*& D) {
    out << "record " << D->getNameAsString() << " {\n";
    for(RecordDecl::field_iterator it = D->field_begin(); it != D->field_end(); it++)
    {
        FieldDecl* FD = *it;
        QualType type = FD->getType();

        out << FD->getNameAsString();
        if(useCTypes) {
            out << " : " << type.getAsString() << ";\n";
        }
        else {
            out << " : " << printType(convert(type)) << ";\n";
        }
    }
    out << "}\n";
}

QualType& BindingsConverter::convert(QualType& cType) {
    return cType;
}

string BindingsConverter::printType(const QualType& qtype) {
    Type& type = *qtype;

    if(type.isBooleanType()) {
        return "Bool";
    }
    else if(type.isSignedIntegerType()){
        return "Int";
    }
    else if(type.isUnsignedIntegerType()){
        return "UInt";
    }
    else if(type.isRealFloatingType()) {
        return "Float";
    }
    else if(type.isPointerType()) {
        PointerType& type_ = (PointerType&)type;
        QualType qtype_ = type_.getPointeeType();
        if((*qtype_).isFunctionType())
        {
            FunctionProtoType& ftype = (FunctionProtoType&) *qtype_;
            string typeStr = "CCodePtr[";
            for(FunctionProtoType::arg_type_iterator it = ftype.arg_type_begin(); it != ftype.arg_type_end(); it++) {
                QualType qtype = *it;
                typeStr += printType(qtype);
                typeStr += ",";
            }
            QualType qtype = ftype.getResultType();
            typeStr += printType(qtype);
            typeStr += "]";

            return typeStr;
        }
        else
        {
            if(useCTypes)
            {
                return "Pointer[" + qtype_.getAsString() + "]";
            }
            else
            {
                return "Pointer[" + printType(qtype_) + "]";
            }
        }
    }
    else if(type.isArrayType()) {
      ArrayType& type_ = (ArrayType&)type;
      return "Array[" + printType(type_.getElementType()) + "]";
    }
    else if(type.isRecordType()) {
        // TODO: Handle
        //case RECORD_TYPE : {
        //    RecordType *x = (RecordType *)t.ptr();
        //    out << x->record->name->str;
        //    if (!x->params.empty())
        //        out << x->params;
        //    break;
        return qtype.getAsString();
    }
    else if(type.isEnumeralType()) {
        return "Enum";
    }
    else if(type.isVoidType()) {
        return "Void";
    }
    else{
        return "???";
        //assert(false);
    }

    return "null";
    }

    // Handle top level declarations observed in the program
    void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) {
        for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) {
            const FunctionDecl *FD = dyn_cast<FunctionDecl>(*it);
            const VarDecl *VD = dyn_cast<VarDecl>(*it);
            const EnumDecl *ED = dyn_cast<EnumDecl>(*it);
            const RecordDecl *RD = dyn_cast<RecordDecl>(*it);
            if (FD) {
                printFuncDecl(FD);
            }
            else if (VD) {
                printVarDecl(VD);
            }
            else if (ED) {
                printEnumDecl(ED);
            }
            else if (RD) {
                printRecordDecl(RD);
            }
        }
    }

<commit_msg>in bindings generator, generate 'RawPointer' for void pointers, because Pointer[Void] is not a valid type in clay.<commit_after>/* vim: set sw=4 ts=4: */
/*
 * BindingConverter.cpp
 * Implements an AST Consumer that outputs clay bindings
 *
 */

#include <iostream>
#include <vector>
using namespace std;

#include "llvm/Config/config.h"
#include "llvm/Support/raw_ostream.h"

#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "llvm/ADT/Triple.h"

#include "BindingsConverter.h"

using namespace clang;
using namespace llvm;

BindingsConverter::BindingsConverter(bool useCTypes, ostream& out)
    :useCTypes(useCTypes), out(out) {
    }

void BindingsConverter::printHeader()
{
    // Print header
    string header = "# Auto-Generated by BindingsGenerator\n";
    header += "import types.*;\n";
    header += "import operators.*;\n";
    header += "import numbers.*;\n";
    header += "import pointers.*;\n";

    out << header;
}

void BindingsConverter::printFooter()
{

}

// Print a variable in clay
void BindingsConverter::printVarDecl(const VarDecl*& D) {
    out << "external ";
    out << D->getNameAsString();
    QualType type = D->getType();       // The return value
    if(useCTypes) {
        out << " : " << type.getAsString() << ";\n";
    }
    else {
        out << " : " << printType(convert(type)) << ";\n";
    }
}

// Print a function in clay
void BindingsConverter::printFuncDecl(const FunctionDecl*& D) {
    out << "external ";
    out << D->getNameAsString() << " (\n";
    int numParams = D->param_size();
    for( int i = 0 ; i < numParams ; i ++ ) {
        const ParmVarDecl * param = D->getParamDecl(i);        // Parameter number i
        const string name = param -> getNameAsString();
        if(name != "")
            out << "\t" << name << " : ";
        else
            out << "\t" << "argument_" << i + 1<< " : ";
        QualType cType = param->getOriginalType();
        if(useCTypes) {
            out << cType.getAsString();
        }
        else {
            out << printType(convert(cType));
        }
        if (i+1 < numParams)
            out << ",";
        out << "\n";
    }
    QualType ret = D->getResultType();       // The return value
    if(useCTypes) {
        out << ") : " << ret.getAsString() << ";\n";
    }
    else {
        out << ") : " << printType(convert(ret)) << ";\n";
    }
}

// Print a enum in clay
void BindingsConverter::printEnumDecl(const EnumDecl*& D) {
    for(EnumDecl::enumerator_iterator it = D->enumerator_begin(); it != D->enumerator_end(); it++)
    {
        EnumConstantDecl* CD = *it;
        out << "static " << CD->getNameAsString() << " = " ;
        out << CD->getInitVal().getLimitedValue() << ";\n"; // XXX: Warning, this limits enum values to 64-bits which is safe, I think
    }
}

// Print a record in clay
void BindingsConverter::printRecordDecl(const RecordDecl*& D) {
    out << "record " << D->getNameAsString() << " {\n";
    for(RecordDecl::field_iterator it = D->field_begin(); it != D->field_end(); it++)
    {
        FieldDecl* FD = *it;
        QualType type = FD->getType();

        out << FD->getNameAsString();
        if(useCTypes) {
            out << " : " << type.getAsString() << ";\n";
        }
        else {
            out << " : " << printType(convert(type)) << ";\n";
        }
    }
    out << "}\n";
}

QualType& BindingsConverter::convert(QualType& cType) {
    return cType;
}

string BindingsConverter::printType(const QualType& qtype) {
    Type& type = *qtype;

    if(type.isBooleanType()) {
        return "Bool";
    }
    else if(type.isSignedIntegerType()){
        return "Int";
    }
    else if(type.isUnsignedIntegerType()){
        return "UInt";
    }
    else if(type.isRealFloatingType()) {
        return "Float";
    }
    else if(type.isPointerType()) {
        PointerType& type_ = (PointerType&)type;
        QualType qtype_ = type_.getPointeeType();
        if((*qtype_).isFunctionType())
        {
            FunctionProtoType& ftype = (FunctionProtoType&) *qtype_;
            string typeStr = "CCodePtr[";
            for(FunctionProtoType::arg_type_iterator it = ftype.arg_type_begin(); it != ftype.arg_type_end(); it++) {
                QualType qtype = *it;
                typeStr += printType(qtype);
                typeStr += ",";
            }
            QualType qtype = ftype.getResultType();
            typeStr += printType(qtype);
            typeStr += "]";

            return typeStr;
        }
        else
        {
            if (qtype_.isVoidType())
                return "RawPointer";
            return "Pointer[" + printType(qtype_) + "]";
        }
    }
    else if(type.isArrayType()) {
      ArrayType& type_ = (ArrayType&)type;
      return "Array[" + printType(type_.getElementType()) + "]";
    }
    else if(type.isRecordType()) {
        // TODO: Handle
        //case RECORD_TYPE : {
        //    RecordType *x = (RecordType *)t.ptr();
        //    out << x->record->name->str;
        //    if (!x->params.empty())
        //        out << x->params;
        //    break;
        return qtype.getAsString();
    }
    else if(type.isEnumeralType()) {
        return "Enum";
    }
    else if(type.isVoidType()) {
        return "Void";
    }
    else{
        return "???";
        //assert(false);
    }

    return "null";
    }

    // Handle top level declarations observed in the program
    void BindingsConverter::HandleTopLevelDecl(DeclGroupRef DG) {
        for (DeclGroupRef::iterator it = DG.begin(); it != DG.end(); ++it) {
            const FunctionDecl *FD = dyn_cast<FunctionDecl>(*it);
            const VarDecl *VD = dyn_cast<VarDecl>(*it);
            const EnumDecl *ED = dyn_cast<EnumDecl>(*it);
            const RecordDecl *RD = dyn_cast<RecordDecl>(*it);
            if (FD) {
                printFuncDecl(FD);
            }
            else if (VD) {
                printVarDecl(VD);
            }
            else if (ED) {
                printEnumDecl(ED);
            }
            else if (RD) {
                printRecordDecl(RD);
            }
        }
    }

<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "RndPointSet.h"

RndPointSet::RndPointSet(void)
{
}

RndPointSet::~RndPointSet(void)
{

}

void RndPointSet::DrawPoints( const CRhinoCommandContext& context, int numPoints )
{

  // Pick a surface to evaluate
  CRhinoGetObject go;
  go.SetCommandPrompt( L"Select surface to evaluate " );
  go.SetGeometryFilter( CRhinoGetObject::surface_object);
  go.GetObjects( 1, 1 );

  // Get the surface geometry
  const CRhinoObjRef& ref = go.Object(0);

  if(ref == NULL)
  {
	RhinoApp().Print(L"reference initialization error");
	return ;
  }

  const ON_Surface* obj = ref.Surface();

  if(obj == NULL)
  {
	RhinoApp().Print(L"object initialization error");
	return ;
  }

  double u1, u2, v1, v2;

  if(obj->GetDomain(0, &u1, &u2) && obj->GetDomain(1, &v1, &v2))
  {
	  int i;
	  for(i = 0; i < numPoints; i++)
	  {
		  ON_3dPoint p0 = obj->PointAt( fRand(u1, u2), fRand(v1, v2));
		  //context.m_doc.AddPointObject(p0);
		  //RhinoApp().Print(L"p0.x = %f\n",p0.x);
		  //RhinoApp().Print(L"p0.y = %f\n",p0.y);
		  //RhinoApp().Print(L"p0.z = %f\n",p0.z);
		  double u, v = 0.0;						//the following might be redundant
		  obj->GetClosestPoint(p0, &u, &v);
		  //RhinoApp().Print(L"p0.u = %f\n",u);
		  //RhinoApp().Print(L"p0.v = %f\n",v);
		  ON_3dPoint p1 = obj->PointAt( u, v);

		  context.m_doc.AddPointObject(p1);
	  }
	  context.m_doc.Redraw();
  }
  else
  {
	RhinoApp().Print(L"object domain error");
	return ;
  }

}

void RndPointSet::Test( const CRhinoCommandContext& context, double a, double b, double c, double d )
{
  // Pick a surface to evaluate
  CRhinoGetObject go;
  go.SetCommandPrompt( L"Select surface to evaluate - test function" );
  go.SetGeometryFilter( CRhinoGetObject::surface_object);
  go.GetObjects( 1, 1 );

  // Get the surface geometry
  const CRhinoObjRef& ref = go.Object(0);
  const ON_Surface* obj = ref.Surface();

  ON_3dPoint p0 = obj->PointAt( a, b);
  double u, v;
  obj->GetClosestPoint(p0, &u, &v);
  ON_3dPoint p1 = obj->PointAt( u, v);

  context.m_doc.AddPointObject(p1);
  context.m_doc.Redraw();
}

double RndPointSet::fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}<commit_msg>Revert "fixed the issue with points out of bounds."<commit_after>#include "StdAfx.h"
#include "RndPointSet.h"

RndPointSet::RndPointSet(void)
{
}

RndPointSet::~RndPointSet(void)
{

}

void RndPointSet::DrawPoints( const CRhinoCommandContext& context, int numPoints )
{

  // Pick a surface to evaluate
  CRhinoGetObject go;
  go.SetCommandPrompt( L"Select surface to evaluate" );
  go.SetGeometryFilter( CRhinoGetObject::surface_object);
  go.GetObjects( 1, 1 );

  // Get the surface geometry
  const CRhinoObjRef& ref = go.Object(0);
  const ON_Surface* obj = ref.Surface();

  double u1, u2, v1, v2;

  if(obj->GetDomain(0, &u1, &u2) && obj->GetDomain(0, &v1, &v2))
  {
	  int i;
	  for(i = 0; i < numPoints; i++)
	  {
		  ON_3dPoint p0 = obj->PointAt( fRand(u1, u2), fRand(v1, v2));
		  double u, v;
		  obj->GetClosestPoint(p0, &u, &v);
		  ON_3dPoint p1 = obj->PointAt( u, v);

		  context.m_doc.AddPointObject(p1);
	  }
	  context.m_doc.Redraw();
  }

 //this is drawing things outside the bounding box for some reason
}

void RndPointSet::Test( const CRhinoCommandContext& context, double a, double b, double c, double d )
{
  // Pick a surface to evaluate
  CRhinoGetObject go;
  go.SetCommandPrompt( L"Select surface to evaluate - test function" );
  go.SetGeometryFilter( CRhinoGetObject::surface_object);
  go.GetObjects( 1, 1 );

  // Get the surface geometry
  const CRhinoObjRef& ref = go.Object(0);
  const ON_Surface* obj = ref.Surface();

  ON_3dPoint p0 = obj->PointAt( a, b);
  double u, v;
  obj->GetClosestPoint(p0, &u, &v);
  ON_3dPoint p1 = obj->PointAt( u, v);

  context.m_doc.AddPointObject(p1);
  context.m_doc.Redraw();
}

double RndPointSet::fRand(double fMin, double fMax)
{
    double f = (double)rand() / RAND_MAX;
    return fMin + f * (fMax - fMin);
}<|endoftext|>


<commit_before>#include "Physics.hpp"

#include "PhysicEngine.hpp"

Physics::Physics()
  : Component(),
    m_growth(sf::Vector2f(1, 1) )
{
}

Physics::~Physics()
{

}

void Physics::update()
{
  //  PhysicEngine::update(this);
}

void Physics::setVelocity(const sf::Vector2f& values )
{
  m_velocity = values;
}

sf::Vector2f Physics::getVelocity() const{
  return m_velocity;
}

void Physics::setRotationForce(const float& value )
{
  m_rotationForce = value;
}

float Physics::getRotationForce() const{
  return m_rotationForce;
}

void Physics::setGrowth(const sf::Vector2f& values )
{
  m_growth += values;
}

sf::Vector2f Physics::getGrowth() const{
  return m_growth;
}

void Physics::setAcceleration(const sf::Vector2f& value )
{
  m_acceleration = value;
}

sf::Vector2f Physics::getAcceleration() const{
  return m_acceleration;
}

void Physics::setRotationAcceleration(const float& value )
{
  m_rotationAcc = value;
}

float Physics::getRotationAcceleration() const{
  return m_rotationAcc;
}

void Physics::setGrowthAcceleration(const sf::Vector2f& value )
{
  m_growthAcc = value;
}

sf::Vector2f Physics::getGrowthAcceleration() const{
  return m_growthAcc;
}

void Physics::setMass(const double& value )
{
  m_mass = value;
}

double Physics::getMass() const{
  return m_mass;
}

void Physics::addMass(const double& value )
{
  m_mass += value;
}

/**
 * adds values to velocity
 */
void Physics::addVelocity(const sf::Vector2f& values )
{
  m_velocity += values;
}

/**
   acceleration adds to velocity on each frame
*/
void Physics::addAcceleration(const sf::Vector2f& value )
{
 m_acceleration += value;
}

/**
   adds value to rotation force
*/
void Physics::addRotationForce(const float& value )
{
  m_rotationForce += value;
}

void Physics::addRotationAcceleration(const float& value )
{
  m_rotationAcc += value;
}

/**
   adds value to growth force
*/
void Physics::addGrowth(const sf::Vector2f& values )
{
  m_growth += values;
}

void Physics::addGrowthAcceleration(const sf::Vector2f& values )
{
  m_growthAcc += values;
}

<commit_msg>Fixed setGrowth<commit_after>#include "Physics.hpp"

#include "PhysicEngine.hpp"

Physics::Physics()
  : Component(),
    m_growth(sf::Vector2f(1, 1) )
{
}

Physics::~Physics()
{

}

void Physics::update()
{
  //  PhysicEngine::update(this);
}

void Physics::setVelocity(const sf::Vector2f& values )
{
  m_velocity = values;
}

sf::Vector2f Physics::getVelocity() const{
  return m_velocity;
}

void Physics::setRotationForce(const float& value )
{
  m_rotationForce = value;
}

float Physics::getRotationForce() const{
  return m_rotationForce;
}

void Physics::setGrowth(const sf::Vector2f& values )
{
  m_growth = values;
}

sf::Vector2f Physics::getGrowth() const{
  return m_growth;
}

void Physics::setAcceleration(const sf::Vector2f& value )
{
  m_acceleration = value;
}

sf::Vector2f Physics::getAcceleration() const{
  return m_acceleration;
}

void Physics::setRotationAcceleration(const float& value )
{
  m_rotationAcc = value;
}

float Physics::getRotationAcceleration() const{
  return m_rotationAcc;
}

void Physics::setGrowthAcceleration(const sf::Vector2f& value )
{
  m_growthAcc = value;
}

sf::Vector2f Physics::getGrowthAcceleration() const{
  return m_growthAcc;
}

void Physics::setMass(const double& value )
{
  m_mass = value;
}

double Physics::getMass() const{
  return m_mass;
}

void Physics::addMass(const double& value )
{
  m_mass += value;
}

/**
 * adds values to velocity
 */
void Physics::addVelocity(const sf::Vector2f& values )
{
  m_velocity += values;
}

/**
   acceleration adds to velocity on each frame
*/
void Physics::addAcceleration(const sf::Vector2f& value )
{
 m_acceleration += value;
}

/**
   adds value to rotation force
*/
void Physics::addRotationForce(const float& value )
{
  m_rotationForce += value;
}

void Physics::addRotationAcceleration(const float& value )
{
  m_rotationAcc += value;
}

/**
   adds value to growth force
*/
void Physics::addGrowth(const sf::Vector2f& values )
{
  m_growth += values;
}

void Physics::addGrowthAcceleration(const sf::Vector2f& values )
{
  m_growthAcc += values;
}

<|endoftext|>


<commit_before>#include <iostream>
#include "TAxis.h"
#include "Corrector.h"

ClassImp(Corrector)

//--------------------------------------------------------------------
Corrector::Corrector(TString name) :
  fName(name),
  fInTree(NULL),
  fCorrectionFile(NULL),
  fCorrectionHist(NULL),
  fNumDims(0),
  fInCut('1'),
  fCutFormula(NULL)
{
  fInExpressions.resize(0);
  fFormulas.resize(0);
  fMins.resize(0);
  fMaxs.resize(0);
}

//--------------------------------------------------------------------
Corrector::~Corrector()
{
  if (fCorrectionFile != NULL) {
    if (fCorrectionFile->IsOpen())
      fCorrectionFile->Close();
  }

  if (fCutFormula != NULL)
    delete fCutFormula;

  for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula)
    delete fFormulas[iFormula];
}

//--------------------------------------------------------------------
void
Corrector::SetCorrectionHist(TString hist1, TString hist2)
{
  fCorrectionHist  = (TH1*) fCorrectionFile->Get(hist1);
  TH1* divisorHist = (TH1*) fCorrectionFile->Get(hist2);
  fCorrectionHist->Divide(divisorHist);
  SetMinMax();
}

//--------------------------------------------------------------------
Double_t
Corrector::GetFormulaResult(Int_t index)
{
  Double_t eval = fFormulas[index]->EvalInstance();
  if (eval < fMins[index])
    eval = fMins[index];
  else if (eval > fMaxs[index])
    eval = fMaxs[index];
  return eval;
}

//--------------------------------------------------------------------
Float_t
Corrector::Evaluate()
{
  if (fInTree == NULL)
    return 1.0;
  else {
    if (fCutFormula->EvalInstance() != 0) {
      if (fNumDims == 1) {
        Double_t evalX = GetFormulaResult(0);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX));
      }
      else if (fNumDims == 2) {
        Double_t evalX = GetFormulaResult(0);
        Double_t evalY = GetFormulaResult(1);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX),
                                              fCorrectionHist->FindBin(evalY));
      }
      else if (fNumDims == 3) {
        Double_t evalX = GetFormulaResult(0);
        Double_t evalY = GetFormulaResult(1);
        Double_t evalZ = GetFormulaResult(2);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX),
                                              fCorrectionHist->FindBin(evalY),
                                              fCorrectionHist->FindBin(evalZ));
      }
      else
        return 1.0;
    }
    else
      return 1.0;
  }
}

//--------------------------------------------------------------------
void
Corrector::InitializeTree()
{
  if (fCutFormula)
    delete fCutFormula;

  fCutFormula = new TTreeFormula(fInCut,fInCut,fInTree);

  if (fFormulas.size() != 0) {
    for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula)
      delete fFormulas[iFormula];
    fFormulas.resize(0);
  }

  TTreeFormula* tempFormula;
  for (UInt_t iExpression = 0; iExpression != fInExpressions.size(); ++iExpression) {
    tempFormula = new TTreeFormula(fInExpressions[iExpression],fInExpressions[iExpression],fInTree);
    fFormulas.push_back(tempFormula);
  }
}

//--------------------------------------------------------------------
void
Corrector::SetMinMax()
{
  for (Int_t iDim = 0; iDim != fNumDims; ++iDim) {
    TAxis* theAxis;
    if (iDim == 0)
      theAxis = fCorrectionHist->GetXaxis();
    else if (iDim == 1)
      theAxis = fCorrectionHist->GetYaxis();
    else if (iDim == 2)
      theAxis = fCorrectionHist->GetZaxis();
    else {
      std::cout << "I don't support this many axes at the moment." << std::endl;
      exit(3);
    }
    fMins.push_back(theAxis->GetBinLowEdge(theAxis->GetFirst()));
    fMaxs.push_back(theAxis->GetBinUpEdge(theAxis->GetLast()));
  }
}
<commit_msg>Changed min max to ensure placement in bins.<commit_after>#include <iostream>
#include "TAxis.h"
#include "Corrector.h"

ClassImp(Corrector)

//--------------------------------------------------------------------
Corrector::Corrector(TString name) :
  fName(name),
  fInTree(NULL),
  fCorrectionFile(NULL),
  fCorrectionHist(NULL),
  fNumDims(0),
  fInCut('1'),
  fCutFormula(NULL)
{
  fInExpressions.resize(0);
  fFormulas.resize(0);
  fMins.resize(0);
  fMaxs.resize(0);
}

//--------------------------------------------------------------------
Corrector::~Corrector()
{
  if (fCorrectionFile != NULL) {
    if (fCorrectionFile->IsOpen())
      fCorrectionFile->Close();
  }

  if (fCutFormula != NULL)
    delete fCutFormula;

  for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula)
    delete fFormulas[iFormula];
}

//--------------------------------------------------------------------
void
Corrector::SetCorrectionHist(TString hist1, TString hist2)
{
  fCorrectionHist  = (TH1*) fCorrectionFile->Get(hist1);
  TH1* divisorHist = (TH1*) fCorrectionFile->Get(hist2);
  fCorrectionHist->Divide(divisorHist);
  SetMinMax();
}

//--------------------------------------------------------------------
Double_t
Corrector::GetFormulaResult(Int_t index)
{
  Double_t eval = fFormulas[index]->EvalInstance();
  if (eval < fMins[index])
    eval = fMins[index];
  else if (eval > fMaxs[index])
    eval = fMaxs[index];
  return eval;
}

//--------------------------------------------------------------------
Float_t
Corrector::Evaluate()
{
  if (fInTree == NULL)
    return 1.0;
  else {
    if (fCutFormula->EvalInstance() != 0) {
      if (fNumDims == 1) {
        Double_t evalX = GetFormulaResult(0);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX));
      }
      else if (fNumDims == 2) {
        Double_t evalX = GetFormulaResult(0);
        Double_t evalY = GetFormulaResult(1);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX),
                                              fCorrectionHist->FindBin(evalY));
      }
      else if (fNumDims == 3) {
        Double_t evalX = GetFormulaResult(0);
        Double_t evalY = GetFormulaResult(1);
        Double_t evalZ = GetFormulaResult(2);
        return fCorrectionHist->GetBinContent(fCorrectionHist->FindBin(evalX),
                                              fCorrectionHist->FindBin(evalY),
                                              fCorrectionHist->FindBin(evalZ));
      }
      else
        return 1.0;
    }
    else
      return 1.0;
  }
}

//--------------------------------------------------------------------
void
Corrector::InitializeTree()
{
  if (fCutFormula)
    delete fCutFormula;

  fCutFormula = new TTreeFormula(fInCut,fInCut,fInTree);

  if (fFormulas.size() != 0) {
    for (UInt_t iFormula = 0; iFormula != fFormulas.size(); ++iFormula)
      delete fFormulas[iFormula];
    fFormulas.resize(0);
  }

  TTreeFormula* tempFormula;
  for (UInt_t iExpression = 0; iExpression != fInExpressions.size(); ++iExpression) {
    tempFormula = new TTreeFormula(fInExpressions[iExpression],fInExpressions[iExpression],fInTree);
    fFormulas.push_back(tempFormula);
  }
}

//--------------------------------------------------------------------
void
Corrector::SetMinMax()
{
  for (Int_t iDim = 0; iDim != fNumDims; ++iDim) {
    TAxis* theAxis;
    if (iDim == 0)
      theAxis = fCorrectionHist->GetXaxis();
    else if (iDim == 1)
      theAxis = fCorrectionHist->GetYaxis();
    else if (iDim == 2)
      theAxis = fCorrectionHist->GetZaxis();
    else {
      std::cout << "I don't support this many axes at the moment." << std::endl;
      exit(3);
    }
    fMins.push_back(theAxis->GetBinCenter(theAxis->GetFirst()));
    fMaxs.push_back(theAxis->GetBinCenter(theAxis->GetLast()));
  }
}
<|endoftext|>