<commit_before>/**
 *    @file  main.cc
 *   @brief  gcsa_locate main program.
 *
 *  Uses GCSA2 index to locate k-mers in the underlying graph.
 *
 *  @author  Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de>
 *
 *  @internal
 *       Created:  Thu Aug 03, 2017  04:37
 *  Organization:  Max-Planck-Institut fuer Informatik
 *     Copyright:  Copyright (c) 2017, Ali Ghaffaari
 *
 *  This source code is released under the terms of the MIT License.
 *  See LICENSE file for more information.
 */

#include <cstdlib>
#include <fstream>
#include <vector>
#include <string>

#include <seqan/arg_parse.h>
#include <gcsa/gcsa.h>

#include <config.h>
#include "seed.h"
#include "timer.h"
#include "options.h"
#include "release.h"

  seqan::ArgumentParser::ParseResult
parse_args( Options& options, int argc, char* argv[] );

  void
setup_argparser( seqan::ArgumentParser& parser );

  inline void
get_option_values( Options& options, seqan::ArgumentParser& parser );

  void
locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len,
    bool nonoverlapping, std::string& output_name );

  int
main( int argc, char* argv[] )
{
  // Parse the command line.
  Options options;
  auto res = parse_args( options, argc, argv );
  // If parsing was not successful then exit with code 1 if there were errors.
  // Otherwise, exit with code 0 (e.g. help was printed).
  if (res != seqan::ArgumentParser::PARSE_OK)
    return res == seqan::ArgumentParser::PARSE_ERROR;

  locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len,
      options.nonoverlapping, options.output_filename );

  return EXIT_SUCCESS;
}

  void
locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len,
    bool nonoverlapping, std::string& output_name )
{
  std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary );
  if ( !seq_file ) {
    throw std::runtime_error("could not open file '" + seq_name + "'" );
  }
  std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary );
  if ( !gcsa_file ) {
    throw std::runtime_error("could not open file '" + gcsa_name + "'" );
  }
  gcsa::GCSA index;
  std::vector< std::string > sequences;
  std::vector< std::string > patterns;
  std::vector< gcsa::node_type > results;

  std::cout << "Loading GCSA index..." << std::endl;
  index.load( gcsa_file );
  std::cout << "Loading sequences..." << std::endl;
  {
    auto timer = Timer( "sequences" );
    std::string line;
    while ( std::getline( seq_file, line ) ) {
      sequences.push_back( line );
    }
  }
  std::cout << "Loaded " << sequences.size() << " sequences in "
            << Timer::get_duration( "sequences" ).count() << " us." << std::endl;
  std::cout << "Generating patterns..." << std::endl;
  {
    auto timer = Timer( "patterns" );
    if ( nonoverlapping ) {
      seeding( patterns, sequences, seed_len, GreedyNonOverlapping() );
    }
    else {
      seeding( patterns, sequences, seed_len, GreedyOverlapping() );
    }
  }
  std::cout << "Generated " << patterns.size() << " patterns in "
            << Timer::get_duration( "patterns" ).count() << " us." << std::endl;
  std::cout << "Locating patterns..." << std::endl;
  {
    auto timer = Timer( "locate" );
    for ( const auto& p : patterns ) {
      gcsa::range_type range = index.find( p );
      index.locate( range, results, true );
    }
  }
  std::cout << "Located " << results.size() << " occurrences in "
            << Timer::get_duration( "locate" ).count() << " us." << std::endl;
  std::cout << "Writing occurrences into file..." << std::endl;
  std::ofstream output_file( output_name, std::ofstream::out );
  for ( auto && r : results ) {
    output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl;
  }
}

  inline seqan::ArgumentParser::ParseResult
parse_args( Options& options, int argc, char* argv[] )
{
  // setup ArgumentParser.
  seqan::ArgumentParser parser( release::name );
  setup_argparser( parser );
  // Embedding program's meta data and build information.
  setShortDescription( parser, release::short_desc );
  setVersion( parser, release::version );
  setDate( parser, LAST_MOD_DATE );
  addDescription( parser, release::desc );
  // parse command line.
  auto res = seqan::parse( parser, argc, argv );
  // only extract options if the program will continue after parse_args()
  if ( res != seqan::ArgumentParser::PARSE_OK ) {
    return res;
  }

  get_option_values( options, parser );

  return seqan::ArgumentParser::PARSE_OK;
}

  inline void
setup_argparser( seqan::ArgumentParser& parser )
{
  // positional arguments.
  std::string POSARG1 = "SEQ_FILE";
  // add usage line.
  addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\"");
  // sequence file -- positional argument.
  seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 );
  addArgument( parser, seq_arg );
  // GCSA2 index file -- **required** option.
  seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.",
      seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" );
  setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION );
  addOption( parser, gcsa_arg );
  setRequired( parser, "g" );
  // Seed length.
  addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.",
        seqan::ArgParseArgument::INTEGER, "INT" ) );
  setRequired( parser, "l" );
  // Overlapping seeds?
  addOption( parser, seqan::ArgParseOption( "n", "non-overlapping",
        "Use non-overlapping seeds." ) );
  // Output file.
  seqan::ArgParseOption output_arg( "o", "output",
      "Write positions where sequences are matched.",
      seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" );
  addOption( parser, output_arg );
  setRequired( parser, "o" );
}

  inline void
get_option_values( Options& options, seqan::ArgumentParser& parser )
{
  getArgumentValue( options.seq_filename, parser, 0 );
  getOptionValue( options.gcsa_filename, parser, "gcsa" );
  getOptionValue( options.output_filename, parser, "output" );
  getOptionValue( options.seed_len, parser, "seed-len" );
  options.nonoverlapping = isSet( parser, "non-overlapping" );
}
<commit_msg>Handle SIGUSR1 for reporting<commit_after>/**
 *    @file  main.cc
 *   @brief  gcsa_locate main program.
 *
 *  Uses GCSA2 index to locate k-mers in the underlying graph.
 *
 *  @author  Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de>
 *
 *  @internal
 *       Created:  Thu Aug 03, 2017  04:37
 *  Organization:  Max-Planck-Institut fuer Informatik
 *     Copyright:  Copyright (c) 2017, Ali Ghaffaari
 *
 *  This source code is released under the terms of the MIT License.
 *  See LICENSE file for more information.
 */

#include <cstdlib>
#include <csignal>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include <seqan/arg_parse.h>
#include <gcsa/gcsa.h>

#include <config.h>
#include "seed.h"
#include "timer.h"
#include "options.h"
#include "release.h"

  seqan::ArgumentParser::ParseResult
parse_args( Options& options, int argc, char* argv[] );

  void
setup_argparser( seqan::ArgumentParser& parser );

  inline void
get_option_values( Options& options, seqan::ArgumentParser& parser );

  void
locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len,
    bool nonoverlapping, std::string& output_name );

  void
signal_handler( int signal );

std::size_t done_idx = 0;
std::size_t total_no = 0;

  int
main( int argc, char* argv[] )
{
  // Parse the command line.
  Options options;
  auto res = parse_args( options, argc, argv );
  // If parsing was not successful then exit with code 1 if there were errors.
  // Otherwise, exit with code 0 (e.g. help was printed).
  if (res != seqan::ArgumentParser::PARSE_OK)
    return res == seqan::ArgumentParser::PARSE_ERROR;

  /* Install signal handler */
  std::signal( SIGUSR1, signal_handler );

  locate_seeds( options.seq_filename, options.gcsa_filename, options.seed_len,
      options.nonoverlapping, options.output_filename );

  return EXIT_SUCCESS;
}

  void
signal_handler( int signal )
{
  std::cout << "Located " << ::done_idx << " out of " << ::total_no << " in "
            << Timer::get_lap( "locate" ).count() << " us: "
            << ::done_idx * 100 / total_no << "% done." << std::endl;
}

  void
locate_seeds( std::string& seq_name, std::string& gcsa_name, unsigned int seed_len,
    bool nonoverlapping, std::string& output_name )
{
  std::ifstream seq_file( seq_name, std::ifstream::in | std::ifstream::binary );
  if ( !seq_file ) {
    throw std::runtime_error("could not open file '" + seq_name + "'" );
  }
  std::ifstream gcsa_file( gcsa_name, std::ifstream::in | std::ifstream::binary );
  if ( !gcsa_file ) {
    throw std::runtime_error("could not open file '" + gcsa_name + "'" );
  }
  gcsa::GCSA index;
  std::vector< std::string > sequences;
  std::vector< std::string > patterns;
  std::vector< gcsa::node_type > results;

  std::cout << "Loading GCSA index..." << std::endl;
  index.load( gcsa_file );
  std::cout << "Loading sequences..." << std::endl;
  {
    auto timer = Timer( "sequences" );
    std::string line;
    while ( std::getline( seq_file, line ) ) {
      sequences.push_back( line );
    }
  }
  std::cout << "Loaded " << sequences.size() << " sequences in "
            << Timer::get_duration( "sequences" ).count() << " us." << std::endl;
  std::cout << "Generating patterns..." << std::endl;
  {
    auto timer = Timer( "patterns" );
    if ( nonoverlapping ) {
      seeding( patterns, sequences, seed_len, GreedyNonOverlapping() );
    }
    else {
      seeding( patterns, sequences, seed_len, GreedyOverlapping() );
    }
  }
  ::total_no = patterns.size();
  std::cout << "Generated " << patterns.size() << " patterns in "
            << Timer::get_duration( "patterns" ).count() << " us." << std::endl;
  std::cout << "Locating patterns..." << std::endl;
  {
    auto timer = Timer( "locate" );
    for ( const auto& p : patterns ) {
      gcsa::range_type range = index.find( p );
      index.locate( range, results, true );
      ::done_idx++;
    }
  }
  std::cout << "Located " << results.size() << " occurrences in "
            << Timer::get_duration( "locate" ).count() << " us." << std::endl;
  std::cout << "Writing occurrences into file..." << std::endl;
  std::ofstream output_file( output_name, std::ofstream::out );
  for ( auto && r : results ) {
    output_file << gcsa::Node::id( r ) << "\t" << gcsa::Node::offset( r ) << std::endl;
  }
}

  inline seqan::ArgumentParser::ParseResult
parse_args( Options& options, int argc, char* argv[] )
{
  // setup ArgumentParser.
  seqan::ArgumentParser parser( release::name );
  setup_argparser( parser );
  // Embedding program's meta data and build information.
  setShortDescription( parser, release::short_desc );
  setVersion( parser, release::version );
  setDate( parser, LAST_MOD_DATE );
  addDescription( parser, release::desc );
  // parse command line.
  auto res = seqan::parse( parser, argc, argv );
  // only extract options if the program will continue after parse_args()
  if ( res != seqan::ArgumentParser::PARSE_OK ) {
    return res;
  }

  get_option_values( options, parser );

  return seqan::ArgumentParser::PARSE_OK;
}

  inline void
setup_argparser( seqan::ArgumentParser& parser )
{
  // positional arguments.
  std::string POSARG1 = "SEQ_FILE";
  // add usage line.
  addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fI" + POSARG1 + "\\fP\"");
  // sequence file -- positional argument.
  seqan::ArgParseArgument seq_arg( seqan::ArgParseArgument::INPUT_FILE, POSARG1 );
  addArgument( parser, seq_arg );
  // GCSA2 index file -- **required** option.
  seqan::ArgParseOption gcsa_arg( "g", "gcsa", "GCSA2 index file.",
      seqan::ArgParseArgument::INPUT_FILE, "GCSA2_FILE" );
  setValidValues( gcsa_arg, gcsa::GCSA::EXTENSION );
  addOption( parser, gcsa_arg );
  setRequired( parser, "g" );
  // Seed length.
  addOption( parser, seqan::ArgParseOption( "l", "seed-len", "Seed length.",
        seqan::ArgParseArgument::INTEGER, "INT" ) );
  setRequired( parser, "l" );
  // Overlapping seeds?
  addOption( parser, seqan::ArgParseOption( "n", "non-overlapping",
        "Use non-overlapping seeds." ) );
  // Output file.
  seqan::ArgParseOption output_arg( "o", "output",
      "Write positions where sequences are matched.",
      seqan::ArgParseArgument::OUTPUT_FILE, "OUTPUT" );
  addOption( parser, output_arg );
  setRequired( parser, "o" );
}

  inline void
get_option_values( Options& options, seqan::ArgumentParser& parser )
{
  getArgumentValue( options.seq_filename, parser, 0 );
  getOptionValue( options.gcsa_filename, parser, "gcsa" );
  getOptionValue( options.output_filename, parser, "output" );
  getOptionValue( options.seed_len, parser, "seed-len" );
  options.nonoverlapping = isSet( parser, "non-overlapping" );
}
<|endoftext|>


<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
//                     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 family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;

//===----------------------------------------------------------------------===//
//  Local constant propagation...
//

/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
  if (Constant *C = ConstantFoldInstruction(II)) {
    // Replaces all of the uses of a variable with uses of the constant.
    II->replaceAllUsesWith(C);

    // Remove the instruction from the basic block...
    II = II->getParent()->getInstList().erase(II);
    return true;
  }

  return false;
}

/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction.  If successful, the constant result is returned, if not, null
/// is returned.  Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
  if (PHINode *PN = dyn_cast<PHINode>(I)) {
    if (PN->getNumIncomingValues() == 0)
      return Constant::getNullValue(PN->getType());

    Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
    if (Result == 0) return 0;

    // Handle PHI nodes specially here...
    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
      if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
        return 0;   // Not all the same incoming constants...

    // If we reach here, all incoming values are the same constant.
    return Result;
  } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
    if (Function *F = CI->getCalledFunction())
      if (canConstantFoldCallTo(F)) {
        std::vector<Constant*> Args;
        for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
          if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
            Args.push_back(Op);
          else
            return 0;
        return ConstantFoldCall(F, Args);
      }
    return 0;
  }

  Constant *Op0 = 0, *Op1 = 0;
  switch (I->getNumOperands()) {
  default:
  case 2:
    Op1 = dyn_cast<Constant>(I->getOperand(1));
    if (Op1 == 0) return 0;        // Not a constant?, can't fold
  case 1:
    Op0 = dyn_cast<Constant>(I->getOperand(0));
    if (Op0 == 0) return 0;        // Not a constant?, can't fold
    break;
  case 0: return 0;
  }

  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
    return ConstantExpr::get(I->getOpcode(), Op0, Op1);

  switch (I->getOpcode()) {
  default: return 0;
  case Instruction::Cast:
    return ConstantExpr::getCast(Op0, I->getType());
  case Instruction::Select:
    if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
      return ConstantExpr::getSelect(Op0, Op1, Op2);
    return 0;
  case Instruction::ExtractElement:
    return ConstantExpr::getExtractElement(Op0, Op1);
  case Instruction::GetElementPtr:
    std::vector<Constant*> IdxList;
    IdxList.reserve(I->getNumOperands()-1);
    if (Op1) IdxList.push_back(Op1);
    for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
      if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
        IdxList.push_back(C);
      else
        return 0;  // Non-constant operand
    return ConstantExpr::getGetElementPtr(Op0, IdxList);
  }
}

// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  TerminatorInst *T = BB->getTerminator();

  // Branch - See if we are conditional jumping on constant
  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
    BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
    BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));

    if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
      // Are we branching on constant?
      // YES.  Change to unconditional branch...
      BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
      BasicBlock *OldDest     = Cond->getValue() ? Dest2 : Dest1;

      //cerr << "Function: " << T->getParent()->getParent()
      //     << "\nRemoving branch from " << T->getParent()
      //     << "\n\nTo: " << OldDest << endl;

      // Let the basic block know that we are letting go of it.  Based on this,
      // it will adjust it's PHI nodes.
      assert(BI->getParent() && "Terminator not inserted in block!");
      OldDest->removePredecessor(BI->getParent());

      // Set the unconditional destination, and change the insn to be an
      // unconditional branch.
      BI->setUnconditionalDest(Destination);
      return true;
    } else if (Dest2 == Dest1) {       // Conditional branch to same location?
      // This branch matches something like this:
      //     br bool %cond, label %Dest, label %Dest
      // and changes it into:  br label %Dest

      // Let the basic block know that we are letting go of one copy of it.
      assert(BI->getParent() && "Terminator not inserted in block!");
      Dest1->removePredecessor(BI->getParent());

      // Change a conditional branch to unconditional.
      BI->setUnconditionalDest(Dest1);
      return true;
    }
  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
    // If we are switching on a constant, we can convert the switch into a
    // single branch instruction!
    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
    BasicBlock *DefaultDest = TheOnlyDest;
    assert(TheOnlyDest == SI->getDefaultDest() &&
           "Default destination is not successor #0?");

    // Figure out which case it goes to...
    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
      // Found case matching a constant operand?
      if (SI->getSuccessorValue(i) == CI) {
        TheOnlyDest = SI->getSuccessor(i);
        break;
      }

      // Check to see if this branch is going to the same place as the default
      // dest.  If so, eliminate it as an explicit compare.
      if (SI->getSuccessor(i) == DefaultDest) {
        // Remove this entry...
        DefaultDest->removePredecessor(SI->getParent());
        SI->removeCase(i);
        --i; --e;  // Don't skip an entry...
        continue;
      }

      // Otherwise, check to see if the switch only branches to one destination.
      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
      // destinations.
      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
    }

    if (CI && !TheOnlyDest) {
      // Branching on a constant, but not any of the cases, go to the default
      // successor.
      TheOnlyDest = SI->getDefaultDest();
    }

    // If we found a single destination that we can fold the switch into, do so
    // now.
    if (TheOnlyDest) {
      // Insert the new branch..
      new BranchInst(TheOnlyDest, SI);
      BasicBlock *BB = SI->getParent();

      // Remove entries from PHI nodes which we no longer branch to...
      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
        // Found case matching a constant operand?
        BasicBlock *Succ = SI->getSuccessor(i);
        if (Succ == TheOnlyDest)
          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
        else
          Succ->removePredecessor(BB);
      }

      // Delete the old switch...
      BB->getInstList().erase(SI);
      return true;
    } else if (SI->getNumSuccessors() == 2) {
      // Otherwise, we can fold this switch into a conditional branch
      // instruction if it has only one non-default destination.
      Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
                                    SI->getSuccessorValue(1), "cond", SI);
      // Insert the new branch...
      new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);

      // Delete the old switch...
      SI->getParent()->getInstList().erase(SI);
      return true;
    }
  }
  return false;
}

/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
                                                       ConstantExpr *CE) {
  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
    return 0;  // Do not allow stepping over the value!

  // Loop over all of the operands, tracking down which value we are
  // addressing...
  gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
  for (++I; I != E; ++I)
    if (const StructType *STy = dyn_cast<StructType>(*I)) {
      ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
      assert(CU->getValue() < STy->getNumElements() &&
             "Struct index out of range!");
      unsigned El = (unsigned)CU->getValue();
      if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
        C = CS->getOperand(El);
      } else if (isa<ConstantAggregateZero>(C)) {
        C = Constant::getNullValue(STy->getElementType(El));
      } else if (isa<UndefValue>(C)) {
        C = UndefValue::get(STy->getElementType(El));
      } else {
        return 0;
      }
    } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
      const ArrayType *ATy = cast<ArrayType>(*I);
      if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
      if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
        C = CA->getOperand((unsigned)CI->getRawValue());
      else if (isa<ConstantAggregateZero>(C))
        C = Constant::getNullValue(ATy->getElementType());
      else if (isa<UndefValue>(C))
        C = UndefValue::get(ATy->getElementType());
      else
        return 0;
    } else {
      return 0;
    }
  return C;
}

//===----------------------------------------------------------------------===//
//  Local dead code elimination...
//

bool llvm::isInstructionTriviallyDead(Instruction *I) {
  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;

  if (!I->mayWriteToMemory()) return true;

  if (CallInst *CI = dyn_cast<CallInst>(I))
    if (Function *F = CI->getCalledFunction())
      switch (F->getIntrinsicID()) {
      default: break;
      case Intrinsic::returnaddress:
      case Intrinsic::frameaddress:
      case Intrinsic::stacksave:
      case Intrinsic::isunordered_f32:
      case Intrinsic::isunordered_f64:
      case Intrinsic::bswap_i16:
      case Intrinsic::bswap_i32:
      case Intrinsic::bswap_i64:
      case Intrinsic::ctpop_i8:
      case Intrinsic::ctpop_i16:
      case Intrinsic::ctpop_i32:
      case Intrinsic::ctpop_i64:
      case Intrinsic::ctlz_i8:
      case Intrinsic::ctlz_i16:
      case Intrinsic::ctlz_i32:
      case Intrinsic::ctlz_i64:
      case Intrinsic::cttz_i8:
      case Intrinsic::cttz_i16:
      case Intrinsic::cttz_i32:
      case Intrinsic::cttz_i64:
      case Intrinsic::sqrt_f32:
      case Intrinsic::sqrt_f64:
        return true;             // These intrinsics have no side effects.
      }
  return false;
}

// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead.  If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
  // Look for un"used" definitions...
  if (isInstructionTriviallyDead(BBI)) {
    BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
    return true;
  }
  return false;
}
<commit_msg>Constant folding support for the insertelement operation.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
//                     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 family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;

//===----------------------------------------------------------------------===//
//  Local constant propagation...
//

/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
  if (Constant *C = ConstantFoldInstruction(II)) {
    // Replaces all of the uses of a variable with uses of the constant.
    II->replaceAllUsesWith(C);

    // Remove the instruction from the basic block...
    II = II->getParent()->getInstList().erase(II);
    return true;
  }

  return false;
}

/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction.  If successful, the constant result is returned, if not, null
/// is returned.  Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
  if (PHINode *PN = dyn_cast<PHINode>(I)) {
    if (PN->getNumIncomingValues() == 0)
      return Constant::getNullValue(PN->getType());

    Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
    if (Result == 0) return 0;

    // Handle PHI nodes specially here...
    for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
      if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
        return 0;   // Not all the same incoming constants...

    // If we reach here, all incoming values are the same constant.
    return Result;
  } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
    if (Function *F = CI->getCalledFunction())
      if (canConstantFoldCallTo(F)) {
        std::vector<Constant*> Args;
        for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
          if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
            Args.push_back(Op);
          else
            return 0;
        return ConstantFoldCall(F, Args);
      }
    return 0;
  }

  Constant *Op0 = 0, *Op1 = 0;
  switch (I->getNumOperands()) {
  default:
  case 2:
    Op1 = dyn_cast<Constant>(I->getOperand(1));
    if (Op1 == 0) return 0;        // Not a constant?, can't fold
  case 1:
    Op0 = dyn_cast<Constant>(I->getOperand(0));
    if (Op0 == 0) return 0;        // Not a constant?, can't fold
    break;
  case 0: return 0;
  }

  if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
    return ConstantExpr::get(I->getOpcode(), Op0, Op1);

  switch (I->getOpcode()) {
  default: return 0;
  case Instruction::Cast:
    return ConstantExpr::getCast(Op0, I->getType());
  case Instruction::Select:
    if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
      return ConstantExpr::getSelect(Op0, Op1, Op2);
    return 0;
  case Instruction::ExtractElement:
    return ConstantExpr::getExtractElement(Op0, Op1);
  case Instruction::InsertElement:
    if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
      return ConstantExpr::getInsertElement(Op0, Op1, Op2);
  case Instruction::GetElementPtr:
    std::vector<Constant*> IdxList;
    IdxList.reserve(I->getNumOperands()-1);
    if (Op1) IdxList.push_back(Op1);
    for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
      if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
        IdxList.push_back(C);
      else
        return 0;  // Non-constant operand
    return ConstantExpr::getGetElementPtr(Op0, IdxList);
  }
}

// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
  TerminatorInst *T = BB->getTerminator();

  // Branch - See if we are conditional jumping on constant
  if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
    if (BI->isUnconditional()) return false;  // Can't optimize uncond branch
    BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
    BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));

    if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
      // Are we branching on constant?
      // YES.  Change to unconditional branch...
      BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
      BasicBlock *OldDest     = Cond->getValue() ? Dest2 : Dest1;

      //cerr << "Function: " << T->getParent()->getParent()
      //     << "\nRemoving branch from " << T->getParent()
      //     << "\n\nTo: " << OldDest << endl;

      // Let the basic block know that we are letting go of it.  Based on this,
      // it will adjust it's PHI nodes.
      assert(BI->getParent() && "Terminator not inserted in block!");
      OldDest->removePredecessor(BI->getParent());

      // Set the unconditional destination, and change the insn to be an
      // unconditional branch.
      BI->setUnconditionalDest(Destination);
      return true;
    } else if (Dest2 == Dest1) {       // Conditional branch to same location?
      // This branch matches something like this:
      //     br bool %cond, label %Dest, label %Dest
      // and changes it into:  br label %Dest

      // Let the basic block know that we are letting go of one copy of it.
      assert(BI->getParent() && "Terminator not inserted in block!");
      Dest1->removePredecessor(BI->getParent());

      // Change a conditional branch to unconditional.
      BI->setUnconditionalDest(Dest1);
      return true;
    }
  } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
    // If we are switching on a constant, we can convert the switch into a
    // single branch instruction!
    ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
    BasicBlock *TheOnlyDest = SI->getSuccessor(0);  // The default dest
    BasicBlock *DefaultDest = TheOnlyDest;
    assert(TheOnlyDest == SI->getDefaultDest() &&
           "Default destination is not successor #0?");

    // Figure out which case it goes to...
    for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
      // Found case matching a constant operand?
      if (SI->getSuccessorValue(i) == CI) {
        TheOnlyDest = SI->getSuccessor(i);
        break;
      }

      // Check to see if this branch is going to the same place as the default
      // dest.  If so, eliminate it as an explicit compare.
      if (SI->getSuccessor(i) == DefaultDest) {
        // Remove this entry...
        DefaultDest->removePredecessor(SI->getParent());
        SI->removeCase(i);
        --i; --e;  // Don't skip an entry...
        continue;
      }

      // Otherwise, check to see if the switch only branches to one destination.
      // We do this by reseting "TheOnlyDest" to null when we find two non-equal
      // destinations.
      if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
    }

    if (CI && !TheOnlyDest) {
      // Branching on a constant, but not any of the cases, go to the default
      // successor.
      TheOnlyDest = SI->getDefaultDest();
    }

    // If we found a single destination that we can fold the switch into, do so
    // now.
    if (TheOnlyDest) {
      // Insert the new branch..
      new BranchInst(TheOnlyDest, SI);
      BasicBlock *BB = SI->getParent();

      // Remove entries from PHI nodes which we no longer branch to...
      for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
        // Found case matching a constant operand?
        BasicBlock *Succ = SI->getSuccessor(i);
        if (Succ == TheOnlyDest)
          TheOnlyDest = 0;  // Don't modify the first branch to TheOnlyDest
        else
          Succ->removePredecessor(BB);
      }

      // Delete the old switch...
      BB->getInstList().erase(SI);
      return true;
    } else if (SI->getNumSuccessors() == 2) {
      // Otherwise, we can fold this switch into a conditional branch
      // instruction if it has only one non-default destination.
      Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
                                    SI->getSuccessorValue(1), "cond", SI);
      // Insert the new branch...
      new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);

      // Delete the old switch...
      SI->getParent()->getInstList().erase(SI);
      return true;
    }
  }
  return false;
}

/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
                                                       ConstantExpr *CE) {
  if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
    return 0;  // Do not allow stepping over the value!

  // Loop over all of the operands, tracking down which value we are
  // addressing...
  gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
  for (++I; I != E; ++I)
    if (const StructType *STy = dyn_cast<StructType>(*I)) {
      ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
      assert(CU->getValue() < STy->getNumElements() &&
             "Struct index out of range!");
      unsigned El = (unsigned)CU->getValue();
      if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
        C = CS->getOperand(El);
      } else if (isa<ConstantAggregateZero>(C)) {
        C = Constant::getNullValue(STy->getElementType(El));
      } else if (isa<UndefValue>(C)) {
        C = UndefValue::get(STy->getElementType(El));
      } else {
        return 0;
      }
    } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
      const ArrayType *ATy = cast<ArrayType>(*I);
      if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
      if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
        C = CA->getOperand((unsigned)CI->getRawValue());
      else if (isa<ConstantAggregateZero>(C))
        C = Constant::getNullValue(ATy->getElementType());
      else if (isa<UndefValue>(C))
        C = UndefValue::get(ATy->getElementType());
      else
        return 0;
    } else {
      return 0;
    }
  return C;
}

//===----------------------------------------------------------------------===//
//  Local dead code elimination...
//

bool llvm::isInstructionTriviallyDead(Instruction *I) {
  if (!I->use_empty() || isa<TerminatorInst>(I)) return false;

  if (!I->mayWriteToMemory()) return true;

  if (CallInst *CI = dyn_cast<CallInst>(I))
    if (Function *F = CI->getCalledFunction())
      switch (F->getIntrinsicID()) {
      default: break;
      case Intrinsic::returnaddress:
      case Intrinsic::frameaddress:
      case Intrinsic::stacksave:
      case Intrinsic::isunordered_f32:
      case Intrinsic::isunordered_f64:
      case Intrinsic::bswap_i16:
      case Intrinsic::bswap_i32:
      case Intrinsic::bswap_i64:
      case Intrinsic::ctpop_i8:
      case Intrinsic::ctpop_i16:
      case Intrinsic::ctpop_i32:
      case Intrinsic::ctpop_i64:
      case Intrinsic::ctlz_i8:
      case Intrinsic::ctlz_i16:
      case Intrinsic::ctlz_i32:
      case Intrinsic::ctlz_i64:
      case Intrinsic::cttz_i8:
      case Intrinsic::cttz_i16:
      case Intrinsic::cttz_i32:
      case Intrinsic::cttz_i64:
      case Intrinsic::sqrt_f32:
      case Intrinsic::sqrt_f64:
        return true;             // These intrinsics have no side effects.
      }
  return false;
}

// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead.  If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
  // Look for un"used" definitions...
  if (isInstructionTriviallyDead(BBI)) {
    BBI = BBI->getParent()->getInstList().erase(BBI);   // Bye bye
    return true;
  }
  return false;
}
<|endoftext|>


<commit_before>
// FILE: main.cc

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
//
//
//                   Main Startup Code for the Cutplane Editor
//              (Faster, Stronger, and Much Much More Powerful)
//
// Authors: LJE and WAK                           Date: December 27,1989
//
// Copyright (C) 1987,1988,1989,1990 The Board of Trustees of The Leland
// Stanford Junior University, and William Kessler and Larry Edwards.
// All Rights Reserved.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//

#define MAINMODULE

#include <config.h>

#include <platform_gl.h>
#include <platform_glu.h>
#include <platform_glut.h>

#include <stdio.h>
#ifndef _WIN32
#include <signal.h>
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <time.h>

#include <cutplane.h>
#include <globals.h>
#include <init.h>
#include <grafx.h>		// for definition of black
#include <update.h>
#include <tools.h>

#include "device.h"

// things we are testing today:
/*
#define Createfullworkspace
#define Copslikedonuts
#define Timetest
#define Testboolbeam
#define Testboolholes
#define Testboolcube
#define Testsegments
#define Aliasvs3formdemo
#define Twolbeams
#define Stocksdemo
#define Onelbeam
#define Createtools
#define Shipcube
*/

char *className = "3Form";
char *windowName = "3Form";

// FIXE ME -- LJE
// HDC hDC;
// HGLRC hGLRC;
// HPALETTE hPalette;

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
// Stuff from OGLSDK's cube.c begins here, adapted for cutplane usage.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//

#if 0

void
set_pc_window_values(int new_winLeft, int new_winTop,
		     int new_winWidth, int new_winHeight)
{
  if (new_winLeft > -1) {
    pc_winLeft = new_winLeft;
    pc_winTop = new_winTop;
  } else {
    pc_winLeft = 10;
    pc_winTop = 10;
  }

  if (new_winWidth > -1) {
    pc_winWidth = new_winWidth;
    pc_winHeight = new_winHeight;
  }

  pc_xMargin = pc_winWidth * pc_windowMargin;
  pc_yMargin = pc_winHeight * pc_windowMargin;

  pc_winRight = pc_winLeft + pc_winWidth;
  pc_winBottom = pc_winTop + pc_winHeight;
  pc_innerLeft = pc_winLeft + pc_xMargin;
  pc_innerRight = pc_winRight - pc_xMargin;
  pc_innerTop = pc_winTop + pc_yMargin;
  pc_innerBottom = pc_winBottom - pc_yMargin;
}

void
setupPalette(HDC hDC)
{
    int pixelFormat = GetPixelFormat(hDC);
    PIXELFORMATDESCRIPTOR pfd;
    LOGPALETTE* pPal;
    int paletteSize;

    DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

    if (pfd.dwFlags & PFD_NEED_PALETTE) {
	paletteSize = 1 << pfd.cColorBits;
    } else {
	return;
    }

    pPal = (LOGPALETTE*)
	malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
    pPal->palVersion = 0x300;
    pPal->palNumEntries = paletteSize;

    // build a simple RGB color palette
    {
	int redMask = (1 << pfd.cRedBits) - 1;
	int greenMask = (1 << pfd.cGreenBits) - 1;
	int blueMask = (1 << pfd.cBlueBits) - 1;
	int i;

	for (i=0; i<paletteSize; ++i) {
	    pPal->palPalEntry[i].peRed =
		    (((i >> pfd.cRedShift) & redMask) * 255) / redMask;
	    pPal->palPalEntry[i].peGreen =
		    (((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
	    pPal->palPalEntry[i].peBlue =
		    (((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
	    pPal->palPalEntry[i].peFlags = 0;
	}
    }

    hPalette = CreatePalette(pPal);
    free(pPal);

    if (hPalette) {
	SelectPalette(hDC, hPalette, FALSE);
	RealizePalette(hDC);
    }
}

LRESULT APIENTRY
WndProc(
    HWND hWnd,
    UINT message,
    WPARAM wParam,
    LPARAM lParam)
{
  int new_winLeft, new_winTop, new_winWidth, new_winHeight;

  switch (message) {
  case WM_CREATE:
    init_dbgdump("./tmptest");
    // initialize OpenGL rendering
    hDC = GetDC(hWnd);
    setupPixelFormat(hDC);
    setupPalette(hDC);
    hGLRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hGLRC);

    init_grafx(hDC);
    init_3form();
    toggle_cpldebug();

    ShowCursor(FALSE);
    // Initially, move cursor to ctr of screen.
#if 0
    SetCursorPos(pc_winLeft + (pc_winWidth / 2),
		 pc_winTop + (pc_winHeight /2));
#endif
    return 0;
  case WM_DESTROY:
    close_dbgdump();
    // finish OpenGL rendering
    if (hGLRC) {
      wglMakeCurrent(NULL, NULL);
      wglDeleteContext(hGLRC);
    }
    if (hPalette) {
      DeleteObject(hPalette);
    }
    ReleaseDC(hWnd, hDC);
    PostQuitMessage(0);
    ShowCursor(TRUE);
    return 0;
  case WM_MOVE:
    // track window size changes
    if (hGLRC) {
      new_winLeft = (int) LOWORD(lParam);
      new_winTop = (int) HIWORD(lParam);
      set_pc_window_values(new_winLeft, new_winTop,-1,-1);
      reset_pc_valuator_store();
      grafx_resize(pc_winWidth, pc_winHeight);
      new_user_input(world_list,state,oldstate, hDC);
      return 0;
    }
  case WM_SIZE:
    // track window size changes
    if (hGLRC) {
      new_winWidth = (int) LOWORD(lParam);
      new_winHeight = (int) HIWORD(lParam);
      set_pc_window_values(-1,-1,new_winWidth, new_winHeight);
      reset_pc_valuator_store();
      grafx_resize(pc_winWidth, pc_winHeight);
      new_user_input(world_list,state,oldstate, hDC);
      return 0;
    }
  case WM_PALETTECHANGED:
    // realize palette if this is *not* the current window
    if (hGLRC && hPalette && (HWND) wParam != hWnd) {
      UnrealizeObject(hPalette);
      SelectPalette(hDC, hPalette, FALSE);
      RealizePalette(hDC);
      redraw_grafx(hDC);
      break;
    }
    break;
  case WM_QUERYNEWPALETTE:
    // realize palette if this is the current window
    if (hGLRC && hPalette) {
      UnrealizeObject(hPalette);
      SelectPalette(hDC, hPalette, FALSE);
      RealizePalette(hDC);
      redraw_grafx(hDC);
      return TRUE;
    }
    break;
  case WM_PAINT:
    {
      PAINTSTRUCT ps;
      BeginPaint(hWnd, &ps);
      if (hGLRC) {
	redraw_grafx(hDC);
	new_user_input(world_list,state,oldstate, hDC);
      }
      EndPaint(hWnd, &ps);
      return 0;
    }
    break;
  case WM_MOUSEMOVE:
    if (hGLRC) {
      int x = ((int) LOWORD(lParam) << 16) >> 16;
      int y = ((int) HIWORD(lParam) << 16) >> 16;
      // Translate from pc devices->iris universe.

      scan_pc_buttons();
      set_pc_valuators(x,y);

      // Now run 3form's user input handling code.
      new_user_input(world_list,state,oldstate, hDC);
      break;
    }
  case WM_LBUTTONDOWN:
    pc_queue_push(PICKBUTTON, (short) 1);
    new_user_input(world_list,state,oldstate, hDC);

    break;
  case WM_LBUTTONUP:
    pc_queue_push(PICKBUTTON, (short) -1);
    // Now run 3form's user input handling code.
    new_user_input(world_list,state,oldstate, hDC);
    break;
  case WM_RBUTTONDOWN:
    pc_queue_push(PLANEMOVEBUTTON, (short) 1);
    break;
  case WM_RBUTTONUP:
    pc_queue_push(PLANEMOVEBUTTON, (short) -1);
    break;
  case WM_CHAR:
    // handle keyboard input
    switch ((int)wParam) {
    case VK_ESCAPE:
      DestroyWindow(hWnd);
      return 0;
    default:
      break;
    }
    break;
  default:
    break;
  }
  return DefWindowProc(hWnd, message, wParam, lParam);
}

int APIENTRY
WinMain(
    HINSTANCE hCurrentInst,
    HINSTANCE hPreviousInst,
    LPSTR lpszCmdLine,
    int nCmdShow)
{
    WNDCLASS wndClass;
    HWND hWnd;
    MSG msg;

    // Presumably handle a crash gracefully?
    // Only for unix, really.
#ifdef IRIS
    signal(SIGSEGV, error_handler);
#endif

    // register window class
    wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = WndProc;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hInstance = hCurrentInst;
    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = GetStockObject(BLACK_BRUSH);
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = className;
    RegisterClass(&wndClass);

    pc_windowMargin = .25;
    set_pc_window_values(10,10,500,500);

    // create window
    hWnd = CreateWindow(
	className, windowName,
	WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
	pc_winLeft, pc_winTop, pc_winWidth, pc_winHeight,
	NULL, NULL, hCurrentInst, NULL);

    // display window
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // process messages
    while (GetMessage(&msg, NULL, 0, 0) == TRUE) {
	TranslateMessage(&msg);
	DispatchMessage(&msg);
    }

    return msg.wParam;
}
#endif

void
Init()
{
  GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
  GLfloat light_direction[] = { 1.0, 1.0, 1.0, 0.0 };

  // Enable a single OpenGL light.
  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, light_direction);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHTING);

  // Use depth buffering for hidden surface elimination.
  glEnable(GL_DEPTH_TEST);

  // Setup the view
  glMatrixMode(GL_PROJECTION);
  gluPerspective(40.0,		// FOV in degrees
		 1.0,		// aspect ratio
		 1.0,		// Z near
		 10.0);		// Z far
  glMatrixMode(GL_MODELVIEW);
  gluLookAt(0.0, 0.0, 5.0,	// Eye point
	    0.0, 0.0, 0.0,      // Reference point
	    0.0, 1.0, 0.);      // Up vector (+Y axis)
}

void
Render()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  // Draw the scene...
  new_user_input(world_list, state, oldstate);
  glutSwapBuffers();
}

int
main(int argc, char *argv[])
{
  init_dbgdump("./debug-dump.txt");
#ifndef WIN32
  init_error_handling();
#endif
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutCreateWindow(windowName);
  glutDisplayFunc(Render);
  glutReshapeFunc(grafx_resize);

// void processMouse(int button, int state, int x, int y)
//
// Button will recieve an integer constant identified by a name in all
// caps. These identifiers have names like GLUT_DOWN, GLUT_UP etc. and
// represent the current state of the mouse buttons (using 0 and 1 for
// true or false). x and y are the position of the mouse measured from
// the upper left corner of the current window. The callback for
// glutMotionFunc should have the format:
//
//   void processMouseActiveMotion(int x, int y)
  glutKeyboardFunc(keyboard_event_handler);
  // Triggered when a mouse button is pressed...
  glutMouseFunc(mouse_button_event_handler);
  // Triggered when the mouse moves within a window and buttons are
  // pressed...
  glutMotionFunc(drag_event_handler);
  // Triggered when the mouse moves within a window and no buttons are
  // pressed...
  glutPassiveMotionFunc(motion_event_handler);

  init_grafx();
  init_3form();
//   toggle_cpldebug();

  glutDisplayFunc(update_display);

  glutMainLoop();

  return 0;
}
<commit_msg>Added const qualifiers to char strings to get rid of warnings.<commit_after>
// FILE: main.cc

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
//
//
//                   Main Startup Code for the Cutplane Editor
//              (Faster, Stronger, and Much Much More Powerful)
//
// Authors: LJE and WAK                           Date: December 27,1989
//
// Copyright (C) 1987,1988,1989,1990 The Board of Trustees of The Leland
// Stanford Junior University, and William Kessler and Larry Edwards.
// All Rights Reserved.
//
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//

#define MAINMODULE

#include <config.h>

#include <platform_gl.h>
#include <platform_glu.h>
#include <platform_glut.h>

#include <stdio.h>
#ifndef _WIN32
#include <signal.h>
#endif
#ifdef __APPLE__
#include <sys/malloc.h>
#else
#include <malloc.h>
#endif
#include <time.h>

#include <cutplane.h>
#include <globals.h>
#include <init.h>
#include <grafx.h>		// for definition of black
#include <update.h>
#include <tools.h>

#include "device.h"

// things we are testing today:
/*
#define Createfullworkspace
#define Copslikedonuts
#define Timetest
#define Testboolbeam
#define Testboolholes
#define Testboolcube
#define Testsegments
#define Aliasvs3formdemo
#define Twolbeams
#define Stocksdemo
#define Onelbeam
#define Createtools
#define Shipcube
*/

const char className[] = { "3Form" };
const char windowName[] = { "3Form" };

// FIXE ME -- LJE
// HDC hDC;
// HGLRC hGLRC;
// HPALETTE hPalette;

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//
// Stuff from OGLSDK's cube.c begins here, adapted for cutplane usage.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-//

#if 0

void
set_pc_window_values(int new_winLeft, int new_winTop,
		     int new_winWidth, int new_winHeight)
{
  if (new_winLeft > -1) {
    pc_winLeft = new_winLeft;
    pc_winTop = new_winTop;
  } else {
    pc_winLeft = 10;
    pc_winTop = 10;
  }

  if (new_winWidth > -1) {
    pc_winWidth = new_winWidth;
    pc_winHeight = new_winHeight;
  }

  pc_xMargin = pc_winWidth * pc_windowMargin;
  pc_yMargin = pc_winHeight * pc_windowMargin;

  pc_winRight = pc_winLeft + pc_winWidth;
  pc_winBottom = pc_winTop + pc_winHeight;
  pc_innerLeft = pc_winLeft + pc_xMargin;
  pc_innerRight = pc_winRight - pc_xMargin;
  pc_innerTop = pc_winTop + pc_yMargin;
  pc_innerBottom = pc_winBottom - pc_yMargin;
}

void
setupPalette(HDC hDC)
{
    int pixelFormat = GetPixelFormat(hDC);
    PIXELFORMATDESCRIPTOR pfd;
    LOGPALETTE* pPal;
    int paletteSize;

    DescribePixelFormat(hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd);

    if (pfd.dwFlags & PFD_NEED_PALETTE) {
	paletteSize = 1 << pfd.cColorBits;
    } else {
	return;
    }

    pPal = (LOGPALETTE*)
	malloc(sizeof(LOGPALETTE) + paletteSize * sizeof(PALETTEENTRY));
    pPal->palVersion = 0x300;
    pPal->palNumEntries = paletteSize;

    // build a simple RGB color palette
    {
	int redMask = (1 << pfd.cRedBits) - 1;
	int greenMask = (1 << pfd.cGreenBits) - 1;
	int blueMask = (1 << pfd.cBlueBits) - 1;
	int i;

	for (i=0; i<paletteSize; ++i) {
	    pPal->palPalEntry[i].peRed =
		    (((i >> pfd.cRedShift) & redMask) * 255) / redMask;
	    pPal->palPalEntry[i].peGreen =
		    (((i >> pfd.cGreenShift) & greenMask) * 255) / greenMask;
	    pPal->palPalEntry[i].peBlue =
		    (((i >> pfd.cBlueShift) & blueMask) * 255) / blueMask;
	    pPal->palPalEntry[i].peFlags = 0;
	}
    }

    hPalette = CreatePalette(pPal);
    free(pPal);

    if (hPalette) {
	SelectPalette(hDC, hPalette, FALSE);
	RealizePalette(hDC);
    }
}

LRESULT APIENTRY
WndProc(
    HWND hWnd,
    UINT message,
    WPARAM wParam,
    LPARAM lParam)
{
  int new_winLeft, new_winTop, new_winWidth, new_winHeight;

  switch (message) {
  case WM_CREATE:
    init_dbgdump("./tmptest");
    // initialize OpenGL rendering
    hDC = GetDC(hWnd);
    setupPixelFormat(hDC);
    setupPalette(hDC);
    hGLRC = wglCreateContext(hDC);
    wglMakeCurrent(hDC, hGLRC);

    init_grafx(hDC);
    init_3form();
    toggle_cpldebug();

    ShowCursor(FALSE);
    // Initially, move cursor to ctr of screen.
#if 0
    SetCursorPos(pc_winLeft + (pc_winWidth / 2),
		 pc_winTop + (pc_winHeight /2));
#endif
    return 0;
  case WM_DESTROY:
    close_dbgdump();
    // finish OpenGL rendering
    if (hGLRC) {
      wglMakeCurrent(NULL, NULL);
      wglDeleteContext(hGLRC);
    }
    if (hPalette) {
      DeleteObject(hPalette);
    }
    ReleaseDC(hWnd, hDC);
    PostQuitMessage(0);
    ShowCursor(TRUE);
    return 0;
  case WM_MOVE:
    // track window size changes
    if (hGLRC) {
      new_winLeft = (int) LOWORD(lParam);
      new_winTop = (int) HIWORD(lParam);
      set_pc_window_values(new_winLeft, new_winTop,-1,-1);
      reset_pc_valuator_store();
      grafx_resize(pc_winWidth, pc_winHeight);
      new_user_input(world_list,state,oldstate, hDC);
      return 0;
    }
  case WM_SIZE:
    // track window size changes
    if (hGLRC) {
      new_winWidth = (int) LOWORD(lParam);
      new_winHeight = (int) HIWORD(lParam);
      set_pc_window_values(-1,-1,new_winWidth, new_winHeight);
      reset_pc_valuator_store();
      grafx_resize(pc_winWidth, pc_winHeight);
      new_user_input(world_list,state,oldstate, hDC);
      return 0;
    }
  case WM_PALETTECHANGED:
    // realize palette if this is *not* the current window
    if (hGLRC && hPalette && (HWND) wParam != hWnd) {
      UnrealizeObject(hPalette);
      SelectPalette(hDC, hPalette, FALSE);
      RealizePalette(hDC);
      redraw_grafx(hDC);
      break;
    }
    break;
  case WM_QUERYNEWPALETTE:
    // realize palette if this is the current window
    if (hGLRC && hPalette) {
      UnrealizeObject(hPalette);
      SelectPalette(hDC, hPalette, FALSE);
      RealizePalette(hDC);
      redraw_grafx(hDC);
      return TRUE;
    }
    break;
  case WM_PAINT:
    {
      PAINTSTRUCT ps;
      BeginPaint(hWnd, &ps);
      if (hGLRC) {
	redraw_grafx(hDC);
	new_user_input(world_list,state,oldstate, hDC);
      }
      EndPaint(hWnd, &ps);
      return 0;
    }
    break;
  case WM_MOUSEMOVE:
    if (hGLRC) {
      int x = ((int) LOWORD(lParam) << 16) >> 16;
      int y = ((int) HIWORD(lParam) << 16) >> 16;
      // Translate from pc devices->iris universe.

      scan_pc_buttons();
      set_pc_valuators(x,y);

      // Now run 3form's user input handling code.
      new_user_input(world_list,state,oldstate, hDC);
      break;
    }
  case WM_LBUTTONDOWN:
    pc_queue_push(PICKBUTTON, (short) 1);
    new_user_input(world_list,state,oldstate, hDC);

    break;
  case WM_LBUTTONUP:
    pc_queue_push(PICKBUTTON, (short) -1);
    // Now run 3form's user input handling code.
    new_user_input(world_list,state,oldstate, hDC);
    break;
  case WM_RBUTTONDOWN:
    pc_queue_push(PLANEMOVEBUTTON, (short) 1);
    break;
  case WM_RBUTTONUP:
    pc_queue_push(PLANEMOVEBUTTON, (short) -1);
    break;
  case WM_CHAR:
    // handle keyboard input
    switch ((int)wParam) {
    case VK_ESCAPE:
      DestroyWindow(hWnd);
      return 0;
    default:
      break;
    }
    break;
  default:
    break;
  }
  return DefWindowProc(hWnd, message, wParam, lParam);
}

int APIENTRY
WinMain(
    HINSTANCE hCurrentInst,
    HINSTANCE hPreviousInst,
    LPSTR lpszCmdLine,
    int nCmdShow)
{
    WNDCLASS wndClass;
    HWND hWnd;
    MSG msg;

    // Presumably handle a crash gracefully?
    // Only for unix, really.
#ifdef IRIS
    signal(SIGSEGV, error_handler);
#endif

    // register window class
    wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = WndProc;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hInstance = hCurrentInst;
    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = GetStockObject(BLACK_BRUSH);
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = className;
    RegisterClass(&wndClass);

    pc_windowMargin = .25;
    set_pc_window_values(10,10,500,500);

    // create window
    hWnd = CreateWindow(
	className, windowName,
	WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS,
	pc_winLeft, pc_winTop, pc_winWidth, pc_winHeight,
	NULL, NULL, hCurrentInst, NULL);

    // display window
    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    // process messages
    while (GetMessage(&msg, NULL, 0, 0) == TRUE) {
	TranslateMessage(&msg);
	DispatchMessage(&msg);
    }

    return msg.wParam;
}
#endif

void
Init()
{
  GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
  GLfloat light_direction[] = { 1.0, 1.0, 1.0, 0.0 };

  // Enable a single OpenGL light.
  glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
  glLightfv(GL_LIGHT0, GL_POSITION, light_direction);
  glEnable(GL_LIGHT0);
  glEnable(GL_LIGHTING);

  // Use depth buffering for hidden surface elimination.
  glEnable(GL_DEPTH_TEST);

  // Setup the view
  glMatrixMode(GL_PROJECTION);
  gluPerspective(40.0,		// FOV in degrees
		 1.0,		// aspect ratio
		 1.0,		// Z near
		 10.0);		// Z far
  glMatrixMode(GL_MODELVIEW);
  gluLookAt(0.0, 0.0, 5.0,	// Eye point
	    0.0, 0.0, 0.0,      // Reference point
	    0.0, 1.0, 0.);      // Up vector (+Y axis)
}

void
Render()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  // Draw the scene...
  new_user_input(world_list, state, oldstate);
  glutSwapBuffers();
}

int
main(int argc, char *argv[])
{
  init_dbgdump("./debug-dump.txt");
#ifndef WIN32
  init_error_handling();
#endif
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
  glutCreateWindow(windowName);
  glutDisplayFunc(Render);
  glutReshapeFunc(grafx_resize);

// void processMouse(int button, int state, int x, int y)
//
// Button will recieve an integer constant identified by a name in all
// caps. These identifiers have names like GLUT_DOWN, GLUT_UP etc. and
// represent the current state of the mouse buttons (using 0 and 1 for
// true or false). x and y are the position of the mouse measured from
// the upper left corner of the current window. The callback for
// glutMotionFunc should have the format:
//
//   void processMouseActiveMotion(int x, int y)
  glutKeyboardFunc(keyboard_event_handler);
  // Triggered when a mouse button is pressed...
  glutMouseFunc(mouse_button_event_handler);
  // Triggered when the mouse moves within a window and buttons are
  // pressed...
  glutMotionFunc(drag_event_handler);
  // Triggered when the mouse moves within a window and no buttons are
  // pressed...
  glutPassiveMotionFunc(motion_event_handler);

  init_grafx();
  init_3form();
//   toggle_cpldebug();

  glutDisplayFunc(update_display);

  glutMainLoop();

  return 0;
}
<|endoftext|>


<commit_before>//===--------------- LLVMContextImpl.cpp - Implementation ------*- C++ -*--===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements LLVMContextImpl, the opaque implementation
//  of LLVMContext.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace llvm;

LLVMContextImpl::LLVMContextImpl(LLVMContext &C) :
    Context(C), TheTrueVal(0), TheFalseVal(0) { }<commit_msg>Fix no newline at end of LLVMContextImpl.cpp<commit_after>//===--------------- LLVMContextImpl.cpp - Implementation ------*- C++ -*--===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements LLVMContextImpl, the opaque implementation
//  of LLVMContext.
//
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Metadata.h"
using namespace llvm;

LLVMContextImpl::LLVMContextImpl(LLVMContext &C) :
    Context(C), TheTrueVal(0), TheFalseVal(0) { }

<|endoftext|>


<commit_before>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#define GLM_FORCE_RADIANS

#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>

#include "common.h"
#include "GameWorld.h"

// Lousy global variables
const Uint8* keyboard_input;

SDL_Window * _window;

int window_width, window_height;
bool fullscreen = false;

/*
 * SDL timers run in separate threads.  In the timer thread
 * push an event onto the event queue.  This event signifies
 * to call display() from the thread in which the OpenGL
 * context was created.
 */
Uint32 tick(Uint32 interval, void *param)
{
	SDL_Event event;
	event.type = SDL_USEREVENT;
	event.user.code = RUN_GRAPHICS_DISPLAY;
	event.user.data1 = 0;
	event.user.data2 = 0;
	SDL_PushEvent(&event);
	return interval;
}

struct SDLWindowDeleter
{
	inline void operator()(SDL_Window* window)
	{
		SDL_DestroyWindow(window);
	}
};

/*
 * Handles input
 */
void HandleInput(const std::shared_ptr<GameWorld> game_world)
{
	// Camera controller
	int x, y;
	SDL_PumpEvents();
	SDL_GetMouseState(&x, &y);
	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
	SDL_WarpMouseInWindow(_window, window_width/2, window_height/2);
	SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
	SDL_PumpEvents();
	game_world->MoveCamera(glm::vec2(x,y), glm::vec2(window_width, window_height));

	// Update game_world camera
	if(keyboard_input[SDL_SCANCODE_W])
		game_world->CameraController(1); // forward
	if(keyboard_input[SDL_SCANCODE_A])
		game_world->CameraController(2); // left
	if(keyboard_input[SDL_SCANCODE_S])
		game_world->CameraController(3); // back
	if(keyboard_input[SDL_SCANCODE_D])
		game_world->CameraController(4); // right
	if(keyboard_input[SDL_SCANCODE_SPACE])
		game_world->CameraController(9); // player: +y ("fly" up)
	if(keyboard_input[SDL_SCANCODE_LCTRL])
		game_world->CameraController(10); // player: -y ("fly" down)

	if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
		game_world->DoAction(1);
	if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
		game_world->DoAction(2);
	if(keyboard_input[SDL_SCANCODE_G])
		game_world->DoAction(3);
	if(keyboard_input[SDL_SCANCODE_H])
		game_world->DoAction(4);

	if(keyboard_input[SDL_SCANCODE_E])
		game_world->ChangeBlockDist(1);
	if(keyboard_input[SDL_SCANCODE_Q])
		game_world->ChangeBlockDist(-1);

	if(keyboard_input[SDL_SCANCODE_ESCAPE])
		SDL_Quit();
}

/*
 * Draws the game world and handles buffer switching.
 */
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
	// Background colour for the window
	glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	// Draw the gameworld
	game_world->Draw();

	// Swap buffers
	SDL_GL_SwapWindow(window.get());
}

/*
 * Handles the initialisation of the game world.
 * Configures the SDL window and initialises GLEW
 */
std::shared_ptr<SDL_Window> InitWorld()
{
	// Window properties
	std::shared_ptr<SDL_Window> window;

	// Glew will later ensure that OpenGL 3 *is* supported
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

	// Do double buffering in GL
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	// Initialise SDL - when using C/C++ it's common to have to
	// initialise libraries by calling a function within them.
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
	{
		std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
		return nullptr;
	}
	SDL_GetError();

	// When we close a window quit the SDL application
	atexit(SDL_Quit);

	SDL_ShowCursor(0);

	if(fullscreen)
	{
		SDL_DisplayMode display;
		SDL_GetCurrentDisplayMode(0, &display);
		window_width = display.w;
		window_height = display.h;
	}
	else
	{
		window_width = 1024;
		window_height = 768;
	}

	// Create a new window with an OpenGL surface
	_window = SDL_CreateWindow("BlockWorld"
							 , SDL_WINDOWPOS_CENTERED
							 , SDL_WINDOWPOS_CENTERED
							 , window_width
							 , window_height
							 , SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);

	if(fullscreen)
	{
		SDL_SetWindowFullscreen(_window, SDL_WINDOW_FULLSCREEN);
	}

	if(!_window)
	{
		std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
		return nullptr;
	}

	SDL_GLContext glContext = SDL_GL_CreateContext(_window);
	if (!glContext)
	{
		std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
		return nullptr;
	}

	// Initialise GLEW - an easy way to ensure OpenGl 3.0+
	// The *must* be done after we have set the video mode - otherwise we have no
	// OpenGL context to test.
	glewInit();
	if(!glewIsSupported("GL_VERSION_3_0"))
	{
		std::cerr << "OpenGL 3.0 not available" << std::endl;
		return nullptr;
	}

	// OpenGL settings
	glDisable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	window.reset(_window, SDL_DestroyWindow);
	return window;
}

ApplicationMode ParseOptions (int argc, char ** argv)
{
	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "print this help message")
		("fullscreen", "Runs the game in fullscreen")
		("translate", "Show translation example (default)")
		("rotate", "Show rotation example")
		("scale", "Show scale example");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help"))
	{
		std::cout << desc << std::endl;
		exit(0);
	}

	if(vm.count("fullscreen"))
	{
		fullscreen = true;
	}

	if(vm.count("rotate"))
	{
		return ROTATE;
	}

	if(vm.count("scale"))
	{
		return SCALE;
	}

	// The default
	return TRANSFORM;
}

int main(int argc, char ** argv) {
	Uint32 delay = 1000/60; // in milliseconds

	auto mode = ParseOptions(argc, argv);
	auto window = InitWorld();
	auto game_world = std::make_shared<GameWorld>(mode);

	if(!window)
	{
		SDL_Quit();
	}

	keyboard_input = SDL_GetKeyboardState(NULL);

	// Call the function "tick" every delay milliseconds
	SDL_AddTimer(delay, tick, NULL);

	// Add the main event loop
	SDL_Event event;
	while (SDL_WaitEvent(&event))
	{
		switch (event.type)
		{
			case SDL_QUIT:
				SDL_Quit();
				break;
			case SDL_USEREVENT:
				Draw(window, game_world);
				HandleInput(game_world);
				break;
			default:
			  break;
		}
	}
}
<commit_msg>Capitalise global variables<commit_after>#define GLEW_STATIC
#define RUN_GRAPHICS_DISPLAY 0x00;
#define GLM_FORCE_RADIANS

#include <GL/glew.h>
#include <GL/gl.h>
#include <SDL2/SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>
#include <memory>
#include <boost/program_options.hpp>

#include "common.h"
#include "GameWorld.h"

/**
* Global variables
*/
const Uint8* KEYBOARD_INPUT;
SDL_Window * _WINDOW;
int WINDOW_WIDTH, WINDOW_HEIGHT;
bool FULLSCREEN = false;

/*
 * SDL timers run in separate threads.  In the timer thread
 * push an event onto the event queue.  This event signifies
 * to call display() from the thread in which the OpenGL
 * context was created.
 */
Uint32 tick(Uint32 interval, void *param)
{
	SDL_Event event;
	event.type = SDL_USEREVENT;
	event.user.code = RUN_GRAPHICS_DISPLAY;
	event.user.data1 = 0;
	event.user.data2 = 0;
	SDL_PushEvent(&event);
	return interval;
}

struct SDLWindowDeleter
{
	inline void operator()(SDL_Window* window)
	{
		SDL_DestroyWindow(window);
	}
};

/*
 * Handles input
 */
void HandleInput(const std::shared_ptr<GameWorld> game_world)
{
	// Camera controller
	int x, y;
	SDL_PumpEvents();
	SDL_GetMouseState(&x, &y);
	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
	SDL_WarpMouseInWindow(_WINDOW, WINDOW_WIDTH/2, WINDOW_HEIGHT/2);
	SDL_EventState(SDL_MOUSEMOTION, SDL_ENABLE);
	SDL_PumpEvents();
	game_world->MoveCamera(glm::vec2(x,y), glm::vec2(WINDOW_WIDTH, WINDOW_HEIGHT));

	// Update game_world camera
	if(KEYBOARD_INPUT[SDL_SCANCODE_W])
		game_world->CameraController(1); // forward
	if(KEYBOARD_INPUT[SDL_SCANCODE_A])
		game_world->CameraController(2); // left
	if(KEYBOARD_INPUT[SDL_SCANCODE_S])
		game_world->CameraController(3); // back
	if(KEYBOARD_INPUT[SDL_SCANCODE_D])
		game_world->CameraController(4); // right
	if(KEYBOARD_INPUT[SDL_SCANCODE_SPACE])
		game_world->CameraController(9); // player: +y ("fly" up)
	if(KEYBOARD_INPUT[SDL_SCANCODE_LCTRL])
		game_world->CameraController(10); // player: -y ("fly" down)

	if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_LEFT))
		game_world->DoAction(1);
	if(SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(SDL_BUTTON_RIGHT))
		game_world->DoAction(2);
	if(KEYBOARD_INPUT[SDL_SCANCODE_G])
		game_world->DoAction(3);
	if(KEYBOARD_INPUT[SDL_SCANCODE_H])
		game_world->DoAction(4);

	if(KEYBOARD_INPUT[SDL_SCANCODE_E])
		game_world->ChangeBlockDist(1);
	if(KEYBOARD_INPUT[SDL_SCANCODE_Q])
		game_world->ChangeBlockDist(-1);

	if(KEYBOARD_INPUT[SDL_SCANCODE_ESCAPE])
		SDL_Quit();
}

/*
 * Draws the game world and handles buffer switching.
 */
void Draw(const std::shared_ptr<SDL_Window> window, const std::shared_ptr<GameWorld> game_world)
{
	// Background colour for the window
	glClearColor(0.0f, 0.2f, 0.2f, 0.3f);
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

	// Draw the gameworld
	game_world->Draw();

	// Swap buffers
	SDL_GL_SwapWindow(window.get());
}

/*
 * Handles the initialisation of the game world.
 * Configures the SDL window and initialises GLEW
 */
std::shared_ptr<SDL_Window> InitWorld()
{
	// Window properties
	std::shared_ptr<SDL_Window> window;

	// Glew will later ensure that OpenGL 3 *is* supported
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

	// Do double buffering in GL
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

	// Initialise SDL - when using C/C++ it's common to have to
	// initialise libraries by calling a function within them.
	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) < 0)
	{
		std::cout << "Failed to initialise SDL: " << SDL_GetError() << std::endl;
		return nullptr;
	}
	SDL_GetError();

	// When we close a window quit the SDL application
	atexit(SDL_Quit);

	SDL_ShowCursor(0);

	if(FULLSCREEN)
	{
		SDL_DisplayMode display;
		SDL_GetCurrentDisplayMode(0, &display);
		WINDOW_WIDTH = display.w;
		WINDOW_HEIGHT = display.h;
	}
	else
	{
		WINDOW_WIDTH = 1024;
		WINDOW_HEIGHT = 768;
	}

	// Create a new window with an OpenGL surface
	_WINDOW = SDL_CreateWindow("BlockWorld"
							 , SDL_WindowPOS_CENTERED
							 , SDL_WindowPOS_CENTERED
							 , WINDOW_WIDTH
							 , WINDOW_HEIGHT
							 , SDL_Window_OPENGL | SDL_Window_SHOWN);

	if(FULLSCREEN)
	{
		SDL_SetWindowFULLSCREEN(_WINDOW, SDL_Window_FULLSCREEN);
	}

	if(!_WINDOW)
	{
		std::cout << "Failed to create SDL window: " << SDL_GetError() << std::endl;
		return nullptr;
	}

	SDL_GLContext glContext = SDL_GL_CreateContext(_WINDOW);
	if (!glContext)
	{
		std::cout << "Failed to create OpenGL context: " << SDL_GetError() << std::endl;
		return nullptr;
	}

	// Initialise GLEW - an easy way to ensure OpenGl 3.0+
	// The *must* be done after we have set the video mode - otherwise we have no
	// OpenGL context to test.
	glewInit();
	if(!glewIsSupported("GL_VERSION_3_0"))
	{
		std::cerr << "OpenGL 3.0 not available" << std::endl;
		return nullptr;
	}

	// OpenGL settings
	glDisable(GL_CULL_FACE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

	window.reset(_WINDOW, SDL_DestroyWindow);
	return window;
}

ApplicationMode ParseOptions (int argc, char ** argv)
{
	namespace po = boost::program_options;

	po::options_description desc("Allowed options");
	desc.add_options()
		("help", "print this help message")
		("FULLSCREEN", "Runs the game in FULLSCREEN")
		("translate", "Show translation example (default)")
		("rotate", "Show rotation example")
		("scale", "Show scale example");

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help"))
	{
		std::cout << desc << std::endl;
		exit(0);
	}

	if(vm.count("FULLSCREEN"))
	{
		FULLSCREEN = true;
	}

	if(vm.count("rotate"))
	{
		return ROTATE;
	}

	if(vm.count("scale"))
	{
		return SCALE;
	}

	// The default
	return TRANSFORM;
}

int main(int argc, char ** argv) {
	Uint32 delay = 1000/60; // in milliseconds

	auto mode = ParseOptions(argc, argv);
	auto window = InitWorld();
	auto game_world = std::make_shared<GameWorld>(mode);

	if(!window)
	{
		SDL_Quit();
	}

	KEYBOARD_INPUT = SDL_GetKeyboardState(NULL);

	// Call the function "tick" every delay milliseconds
	SDL_AddTimer(delay, tick, NULL);

	// Add the main event loop
	SDL_Event event;
	while (SDL_WaitEvent(&event))
	{
		switch (event.type)
		{
			case SDL_QUIT:
				SDL_Quit();
				break;
			case SDL_USEREVENT:
				Draw(window, game_world);
				HandleInput(game_world);
				break;
			default:
			  break;
		}
	}
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2013, William Magato
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/

#include <iostream>

#include <llamaos/api/pci/BAR.h>
#include <llamaos/api/pci/Command.h>
#include <llamaos/api/pci/PCI.h>
#include <llamaos/api/pci/Status.h>
#include <llamaos/api/sleep.h>

using namespace std;
using namespace llamaos::api;
using namespace llamaos::api::pci;

int main (int /* argc */, char ** /* argv [] */)
{
   cout << "running 80003es2lan llamaNET domain...\n" << endl;
   PCI pci;

   sleep (1);
   cout << "PCI config:" << endl;
   cout << pci << endl;

   cout << "checking PCI config for valid 80003es2lan..." << endl;
   uint16_t vendor_id = pci.read_config_word (0);
   uint16_t device_id = pci.read_config_word (2);
   uint32_t class_code = (pci.read_config_byte (11) << 16) | (pci.read_config_byte (10) << 8) | pci.read_config_byte(9);
   uint16_t subvendor_id = pci.read_config_word (44);

   if (   (vendor_id != 0x8086)
       || (   (device_id != 0x1096)
           && (device_id != 0x10ba))
       || (class_code != 0x020000)
       || (subvendor_id != 0x8086))
   {
      cout << "PCI hardware detected is NOT 80003es2lan" << endl;
      cout << hex << "   vendor: " << vendor_id << endl;
      cout << hex << "   devide: " << device_id << endl;
      cout << hex << "    class: " << class_code << endl;
      cout << hex << "subvendor: " << subvendor_id << endl << endl;

      cout << "waiting 3 sec, then exit..." << endl;
      cout.flush ();
      sleep (3);
      return -1;
   }
   else
   {
      cout << "valid hardware detected." << endl;
   }

   cout << "waiting 3 sec, then exit..." << endl;
   cout.flush ();
   sleep (3);

   return 0;
}

<commit_msg>minor change to intel driver<commit_after>/*
Copyright (c) 2013, William Magato
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/

#include <iostream>

#include <llamaos/api/pci/BAR.h>
#include <llamaos/api/pci/Command.h>
#include <llamaos/api/pci/PCI.h>
#include <llamaos/api/pci/Status.h>
#include <llamaos/api/sleep.h>

using namespace std;
using namespace llamaos::api;
using namespace llamaos::api::pci;

int main (int /* argc */, char ** /* argv [] */)
{
   cout << "running 80003es2lan llamaNET domain...\n" << endl;
   PCI pci;

   sleep (1);
   cout << "PCI config:" << endl;
   cout << pci << endl;

   cout << "checking PCI config for valid 80003es2lan..." << endl;
   uint16_t vendor_id = pci.read_config_word (0);
   uint16_t device_id = pci.read_config_word (2);
   uint32_t class_code = (pci.read_config_byte (11) << 16) | (pci.read_config_byte (10) << 8) | pci.read_config_byte(9);
   uint16_t subvendor_id = pci.read_config_word (44);

   if (   (vendor_id != 0x8086)
       || (device_id != 0x1096)
//           && (device_id != 0x10ba))
       || (class_code != 0x020000))
//       || (subvendor_id != 0x8086))
   {
      cout << "PCI hardware detected is NOT 80003es2lan" << endl;
      cout << hex << "   vendor: " << vendor_id << endl;
      cout << hex << "   devide: " << device_id << endl;
      cout << hex << "    class: " << class_code << endl;
      cout << hex << "subvendor: " << subvendor_id << endl << endl;

      cout << "waiting 3 sec, then exit..." << endl;
      cout.flush ();
      sleep (3);
      return -1;
   }
   else
   {
      cout << "valid hardware detected." << endl;
   }

   cout << "waiting 3 sec, then exit..." << endl;
   cout.flush ();
   sleep (3);

   return 0;
}

<|endoftext|>


<commit_before>#include "ros/ros.h"
#include <string>
#include <boost/format.hpp>

#include "constants.h"
#include "uinput_device.h"
#include "viewport_mapper.h"
#include "ros_event_relay.h"
#include "lg_mirror/EvdevDeviceInfo.h"

const char* DEVICE_NAME_BASE = "Virtual Touchscreen (%s)";
const char* VIEWPORT_PARAM = "viewport";

using lg_mirror::DEVICE_INFO_SERVICE;
using lg_mirror::TOUCH_ROUTE_TOPIC;

bool init(ros::NodeHandle n) {
  std::string viewport_name;
  std::string device_name;
  std::string viewport_geometry;
  ViewportMapper *viewport_mapper = NULL;

  /* grab parameters */

  if (!n.getParam(VIEWPORT_PARAM, viewport_name)) {
    ROS_ERROR("'viewport' parameter is required");
    return false;
  }
  device_name = str(boost::format(DEVICE_NAME_BASE) % viewport_name);

  /* discover viewport geometry */

  std::ostringstream viewport_geometry_key;
  viewport_geometry_key << "/viewport/" << viewport_name;
  if (!n.getParam(viewport_geometry_key.str(), viewport_geometry)) {
    ROS_ERROR_STREAM("Viewport " << viewport_name << " was not found");
    return false;
  }

  /* create viewport mapper */

  try {
    viewport_mapper = new ViewportMapper(device_name, viewport_geometry);
  } catch(ViewportMapperStringError e) {
    ROS_ERROR_STREAM("ViewportMapper: " << e.what());
    return false;
  }

  /* call the device_info service before creating the device */

  ros::ServiceClient client = n.serviceClient<lg_mirror::EvdevDeviceInfo>(DEVICE_INFO_SERVICE);
  lg_mirror::EvdevDeviceInfo srv;

  client.waitForExistence();
  if (!client.call(srv)) {
    ROS_ERROR("Failed to call the device_info service");
    return false;
  }

  /* spin up the uinput device */

  UinputDevice uinput_device(device_name);
  ROS_DEBUG_STREAM("Creating device: " << device_name << " for viewport " << viewport_name);
  if (!uinput_device.Init(srv.response)) {
    ROS_ERROR("Failed to create uinput device");
    return false;
  }

  /* wait for xinput to reflect the new device */

  if (!uinput_device.WaitForXinput()) {
    ROS_ERROR("xinput query was cancelled");
    return false;
  }

  /* instantiate an event relay */

  RosEventRelay relay(n, viewport_name, uinput_device, *viewport_mapper);
  n.subscribe(TOUCH_ROUTE_TOPIC, 10, &RosEventRelay::HandleRouterMessage, &relay);

  return true;
}

int main(int argc, char** argv) {

  /* initialize ros */

  ros::init(argc, argv, "lg_mirror_receiver");

  ros::NodeHandle n("~");

  bool init_success = init(n);
  if (!init_success) {
    ros::shutdown();
    exit(EXIT_FAILURE);
  }

  /* react until termination */

  ros::spin();
}
<commit_msg>Prevent mirror route subscriber descoping<commit_after>#include "ros/ros.h"
#include <string>
#include <boost/format.hpp>

#include "constants.h"
#include "uinput_device.h"
#include "viewport_mapper.h"
#include "ros_event_relay.h"
#include "lg_mirror/EvdevDeviceInfo.h"

const char* DEVICE_NAME_BASE = "Virtual Touchscreen (%s)";
const char* VIEWPORT_PARAM = "viewport";

using lg_mirror::DEVICE_INFO_SERVICE;
using lg_mirror::TOUCH_ROUTE_TOPIC;

void fail() {
  ros::shutdown();
  exit(EXIT_FAILURE);
}

int main(int argc, char** argv) {

  /* initialize ros */

  ros::init(argc, argv, "lg_mirror_receiver");

  ros::NodeHandle n("~");

  std::string viewport_name;
  std::string device_name;
  std::string viewport_geometry;
  ViewportMapper *viewport_mapper = NULL;

  /* grab parameters */

  if (!n.getParam(VIEWPORT_PARAM, viewport_name)) {
    ROS_ERROR("'viewport' parameter is required");
    fail();
  }
  device_name = str(boost::format(DEVICE_NAME_BASE) % viewport_name);

  /* discover viewport geometry */

  std::ostringstream viewport_geometry_key;
  viewport_geometry_key << "/viewport/" << viewport_name;
  if (!n.getParam(viewport_geometry_key.str(), viewport_geometry)) {
    ROS_ERROR_STREAM("Viewport " << viewport_name << " was not found");
    fail();
  }

  /* create viewport mapper */

  try {
    viewport_mapper = new ViewportMapper(device_name, viewport_geometry);
  } catch(ViewportMapperStringError e) {
    ROS_ERROR_STREAM("ViewportMapper: " << e.what());
    fail();
  }

  /* call the device_info service before creating the device */

  ros::ServiceClient client = n.serviceClient<lg_mirror::EvdevDeviceInfo>(DEVICE_INFO_SERVICE);
  lg_mirror::EvdevDeviceInfo srv;

  client.waitForExistence();
  if (!client.call(srv)) {
    ROS_ERROR("Failed to call the device_info service");
    fail();
  }

  /* spin up the uinput device */

  UinputDevice uinput_device(device_name);
  ROS_DEBUG_STREAM("Creating device: " << device_name << " for viewport " << viewport_name);
  if (!uinput_device.Init(srv.response)) {
    ROS_ERROR("Failed to create uinput device");
    fail();
  }

  /* wait for xinput to reflect the new device */

  if (!uinput_device.WaitForXinput()) {
    ROS_ERROR("xinput query was cancelled");
    fail();
  }

  /* instantiate an event relay */

  RosEventRelay relay(n, viewport_name, uinput_device, *viewport_mapper);
  ros::Subscriber relay_sub = n.subscribe(TOUCH_ROUTE_TOPIC, 10, &RosEventRelay::HandleRouterMessage, &relay);

  /* react until termination */

  ros::spin();
}
<|endoftext|>


<commit_before>/*
  NUI3 - C++ cross-platform GUI framework for OpenGL based applications
  Copyright (C) 2002-2003 Sebastien Metrot

  licence: see nui3/LICENCE.TXT
*/

#include "nui.h"
#include "nuiSeparator.h"

nuiSeparator::nuiSeparator(nuiOrientation orientation)
: nuiWidget()
{
  SetObjectClass(_T("nuiSeparator"));
  mOrientation = orientation;
}

nuiSeparator::~nuiSeparator()
{
}

nuiRect nuiSeparator::CalcIdealSize()
{
  nuiContainer* pParent = GetParent();
  nuiRect rect(0,0,32, 32);
  if (pParent)
    rect = pParent->GetRect();
  nuiRect res;
  switch (mOrientation)
  {
  case nuiHorizontal:
    res.Set(0.0f, 0.0f, rect.GetWidth(), 2.0f);
    break;
  case nuiVertical:
    res.Set(0.0f, 0.0f, 2.0f, rect.GetHeight());
    break;
  }

  return res;
}

bool nuiSeparator::Draw(nuiDrawContext *pContext)
{
  nuiRect r(GetRect());

  pContext->SetBlendFunc(nuiBlendTransp);
  pContext->EnableBlending(true);

  pContext->SetStrokeColor(nuiColor(255, 255, 255, 120));
  pContext->DrawLine(r.Left(), 0, r.Right(), 0);

  pContext->SetStrokeColor(nuiColor(0, 0, 0, 32));
  pContext->DrawLine(r.Left(), 1, r.Right(), 1);

  return true;
}

<commit_msg>minor update on nuiSeparator<commit_after>/*
  NUI3 - C++ cross-platform GUI framework for OpenGL based applications
  Copyright (C) 2002-2003 Sebastien Metrot

  licence: see nui3/LICENCE.TXT
*/

#include "nui.h"
#include "nuiSeparator.h"

nuiSeparator::nuiSeparator(nuiOrientation orientation)
: nuiWidget()
{
  SetObjectClass(_T("nuiSeparator"));
  mOrientation = orientation;
}

nuiSeparator::~nuiSeparator()
{
}

nuiRect nuiSeparator::CalcIdealSize()
{
  nuiContainer* pParent = GetParent();
  nuiRect rect(0,0,32, 32);
  if (pParent)
    rect = pParent->GetRect();
  nuiRect res;
  switch (mOrientation)
  {
  case nuiHorizontal:
    res.Set(0.0f, 0.0f, rect.GetWidth(), 3.0f);
    break;
  case nuiVertical:
    res.Set(0.0f, 0.0f, 3.0f, rect.GetHeight());
    break;
  }

  return res;
}

bool nuiSeparator::Draw(nuiDrawContext *pContext)
{
  nuiRect r(GetRect());

  // TODO : vertical draw

  pContext->SetStrokeColor(nuiColor(255, 255, 255));
  pContext->DrawLine(r.Left(), 0, r.Right(), 0);

  pContext->SetStrokeColor(nuiColor(0, 0, 0, 56));
  pContext->DrawLine(r.Left(), 1.5, r.Right(), 1.5);

  return true;
}

<|endoftext|>


<commit_before>#ifndef FACTOR_ENCODER
#define FACTOR_ENCODER

#include <map>
#include <string>
#include <vector>

int read_vocab(const char* fname,
               std::map<std::string, double> &vocab,
               int &maxlen);

void viterbi(const std::map<std::string, double> &vocab,
             int maxlen,
             const std::string &sentence,
             std::vector<std::string> &best_path);

#endif
<commit_msg>roughly working code for removing subwords.<commit_after>#ifndef FACTOR_ENCODER
#define FACTOR_ENCODER

#include <map>
#include <string>
#include <vector>

int read_vocab(const char* fname,
               std::map<std::string, double> &vocab,
               int &maxlen);

int write_vocab(const char* fname,
                  const std::map<std::string, double> &vocab);

void sort_vocab(const std::map<std::string, double> &vocab,
                  std::vector<std::pair<std::string, double> > &sorted_vocab);

void viterbi(const std::map<std::string, double> &vocab,
             int maxlen,
             const std::string &sentence,
             std::vector<std::string> &best_path,
             bool reverse=true);

#endif
<|endoftext|>