<commit_before>/**************************************************************************
 *
 * Copyright 2009-2011 VMware, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **************************************************************************/

#include <stddef.h>

#include <llvm-c/Core.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetInstrInfo.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/MemoryObject.h>

#include <llvm/Support/TargetRegistry.h>
#include <llvm/MC/MCSubtargetInfo.h>

#include <llvm/Support/Host.h>

#if HAVE_LLVM >= 0x0303
#include <llvm/IR/Module.h>
#else
#include <llvm/Module.h>
#endif

#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#include <llvm/MC/MCRegisterInfo.h>

#if HAVE_LLVM >= 0x0305
#define OwningPtr std::unique_ptr
#elif HAVE_LLVM >= 0x0303
#include <llvm/ADT/OwningPtr.h>
#endif

#if HAVE_LLVM >= 0x0305
#include <llvm/MC/MCContext.h>
#endif

#include "util/u_math.h"
#include "util/u_debug.h"

#include "lp_bld_debug.h"

#ifdef __linux__
#include <sys/stat.h>
#include <fcntl.h>
#endif

/**
 * Check alignment.
 *
 * It is important that this check is not implemented as a macro or inlined
 * function, as the compiler assumptions in respect to alignment of global
 * and stack variables would often make the check a no op, defeating the
 * whole purpose of the exercise.
 */
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
   assert(util_is_power_of_two(alignment));
   return ((uintptr_t)ptr & (alignment - 1)) == 0;
}

class raw_debug_ostream :
   public llvm::raw_ostream
{
private:
   uint64_t pos;

public:
   raw_debug_ostream() : pos(0) { }

   void write_impl(const char *Ptr, size_t Size);

   uint64_t current_pos() const { return pos; }
   size_t preferred_buffer_size() const { return 512; }
};

void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
   if (Size > 0) {
      char *lastPtr = (char *)&Ptr[Size];
      char last = *lastPtr;
      *lastPtr = 0;
      _debug_printf("%*s", Size, Ptr);
      *lastPtr = last;
      pos += Size;
   }
}

extern "C" const char *
lp_get_module_id(LLVMModuleRef module)
{
   return llvm::unwrap(module)->getModuleIdentifier().c_str();
}

/**
 * Same as LLVMDumpValue, but through our debugging channels.
 */
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
   raw_debug_ostream os;
   llvm::unwrap(value)->print(os);
   os.flush();
#else
   LLVMDumpValue(value);
#endif
}

/*
 * MemoryObject wrapper around a buffer of memory, to be used by MC
 * disassembler.
 */
class BufferMemoryObject:
   public llvm::MemoryObject
{
private:
   const uint8_t *Bytes;
   uint64_t Length;
public:
   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
      Bytes(bytes), Length(length)
   {
   }

   uint64_t getBase() const
   {
      return 0;
   }

   uint64_t getExtent() const
   {
      return Length;
   }

   int readByte(uint64_t addr, uint8_t *byte) const
   {
      if (addr > getExtent())
         return -1;
      *byte = Bytes[addr];
      return 0;
   }
};

/*
 * Disassemble a function, using the LLVM MC disassembler.
 *
 * See also:
 * - http://blog.llvm.org/2010/01/x86-disassembler.html
 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
 */
static size_t
disassemble(const void* func, llvm::raw_ostream & Out)
{
   using namespace llvm;

   const uint8_t *bytes = (const uint8_t *)func;

   /*
    * Limit disassembly to this extent
    */
   const uint64_t extent = 96 * 1024;

   uint64_t max_pc = 0;

   /*
    * Initialize all used objects.
    */

   std::string Triple = sys::getDefaultTargetTriple();

   std::string Error;
   const Target *T = TargetRegistry::lookupTarget(Triple, Error);

#if HAVE_LLVM >= 0x0304
   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));
#else
   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
#endif

   if (!AsmInfo) {
      Out << "error: no assembly info for target " << Triple << "\n";
      Out.flush();
      return 0;
   }

   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();

   OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple));
   if (!MRI) {
      Out << "error: no register info for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

   OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
   if (!MII) {
      Out << "error: no instruction info for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

#if HAVE_LLVM >= 0x0305
   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
   OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));
   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx));
#else
   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
#endif
   if (!DisAsm) {
      Out << "error: no disassembler for target " << Triple << "\n";
      Out.flush();
      return 0;
   }

   OwningPtr<MCInstPrinter> Printer(
         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
   if (!Printer) {
      Out << "error: no instruction printer for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

   TargetOptions options;
#if defined(DEBUG)
   options.JITEmitDebugInfo = true;
#endif
#if defined(PIPE_ARCH_X86)
   options.StackAlignmentOverride = 4;
#endif
#if defined(DEBUG) || defined(PROFILE)
   options.NoFramePointerElim = true;
#endif
   OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options));

   const TargetInstrInfo *TII = TM->getInstrInfo();

   /*
    * Wrap the data in a MemoryObject
    */
   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);

   uint64_t pc;
   pc = 0;
   while (true) {
      MCInst Inst;
      uint64_t Size;

      /*
       * Print address.  We use addresses relative to the start of the function,
       * so that between runs.
       */

      Out << llvm::format("%6lu:\t", (unsigned long)pc);

      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
                                 pc,
				  nulls(), nulls())) {
         Out << "invalid";
         pc += 1;
      }

      /*
       * Output the bytes in hexidecimal format.
       */

      if (0) {
         unsigned i;
         for (i = 0; i < Size; ++i) {
            Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]);
         }
         for (; i < 16; ++i) {
            Out << "   ";
         }
      }

      /*
       * Print the instruction.
       */
      Printer->printInst(&Inst, Out, "");

      /*
       * Advance.
       */

      pc += Size;

      const MCInstrDesc &TID = TII->get(Inst.getOpcode());

      /*
       * Keep track of forward jumps to a nearby address.
       */

      if (TID.isBranch()) {
         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
            const MCOperand &operand = Inst.getOperand(i);
            if (operand.isImm()) {
               uint64_t jump;

               /*
                * FIXME: Handle both relative and absolute addresses correctly.
                * EDInstInfo actually has this info, but operandTypes and
                * operandFlags enums are not exposed in the public interface.
                */

               if (1) {
                  /*
                   * PC relative addr.
                   */

                  jump = pc + operand.getImm();
               } else {
                  /*
                   * Absolute addr.
                   */

                  jump = (uint64_t)operand.getImm();
               }

               /*
                * Output the address relative to the function start, given
                * that MC will print the addresses relative the current pc.
                */
               Out << "\t\t; " << jump;

               /*
                * Ignore far jumps given it could be actually a tail return to
                * a random address.
                */

               if (jump > max_pc &&
                   jump < extent) {
                  max_pc = jump;
               }
            }
         }
      }

      Out << "\n";

      /*
       * Stop disassembling on return statements, if there is no record of a
       * jump to a successive address.
       */

      if (TID.isReturn()) {
         if (pc > max_pc) {
            break;
         }
      }
   }

   /*
    * Print GDB command, useful to verify output.
    */

   if (0) {
      _debug_printf("disassemble %p %p\n", bytes, bytes + pc);
   }

   Out << "\n";
   Out.flush();

   return pc;
}

extern "C" void
lp_disassemble(LLVMValueRef func, const void *code) {
   raw_debug_ostream Out;
   disassemble(code, Out);
}

/*
 * Linux perf profiler integration.
 *
 * See also:
 * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
 * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
 * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
 */
extern "C" void
lp_profile(LLVMValueRef func, const void *code)
{
#if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
   static boolean first_time = TRUE;
   static FILE *perf_map_file = NULL;
   static int perf_asm_fd = -1;
   if (first_time) {
      /*
       * We rely on the disassembler for determining a function's size, but
       * the disassembly is a leaky and slow operation, so avoid running
       * this except when running inside linux perf, which can be inferred
       * by the PERF_BUILDID_DIR environment variable.
       */
      if (getenv("PERF_BUILDID_DIR")) {
         pid_t pid = getpid();
         char filename[256];
         util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
         perf_map_file = fopen(filename, "wt");
         util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
         perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
      }
      first_time = FALSE;
   }
   if (perf_map_file) {
      const char *symbol = LLVMGetValueName(func);
      unsigned long addr = (uintptr_t)code;
      llvm::raw_fd_ostream Out(perf_asm_fd, false);
      Out << symbol << ":\n";
      unsigned long size = disassemble(code, Out);
      fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
      fflush(perf_map_file);
   }
#else
   (void)func;
   (void)code;
#endif
}

<commit_msg>gallivm: Fix build with latest LLVM<commit_after>/**************************************************************************
 *
 * Copyright 2009-2011 VMware, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sub license, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice (including the
 * next paragraph) shall be included in all copies or substantial portions
 * of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
 * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 **************************************************************************/

#include <stddef.h>

#include <llvm-c/Core.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetInstrInfo.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Format.h>
#include <llvm/Support/MemoryObject.h>

#if HAVE_LLVM >= 0x0306
#include <llvm/Target/TargetSubtargetInfo.h>
#endif

#include <llvm/Support/TargetRegistry.h>
#include <llvm/MC/MCSubtargetInfo.h>

#include <llvm/Support/Host.h>

#if HAVE_LLVM >= 0x0303
#include <llvm/IR/Module.h>
#else
#include <llvm/Module.h>
#endif

#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#include <llvm/MC/MCRegisterInfo.h>

#if HAVE_LLVM >= 0x0305
#define OwningPtr std::unique_ptr
#elif HAVE_LLVM >= 0x0303
#include <llvm/ADT/OwningPtr.h>
#endif

#if HAVE_LLVM >= 0x0305
#include <llvm/MC/MCContext.h>
#endif

#include "util/u_math.h"
#include "util/u_debug.h"

#include "lp_bld_debug.h"

#ifdef __linux__
#include <sys/stat.h>
#include <fcntl.h>
#endif

/**
 * Check alignment.
 *
 * It is important that this check is not implemented as a macro or inlined
 * function, as the compiler assumptions in respect to alignment of global
 * and stack variables would often make the check a no op, defeating the
 * whole purpose of the exercise.
 */
extern "C" boolean
lp_check_alignment(const void *ptr, unsigned alignment)
{
   assert(util_is_power_of_two(alignment));
   return ((uintptr_t)ptr & (alignment - 1)) == 0;
}

class raw_debug_ostream :
   public llvm::raw_ostream
{
private:
   uint64_t pos;

public:
   raw_debug_ostream() : pos(0) { }

   void write_impl(const char *Ptr, size_t Size);

   uint64_t current_pos() const { return pos; }
   size_t preferred_buffer_size() const { return 512; }
};

void
raw_debug_ostream::write_impl(const char *Ptr, size_t Size)
{
   if (Size > 0) {
      char *lastPtr = (char *)&Ptr[Size];
      char last = *lastPtr;
      *lastPtr = 0;
      _debug_printf("%*s", Size, Ptr);
      *lastPtr = last;
      pos += Size;
   }
}

extern "C" const char *
lp_get_module_id(LLVMModuleRef module)
{
   return llvm::unwrap(module)->getModuleIdentifier().c_str();
}

/**
 * Same as LLVMDumpValue, but through our debugging channels.
 */
extern "C" void
lp_debug_dump_value(LLVMValueRef value)
{
#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)
   raw_debug_ostream os;
   llvm::unwrap(value)->print(os);
   os.flush();
#else
   LLVMDumpValue(value);
#endif
}

/*
 * MemoryObject wrapper around a buffer of memory, to be used by MC
 * disassembler.
 */
class BufferMemoryObject:
   public llvm::MemoryObject
{
private:
   const uint8_t *Bytes;
   uint64_t Length;
public:
   BufferMemoryObject(const uint8_t *bytes, uint64_t length) :
      Bytes(bytes), Length(length)
   {
   }

   uint64_t getBase() const
   {
      return 0;
   }

   uint64_t getExtent() const
   {
      return Length;
   }

   int readByte(uint64_t addr, uint8_t *byte) const
   {
      if (addr > getExtent())
         return -1;
      *byte = Bytes[addr];
      return 0;
   }
};

/*
 * Disassemble a function, using the LLVM MC disassembler.
 *
 * See also:
 * - http://blog.llvm.org/2010/01/x86-disassembler.html
 * - http://blog.llvm.org/2010/04/intro-to-llvm-mc-project.html
 */
static size_t
disassemble(const void* func, llvm::raw_ostream & Out)
{
   using namespace llvm;

   const uint8_t *bytes = (const uint8_t *)func;

   /*
    * Limit disassembly to this extent
    */
   const uint64_t extent = 96 * 1024;

   uint64_t max_pc = 0;

   /*
    * Initialize all used objects.
    */

   std::string Triple = sys::getDefaultTargetTriple();

   std::string Error;
   const Target *T = TargetRegistry::lookupTarget(Triple, Error);

#if HAVE_LLVM >= 0x0304
   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));
#else
   OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(Triple));
#endif

   if (!AsmInfo) {
      Out << "error: no assembly info for target " << Triple << "\n";
      Out.flush();
      return 0;
   }

   unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();

   OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(Triple));
   if (!MRI) {
      Out << "error: no register info for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

   OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
   if (!MII) {
      Out << "error: no instruction info for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

#if HAVE_LLVM >= 0x0305
   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
   OwningPtr<MCContext> MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));
   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI, *MCCtx));
#else
   OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), ""));
   OwningPtr<const MCDisassembler> DisAsm(T->createMCDisassembler(*STI));
#endif
   if (!DisAsm) {
      Out << "error: no disassembler for target " << Triple << "\n";
      Out.flush();
      return 0;
   }

   OwningPtr<MCInstPrinter> Printer(
         T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
   if (!Printer) {
      Out << "error: no instruction printer for target " << Triple.c_str() << "\n";
      Out.flush();
      return 0;
   }

   TargetOptions options;
#if defined(DEBUG)
   options.JITEmitDebugInfo = true;
#endif
#if defined(PIPE_ARCH_X86)
   options.StackAlignmentOverride = 4;
#endif
#if defined(DEBUG) || defined(PROFILE)
   options.NoFramePointerElim = true;
#endif
   OwningPtr<TargetMachine> TM(T->createTargetMachine(Triple, sys::getHostCPUName(), "", options));

#if HAVE_LLVM >= 0x0306
   const TargetInstrInfo *TII = TM->getSubtargetImpl()->getInstrInfo();
#else
   const TargetInstrInfo *TII = TM->getInstrInfo();
#endif

   /*
    * Wrap the data in a MemoryObject
    */
   BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);

   uint64_t pc;
   pc = 0;
   while (true) {
      MCInst Inst;
      uint64_t Size;

      /*
       * Print address.  We use addresses relative to the start of the function,
       * so that between runs.
       */

      Out << llvm::format("%6lu:\t", (unsigned long)pc);

      if (!DisAsm->getInstruction(Inst, Size, memoryObject,
                                 pc,
				  nulls(), nulls())) {
         Out << "invalid";
         pc += 1;
      }

      /*
       * Output the bytes in hexidecimal format.
       */

      if (0) {
         unsigned i;
         for (i = 0; i < Size; ++i) {
            Out << llvm::format("%02x ", ((const uint8_t*)bytes)[pc + i]);
         }
         for (; i < 16; ++i) {
            Out << "   ";
         }
      }

      /*
       * Print the instruction.
       */
      Printer->printInst(&Inst, Out, "");

      /*
       * Advance.
       */

      pc += Size;

      const MCInstrDesc &TID = TII->get(Inst.getOpcode());

      /*
       * Keep track of forward jumps to a nearby address.
       */

      if (TID.isBranch()) {
         for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {
            const MCOperand &operand = Inst.getOperand(i);
            if (operand.isImm()) {
               uint64_t jump;

               /*
                * FIXME: Handle both relative and absolute addresses correctly.
                * EDInstInfo actually has this info, but operandTypes and
                * operandFlags enums are not exposed in the public interface.
                */

               if (1) {
                  /*
                   * PC relative addr.
                   */

                  jump = pc + operand.getImm();
               } else {
                  /*
                   * Absolute addr.
                   */

                  jump = (uint64_t)operand.getImm();
               }

               /*
                * Output the address relative to the function start, given
                * that MC will print the addresses relative the current pc.
                */
               Out << "\t\t; " << jump;

               /*
                * Ignore far jumps given it could be actually a tail return to
                * a random address.
                */

               if (jump > max_pc &&
                   jump < extent) {
                  max_pc = jump;
               }
            }
         }
      }

      Out << "\n";

      /*
       * Stop disassembling on return statements, if there is no record of a
       * jump to a successive address.
       */

      if (TID.isReturn()) {
         if (pc > max_pc) {
            break;
         }
      }
   }

   /*
    * Print GDB command, useful to verify output.
    */

   if (0) {
      _debug_printf("disassemble %p %p\n", bytes, bytes + pc);
   }

   Out << "\n";
   Out.flush();

   return pc;
}

extern "C" void
lp_disassemble(LLVMValueRef func, const void *code) {
   raw_debug_ostream Out;
   disassemble(code, Out);
}

/*
 * Linux perf profiler integration.
 *
 * See also:
 * - http://penberg.blogspot.co.uk/2009/06/jato-has-profiler.html
 * - https://github.com/penberg/jato/commit/73ad86847329d99d51b386f5aba692580d1f8fdc
 * - http://git.kernel.org/?p=linux/kernel/git/torvalds/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d
 */
extern "C" void
lp_profile(LLVMValueRef func, const void *code)
{
#if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))
   static boolean first_time = TRUE;
   static FILE *perf_map_file = NULL;
   static int perf_asm_fd = -1;
   if (first_time) {
      /*
       * We rely on the disassembler for determining a function's size, but
       * the disassembly is a leaky and slow operation, so avoid running
       * this except when running inside linux perf, which can be inferred
       * by the PERF_BUILDID_DIR environment variable.
       */
      if (getenv("PERF_BUILDID_DIR")) {
         pid_t pid = getpid();
         char filename[256];
         util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map", (unsigned long long)pid);
         perf_map_file = fopen(filename, "wt");
         util_snprintf(filename, sizeof filename, "/tmp/perf-%llu.map.asm", (unsigned long long)pid);
         mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
         perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);
      }
      first_time = FALSE;
   }
   if (perf_map_file) {
      const char *symbol = LLVMGetValueName(func);
      unsigned long addr = (uintptr_t)code;
      llvm::raw_fd_ostream Out(perf_asm_fd, false);
      Out << symbol << ":\n";
      unsigned long size = disassemble(code, Out);
      fprintf(perf_map_file, "%lx %lx %s\n", addr, size, symbol);
      fflush(perf_map_file);
   }
#else
   (void)func;
   (void)code;
#endif
}

<|endoftext|>


<commit_before><commit_msg>tools/scylla-sstable: update general description<commit_after><|endoftext|>


<commit_before>// TODO(dkorolev): Factor out fncas.h, add a proper test.
// TODO(dkorolev): Use BFS instead of DFS for evaluating and printing.

// TODO(dkorolev): Readme, build instructions and a reference from this file.
//
// Requires:
// * C++0X, use g++ --std=c++0x
// * Boost, sudo apt-get install libboost-dev

#include <cassert>
#include <cstdio>
#include <limits>
#include <string>
#include <vector>

#include <boost/assert.hpp>
#include <boost/function.hpp>
#include <boost/static_assert.hpp>
#include <boost/utility.hpp>

#define BOOST_TEST_MODULE FNCAS
#include <boost/test/included/unit_test.hpp>

namespace fncas {

typedef double fncas_value_type;

// Parsed expression are stored in an array of node_impl objects.
// Instances of node_impl take 10 bytes each and are packed.
// Each node_impl refers to a value, an input variable, an operation or math function invocation.
// Singleton vector<node_impl> is the allocator, therefore the code is single-threaded.

enum type_t : uint8_t { var, value, op };
enum op_t : uint8_t { add = 0, subtract = 1, multiply = 2, end = 3 };

std::string op_as_string(op_t op) {
  static std::string represenatation[op_t::end] = { "+", "-", "*" };
  return (op >= 0 && op < static_cast<int>(op_t::end)) ? represenatation[op] : "?";
}

template<typename T> T apply_op(op_t op, T lhs, T rhs) {
  static boost::function<T(T, T)> evaluator[op_t::end] = {
    std::plus<T>(),
    std::minus<T>(),
    std::multiplies<T>(),
  };
  return
    (op >= 0 && op < static_cast<int>(op_t::end))
    ? evaluator[op](lhs, rhs)
    : std::numeric_limits<T>::quiet_NaN();
}

BOOST_STATIC_ASSERT(sizeof(type_t) == 1);
BOOST_STATIC_ASSERT(sizeof(op_t) == 1);

// Counting on "double", comment if trying other data type.
BOOST_STATIC_ASSERT(sizeof(fncas_value_type) == 8);

struct node_impl {
  uint8_t data_[10];
  type_t& type() {
    return *reinterpret_cast<type_t*>(&data_[0]);
  }
  uint32_t& var_index() {
    BOOST_ASSERT(type() == type_t::var);
    return *reinterpret_cast<uint32_t*>(&data_[2]);
  }
  op_t& op() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<op_t*>(&data_[1]);
  }
  uint32_t& lhs_index() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<uint32_t*>(&data_[2]);
  }
  uint32_t& rhs_index() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<uint32_t*>(&data_[6]);
  }
  fncas_value_type& value() {
    BOOST_ASSERT(type() == type_t::value);
    return *reinterpret_cast<fncas_value_type*>(&data_[2]);
  }
};
BOOST_STATIC_ASSERT(sizeof(node_impl) == 10);

inline std::vector<node_impl>& node_vector_singleton() {
  static std::vector<node_impl> storage;
  return storage;
}

// The code that deals with nodes directly uses class node as a wrapper to node_impl.
// Since the storage for node_impl-s is global, class node just holds an index of node_impl.
// User code that defines the function to work with is effectively dealing with class node objects:
// arithmetical and mathematical operations are overloaded for class node.

struct node_constructor {
  mutable uint64_t index_;
  explicit node_constructor(uint64_t index) : index_(static_cast<uint64_t>(index)) {}
  explicit node_constructor() : index_(node_vector_singleton().size()) {
    node_vector_singleton().resize(index_ + 1);
  }
};

struct node : node_constructor {
 private:
  node() : node_constructor() {}
  node(const node_constructor& instance) : node_constructor(instance) {}
 public:
  node(fncas_value_type x) : node_constructor() { type() = type_t::value; value() = x; }
  type_t& type() const { return node_vector_singleton()[index_].type(); }
  uint32_t& var_index() const { return node_vector_singleton()[index_].var_index(); }
  op_t& op() const { return node_vector_singleton()[index_].op(); }
  uint32_t& lhs_index() const { return node_vector_singleton()[index_].lhs_index(); }
  uint32_t& rhs_index() const { return node_vector_singleton()[index_].rhs_index(); }
  node lhs() const { return node_constructor(node_vector_singleton()[index_].lhs_index()); }
  node rhs() const { return node_constructor(node_vector_singleton()[index_].rhs_index()); }
  fncas_value_type& value() const { return node_vector_singleton()[index_].value(); }
  static node alloc() { return node(); }
  static node var(uint32_t index) {
    node result;
    result.type() = type_t::var;
    result.var_index() = index;
    return result;
  }
  std::string debug_as_string() const {
    if (type() == type_t::var) {
      return "x[" + std::to_string(var_index()) + "]";
    } else if (type() == type_t::value) {
      return std::to_string(value());
    } else if (type() == type_t::op) {
      return "(" + lhs().debug_as_string() + op_as_string(op()) + rhs().debug_as_string() + ")";
    } else {
      return "?";
    }
  }
  fncas_value_type eval(const std::vector<fncas_value_type>& x) const {
    if (type() == type_t::var) {
      uint32_t i = var_index();
      BOOST_ASSERT(i >= 0 && i < x.size());
      return x[i];
    } else if (type() == type_t::value) {
      return value();
    } else if (type() == type_t::op) {
      return apply_op<fncas_value_type>(op(), lhs().eval(x), rhs().eval(x));
    } else {
      return std::numeric_limits<fncas_value_type>::quiet_NaN();
    }
  }
};
BOOST_STATIC_ASSERT(sizeof(node) == 8);

// Class "x" is the placeholder class an instance of which is to be passed to the user function
// to record the computation rather than perform it.

struct x : boost::noncopyable {
  int dim;
  explicit x(int dim) : dim(dim) {
    BOOST_ASSERT(dim > 0);
  }
  node operator[](int i) const {
    BOOST_ASSERT(i >= 0);
    BOOST_ASSERT(i < dim);
    return node::var(i);
  }
};

// Helper code to allow writing polymorphic function that can be both evaluated and recorded.
// Synopsis: template<typename T> typename fncas::output<T>::type f(const T& x);

template<typename T> struct output {};
template<> struct output<std::vector<fncas_value_type> > { typedef fncas_value_type type; };
template<> struct output<x> { typedef fncas::node type; };

}  // namespace fncas

#define DECLARE_OP(OP,NAME) \
inline fncas::node operator OP(const fncas::node& lhs, const fncas::node& rhs) { \
  fncas::node result = fncas::node::alloc(); \
  result.type() = fncas::type_t::op; \
  result.op() = fncas::op_t::NAME; \
  result.lhs_index() = lhs.index_; \
  result.rhs_index() = rhs.index_; \
  return result; \
}
DECLARE_OP(+,add);
DECLARE_OP(-,subtract);
DECLARE_OP(*,multiply);

template<typename T> typename fncas::output<T>::type f(const T& x) {
  return 1 + x[0] * x[1] + x[2] - x[3] + 1;
}

BOOST_AUTO_TEST_CASE(SimpleTest) {
  std::vector<double> x({5,8,9,7});
  BOOST_CHECK_EQUAL(f(x), 44);
  auto e = f(fncas::x(4));
  BOOST_CHECK_EQUAL(e.debug_as_string(), "((((1.000000+(x[0]*x[1]))+x[2])-x[3])+1.000000)");
  BOOST_CHECK_EQUAL(e.eval(x), 44);
}
<commit_msg>Comment nits.<commit_after>// TODO(dkorolev): Factor out fncas.h, add a proper test.
// TODO(dkorolev): Use BFS instead of DFS for evaluating and printing.

// TODO(dkorolev): Readme, build instructions and a reference from this file.
//
// Requires:
// * C++0X, use g++ --std=c++0x
// * Boost, sudo apt-get install libboost-dev

#include <cassert>
#include <cstdio>
#include <limits>
#include <string>
#include <vector>

#include <boost/assert.hpp>
#include <boost/function.hpp>
#include <boost/static_assert.hpp>
#include <boost/utility.hpp>

#define BOOST_TEST_MODULE FNCAS
#include <boost/test/included/unit_test.hpp>

namespace fncas {

typedef double fncas_value_type;

// Parsed expressions are stored in an array of node_impl objects.
// Instances of node_impl take 10 bytes each and are packed.
// Each node_impl refers to a value, an input variable, an operation or math function invocation.
// Singleton vector<node_impl> is the allocator, therefore the code is single-threaded.

enum type_t : uint8_t { var, value, op };
enum op_t : uint8_t { add = 0, subtract = 1, multiply = 2, end = 3 };

std::string op_as_string(op_t op) {
  static std::string represenatation[op_t::end] = { "+", "-", "*" };
  return (op >= 0 && op < static_cast<int>(op_t::end)) ? represenatation[op] : "?";
}

template<typename T> T apply_op(op_t op, T lhs, T rhs) {
  static boost::function<T(T, T)> evaluator[op_t::end] = {
    std::plus<T>(),
    std::minus<T>(),
    std::multiplies<T>(),
  };
  return
    (op >= 0 && op < static_cast<int>(op_t::end))
    ? evaluator[op](lhs, rhs)
    : std::numeric_limits<T>::quiet_NaN();
}

BOOST_STATIC_ASSERT(sizeof(type_t) == 1);
BOOST_STATIC_ASSERT(sizeof(op_t) == 1);

// Counting on "double", comment out if trying other data type.
BOOST_STATIC_ASSERT(sizeof(fncas_value_type) == 8);

struct node_impl {
  uint8_t data_[10];
  type_t& type() {
    return *reinterpret_cast<type_t*>(&data_[0]);
  }
  uint32_t& var_index() {
    BOOST_ASSERT(type() == type_t::var);
    return *reinterpret_cast<uint32_t*>(&data_[2]);
  }
  op_t& op() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<op_t*>(&data_[1]);
  }
  uint32_t& lhs_index() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<uint32_t*>(&data_[2]);
  }
  uint32_t& rhs_index() {
    BOOST_ASSERT(type() == type_t::op);
    return *reinterpret_cast<uint32_t*>(&data_[6]);
  }
  fncas_value_type& value() {
    BOOST_ASSERT(type() == type_t::value);
    return *reinterpret_cast<fncas_value_type*>(&data_[2]);
  }
};
BOOST_STATIC_ASSERT(sizeof(node_impl) == 10);

inline std::vector<node_impl>& node_vector_singleton() {
  static std::vector<node_impl> storage;
  return storage;
}

// The code that deals with nodes directly uses class node as a wrapper to node_impl.
// Since the storage for node_impl-s is global, class node just holds an index of node_impl.
// User code that defines the function to work with is effectively dealing with class node objects:
// arithmetical and mathematical operations are overloaded for class node.

struct node_constructor {
  mutable uint64_t index_;
  explicit node_constructor(uint64_t index) : index_(static_cast<uint64_t>(index)) {}
  explicit node_constructor() : index_(node_vector_singleton().size()) {
    node_vector_singleton().resize(index_ + 1);
  }
};

struct node : node_constructor {
 private:
  node() : node_constructor() {}
  node(const node_constructor& instance) : node_constructor(instance) {}
 public:
  node(fncas_value_type x) : node_constructor() { type() = type_t::value; value() = x; }
  type_t& type() const { return node_vector_singleton()[index_].type(); }
  uint32_t& var_index() const { return node_vector_singleton()[index_].var_index(); }
  op_t& op() const { return node_vector_singleton()[index_].op(); }
  uint32_t& lhs_index() const { return node_vector_singleton()[index_].lhs_index(); }
  uint32_t& rhs_index() const { return node_vector_singleton()[index_].rhs_index(); }
  node lhs() const { return node_constructor(node_vector_singleton()[index_].lhs_index()); }
  node rhs() const { return node_constructor(node_vector_singleton()[index_].rhs_index()); }
  fncas_value_type& value() const { return node_vector_singleton()[index_].value(); }
  static node alloc() { return node(); }
  static node var(uint32_t index) {
    node result;
    result.type() = type_t::var;
    result.var_index() = index;
    return result;
  }
  std::string debug_as_string() const {
    if (type() == type_t::var) {
      return "x[" + std::to_string(var_index()) + "]";
    } else if (type() == type_t::value) {
      return std::to_string(value());
    } else if (type() == type_t::op) {
      return "(" + lhs().debug_as_string() + op_as_string(op()) + rhs().debug_as_string() + ")";
    } else {
      return "?";
    }
  }
  fncas_value_type eval(const std::vector<fncas_value_type>& x) const {
    if (type() == type_t::var) {
      uint32_t i = var_index();
      BOOST_ASSERT(i >= 0 && i < x.size());
      return x[i];
    } else if (type() == type_t::value) {
      return value();
    } else if (type() == type_t::op) {
      return apply_op<fncas_value_type>(op(), lhs().eval(x), rhs().eval(x));
    } else {
      return std::numeric_limits<fncas_value_type>::quiet_NaN();
    }
  }
};
BOOST_STATIC_ASSERT(sizeof(node) == 8);

// Class "x" is the placeholder class an instance of which is to be passed to the user function
// to record the computation rather than perform it.

struct x : boost::noncopyable {
  int dim;
  explicit x(int dim) : dim(dim) {
    BOOST_ASSERT(dim > 0);
  }
  node operator[](int i) const {
    BOOST_ASSERT(i >= 0);
    BOOST_ASSERT(i < dim);
    return node::var(i);
  }
};

// Helper code to allow writing polymorphic function that can be both evaluated and recorded.
// Synopsis: template<typename T> typename fncas::output<T>::type f(const T& x);

template<typename T> struct output {};
template<> struct output<std::vector<fncas_value_type> > { typedef fncas_value_type type; };
template<> struct output<x> { typedef fncas::node type; };

}  // namespace fncas

// Aritmetical operations and mathematical functions are defined outside namespace fncas.

#define DECLARE_OP(OP,NAME) \
inline fncas::node operator OP(const fncas::node& lhs, const fncas::node& rhs) { \
  fncas::node result = fncas::node::alloc(); \
  result.type() = fncas::type_t::op; \
  result.op() = fncas::op_t::NAME; \
  result.lhs_index() = lhs.index_; \
  result.rhs_index() = rhs.index_; \
  return result; \
}
DECLARE_OP(+,add);
DECLARE_OP(-,subtract);
DECLARE_OP(*,multiply);

template<typename T> typename fncas::output<T>::type f(const T& x) {
  return 1 + x[0] * x[1] + x[2] - x[3] + 1;
}

BOOST_AUTO_TEST_CASE(SimpleTest) {
  std::vector<double> x({5,8,9,7});
  BOOST_CHECK_EQUAL(f(x), 44);
  auto e = f(fncas::x(4));
  BOOST_CHECK_EQUAL(e.debug_as_string(), "((((1.000000+(x[0]*x[1]))+x[2])-x[3])+1.000000)");
  BOOST_CHECK_EQUAL(e.eval(x), 44);
}
<|endoftext|>


<commit_before><commit_msg>Support ls without a path<commit_after><|endoftext|>


<commit_before>/*
 * FilenameParsingGroundTruthLayer.cpp
 *
 *  Created on: Nov 10, 2014
 *      Author: wchavez
 */

#include "FilenameParsingGroundTruthLayer.hpp"

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

namespace PV {
FilenameParsingGroundTruthLayer::FilenameParsingGroundTruthLayer(const char *name, HyPerCol *hc) {
   initialize(name, hc);
}

FilenameParsingGroundTruthLayer::~FilenameParsingGroundTruthLayer() { free(mInputLayerName); }

int FilenameParsingGroundTruthLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {
   int status = ANNLayer::ioParamsFillGroup(ioFlag);
   ioParam_classes(ioFlag);
   ioParam_inputLayerName(ioFlag);
   ioParam_gtClassTrueValue(ioFlag);
   ioParam_gtClassFalseValue(ioFlag);
   return status;
}

void FilenameParsingGroundTruthLayer::ioParam_gtClassTrueValue(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamValue(
         ioFlag, name, "gtClassTrueValue", &mGtClassTrueValue, 1.0f, false);
}

void FilenameParsingGroundTruthLayer::ioParam_gtClassFalseValue(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamValue(
         ioFlag, name, "gtClassFalseValue", &mGtClassFalseValue, -1.0f, false);
}

void FilenameParsingGroundTruthLayer::ioParam_inputLayerName(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamStringRequired(ioFlag, name, "inputLayerName", &mInputLayerName);
}

void FilenameParsingGroundTruthLayer::ioParam_classes(enum ParamsIOFlag ioFlag) {
   std::string outPath = parent->getOutputPath();
   outPath             = outPath + "/classes.txt";
   mInputFile.open(outPath.c_str(), std::ifstream::in);
   pvErrorIf(!mInputFile.is_open(), "%s: Unable to open file %s\n", getName(), outPath.c_str());

   mClasses.clear();
   std::string line;
   while (getline(mInputFile, line)) {
      mClasses.push_back(line);
   }
   mInputFile.close();
}

int FilenameParsingGroundTruthLayer::communicateInitInfo() {
   mInputLayer = dynamic_cast<InputLayer *>(parent->getLayerFromName(mInputLayerName));
   pvErrorIf(mInputLayer == nullptr && parent->columnId() == 0,
         "%s: inputLayerName \"%s\" is not a layer in the HyPerCol.\n",
         getDescription_c(),
         mInputLayerName);
   pvErrorIf(mInputLayer->getPhase() >= getPhase(),
         "%s: The phase of layer %s (%d) must be less than the phase of the "
         "FilenameParsingGroundTruthLayer (%d)\n",
         getName(),
         mInputLayerName,
         mInputLayer->getPhase(),
         getPhase());
   return PV_SUCCESS;
}

bool FilenameParsingGroundTruthLayer::needUpdate(double time, double dt) {
   return mInputLayer->needUpdate(parent->simulationTime(), parent->getDeltaTime());
}

int FilenameParsingGroundTruthLayer::updateState(double time, double dt) {
   update_timer->start();
   pvdata_t *A           = getCLayer()->activity->data;
   const PVLayerLoc *loc = getLayerLoc();
   int num_neurons       = getNumNeurons();
   pvErrorIf(
         num_neurons != mClasses.size(),
         "The number of neurons in %s is not equal to the number of classes specified in "
         "%s/classes.txt\n",
         getName(),
         parent->getOutputPath());

   for (int b = 0; b < loc->nbatch; ++b) {
      char *currentFilename = nullptr;
      int filenameLen       = 0;
      if (parent->getCommunicator()->commRank() == 0) {
         currentFilename = strdup(mInputLayer->getFileName(b).c_str());
         int filenameLen = (int)strlen(currentFilename) + 1; // +1 for the null terminator
         MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());
         // Braodcast filename to all other local processes
         MPI_Bcast(
               currentFilename,
               filenameLen,
               MPI_CHAR,
               0,
               parent->getCommunicator()->communicator());
      }
      else {
         // Receive broadcast about length of filename
         MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());
         currentFilename = (char *)calloc(sizeof(char), filenameLen);
         // Receive filename
         MPI_Bcast(
               currentFilename,
               filenameLen,
               MPI_CHAR,
               0,
               parent->getCommunicator()->communicator());
      }

      std::string fil  = currentFilename;
      pvdata_t *ABatch = A + b * getNumExtended();
      for (int i = 0; i < num_neurons; i++) {
         int nExt = kIndexExtended(
               i,
               loc->nx,
               loc->ny,
               loc->nf,
               loc->halo.lt,
               loc->halo.rt,
               loc->halo.dn,
               loc->halo.up);
         int fi = featureIndex(
               nExt,
               loc->nx + loc->halo.rt + loc->halo.lt,
               loc->ny + loc->halo.dn + loc->halo.up,
               loc->nf);
         int match = fil.find(mClasses.at(i));
         if (0 <= match) {
            ABatch[nExt] = mGtClassTrueValue;
         }
         else {
            ABatch[nExt] = mGtClassFalseValue;
         }
      }
      free(currentFilename);
   }
   update_timer->stop();
   return PV_SUCCESS;
}
}
<commit_msg>Hotfix for previous error message. Functions correctly now.<commit_after>/*
 * FilenameParsingGroundTruthLayer.cpp
 *
 *  Created on: Nov 10, 2014
 *      Author: wchavez
 */

#include "FilenameParsingGroundTruthLayer.hpp"

#include <algorithm>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

namespace PV {
FilenameParsingGroundTruthLayer::FilenameParsingGroundTruthLayer(const char *name, HyPerCol *hc) {
   initialize(name, hc);
}

FilenameParsingGroundTruthLayer::~FilenameParsingGroundTruthLayer() { free(mInputLayerName); }

int FilenameParsingGroundTruthLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {
   int status = ANNLayer::ioParamsFillGroup(ioFlag);
   ioParam_classes(ioFlag);
   ioParam_inputLayerName(ioFlag);
   ioParam_gtClassTrueValue(ioFlag);
   ioParam_gtClassFalseValue(ioFlag);
   return status;
}

void FilenameParsingGroundTruthLayer::ioParam_gtClassTrueValue(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamValue(
         ioFlag, name, "gtClassTrueValue", &mGtClassTrueValue, 1.0f, false);
}

void FilenameParsingGroundTruthLayer::ioParam_gtClassFalseValue(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamValue(
         ioFlag, name, "gtClassFalseValue", &mGtClassFalseValue, -1.0f, false);
}

void FilenameParsingGroundTruthLayer::ioParam_inputLayerName(enum ParamsIOFlag ioFlag) {
   parent->parameters()->ioParamStringRequired(ioFlag, name, "inputLayerName", &mInputLayerName);
}

void FilenameParsingGroundTruthLayer::ioParam_classes(enum ParamsIOFlag ioFlag) {
   std::string outPath = parent->getOutputPath();
   outPath             = outPath + "/classes.txt";
   mInputFile.open(outPath.c_str(), std::ifstream::in);
   pvErrorIf(!mInputFile.is_open(), "%s: Unable to open file %s\n", getName(), outPath.c_str());

   mClasses.clear();
   std::string line;
   while (getline(mInputFile, line)) {
      mClasses.push_back(line);
   }
   mInputFile.close();
}

int FilenameParsingGroundTruthLayer::communicateInitInfo() {
   mInputLayer = dynamic_cast<InputLayer *>(parent->getLayerFromName(mInputLayerName));
   pvErrorIf(mInputLayer == nullptr && parent->columnId() == 0,
         "%s: inputLayerName \"%s\" is not a layer in the HyPerCol.\n",
         getDescription_c(),
         mInputLayerName);
   pvErrorIf(mInputLayer->getPhase() <= getPhase(),
         "%s: The phase of layer %s (%d) must be greater than the phase of the "
         "FilenameParsingGroundTruthLayer (%d)\n",
         getName(),
         mInputLayerName,
         mInputLayer->getPhase(),
         getPhase());
   return PV_SUCCESS;
}

bool FilenameParsingGroundTruthLayer::needUpdate(double time, double dt) {
   return mInputLayer->needUpdate(parent->simulationTime(), parent->getDeltaTime());
}

int FilenameParsingGroundTruthLayer::updateState(double time, double dt) {
   update_timer->start();
   pvdata_t *A           = getCLayer()->activity->data;
   const PVLayerLoc *loc = getLayerLoc();
   int num_neurons       = getNumNeurons();
   pvErrorIf(
         num_neurons != mClasses.size(),
         "The number of neurons in %s is not equal to the number of classes specified in "
         "%s/classes.txt\n",
         getName(),
         parent->getOutputPath());

   for (int b = 0; b < loc->nbatch; ++b) {
      char *currentFilename = nullptr;
      int filenameLen       = 0;
      if (parent->getCommunicator()->commRank() == 0) {
         currentFilename = strdup(mInputLayer->getFileName(b).c_str());
         int filenameLen = (int)strlen(currentFilename) + 1; // +1 for the null terminator
         MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());
         // Braodcast filename to all other local processes
         MPI_Bcast(
               currentFilename,
               filenameLen,
               MPI_CHAR,
               0,
               parent->getCommunicator()->communicator());
      }
      else {
         // Receive broadcast about length of filename
         MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());
         currentFilename = (char *)calloc(sizeof(char), filenameLen);
         // Receive filename
         MPI_Bcast(
               currentFilename,
               filenameLen,
               MPI_CHAR,
               0,
               parent->getCommunicator()->communicator());
      }

      std::string fil  = currentFilename;
      pvdata_t *ABatch = A + b * getNumExtended();
      for (int i = 0; i < num_neurons; i++) {
         int nExt = kIndexExtended(
               i,
               loc->nx,
               loc->ny,
               loc->nf,
               loc->halo.lt,
               loc->halo.rt,
               loc->halo.dn,
               loc->halo.up);
         int fi = featureIndex(
               nExt,
               loc->nx + loc->halo.rt + loc->halo.lt,
               loc->ny + loc->halo.dn + loc->halo.up,
               loc->nf);
         int match = fil.find(mClasses.at(i));
         if (0 <= match) {
            ABatch[nExt] = mGtClassTrueValue;
         }
         else {
            ABatch[nExt] = mGtClassFalseValue;
         }
      }
      free(currentFilename);
   }
   update_timer->stop();
   return PV_SUCCESS;
}
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2017 PX4 Development Team. 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.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/**
 * @file FlightTaskManual.cpp
 *
 * Linear and exponential map from stick inputs to range -1 and 1.
 *
 */

#include "FlightTaskManual.hpp"
#include <mathlib/mathlib.h>
#include <float.h>

using namespace matrix;

FlightTaskManual::FlightTaskManual(control::SuperBlock *parent, const char *name) :
	FlightTask(parent, name),
	_hold_dz(parent, "MPC_HOLD_DZ", false),
	_xy_vel_man_expo(parent, "MPC_XY_MAN_EXPO", false),
	_z_vel_man_expo(parent, "MPC_Z_MAN_EXPO", false)
{
}

bool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array)
{
	if (!FlightTask::initializeSubscriptions(subscription_array)) {
		return false;
	}

	if (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) {
		return false;
	}

	return true;
}

bool FlightTaskManual::activate()
{
	bool ret = FlightTask::activate();
	_hold_position = Vector3f(NAN, NAN, NAN);
	_hold_yaw = NAN;
	return ret;
}

bool FlightTaskManual::updateInitialize()
{
	bool ret = FlightTask::updateInitialize();
	const bool sticks_available = _evaluateSticks();

	if (_sticks_data_required) {
		ret = ret && sticks_available;
	}

	return ret;
}

bool FlightTaskManual::update()
{
	/* TODO
	 * FlightTask setpoint interface and Position Controller need to be updated to include
	 * thrust setpoint. With thrust setpoint FlightTaskManual can be used as manual flight mode.
	 */
	return true;
}

float FlightTaskManual::_get_input_frame_yaw()
{
	/* using constant yaw angle from setpoint here to prevent sideways oscillation in fast forward flight */
	if (PX4_ISFINITE(_hold_yaw)) {
		return _hold_yaw;

	} else {
		return _yaw;
	}
}

void FlightTaskManual::_updateYaw()
{
	const float yaw_speed = _sticks(3) * math::radians(_man_yaw_max.get());
	_setYawspeedSetpoint(yaw_speed);

	const bool stick_yaw_zero = fabsf(yaw_speed) <= FLT_EPSILON;

	if (stick_yaw_zero && !PX4_ISFINITE(_hold_yaw)) {
		_hold_yaw = _yaw;

	} else if (!stick_yaw_zero) {
		_hold_yaw = NAN;
	}

	_setYawSetpoint(_hold_yaw);
}

bool FlightTaskManual::_evaluateSticks()
{
	/* Sticks are rescaled linearly and exponentially from [0,1] to [-1,1] */
	if ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) {

		/* Linear scale  */
		_sticks(0) = _sub_manual_control_setpoint->get().x; /* NED x, "pitch" [-1,1] */
		_sticks(1) = _sub_manual_control_setpoint->get().y; /* NED y, "roll" [-1,1] */
		_sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; /* NED z, "thrust" resacaled from [0,1] to [-1,1] */
		_sticks(3) = _sub_manual_control_setpoint->get().r; /* "yaw" [-1,1] */

		/* Exponential scale */
		_sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _hold_dz.get());
		_sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _hold_dz.get());
		_sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _hold_dz.get());

		return true;

	} else {
		/* Timeout: set all sticks to zero */
		_sticks.zero();
		_sticks_expo.zero();
		return false;
	}
}
<commit_msg>FlightTaskManual: remove unused methods<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2017 PX4 Development Team. 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.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/
/**
 * @file FlightTaskManual.cpp
 *
 * Linear and exponential map from stick inputs to range -1 and 1.
 *
 */

#include "FlightTaskManual.hpp"
#include <mathlib/mathlib.h>
#include <float.h>

using namespace matrix;

FlightTaskManual::FlightTaskManual(control::SuperBlock *parent, const char *name) :
	FlightTask(parent, name),
	_hold_dz(parent, "MPC_HOLD_DZ", false),
	_xy_vel_man_expo(parent, "MPC_XY_MAN_EXPO", false),
	_z_vel_man_expo(parent, "MPC_Z_MAN_EXPO", false)
{
}

bool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array)
{
	if (!FlightTask::initializeSubscriptions(subscription_array)) {
		return false;
	}

	if (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) {
		return false;
	}

	return true;
}

bool FlightTaskManual::activate()
{
	bool ret = FlightTask::activate();
	return ret;
}

bool FlightTaskManual::updateInitialize()
{
	bool ret = FlightTask::updateInitialize();
	const bool sticks_available = _evaluateSticks();

	if (_sticks_data_required) {
		ret = ret && sticks_available;
	}

	return ret;
}

bool FlightTaskManual::update()
{
	/* TODO
	 * FlightTask setpoint interface and Position Controller need to be updated to include
	 * thrust setpoint. With thrust setpoint FlightTaskManual can be used as manual flight mode.
	 */
	return true;
}

bool FlightTaskManual::_evaluateSticks()
{
	/* Sticks are rescaled linearly and exponentially from [0,1] to [-1,1] */
	if ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) {

		/* Linear scale  */
		_sticks(0) = _sub_manual_control_setpoint->get().x; /* NED x, "pitch" [-1,1] */
		_sticks(1) = _sub_manual_control_setpoint->get().y; /* NED y, "roll" [-1,1] */
		_sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; /* NED z, "thrust" resacaled from [0,1] to [-1,1] */
		_sticks(3) = _sub_manual_control_setpoint->get().r; /* "yaw" [-1,1] */

		/* Exponential scale */
		_sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _hold_dz.get());
		_sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _hold_dz.get());
		_sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _hold_dz.get());

		return true;

	} else {
		/* Timeout: set all sticks to zero */
		_sticks.zero();
		_sticks_expo.zero();
		return false;
	}
}
<|endoftext|>


<commit_before>#include <vector>

#include "texture.h"
#include "texture_pack.h"
#include "font_renderer.h"
#include "ball.h"
#include "paddle.h"
#include "constants.h"
#include "collision.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
#include <string>
#include <sstream>

//The window we'll be rendering to
SDL_Window* window = nullptr;

//The window renderer
SDL_Renderer* renderer = nullptr;

Mix_Chunk* bop = nullptr;
Mix_Chunk* boop = nullptr;

bool Init(TexturePack* textures) {
  //Initialization flag
  bool success = true;

  //Initialize SDL
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Set texture filtering to linear
  if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) {
    printf("Warning: Linear texture filtering not enabled!");
  }

  //Create window
  window = SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, constants::SCREEN_WIDTH, constants::SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
  if (window == nullptr) {
    printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Create vsynced renderer for window
  renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (renderer == nullptr) {
    printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

  //Initialize PNG loading
  int img_flags = IMG_INIT_PNG;
  if (!(IMG_Init(img_flags) & img_flags)) {
    printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
    return false;
  }

  //Initialize SDL_ttf
  if(TTF_Init() == -1) {
    printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError());
    return false;
  }

  //Initialize SDL_mixer
  if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) {
    printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
    return false;
  }

  //TODO: use seperate texture pack for fonts
  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    textures->InitTexture(static_cast<TextureName>(i), renderer);
  }

  return success;
}

bool LoadMedia(TexturePack* textures) {
  //Loading success flag
  bool success = true;

  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    Texture* current = textures->GetTexture(static_cast<TextureName>(i));
    std::string path = textures->TexturePath(static_cast<TextureName>(i));
    if (!current->LoadFromFile(path)) {
      printf("Failed to load texture: %s\n", path.c_str());
      success = false;
    }
  }

  bop = Mix_LoadWAV("assets/sfx/blip-fs5.wav");
  if(bop == nullptr) {
		printf( "Failed to load bop sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
		success = false;
  }

  boop = Mix_LoadWAV("assets/sfx/blip-fs4.wav");
  if(boop == nullptr) {
		printf( "Failed to load boop sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
		success = false;
  }

  return success;
}

void Close(TexturePack* textures) {
  //Free loaded images
  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    Texture* current = textures->GetTexture(static_cast<TextureName>(i));
    current->Free();
  }

  //Destroy window
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  window = nullptr;
  renderer = nullptr;

  Mix_FreeChunk(bop);
  bop = nullptr;

  Mix_FreeChunk(boop);
  boop = nullptr;

  //Quit SDL subsystems
  Mix_Quit();
  TTF_Quit();
  IMG_Quit();
  SDL_Quit();
}

void PrintRect(SDL_Rect* rect) {
  printf("Rect - x: %d, y: %d, w: %d, h: %d\n", rect->x, rect->y, rect->w, rect->h);
}

void GameLoop(TexturePack* textures) {
  bool quit = false;

  SDL_Event e;

  Ball ball;

  Paddle player(true);
  Paddle ai(false);

  int player_score = 0;
  int ai_score = 0;

  std::vector<SDL_Rect*> ball_colliders;

  ball_colliders.push_back(player.GetCollider());
  ball_colliders.push_back(ai.GetCollider());

  Uint64 time_now = SDL_GetPerformanceCounter();
  Uint64 time_last = 0;
  double delta_time = 0;

  SDL_Color text_color = { 255, 255, 255, 255 };

  FontRenderer font_renderer;

  while (!quit) {
    time_last = time_now;
    time_now = SDL_GetPerformanceCounter();

    delta_time = ((time_now - time_last)*1000 / (double)SDL_GetPerformanceFrequency());

    //Handle events on queue
    while(SDL_PollEvent(&e) != 0) {
      //User requests quit
      if(e.type == SDL_QUIT) {
        quit = true;
      }

      player.HandleEvent(e);
    }

    ai.Autopilot(ball.GetCollider());

    // Paddles must move before ball!
    ai.Move(delta_time);
    player.Move(delta_time);
    CollisionType collision = ball.Move(delta_time, ball_colliders, &player_score, &ai_score);

    //Clear screen
    SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
    SDL_RenderClear(renderer);

    //Render bg
    textures->GetTexture(TextureName::BG)->Render(0, 0);

    // Render paddles
    ai.Render(textures->GetTexture(TextureName::PADDLE));
    player.Render(textures->GetTexture(TextureName::PADDLE));

    //Render dot
    ball.Render(textures->GetTexture(TextureName::BALL));

    // Render text
    int text_width = 0;
    int text_height = 0;
    std::ostringstream score_stream;
    score_stream << player_score << "  " << ai_score;

    std::string score_text = score_stream.str();

    if (font_renderer.SizeFont(FontName::FORWARD, 42, score_text, &text_width, &text_height) != 0) {
      printf("Failure to size font!\n");
    }

    font_renderer.RenderFont(renderer, FontName::FORWARD, 42,
    /*x=*/(constants::SCREEN_WIDTH - text_width) / 2, /*y=*/10, score_text, text_color);

    // This is a terrible hack due to the font rendering being broken
    if (player_score == -1) {
      player_score = 0;
    }

    switch (collision) {
      case CollisionType::WALL:
      case CollisionType::PADDLE:
        Mix_PlayChannel( -1, bop, 0 );
        break;
      case CollisionType::SCORE:
        Mix_PlayChannel(-1, boop, 0);
        break;
      default: break;
    }

    //Update screen
    SDL_RenderPresent(renderer);
  }
}

int main(int argc, char *args[]) {
  TexturePack textures;

  if (!Init(&textures)) {
    printf("Failed to initialize main game!\n");
    return -1;
  }

  if (!LoadMedia(&textures)) {
    printf("Failed to load media!\n");
    return -1;
  }

  GameLoop(&textures);

  Close(&textures);

  return 0;
}
<commit_msg>Remove the hack to make font rendering work<commit_after>#include <vector>

#include "texture.h"
#include "texture_pack.h"
#include "font_renderer.h"
#include "ball.h"
#include "paddle.h"
#include "constants.h"
#include "collision.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include <stdio.h>
#include <string>
#include <sstream>

//The window we'll be rendering to
SDL_Window* window = nullptr;

//The window renderer
SDL_Renderer* renderer = nullptr;

Mix_Chunk* bop = nullptr;
Mix_Chunk* boop = nullptr;

bool Init(TexturePack* textures) {
  //Initialization flag
  bool success = true;

  //Initialize SDL
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Set texture filtering to linear
  if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1")) {
    printf("Warning: Linear texture filtering not enabled!");
  }

  //Create window
  window = SDL_CreateWindow("Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, constants::SCREEN_WIDTH, constants::SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
  if (window == nullptr) {
    printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Create vsynced renderer for window
  renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (renderer == nullptr) {
    printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
    return false;
  }

  //Initialize renderer color
  SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);

  //Initialize PNG loading
  int img_flags = IMG_INIT_PNG;
  if (!(IMG_Init(img_flags) & img_flags)) {
    printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
    return false;
  }

  //Initialize SDL_ttf
  if(TTF_Init() == -1) {
    printf("SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError());
    return false;
  }

  //Initialize SDL_mixer
  if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) {
    printf("SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError());
    return false;
  }

  //TODO: use seperate texture pack for fonts
  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    textures->InitTexture(static_cast<TextureName>(i), renderer);
  }

  return success;
}

bool LoadMedia(TexturePack* textures) {
  //Loading success flag
  bool success = true;

  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    Texture* current = textures->GetTexture(static_cast<TextureName>(i));
    std::string path = textures->TexturePath(static_cast<TextureName>(i));
    if (!current->LoadFromFile(path)) {
      printf("Failed to load texture: %s\n", path.c_str());
      success = false;
    }
  }

  bop = Mix_LoadWAV("assets/sfx/blip-fs5.wav");
  if(bop == nullptr) {
		printf( "Failed to load bop sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
		success = false;
  }

  boop = Mix_LoadWAV("assets/sfx/blip-fs4.wav");
  if(boop == nullptr) {
		printf( "Failed to load boop sound effect! SDL_mixer Error: %s\n", Mix_GetError() );
		success = false;
  }

  return success;
}

void Close(TexturePack* textures) {
  //Free loaded images
  for (int i = 0; i < static_cast<int>(TextureName::TOTAL_NUM_TEXTURES); ++i) {
    Texture* current = textures->GetTexture(static_cast<TextureName>(i));
    current->Free();
  }

  //Destroy window
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  window = nullptr;
  renderer = nullptr;

  Mix_FreeChunk(bop);
  bop = nullptr;

  Mix_FreeChunk(boop);
  boop = nullptr;

  //Quit SDL subsystems
  Mix_Quit();
  TTF_Quit();
  IMG_Quit();
  SDL_Quit();
}

void PrintRect(SDL_Rect* rect) {
  printf("Rect - x: %d, y: %d, w: %d, h: %d\n", rect->x, rect->y, rect->w, rect->h);
}

void GameLoop(TexturePack* textures) {
  bool quit = false;

  SDL_Event e;

  Ball ball;

  Paddle player(true);
  Paddle ai(false);

  int player_score = 0;
  int ai_score = 0;

  std::vector<SDL_Rect*> ball_colliders;

  ball_colliders.push_back(player.GetCollider());
  ball_colliders.push_back(ai.GetCollider());

  Uint64 time_now = SDL_GetPerformanceCounter();
  Uint64 time_last = 0;
  double delta_time = 0;

  SDL_Color text_color = { 255, 255, 255, 255 };

  FontRenderer font_renderer;

  while (!quit) {
    time_last = time_now;
    time_now = SDL_GetPerformanceCounter();

    delta_time = ((time_now - time_last)*1000 / (double)SDL_GetPerformanceFrequency());

    //Handle events on queue
    while(SDL_PollEvent(&e) != 0) {
      //User requests quit
      if(e.type == SDL_QUIT) {
        quit = true;
      }

      player.HandleEvent(e);
    }

    ai.Autopilot(ball.GetCollider());

    // Paddles must move before ball!
    ai.Move(delta_time);
    player.Move(delta_time);
    CollisionType collision = ball.Move(delta_time, ball_colliders, &player_score, &ai_score);

    //Clear screen
    SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
    SDL_RenderClear(renderer);

    //Render bg
    textures->GetTexture(TextureName::BG)->Render(0, 0);

    // Render paddles
    ai.Render(textures->GetTexture(TextureName::PADDLE));
    player.Render(textures->GetTexture(TextureName::PADDLE));

    //Render dot
    ball.Render(textures->GetTexture(TextureName::BALL));

    // Render text
    int text_width = 0;
    int text_height = 0;
    std::ostringstream score_stream;
    score_stream << player_score << "  " << ai_score;

    std::string score_text = score_stream.str();

    if (font_renderer.SizeFont(FontName::FORWARD, 42, score_text, &text_width, &text_height) != 0) {
      printf("Failure to size font!\n");
    }

    font_renderer.RenderFont(renderer, FontName::FORWARD, 42,
    /*x=*/(constants::SCREEN_WIDTH - text_width) / 2, /*y=*/10, score_text, text_color);

    switch (collision) {
      case CollisionType::WALL:
      case CollisionType::PADDLE:
        Mix_PlayChannel( -1, bop, 0 );
        break;
      case CollisionType::SCORE:
        Mix_PlayChannel(-1, boop, 0);
        break;
      default: break;
    }

    //Update screen
    SDL_RenderPresent(renderer);
  }
}

int main(int argc, char *args[]) {
  TexturePack textures;

  if (!Init(&textures)) {
    printf("Failed to initialize main game!\n");
    return -1;
  }

  if (!LoadMedia(&textures)) {
    printf("Failed to load media!\n");
    return -1;
  }

  GameLoop(&textures);

  Close(&textures);

  return 0;
}
<|endoftext|>


<commit_before>/*
   Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)

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

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

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

#include <ks/gui/KsGuiApplication.hpp>

#include <raintk/RainTkInputSystem.hpp>
#include <raintk/RainTkScene.hpp>
#include <raintk/RainTkInputArea.hpp>
#include <raintk/RainTkLog.hpp>

namespace raintk
{
    // ============================================================= //
    // ============================================================= //

    using InputType = InputArea::Point::Type;

    class InputListener : public ks::Object
    {
    public:
        using base_type = ks::Object;

        InputListener(ks::Object::Key const &key,
                      shared_ptr<ks::EventLoop> event_loop) :
            ks::Object(key,event_loop)
        {
            std::pair<bool,InputArea::Point> pressed_point;
            pressed_point.first = false;

//            list_lk_pressed_by_type.resize(
//                        uint(InputArea::Point::Type::TypeCount),
//                        pressed_point);
        }

        void Init(ks::Object::Key const &,
                  shared_ptr<InputListener> const &)
        {}

        ~InputListener()
        {}

        void OnMouseInput(ks::gui::MouseEvent mouse_event)
        {
//            uint const mouse_type_idx = uint(InputArea::Point::Type::Mouse);

            InputArea::Point mouse_point {
                InputArea::Point::Type::Mouse,
                static_cast<InputArea::Point::Button>(mouse_event.button),
                static_cast<InputArea::Point::Action>(mouse_event.action),
                px(mouse_event.x),
                px(mouse_event.y),
                mouse_event.timestamp
            };

            list_points.push_back(mouse_point);

            // NOTE: We no longer do this, see InputSystem
            // comments for more details
//            // Save the most recent mouse_event if any mouse
//            // buttons are being pressed so that the InputSystem
//            // can repeat last pressed events
//            if(mouse_point.action == InputArea::Point::Action::Press)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].first = true;
//            }
//            else if(mouse_point.action == InputArea::Point::Action::Release)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].first = false;
//            }

//            if(list_lk_pressed_by_type[mouse_type_idx].first)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].second = mouse_point;
//            }
        }

        void ResampleInputs(TimePoint const &prev_upd_time,
                            TimePoint const &curr_upd_time)
        {
            // For some inputs (mouse) on SDL it seems like
            // the timestamp reflects when the event is polled
            // rather than when it actually occurs

            // So we just assign the timestamp to always mean
            // when its polled

            // This means the timestamp of the event represents
            // *the end of the interval the event occured in*

            // To convert the timestamps to reflect when the
            // event occured, we resample by linearly interpolating
            // the events over the interval (this is a guess)

            // @prev_upd_time: start of the interval
            // @curr_upd_time: end of the interval

            // We assume that list_points is cleared between
            // each call to ResampleInputs

            if(list_points.empty())
            {
                return;
            }

            uint const point_count = list_points.size();

            Microseconds avg_interval =
                    ks::CalcDuration<Microseconds>(
                        prev_upd_time,
                        curr_upd_time);

            avg_interval = Microseconds(avg_interval.count()/(point_count+1));

            for(uint i=0; i < point_count; i++)
            {
                list_points[i].timestamp =
                        prev_upd_time +
                        Microseconds(avg_interval.count()*(i+1));
            }
        }

        std::vector<InputArea::Point> list_points;

//        std::vector<
//            std::pair<bool,InputArea::Point>
//        > list_lk_pressed_by_type;
    };

    // ============================================================= //
    // ============================================================= //

    InputSystem::InputSystem(Scene* scene,
                             ks::gui::Application* app) :
        m_scene(scene)
    {
        // Get the InputData mask
        m_inputable_mask =
                m_scene->template GetComponentMask<InputData,TransformData>();

        // Create the InputData component list
        m_scene->template RegisterComponentList<InputData>(
                    make_unique<InputDataComponentList>(*m_scene));

        m_cmlist_input_data =
                static_cast<InputDataComponentList*>(
                    m_scene->template GetComponentList<InputData>());

        // Create the InputListener
        m_input_listener =
                ks::MakeObject<InputListener>(
                    scene->GetEventLoop());

        app->signal_mouse_input->Connect(
                    m_input_listener,
                    &InputListener::OnMouseInput,
                    ks::ConnectionType::Direct);
    }

    InputSystem::~InputSystem()
    {

    }

    std::string InputSystem::GetDesc() const
    {
        return "raintk InputSystem";
    }

    void InputSystem::Update(TimePoint const &prev_upd_time,
                             TimePoint const &curr_upd_time)
    {
        auto& list_entities = m_scene->GetEntityList();
        auto& list_input_data = m_cmlist_input_data->GetSparseList();

        auto const & list_xf_data =
                static_cast<TransformDataComponentList*>(
                    m_scene->template GetComponentList<TransformData>())->
                        GetSparseList();

        m_list_input_areas_by_depth.clear();

        for(uint ent_id=0; ent_id < list_entities.size(); ent_id++)
        {
            if((list_entities[ent_id].mask & m_inputable_mask)==m_inputable_mask)
            {
                auto& input_data = list_input_data[ent_id];
                auto const &xf_data = list_xf_data[ent_id];

                // NOTE: We need to check if the transform data is valid.
                // TransformData is invalid until the TransformSystem has
                // updated it for the first time.
                if(input_data.enabled && xf_data.valid)
                {
                    m_list_input_areas_by_depth.emplace_back(
                                xf_data.world_xf[3].z,
                                input_data.input_area);
                }
            }
        }

        // Sort the InputAreas by height // TODO rename height --> depth!
        std::sort(
                    m_list_input_areas_by_depth.begin(),
                    m_list_input_areas_by_depth.end(),
                    [](std::pair<float,InputArea*> const &a,
                       std::pair<float,InputArea*> const &b) {
                        return(a.first > b.first);
                    });

        // Resample input times
        m_input_listener->ResampleInputs(
                    prev_upd_time,curr_upd_time);

        auto& list_points = m_input_listener->list_points;

        // NOTE (start)
        // We initially repeated inputs that were previously
        // pressed but hadn't been released to be able to
        // detect input speed continuously. This is currently
        // disabled and current widgets will probably break
        // if its reenabled (ie ScrollArea)

//        // If list_points is empty, fill it with any inputs
//        // that were previously pressed but haven't yet been
//        // released

//        if(list_points.empty())
//        {
//            for(auto& pressed_point : m_input_listener->list_lk_pressed_by_type)
//            {
//                if(pressed_point.first)
//                {
//                    list_points.push_back(pressed_point.second);
//                    list_points.back().timestamp = curr_upd_time;
//                }
//            }
//        }

        // NOTE (end)

        while(list_points.empty()==false)
        {
            for(uint i=0; i < m_list_input_areas_by_depth.size();)
            {
                auto input_area = m_list_input_areas_by_depth[i].second;
                auto const &world_pt = list_points[0];

                glm::vec2 world_xy(world_pt.x,world_pt.y);
                glm::vec2 local_xy = Widget::CalcLocalCoords(input_area,world_xy);
                bool inside = Widget::CalcPointInside(input_area,world_xy,local_xy);

                auto local_pt = world_pt;
                local_pt.x = local_xy.x;
                local_pt.y = local_xy.y;

                auto const response = input_area->handleInput(local_pt,inside);

                if(response == InputArea::Response::Accept)
                {
                    list_points.erase(list_points.begin());

                    if(list_points.empty())
                    {
                        break;
                    }
                    else
                    {
                        // Start back at the beginning
                        i=0;
                    }
                }
                else
                {
                    // Try the current point with
                    // the next InputArea
                    i++;
                }
            }

            if(list_points.empty())
            {
                break;
            }

            // When we get here the first entry in list_points
            // has been rejected by all InputAreas. Discard it
            // and try from the beginning with the next point.
            list_points.erase(list_points.begin());
        }
    }

    InputDataComponentList*
    InputSystem::GetInputDataComponentList() const
    {
        return m_cmlist_input_data;
    }

    std::vector<std::pair<float,InputArea*>> const &
    InputSystem::GetInputAreasByDepth() const
    {
        return m_list_input_areas_by_depth;
    }
}
<commit_msg>InputSystem: Added touch event listener<commit_after>/*
   Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)

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

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

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

#include <ks/gui/KsGuiApplication.hpp>

#include <raintk/RainTkInputSystem.hpp>
#include <raintk/RainTkScene.hpp>
#include <raintk/RainTkInputArea.hpp>
#include <raintk/RainTkLog.hpp>

namespace raintk
{
    // ============================================================= //
    // ============================================================= //

    using InputType = InputArea::Point::Type;

    class InputListener : public ks::Object
    {
    public:
        using base_type = ks::Object;

        InputListener(ks::Object::Key const &key,
                      shared_ptr<ks::EventLoop> event_loop) :
            ks::Object(key,event_loop)
        {
            std::pair<bool,InputArea::Point> pressed_point;
            pressed_point.first = false;

//            list_lk_pressed_by_type.resize(
//                        uint(InputArea::Point::Type::TypeCount),
//                        pressed_point);
        }

        void Init(ks::Object::Key const &,
                  shared_ptr<InputListener> const &)
        {}

        ~InputListener()
        {}

        void OnMouseInput(ks::gui::MouseEvent mouse_event)
        {
//            uint const mouse_type_idx = uint(InputArea::Point::Type::Mouse);

            InputArea::Point mouse_point {
                InputArea::Point::Type::Mouse,
                static_cast<InputArea::Point::Button>(mouse_event.button),
                static_cast<InputArea::Point::Action>(mouse_event.action),
                px(mouse_event.x),
                px(mouse_event.y),
                mouse_event.timestamp
            };

            list_points.push_back(mouse_point);

            // NOTE: We no longer do this, see InputSystem
            // comments for more details
//            // Save the most recent mouse_event if any mouse
//            // buttons are being pressed so that the InputSystem
//            // can repeat last pressed events
//            if(mouse_point.action == InputArea::Point::Action::Press)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].first = true;
//            }
//            else if(mouse_point.action == InputArea::Point::Action::Release)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].first = false;
//            }

//            if(list_lk_pressed_by_type[mouse_type_idx].first)
//            {
//                list_lk_pressed_by_type[mouse_type_idx].second = mouse_point;
//            }
        }

        void OnTouchInput(ks::gui::TouchEvent touch_event)
        {
            // TODO support additional touch points
            if(touch_event.index > 2)
            {
                return;
            }

            InputArea::Point touch_point{
                // Type=0 is Mouse, Type=1 is Touch0, etc
                static_cast<InputArea::Point::Type>(touch_event.index+1),
                InputArea::Point::Button::None,
                static_cast<InputArea::Point::Action>(touch_event.action),
                px(touch_event.x),
                px(touch_event.y),
                touch_event.timestamp
            };

            list_points.push_back(touch_point);
        }

        void ResampleInputs(TimePoint const &prev_upd_time,
                            TimePoint const &curr_upd_time)
        {
            // For some inputs (mouse) on SDL it seems like
            // the timestamp reflects when the event is polled
            // rather than when it actually occurs

            // So we just assign the timestamp to always mean
            // when its polled

            // This means the timestamp of the event represents
            // *the end of the interval the event occured in*

            // To convert the timestamps to reflect when the
            // event occured, we resample by linearly interpolating
            // the events over the interval (this is a guess)

            // @prev_upd_time: start of the interval
            // @curr_upd_time: end of the interval

            // We assume that list_points is cleared between
            // each call to ResampleInputs

            if(list_points.empty())
            {
                return;
            }

            uint const point_count = list_points.size();

            Microseconds avg_interval =
                    ks::CalcDuration<Microseconds>(
                        prev_upd_time,
                        curr_upd_time);

            avg_interval = Microseconds(avg_interval.count()/(point_count+1));

            for(uint i=0; i < point_count; i++)
            {
                list_points[i].timestamp =
                        prev_upd_time +
                        Microseconds(avg_interval.count()*(i+1));
            }
        }

        std::vector<InputArea::Point> list_points;

//        std::vector<
//            std::pair<bool,InputArea::Point>
//        > list_lk_pressed_by_type;
    };

    // ============================================================= //
    // ============================================================= //

    InputSystem::InputSystem(Scene* scene,
                             ks::gui::Application* app) :
        m_scene(scene)
    {
        // Get the InputData mask
        m_inputable_mask =
                m_scene->template GetComponentMask<InputData,TransformData>();

        // Create the InputData component list
        m_scene->template RegisterComponentList<InputData>(
                    make_unique<InputDataComponentList>(*m_scene));

        m_cmlist_input_data =
                static_cast<InputDataComponentList*>(
                    m_scene->template GetComponentList<InputData>());

        // Create the InputListener
        m_input_listener =
                ks::MakeObject<InputListener>(
                    scene->GetEventLoop());

        app->signal_mouse_input->Connect(
                    m_input_listener,
                    &InputListener::OnMouseInput,
                    ks::ConnectionType::Direct);

        app->signal_touch_input->Connect(
                    m_input_listener,
                    &InputListener::OnTouchInput,
                    ks::ConnectionType::Direct);
    }

    InputSystem::~InputSystem()
    {

    }

    std::string InputSystem::GetDesc() const
    {
        return "raintk InputSystem";
    }

    void InputSystem::Update(TimePoint const &prev_upd_time,
                             TimePoint const &curr_upd_time)
    {
        auto& list_entities = m_scene->GetEntityList();
        auto& list_input_data = m_cmlist_input_data->GetSparseList();

        auto const & list_xf_data =
                static_cast<TransformDataComponentList*>(
                    m_scene->template GetComponentList<TransformData>())->
                        GetSparseList();

        m_list_input_areas_by_depth.clear();

        for(uint ent_id=0; ent_id < list_entities.size(); ent_id++)
        {
            if((list_entities[ent_id].mask & m_inputable_mask)==m_inputable_mask)
            {
                auto& input_data = list_input_data[ent_id];
                auto const &xf_data = list_xf_data[ent_id];

                // NOTE: We need to check if the transform data is valid.
                // TransformData is invalid until the TransformSystem has
                // updated it for the first time.
                if(input_data.enabled && xf_data.valid)
                {
                    m_list_input_areas_by_depth.emplace_back(
                                xf_data.world_xf[3].z,
                                input_data.input_area);
                }
            }
        }

        // Sort the InputAreas by height // TODO rename height --> depth!
        std::sort(
                    m_list_input_areas_by_depth.begin(),
                    m_list_input_areas_by_depth.end(),
                    [](std::pair<float,InputArea*> const &a,
                       std::pair<float,InputArea*> const &b) {
                        return(a.first > b.first);
                    });

        // Resample input times
        m_input_listener->ResampleInputs(
                    prev_upd_time,curr_upd_time);

        auto& list_points = m_input_listener->list_points;

        // NOTE (start)
        // We initially repeated inputs that were previously
        // pressed but hadn't been released to be able to
        // detect input speed continuously. This is currently
        // disabled and current widgets will probably break
        // if its reenabled (ie ScrollArea)

//        // If list_points is empty, fill it with any inputs
//        // that were previously pressed but haven't yet been
//        // released

//        if(list_points.empty())
//        {
//            for(auto& pressed_point : m_input_listener->list_lk_pressed_by_type)
//            {
//                if(pressed_point.first)
//                {
//                    list_points.push_back(pressed_point.second);
//                    list_points.back().timestamp = curr_upd_time;
//                }
//            }
//        }

        // NOTE (end)

        while(list_points.empty()==false)
        {
            for(uint i=0; i < m_list_input_areas_by_depth.size();)
            {
                auto input_area = m_list_input_areas_by_depth[i].second;
                auto const &world_pt = list_points[0];

                glm::vec2 world_xy(world_pt.x,world_pt.y);
                glm::vec2 local_xy = Widget::CalcLocalCoords(input_area,world_xy);
                bool inside = Widget::CalcPointInside(input_area,world_xy,local_xy);

                auto local_pt = world_pt;
                local_pt.x = local_xy.x;
                local_pt.y = local_xy.y;

                auto const response = input_area->handleInput(local_pt,inside);

                if(response == InputArea::Response::Accept)
                {
                    list_points.erase(list_points.begin());

                    if(list_points.empty())
                    {
                        break;
                    }
                    else
                    {
                        // Start back at the beginning
                        i=0;
                    }
                }
                else
                {
                    // Try the current point with
                    // the next InputArea
                    i++;
                }
            }

            if(list_points.empty())
            {
                break;
            }

            // When we get here the first entry in list_points
            // has been rejected by all InputAreas. Discard it
            // and try from the beginning with the next point.
            list_points.erase(list_points.begin());
        }
    }

    InputDataComponentList*
    InputSystem::GetInputDataComponentList() const
    {
        return m_cmlist_input_data;
    }

    std::vector<std::pair<float,InputArea*>> const &
    InputSystem::GetInputAreasByDepth() const
    {
        return m_list_input_areas_by_depth;
    }
}
<|endoftext|>