<commit_before>#ifndef _BBFIND_HPP_
#define _BBFIND_HPP_

#include <vector>
#include <list>

using ::std::vector;
using ::std::list;

class BBFind
{
   public:

      class Rectangle
      {
         public:
            int x,  y, width, height;
            int left()   const { return x - width / 2; }
            int right()  const { return x + width / 2; }
            int top()    const { return y - height/ 2; }
            int bottom() const { return y + height/ 2; }
            static Rectangle  join        (const Rectangle &rectA, const Rectangle &rectB);
            static float      intersecting(const Rectangle &rectA, const Rectangle &rectB);
            static bool       touching    (const Rectangle &rectA, const Rectangle &rectB);
            static bool       equal       (const Rectangle &rectA, const Rectangle &rectB);

      };

      typedef vector< vector< vector<float> > > Map3;       // [feature][y][x]
      typedef vector< vector<float> >           Map2;       // [y][x]
      typedef vector< list<Rectangle> >         Rectangles; // [feature][rectangles]

      // Helper functions to pass in data from PetaVision
      static Map3 bufferToMap3(const float *buffer, int nx, int ny, int nf, int const * displayedCategories, int numDisplayedCategories);
      static Map3 extendedBufferToMap3(const float *buffer, int nx, int ny, int nf, int lt, int rt, int dn, int up, int const * displayedCategories, int numDisplayedCategories);
      static Map3 bufferToMap3(const float *buffer, int nx, int ny, int nf);
      static Map3 extendedBufferToMap3(const float *buffer, int nx, int ny, int nf, int lt, int rt, int dn, int up);

   private:

      // The most recent and next most recent confidence maps handed to us.
      // If framesPerMap > 1, we interpolate between these and store the
      // result in currentConfMap. Otherwise, currentConfMap = interpNextMap.
      Map3 mInterpPreviousMap;
      Map3 mInterpNextMap;

      Map3 mAccumulatedConfMap;
      Map3 mCurrentConfMap;
      Map3 mDistMap;
      Rectangles mDetections;

      // Previous rectangles for each category
      // [category][rectIndex][width=0 height=1]
      Map3 mRectSizesPerCategory;

      float mThreshold = 0.95f;
      float mContrast = 1.5f;
      float mContrastStrength = 1.0f;
      float mPrevInfluence = 1.5f;
      float mAccumulateAmount = 0.05f;
      float mPrevLeakTau = 16.0f;

      int mOriginalConfidenceWidth = -1;
      int mOriginalConfidenceHeight = -1;
      int mInternalConfidenceWidth = 64;
      int mInternalConfidenceHeight = 64;
      int mImageWidth = 256;
      int mImageHeight = 256;
      int mMaxRectangleMemory = 64;
      int mMinBlobSize = 16;
      int mBBGuessSize = 24;
      int mSlidingAverageSize = 4;
      int mFramesPerMap = 1;
      int mFramesSinceNewMap = 0;
      int mDetectionWait = 0;
      int mDetectionWaitTimer = 0;

      // Helper function to index PetaVision buffers
      static int bufferIndexFromCoords(int x, int y, int f, int nx, int ny, int nf);

   protected:

      // Map2 Functions
      Map2 scale(const Map2 &source, int newWidth, int newHeight, bool linear);
      Map2 applyThreshold(const Map2 confMap, float threshold);
      float sigmoidedRMS(const Map2 confMap, const Rectangle &bounds);
      Map2 makeEdgeDistanceMap(const Map2 confMap);
      void squash(Map2 &map, float scaleMin, float scaleMax);

      // Map3 Functions
      Map3 getInterpolatedConfs(int framesSinceNewMap);
      Map3 scale(const Map3 &source, int newWidth, int newHeight, bool linear);
      Map3 increaseContrast(const Map3 fullMap, float contrast, float strength);
      Map3 contrastAndAverage(const Map3 fullMap, float contrast, float strength);
      Map3 blendMaps(const Map3 &mapA, const Map3 &mapB, float interp);
      Map3 sumMaps(const Map3 &mapA, const Map3 &mapB, float scale);
      void clip(Map3 &confMap, float minVal, float maxVal);
      void squash(Map3 &map, float scaleMin, float scaleMax);
      void accumulateIntoPrev(Map3 &prevMap, const Map3 &currentMap, float accumulateAmt, float frameMemory, float scaleMin, float scaleMax);
      void clipSquash(Map3 &map, int numPasses, float initialMax);

      // Bounding box functions
      Rectangles placePotentialBoxes(const Map3 fullMap);
      void joinBoundingBoxes(Rectangles &boundingBoxes);
      void smoothBoundingBoxes(Rectangles &boundingBoxes);
      void competeBoundingBoxes(Rectangles &boundingBoxes, float maxIntersectAllowed);

   public:

      // Every time we have a new confidence map, hand it over with giveMap()
      void giveMap(Map3 newMap);

      // Performs one timestep of detection.
      // The main functionality of this class is performed here.
      // If mFramesPerMap > 1, this should be called mFramesPerMap times
      // inbetween giveMap() calls.
      void detect();

      // Clears previous values and buffers to initial state.
      // Use when switching videos or images.
      void reset();

      // After calling detect(), these functions can retreive the results.
      const Rectangles getDetections() { return mDetections; }
      const Map3 getConfMap() { return mCurrentConfMap; }
      const Map3 getDistMap() { return mDistMap; }

      //These return the maps scaled to the image size for easy overlapping
      const Map3 getScaledConfMap() { return scale(mCurrentConfMap, mImageWidth, mImageHeight, true); }
      const Map3 getScaledDistMap() { return scale(mDistMap, mImageWidth, mImageHeight, true); }

      //These return the maps scaled to the original size
      const Map3 getOrigSizedConfMap() { return scale(mCurrentConfMap, mOriginalConfidenceWidth, mOriginalConfidenceHeight, true); }
      const Map3 getOrigSizedDistMap() { return scale(mDistMap, mOriginalConfidenceWidth, mOriginalConfidenceHeight, true); }

      // Getters (used by BBFindLayer)
      int getFramesPerMap() const { return mFramesPerMap; }

      float getThreshold() const { return mThreshold; }

      float getContrast() const { return mContrast; }

      float getContrastStrength() const { return mContrastStrength; }

      float getPrevInfluence() const { return mPrevInfluence; }

      float getAccumulateAmount() const { return mAccumulateAmount; }

      float getPrevLeakTau() const { return mPrevLeakTau; }

      int getMinBlobSize() const { return mMinBlobSize; }

      int getBBGuessSize() const { return mBBGuessSize; }

      int getSlidingAverageSize() const { return mSlidingAverageSize; }

      int getMaxRectangleMemory() const { return mMaxRectangleMemory; }

      int getDetectionWait() const { return mDetectionWait; }

      int getInternalMapWidth() const { return mInternalConfidenceWidth; }

      int getInternalMapHeight() const { return mInternalConfidenceHeight; }

      int getImageWidth() const { return mImageWidth; }

      int getImageHeight() const { return mImageHeight; }

      // Setters (are getters necessary?)

      // How many frames of video do we interpolate between before receiving
      // a new confidence map? If we advance past framesPerMap frames without
      // new data, we continue to output the final result until new data
      // arrives.
      // Default is 1 for single-frame mode (no video), 16 for video.
      void setFramesPerMap(int framesPerMap) { mFramesPerMap = framesPerMap; }

      // Value from 0-1 indicating cut-off threshold for post-processed
      // confidence map. Values can saturate based on contrast, so a
      // threshold very close to 1.0 is recommended. Default is 0.95.
      void setThreshold(float threshold) { mThreshold = threshold; }

      // Exponent for the last step in the increaseContrast. Larger values
      // cause the output to saturate more easily. Default is 1.5.
      void setContrast(float contrast) { mContrast = contrast; }

      // Blend factor for contrast values. At 0, increaseContrast does not
      // modify values. At 1.0, values are completely replaced with the
      // result of the contrast operation. Default is 1.0
      void setContrastStrength(float contrastStrength) { mContrastStrength = contrastStrength; }

      // How much the accumulated previous buffer should affect detections.
      // Setting this to 0 uses only the current frame to find objects.
      // Default is 1.5
      void setPrevInfluence(float prevInfluence) { mPrevInfluence = prevInfluence; }

      // How much the previous buffer should be affected by each new
      // frame. Small values work best, as a significantly large input
      // can effectively erase the previous buffer's old contents.
      // Default is 0.05
      void setAccumulateAmount(float accumulateAmt) { mAccumulateAmount = accumulateAmt; }

      // How quickly the previous buffer leaks its contents.
      // Larger values mean slower leaking.
      // Default is 16.0
      void setPrevLeakTau(float prevLeakTau) { mPrevLeakTau = prevLeakTau; }

      // A blob of confidences above threshold must be at least
      // this size to be a potential detection.
      // Default is 16
      void setMinBlobSize(int minBlobSize) { mMinBlobSize = minBlobSize; }

      // When we have a potential detection, what's the smallest size
      // bounding box we guess it could have. These are then merged, so
      // it's rare to actually have a single box this small.
      // Default is 24
      void setBBGuessSize(int bbGuessSize) { mBBGuessSize = bbGuessSize; }

      // Determines the area we take each step of the sigmoidedRMS over.
      // Default is 4
      void setSlidingAverageSize(int slidingAverageSize) { mSlidingAverageSize = slidingAverageSize; }

      // How many previous rectangles to keep in memory for each category.
      // Used to push new rectangles towards the average size.
      // Default is 64
      void setMaxRectangleMemory(int maxRectangleMemory) { mMaxRectangleMemory = maxRectangleMemory; }

      // How many frames to wait before starting object detection.
      // This gives the accumulated previous buffer time to fill up
      // before we start labeling objects.
      // Default is 16 for video, 0 for signle frame.
      void setDetectionWait(int detectionWait) { mDetectionWait = detectionWait; }

      // What size the internal confidence buffer should be scaled to.
      // A slightly higher size than the original helps detect bounding
      // boxes more accurately.
      void setInternalMapSize(int width, int height)
      {
         mInternalConfidenceWidth = width;
         mInternalConfidenceHeight = height;
      }

      // What size is the image we're detecting objects in?
      // Bounding box results will be given in this space.
      void setImageSize(int width, int height)
      {
         mImageWidth = width;
         mImageHeight = height;
      }
};

#endif
<commit_msg>Removes underscore from include guard macro<commit_after>#ifndef BBFIND_HPP_
#define BBFIND_HPP_

#include <vector>
#include <list>

using ::std::vector;
using ::std::list;

class BBFind
{
   public:

      class Rectangle
      {
         public:
            int x,  y, width, height;
            int left()   const { return x - width / 2; }
            int right()  const { return x + width / 2; }
            int top()    const { return y - height/ 2; }
            int bottom() const { return y + height/ 2; }
            static Rectangle  join        (const Rectangle &rectA, const Rectangle &rectB);
            static float      intersecting(const Rectangle &rectA, const Rectangle &rectB);
            static bool       touching    (const Rectangle &rectA, const Rectangle &rectB);
            static bool       equal       (const Rectangle &rectA, const Rectangle &rectB);

      };

      typedef vector< vector< vector<float> > > Map3;       // [feature][y][x]
      typedef vector< vector<float> >           Map2;       // [y][x]
      typedef vector< list<Rectangle> >         Rectangles; // [feature][rectangles]

      // Helper functions to pass in data from PetaVision
      static Map3 bufferToMap3(const float *buffer, int nx, int ny, int nf, int const * displayedCategories, int numDisplayedCategories);
      static Map3 extendedBufferToMap3(const float *buffer, int nx, int ny, int nf, int lt, int rt, int dn, int up, int const * displayedCategories, int numDisplayedCategories);
      static Map3 bufferToMap3(const float *buffer, int nx, int ny, int nf);
      static Map3 extendedBufferToMap3(const float *buffer, int nx, int ny, int nf, int lt, int rt, int dn, int up);

   private:

      // The most recent and next most recent confidence maps handed to us.
      // If framesPerMap > 1, we interpolate between these and store the
      // result in currentConfMap. Otherwise, currentConfMap = interpNextMap.
      Map3 mInterpPreviousMap;
      Map3 mInterpNextMap;

      Map3 mAccumulatedConfMap;
      Map3 mCurrentConfMap;
      Map3 mDistMap;
      Rectangles mDetections;

      // Previous rectangles for each category
      // [category][rectIndex][width=0 height=1]
      Map3 mRectSizesPerCategory;

      float mThreshold = 0.95f;
      float mContrast = 1.5f;
      float mContrastStrength = 1.0f;
      float mPrevInfluence = 1.5f;
      float mAccumulateAmount = 0.05f;
      float mPrevLeakTau = 16.0f;

      int mOriginalConfidenceWidth = -1;
      int mOriginalConfidenceHeight = -1;
      int mInternalConfidenceWidth = 64;
      int mInternalConfidenceHeight = 64;
      int mImageWidth = 256;
      int mImageHeight = 256;
      int mMaxRectangleMemory = 64;
      int mMinBlobSize = 16;
      int mBBGuessSize = 24;
      int mSlidingAverageSize = 4;
      int mFramesPerMap = 1;
      int mFramesSinceNewMap = 0;
      int mDetectionWait = 0;
      int mDetectionWaitTimer = 0;

      // Helper function to index PetaVision buffers
      static int bufferIndexFromCoords(int x, int y, int f, int nx, int ny, int nf);

   protected:

      // Map2 Functions
      Map2 scale(const Map2 &source, int newWidth, int newHeight, bool linear);
      Map2 applyThreshold(const Map2 confMap, float threshold);
      float sigmoidedRMS(const Map2 confMap, const Rectangle &bounds);
      Map2 makeEdgeDistanceMap(const Map2 confMap);
      void squash(Map2 &map, float scaleMin, float scaleMax);

      // Map3 Functions
      Map3 getInterpolatedConfs(int framesSinceNewMap);
      Map3 scale(const Map3 &source, int newWidth, int newHeight, bool linear);
      Map3 increaseContrast(const Map3 fullMap, float contrast, float strength);
      Map3 contrastAndAverage(const Map3 fullMap, float contrast, float strength);
      Map3 blendMaps(const Map3 &mapA, const Map3 &mapB, float interp);
      Map3 sumMaps(const Map3 &mapA, const Map3 &mapB, float scale);
      void clip(Map3 &confMap, float minVal, float maxVal);
      void squash(Map3 &map, float scaleMin, float scaleMax);
      void accumulateIntoPrev(Map3 &prevMap, const Map3 &currentMap, float accumulateAmt, float frameMemory, float scaleMin, float scaleMax);
      void clipSquash(Map3 &map, int numPasses, float initialMax);

      // Bounding box functions
      Rectangles placePotentialBoxes(const Map3 fullMap);
      void joinBoundingBoxes(Rectangles &boundingBoxes);
      void smoothBoundingBoxes(Rectangles &boundingBoxes);
      void competeBoundingBoxes(Rectangles &boundingBoxes, float maxIntersectAllowed);

   public:

      // Every time we have a new confidence map, hand it over with giveMap()
      void giveMap(Map3 newMap);

      // Performs one timestep of detection.
      // The main functionality of this class is performed here.
      // If mFramesPerMap > 1, this should be called mFramesPerMap times
      // inbetween giveMap() calls.
      void detect();

      // Clears previous values and buffers to initial state.
      // Use when switching videos or images.
      void reset();

      // After calling detect(), these functions can retreive the results.
      const Rectangles getDetections() { return mDetections; }
      const Map3 getConfMap() { return mCurrentConfMap; }
      const Map3 getDistMap() { return mDistMap; }

      //These return the maps scaled to the image size for easy overlapping
      const Map3 getScaledConfMap() { return scale(mCurrentConfMap, mImageWidth, mImageHeight, true); }
      const Map3 getScaledDistMap() { return scale(mDistMap, mImageWidth, mImageHeight, true); }

      //These return the maps scaled to the original size
      const Map3 getOrigSizedConfMap() { return scale(mCurrentConfMap, mOriginalConfidenceWidth, mOriginalConfidenceHeight, true); }
      const Map3 getOrigSizedDistMap() { return scale(mDistMap, mOriginalConfidenceWidth, mOriginalConfidenceHeight, true); }

      // Getters (used by BBFindLayer)
      int getFramesPerMap() const { return mFramesPerMap; }

      float getThreshold() const { return mThreshold; }

      float getContrast() const { return mContrast; }

      float getContrastStrength() const { return mContrastStrength; }

      float getPrevInfluence() const { return mPrevInfluence; }

      float getAccumulateAmount() const { return mAccumulateAmount; }

      float getPrevLeakTau() const { return mPrevLeakTau; }

      int getMinBlobSize() const { return mMinBlobSize; }

      int getBBGuessSize() const { return mBBGuessSize; }

      int getSlidingAverageSize() const { return mSlidingAverageSize; }

      int getMaxRectangleMemory() const { return mMaxRectangleMemory; }

      int getDetectionWait() const { return mDetectionWait; }

      int getInternalMapWidth() const { return mInternalConfidenceWidth; }

      int getInternalMapHeight() const { return mInternalConfidenceHeight; }

      int getImageWidth() const { return mImageWidth; }

      int getImageHeight() const { return mImageHeight; }

      // Setters (are getters necessary?)

      // How many frames of video do we interpolate between before receiving
      // a new confidence map? If we advance past framesPerMap frames without
      // new data, we continue to output the final result until new data
      // arrives.
      // Default is 1 for single-frame mode (no video), 16 for video.
      void setFramesPerMap(int framesPerMap) { mFramesPerMap = framesPerMap; }

      // Value from 0-1 indicating cut-off threshold for post-processed
      // confidence map. Values can saturate based on contrast, so a
      // threshold very close to 1.0 is recommended. Default is 0.95.
      void setThreshold(float threshold) { mThreshold = threshold; }

      // Exponent for the last step in the increaseContrast. Larger values
      // cause the output to saturate more easily. Default is 1.5.
      void setContrast(float contrast) { mContrast = contrast; }

      // Blend factor for contrast values. At 0, increaseContrast does not
      // modify values. At 1.0, values are completely replaced with the
      // result of the contrast operation. Default is 1.0
      void setContrastStrength(float contrastStrength) { mContrastStrength = contrastStrength; }

      // How much the accumulated previous buffer should affect detections.
      // Setting this to 0 uses only the current frame to find objects.
      // Default is 1.5
      void setPrevInfluence(float prevInfluence) { mPrevInfluence = prevInfluence; }

      // How much the previous buffer should be affected by each new
      // frame. Small values work best, as a significantly large input
      // can effectively erase the previous buffer's old contents.
      // Default is 0.05
      void setAccumulateAmount(float accumulateAmt) { mAccumulateAmount = accumulateAmt; }

      // How quickly the previous buffer leaks its contents.
      // Larger values mean slower leaking.
      // Default is 16.0
      void setPrevLeakTau(float prevLeakTau) { mPrevLeakTau = prevLeakTau; }

      // A blob of confidences above threshold must be at least
      // this size to be a potential detection.
      // Default is 16
      void setMinBlobSize(int minBlobSize) { mMinBlobSize = minBlobSize; }

      // When we have a potential detection, what's the smallest size
      // bounding box we guess it could have. These are then merged, so
      // it's rare to actually have a single box this small.
      // Default is 24
      void setBBGuessSize(int bbGuessSize) { mBBGuessSize = bbGuessSize; }

      // Determines the area we take each step of the sigmoidedRMS over.
      // Default is 4
      void setSlidingAverageSize(int slidingAverageSize) { mSlidingAverageSize = slidingAverageSize; }

      // How many previous rectangles to keep in memory for each category.
      // Used to push new rectangles towards the average size.
      // Default is 64
      void setMaxRectangleMemory(int maxRectangleMemory) { mMaxRectangleMemory = maxRectangleMemory; }

      // How many frames to wait before starting object detection.
      // This gives the accumulated previous buffer time to fill up
      // before we start labeling objects.
      // Default is 16 for video, 0 for signle frame.
      void setDetectionWait(int detectionWait) { mDetectionWait = detectionWait; }

      // What size the internal confidence buffer should be scaled to.
      // A slightly higher size than the original helps detect bounding
      // boxes more accurately.
      void setInternalMapSize(int width, int height)
      {
         mInternalConfidenceWidth = width;
         mInternalConfidenceHeight = height;
      }

      // What size is the image we're detecting objects in?
      // Bounding box results will be given in this space.
      void setImageSize(int width, int height)
      {
         mImageWidth = width;
         mImageHeight = height;
      }
};

#endif // BBFIND_HPP_
<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Johannes Hggqvist

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, sublicense, 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 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 NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS 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 "WaveFile.h"

#include <fstream>
#include <iostream>
#include <cstdint>
#include <cassert>
#include <cstring>

namespace
{
	static const std::uint32_t RIFF_ID = 'FFIR';
	static const std::uint32_t FMT_ID  = ' tmf';
	static const std::uint32_t DATA_ID = 'atad';

	struct RIFFChunk
	{
		static const std::uint32_t FORMAT_WAVE = 'EVAW';

		std::uint32_t chunkID;
		std::uint32_t chunkSize;
		std::uint32_t format;
	};
	struct fmtChunk
	{
		std::uint32_t chunkID;
		std::uint32_t chunkSize;
		std::uint16_t audioFormat;
		std::uint16_t numChannels;
		std::uint32_t sampleRate;
		std::uint32_t byteRate;
		std::uint16_t blockAlign;
		std::uint16_t bitsPerSample;
	};
	struct WaveHeader
	{
		RIFFChunk riff;
		fmtChunk fmt;
	};
}

WaveFile::WaveFile() : data(nullptr), size(0)
{
}
WaveFile::WaveFile(const std::string &filename) : data(nullptr), size(0)
{
	Load(filename);
}
WaveFile::~WaveFile()
{
	Unload();
}

bool WaveFile::Load(const std::string &filename)
{
	if (IsLoaded())
	{
		Unload();
	}

	std::fstream file(filename, std::ios::in | std::ios::binary);

	if (!file.is_open())
	{
		std::cerr << "Error: Could not open file." << std::endl;
		return false;
	}

	WaveHeader header;
	std::memset(&header, 0, sizeof(WaveHeader));

	while (file.peek() != std::char_traits<char>::eof())
	{
		std::uint32_t chunkID;
		std::uint32_t chunkSize;

		file.read(reinterpret_cast<char*>(&chunkID), sizeof(std::uint32_t));
		file.read(reinterpret_cast<char*>(&chunkSize), sizeof(std::uint32_t));

		switch (chunkID)
		{
		case RIFF_ID:
			{
				header.riff.chunkID = chunkID;
				header.riff.chunkSize = chunkSize;
				file.read(reinterpret_cast<char*>(&header.riff.format), sizeof(std::uint32_t));

				if (header.riff.format != RIFFChunk::FORMAT_WAVE)
				{
					std::cerr << "Error: Not a valid WAVE file." << std::endl;
					return false;
				}

				break;
			}
		case FMT_ID:
			{
				header.fmt.chunkID = chunkID;
				header.fmt.chunkSize = chunkSize;
				file.read(reinterpret_cast<char*>(&header.fmt.audioFormat), sizeof(std::uint16_t));
				file.read(reinterpret_cast<char*>(&header.fmt.numChannels), sizeof(std::uint16_t));
				file.read(reinterpret_cast<char*>(&header.fmt.sampleRate), sizeof(std::uint32_t));
				file.read(reinterpret_cast<char*>(&header.fmt.byteRate), sizeof(std::uint32_t));
				file.read(reinterpret_cast<char*>(&header.fmt.blockAlign), sizeof(std::uint16_t));
				file.read(reinterpret_cast<char*>(&header.fmt.bitsPerSample), sizeof(std::uint16_t));

				if (header.fmt.bitsPerSample % 2 != 0)
				{
					std::cerr << "Error: Invalid number of bits per sample" << std::endl;
					return false;
				}
				if (header.fmt.byteRate != (header.fmt.sampleRate * header.fmt.numChannels * header.fmt.bitsPerSample / 8))
				{
					std::cerr << "Error: Invalid byte rate" << std::endl;
					return false;
				}
				if (header.fmt.blockAlign != (header.fmt.numChannels * header.fmt.bitsPerSample / 8))
				{
					std::cerr << "Error: Invalid block align" << std::endl;
					return false;
				}

				break;
			}
		case DATA_ID:
			{
				assert(data == nullptr);
				size = chunkSize;
				data = new char[size];
				file.read(data, chunkSize);

				break;
			}
		default:
			{
				file.ignore(chunkSize);

				break;
			}
		}
	}

	// Check that we got all chunks
	if (header.riff.chunkID != RIFF_ID)
	{
		std::cerr << "Error: Missing RIFF chunk." << std::endl;
		return false;
	}
	if (header.fmt.chunkID != FMT_ID)
	{
		std::cerr << "Error: Missing fmt chunk." << std::endl;
		return false;
	}
	if (data == nullptr)
	{
		std::cerr << "Error: Missing data chunk." << std::endl;
		return false;
	}

	// Fill meta struct
	meta.audioFormat   = static_cast<AudioFormat>(header.fmt.audioFormat);
	meta.numChannels   = header.fmt.numChannels;
	meta.sampleRate    = header.fmt.sampleRate;
	meta.bitsPerSample = header.fmt.bitsPerSample;

	return true;
}
void WaveFile::Unload()
{
	delete[] data;
	data = nullptr;
	size = 0;
}

std::string WaveFile::GetAudioFormatString() const
{
	switch (meta.audioFormat)
	{
	case WaveFile::PCM: return "PCM";
	case WaveFile::IEEE_FLOAT: return "IEEE float";
	default: return "Unknown";
	}
}
<commit_msg>Added ReadField helper function<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Johannes Hggqvist

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, sublicense, 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 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 NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS 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 "WaveFile.h"

#include <fstream>
#include <iostream>
#include <cstdint>
#include <cassert>
#include <cstring>

namespace
{
	static const std::uint32_t RIFF_ID = 'FFIR';
	static const std::uint32_t FMT_ID  = ' tmf';
	static const std::uint32_t DATA_ID = 'atad';

	struct RIFFChunk
	{
		static const std::uint32_t FORMAT_WAVE = 'EVAW';

		std::uint32_t chunkID;
		std::uint32_t chunkSize;
		std::uint32_t format;
	};
	struct fmtChunk
	{
		std::uint32_t chunkID;
		std::uint32_t chunkSize;
		std::uint16_t audioFormat;
		std::uint16_t numChannels;
		std::uint32_t sampleRate;
		std::uint32_t byteRate;
		std::uint16_t blockAlign;
		std::uint16_t bitsPerSample;
	};
	struct WaveHeader
	{
		RIFFChunk riff;
		fmtChunk fmt;
	};

	template<typename T>
	inline void ReadField(std::istream &stream, T *field)
	{
		stream.read(reinterpret_cast<char*>(field), sizeof(T));
	}
}

WaveFile::WaveFile() : data(nullptr), size(0)
{
}
WaveFile::WaveFile(const std::string &filename) : data(nullptr), size(0)
{
	Load(filename);
}
WaveFile::~WaveFile()
{
	Unload();
}

bool WaveFile::Load(const std::string &filename)
{
	if (IsLoaded())
	{
		Unload();
	}

	std::fstream file(filename, std::ios::in | std::ios::binary);

	if (!file.is_open())
	{
		std::cerr << "Error: Could not open file." << std::endl;
		return false;
	}

	WaveHeader header;
	std::memset(&header, 0, sizeof(WaveHeader));

	while (file.peek() != std::char_traits<char>::eof())
	{
		std::uint32_t chunkID;
		std::uint32_t chunkSize;

		ReadField(file, &chunkID);
		ReadField(file, &chunkSize);

		switch (chunkID)
		{
		case RIFF_ID:
			{
				header.riff.chunkID = chunkID;
				header.riff.chunkSize = chunkSize;
				ReadField(file, &header.riff.format);

				if (header.riff.format != RIFFChunk::FORMAT_WAVE)
				{
					std::cerr << "Error: Not a valid WAVE file." << std::endl;
					return false;
				}

				break;
			}
		case FMT_ID:
			{
				header.fmt.chunkID = chunkID;
				header.fmt.chunkSize = chunkSize;
				ReadField(file, &header.fmt.audioFormat);
				ReadField(file, &header.fmt.numChannels);
				ReadField(file, &header.fmt.sampleRate);
				ReadField(file, &header.fmt.byteRate);
				ReadField(file, &header.fmt.blockAlign);
				ReadField(file, &header.fmt.bitsPerSample);

				if (header.fmt.bitsPerSample % 2 != 0)
				{
					std::cerr << "Error: Invalid number of bits per sample" << std::endl;
					return false;
				}
				if (header.fmt.byteRate != (header.fmt.sampleRate * header.fmt.numChannels * header.fmt.bitsPerSample / 8))
				{
					std::cerr << "Error: Invalid byte rate" << std::endl;
					return false;
				}
				if (header.fmt.blockAlign != (header.fmt.numChannels * header.fmt.bitsPerSample / 8))
				{
					std::cerr << "Error: Invalid block align" << std::endl;
					return false;
				}

				break;
			}
		case DATA_ID:
			{
				assert(data == nullptr);
				size = chunkSize;
				data = new char[size];
				file.read(data, chunkSize);

				break;
			}
		default:
			{
				file.ignore(chunkSize);

				break;
			}
		}
	}

	// Check that we got all chunks
	if (header.riff.chunkID != RIFF_ID)
	{
		std::cerr << "Error: Missing RIFF chunk." << std::endl;
		return false;
	}
	if (header.fmt.chunkID != FMT_ID)
	{
		std::cerr << "Error: Missing fmt chunk." << std::endl;
		return false;
	}
	if (data == nullptr)
	{
		std::cerr << "Error: Missing data chunk." << std::endl;
		return false;
	}

	// Fill meta struct
	meta.audioFormat   = static_cast<AudioFormat>(header.fmt.audioFormat);
	meta.numChannels   = header.fmt.numChannels;
	meta.sampleRate    = header.fmt.sampleRate;
	meta.bitsPerSample = header.fmt.bitsPerSample;

	return true;
}
void WaveFile::Unload()
{
	delete[] data;
	data = nullptr;
	size = 0;
}

std::string WaveFile::GetAudioFormatString() const
{
	switch (meta.audioFormat)
	{
	case WaveFile::PCM: return "PCM";
	case WaveFile::IEEE_FLOAT: return "IEEE float";
	default: return "Unknown";
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Sergey Zolotarev
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.

#include <cstddef>
#include <map>

#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "pluginversion.h"

using namespace jit;

typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;

typedef std::map<AMX*, JIT*> JITMap;
static JITMap jit_map;

static JIT *GetJIT(AMX *amx) {
	JITMap::const_iterator it = jit_map.find(amx);
	if (it == jit_map.end()) {
		JIT *jit = new JIT(amx);
		jit_map.insert(std::make_pair(amx, jit));
		return jit;
	} else {
		return it->second;
	}
}

static void DeleteJIT(AMX *amx) {
	JITMap::iterator it = jit_map.find(amx);
	if (it != jit_map.end()) {
		delete it->second;
		jit_map.erase(it);
	}
}

static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) {
	AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
	*phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr);
	return AMX_ERR_NONE;
}

static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
	if (index != AMX_EXEC_CONT) {
		return GetJIT(amx)->CallPublicFunction(index, retval);
	}
	return AMX_ERR_NONE;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

	new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT);
	new JumpX86(((void**)ppData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT);

	logprintf("  JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);

	return true;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
	for (JITMap::iterator it = jit_map.begin(); it != jit_map.end(); ++it) {
		delete it->second;
	}
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
	return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
	DeleteJIT(amx);
	return AMX_ERR_NONE;
}
<commit_msg>Ignore early amx_Exec() call happening on Linux<commit_after>// Copyright (c) 2012, Sergey Zolotarev
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT 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.

#include <cstddef>
#include <map>

#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "pluginversion.h"

using namespace jit;

typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;

typedef std::map<AMX*, JIT*> JITMap;
static JITMap jit_map;

static void **ppPluginData;

static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) {
	AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);
	*phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr);
	return AMX_ERR_NONE;
}

static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
	if (index != AMX_EXEC_CONT) {
		JITMap::const_iterator it = jit_map.find(amx);
		if (it != jit_map.end()) {
			return it->second->CallPublicFunction(index, retval);
		}
	}
	return AMX_ERR_NONE;
}

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
	ppPluginData = ppData;
	logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
	logprintf("  JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
	return true;
}

PLUGIN_EXPORT void PLUGIN_CALL Unload() {
	for (JITMap::iterator it = jit_map.begin(); it != jit_map.end(); ++it) {
		delete it->second;
	}
}

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
	new JumpX86(((void**)ppPluginData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_Exec], (void*)amx_Exec_JIT);
	new JumpX86(((void**)ppPluginData[PLUGIN_DATA_AMX_EXPORTS])[PLUGIN_AMX_EXPORT_GetAddr], (void*)amx_GetAddr_JIT);

	jit_map.insert(std::make_pair(amx, new JIT(amx)));

	return AMX_ERR_NONE;
}

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
	JITMap::iterator it = jit_map.find(amx);
	if (it != jit_map.end()) {
		delete it->second;
		jit_map.erase(it);
	}
	return AMX_ERR_NONE;
}
<|endoftext|>


<commit_before>#include <string>

#include "HTMLContent.h"
#include "HTMLTag.h"
#include "WikiPage.h"

WikiPage::WikiPage(const HTMLTag& tag)
{
  const HTMLTag *content_tag = HTMLTag::traverse_path(tag, {
      { { "__name__", {"body"} } },
      { { "id", {"content"} } }
      });
  const HTMLTag *title_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"firstHeading"} } }
      });
  title_ = title_tag->get_text();
  const HTMLTag *text_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"bodyContent"} } },
      { { "id", {"mw-content-text"} } }
      });
  text_ = text_tag->get_text();
  std::vector<HTMLTag*> all_text_links =
    text_tag->get_all_descendants({ { "__name__", {"a"} } });
  const HTMLTag *categories_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"bodyContent"} } },
      { { "id", {"catlinks"} } }
      });
  std::vector<HTMLTag*> all_categories_links =
    categories_tag->get_all_descendants({ { "__name__", {"a"} } });
  for (size_t index = 0;
      index < all_text_links.size() + all_categories_links.size();
      ++index)
  {
    HTMLTag *link;
    if (index < all_text_links.size())
    {
      link = all_text_links[index];
    }
    else
    {
      link = all_categories_links[index - all_text_links.size()];
    }
    const HTMLTag::Attribute *attribute = link->get_attribute("href");
    if (!attribute)
    {
      continue;
    }
    if (is_link_ok(attribute->value()))
    {
      links_.push_back(transform_link(attribute->value()));
    }
  }
}

const std::string& WikiPage::title()
{
  return title_;
}

const std::string& WikiPage::text()
{
  return text_;
}

const std::vector<std::string>& WikiPage::links()
{
  return links_;
}

bool WikiPage::is_link_ok(const std::string& link)
{
  // If link does not begin with /wiki, we are ignoring it
  std::string wiki = "/wiki/";
  if (link.compare(0, wiki.length(), wiki))
  {
    return false;
  }
  size_t colon_index = link.find(':');
  if (colon_index != std::string::npos)
  {
    std::string allowed_namespace = "Category";
    if (!link.compare(wiki.length(),
          allowed_namespace.length(), allowed_namespace))
    {
      return true;
    }
    return false;
  }
  return true;
}

std::string WikiPage::transform_link(const std::string& link)
{
  size_t hash_index = link.find('#');
  if (hash_index == std::string::npos)
  {
    return link;
  }
  return link.substr(0, hash_index);
}
<commit_msg>Fix bug with SIGSEGVing on unparsable pages.<commit_after>#include <string>

#include "HTMLContent.h"
#include "HTMLTag.h"
#include "WikiPage.h"

WikiPage::WikiPage(const HTMLTag& tag)
{
  const HTMLTag *content_tag = HTMLTag::traverse_path(tag, {
      { { "__name__", {"body"} } },
      { { "id", {"content"} } }
      });
  const HTMLTag *title_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"firstHeading"} } }
      });
  title_ = (title_tag ? title_tag->get_text() : "");
  const HTMLTag *text_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"bodyContent"} } },
      { { "id", {"mw-content-text"} } }
      });
  text_ = (text_tag ? text_tag->get_text() : "");
  std::vector<HTMLTag*> all_text_links =
    (text_tag ?
     text_tag->get_all_descendants({ { "__name__", {"a"} } }) :
     std::vector<HTMLTag*>());
  const HTMLTag *categories_tag = HTMLTag::traverse_path(*content_tag, {
      { { "id", {"bodyContent"} } },
      { { "id", {"catlinks"} } }
      });
  std::vector<HTMLTag*> all_categories_links =
    (categories_tag ?
     categories_tag->get_all_descendants({ { "__name__", {"a"} } }) :
     std::vector<HTMLTag*>());
  for (size_t index = 0;
      index < all_text_links.size() + all_categories_links.size();
      ++index)
  {
    HTMLTag *link;
    if (index < all_text_links.size())
    {
      link = all_text_links[index];
    }
    else
    {
      link = all_categories_links[index - all_text_links.size()];
    }
    if (!link)
    {
      continue;
    }
    const HTMLTag::Attribute *attribute = link->get_attribute("href");
    if (!attribute)
    {
      continue;
    }
    if (is_link_ok(attribute->value()))
    {
      links_.push_back(transform_link(attribute->value()));
    }
  }
}

const std::string& WikiPage::title()
{
  return title_;
}

const std::string& WikiPage::text()
{
  return text_;
}

const std::vector<std::string>& WikiPage::links()
{
  return links_;
}

bool WikiPage::is_link_ok(const std::string& link)
{
  // If link does not begin with /wiki, we are ignoring it
  std::string wiki = "/wiki/";
  if (link.compare(0, wiki.length(), wiki))
  {
    return false;
  }
  size_t colon_index = link.find(':');
  if (colon_index != std::string::npos)
  {
    std::string allowed_namespace = "Category";
    if (!link.compare(wiki.length(),
          allowed_namespace.length(), allowed_namespace))
    {
      return true;
    }
    return false;
  }
  return true;
}

std::string WikiPage::transform_link(const std::string& link)
{
  size_t hash_index = link.find('#');
  if (hash_index == std::string::npos)
  {
    return link;
  }
  return link.substr(0, hash_index);
}
<|endoftext|>


<commit_before>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;

SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
        : manager(m) {

    int r = sqlite3_open(manager->getDBFile(), &db);
    // any value other than SQLITE_OK is an error
    if (r != SQLITE_OK) {
        printf("could not open db\n");
        db = 0;
        manager->deref();
        return;
    }
    // speed up by being unsafe and keeping temp tables in memory
    r = sqlite3_exec(db, "PRAGMA synchronous = OFF;"
        "PRAGMA temp_store = MEMORY;" , 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not speed up database\n");
    }
    // create the tables required
    const char* sql ="create table files (path,"
        "unique (path) on conflict ignore);"
        "create table idx (path, name, value, "
        "unique (path, name, value) on conflict ignore);"
        "create index idx_path on idx(path);"
        "create index idx_name on idx(name);"
        "create index idx_value on idx(value);"
        "create table words (wordid integer primary key, "
        "    word, count, unique(word));"
        "create table filewords (fileid integer, wordid integer, count,"
        "unique (fileid, wordid));";
    r = sqlite3_exec(db, sql, 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not create table %i %s\n", r, sqlite3_errmsg(db));
    }
    // prepare the insert statement
    sql = "insert into idx (path, name, value) values(?, ?, ?)";
    r = sqlite3_prepare(db, sql, 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare insert statement\n");
        stmt = 0;
    }
}
SqliteIndexWriter::~SqliteIndexWriter() {
    if (stmt) {
        int r = sqlite3_finalize(stmt);
        if (r != SQLITE_OK) {
            printf("could not finalize insert statement\n");
        }
    }
    if (db) {
        int r = sqlite3_close(db);
        if (r != SQLITE_OK) {
            printf("could not create table\n");
        }
    }
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
        StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
        const string& value) {
    int64_t id = idx->getId();
    if (id == -1) return;
    if (fieldname == "content") {
        content[id][value]++;
        return;
    }
    manager->ref();
    sqlite3_bind_int64(stmt, 1, idx->getId());
    sqlite3_bind_text(stmt, 2, fieldname.c_str(),
        fieldname.length(), SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, value.c_str(), value.length(), SQLITE_STATIC);
    int r = sqlite3_step(stmt);
    if (r != SQLITE_DONE) {
        printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
    }
    r = sqlite3_reset(stmt);
    if (r != SQLITE_OK) {
        printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
    }
    manager->deref();
}

void
SqliteIndexWriter::startIndexable(Indexable* idx) {
    // get the file name
    string name = SqliteIndexManager::escapeSqlValue(idx->getName());

    // remove the previous version of this file
    // check if there is a previous version
    string sql = "select rowid from files where path = '"+name+"';";
    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare document find sql\n");
        idx->setId(-1);
        manager->deref();
        return;
    }
    r = sqlite3_step(stmt);
    int64_t id = -1;
    if (r == SQLITE_ROW) {
        id = sqlite3_column_int64(stmt, 0);
        sqlite3_finalize(stmt);
    } else if (r == SQLITE_DONE) {
        sqlite3_finalize(stmt);
        // prepare the insert statement
        sql = "insert into files (path) values('";
        sql += name + "');";
        r = sqlite3_exec(db, sql.c_str(), 0, 0, 0);
        if (r != SQLITE_OK) {
            printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
            stmt = 0;
        }
        id = sqlite3_last_insert_rowid(db);
    } else {
        printf("could not look for a document by path\n");
        manager->deref();
        return;
    }
    idx->setId(id);
    manager->deref();
}
/*
    Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
    // store the content field
    map<int64_t, map<string, int> >::const_iterator m
        = content.find(idx->getId());
    if (m == content.end()) return;

    // create a temporary table
    int r = sqlite3_exec(db, "create temp table t(word, count)", 0,0,0);
    if (r != SQLITE_OK) {
        printf("could not create temp table %i %s\n", r, sqlite3_errmsg(db));
    }

    manager->ref();
    sqlite3_stmt* stmt;
    r = sqlite3_prepare(db, "insert into t (word, count) values(?,?);",
         0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare temp insert sql\n");
        content.erase(m->first);
        manager->deref();
        return;
    }
    map<string, int>::const_iterator i = m->second.begin();
    map<string, int>::const_iterator e = m->second.end();
    for (; i!=e; ++i) {
        sqlite3_bind_text(stmt, 1, i->first.c_str(), i->first.length(),
            SQLITE_STATIC);
        sqlite3_bind_int(stmt, 2, i->second);
        r = sqlite3_step(stmt);
        if (r != SQLITE_DONE) {
            printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
        }
        r = sqlite3_reset(stmt);
    }
    sqlite3_finalize(stmt);

    ostringstream sql;
    sql << "replace into words (wordid, word, count) "
        "select wordid, t.word, t.count+ifnull(words.count,0) "
        "from t left join words on t.word = words.word; "
        "replace into filewords (fileid, wordid, count) "
        "select ";
    sql << m->first;
    sql << ", words.rowid, t.count from t join words "
        "on t.word = words.word; drop table t;";
    r = sqlite3_exec(db, sql.str().c_str(),0,0,0);
    if (r != SQLITE_OK) {
        printf("could not drop temp table %i %s\n", r, sqlite3_errmsg(db));
    }
    manager->deref();
    content.erase(m->first);
}
<commit_msg>limit the number of unique words per file to 1000. We will make this configurable later.<commit_after>#include "sqliteindexwriter.h"
#include "sqliteindexmanager.h"
#include <sqlite3.h>
#include <sstream>
using namespace std;
using namespace jstreams;

SqliteIndexWriter::SqliteIndexWriter(SqliteIndexManager *m)
        : manager(m) {

    int r = sqlite3_open(manager->getDBFile(), &db);
    // any value other than SQLITE_OK is an error
    if (r != SQLITE_OK) {
        printf("could not open db\n");
        db = 0;
        manager->deref();
        return;
    }
    // speed up by being unsafe and keeping temp tables in memory
    r = sqlite3_exec(db, "PRAGMA synchronous = OFF;"
        "PRAGMA temp_store = MEMORY;" , 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not speed up database\n");
    }
    // create the tables required
    const char* sql ="create table files (path,"
        "unique (path) on conflict ignore);"
        "create table idx (path, name, value, "
        "unique (path, name, value) on conflict ignore);"
        "create index idx_path on idx(path);"
        "create index idx_name on idx(name);"
        "create index idx_value on idx(value);"
        "create table words (wordid integer primary key, "
        "    word, count, unique(word));"
        "create table filewords (fileid integer, wordid integer, count,"
        "unique (fileid, wordid));";
    r = sqlite3_exec(db, sql, 0, 0, 0);
    if (r != SQLITE_OK) {
        printf("could not create table %i %s\n", r, sqlite3_errmsg(db));
    }
    // prepare the insert statement
    sql = "insert into idx (path, name, value) values(?, ?, ?)";
    r = sqlite3_prepare(db, sql, 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare insert statement\n");
        stmt = 0;
    }
}
SqliteIndexWriter::~SqliteIndexWriter() {
    if (stmt) {
        int r = sqlite3_finalize(stmt);
        if (r != SQLITE_OK) {
            printf("could not finalize insert statement\n");
        }
    }
    if (db) {
        int r = sqlite3_close(db);
        if (r != SQLITE_OK) {
            printf("could not create table\n");
        }
    }
}
void
SqliteIndexWriter::addStream(const Indexable* idx, const string& fieldname,
        StreamBase<wchar_t>* datastream) {
}
void
SqliteIndexWriter::addField(const Indexable* idx, const string &fieldname,
        const string& value) {
    int64_t id = idx->getId();
    if (id == -1) return;
    if (fieldname == "content") {
        // find a pointer to the value
        map<int64_t, map<string, int> >::iterator m = content.find(id);
        if (m == content.end()) {
            // no value at all yet, so fine to add one
            content[id][value]++;
        } else if (m->second.size() >= 1000) {
            map<string, int>::iterator i = m->second.find(value);
            if (i != m->second.end()) {
                i->second++;
            }
        } else {
            content[id][value]++;
        }

        return;
    }
    manager->ref();
    sqlite3_bind_int64(stmt, 1, idx->getId());
    sqlite3_bind_text(stmt, 2, fieldname.c_str(),
        fieldname.length(), SQLITE_STATIC);
    sqlite3_bind_text(stmt, 3, value.c_str(), value.length(), SQLITE_STATIC);
    int r = sqlite3_step(stmt);
    if (r != SQLITE_DONE) {
        printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
    }
    r = sqlite3_reset(stmt);
    if (r != SQLITE_OK) {
        printf("could not reset statement: %i %s\n", r, sqlite3_errmsg(db));
    }
    manager->deref();
}

void
SqliteIndexWriter::startIndexable(Indexable* idx) {
    // get the file name
    string name = SqliteIndexManager::escapeSqlValue(idx->getName());

    // remove the previous version of this file
    // check if there is a previous version
    string sql = "select rowid from files where path = '"+name+"';";
    manager->ref();
    sqlite3_stmt* stmt;
    int r = sqlite3_prepare(db, sql.c_str(), 0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare document find sql\n");
        idx->setId(-1);
        manager->deref();
        return;
    }
    r = sqlite3_step(stmt);
    int64_t id = -1;
    if (r == SQLITE_ROW) {
        id = sqlite3_column_int64(stmt, 0);
        sqlite3_finalize(stmt);
    } else if (r == SQLITE_DONE) {
        sqlite3_finalize(stmt);
        // prepare the insert statement
        sql = "insert into files (path) values('";
        sql += name + "');";
        r = sqlite3_exec(db, sql.c_str(), 0, 0, 0);
        if (r != SQLITE_OK) {
            printf("error in adding file %i %s\n", r, sqlite3_errmsg(db));
            stmt = 0;
        }
        id = sqlite3_last_insert_rowid(db);
    } else {
        printf("could not look for a document by path\n");
        manager->deref();
        return;
    }
    idx->setId(id);
    manager->deref();
}
/*
    Close all left open indexwriters for this path.
*/
void
SqliteIndexWriter::finishIndexable(const Indexable* idx) {
    // store the content field
    map<int64_t, map<string, int> >::const_iterator m
        = content.find(idx->getId());
    if (m == content.end()) return;

    // create a temporary table
    int r = sqlite3_exec(db, "create temp table t(word, count)", 0,0,0);
    if (r != SQLITE_OK) {
        printf("could not create temp table %i %s\n", r, sqlite3_errmsg(db));
    }

    manager->ref();
    sqlite3_stmt* stmt;
    r = sqlite3_prepare(db, "insert into t (word, count) values(?,?);",
         0, &stmt, 0);
    if (r != SQLITE_OK) {
        printf("could not prepare temp insert sql\n");
        content.erase(m->first);
        manager->deref();
        return;
    }
    map<string, int>::const_iterator i = m->second.begin();
    map<string, int>::const_iterator e = m->second.end();
    for (; i!=e; ++i) {
        sqlite3_bind_text(stmt, 1, i->first.c_str(), i->first.length(),
            SQLITE_STATIC);
        sqlite3_bind_int(stmt, 2, i->second);
        r = sqlite3_step(stmt);
        if (r != SQLITE_DONE) {
            printf("could not write into database: %i %s\n", r, sqlite3_errmsg(db));
        }
        r = sqlite3_reset(stmt);
    }
    sqlite3_finalize(stmt);

    ostringstream sql;
    sql << "replace into words (wordid, word, count) "
        "select wordid, t.word, t.count+ifnull(words.count,0) "
        "from t left join words on t.word = words.word; "
        "replace into filewords (fileid, wordid, count) "
        "select ";
    sql << m->first;
    sql << ", words.rowid, t.count from t join words "
        "on t.word = words.word; drop table t;";
    r = sqlite3_exec(db, sql.str().c_str(),0,0,0);
    if (r != SQLITE_OK) {
        printf("could not drop temp table %i %s\n", r, sqlite3_errmsg(db));
    }
    manager->deref();
    content.erase(m->first);
}
<|endoftext|>


<commit_before>#ifndef ARABICA_XPATHIC_XPATH_HPP
#define ARABICA_XPATHIC_XPATH_HPP

#include <XPath/impl/xpath_parser.hpp>
#include <XPath/impl/xpath_value.hpp>
#include <XPath/impl/xpath_function.hpp>
#include <XPath/impl/xpath_step.hpp>
#include <XPath/impl/xpath_relational.hpp>
#include <XPath/impl/xpath_logical.hpp>
#include <XPath/impl/xpath_arithmetic.hpp>

/* To parameterise

DONE - xpath_arithmetic.hpp
DONE - xpath_ast.hpp
DONE - xpath_ast_ids.hpp
xpath_axis_enumerator.hpp
xpath_compile_context.hpp
xpath_execution_context.hpp
xpath_expression.hpp
xpath_function.hpp
xpath_function_holder.hpp
DONE - xpath_function_resolver.hpp
xpath_grammar.hpp
xpath_logical.hpp
DONE - xpath_namespace_context.hpp
DONE - xpath_namespace_node.hpp
xpath_node_test.hpp
xpath_object.hpp
xpath_parser.hpp
xpath_relational.hpp
DONE - xpath_resolver_holder.hpp
xpath_step.hpp
DONE - xpath_union.hpp
DONE - xpath_value.hpp
DONE - xpath_variable.hpp
DONE - xpath_variable_resolver.hpp

xpath_axis_enumerator.cpp
xpath_object.cpp
DONE - xpath_parser.cpp
*/
#endif
<commit_msg>*** empty log message ***<commit_after>#ifndef ARABICA_XPATHIC_XPATH_HPP
#define ARABICA_XPATHIC_XPATH_HPP

#include <XPath/impl/xpath_parser.hpp>
#include <XPath/impl/xpath_value.hpp>
#include <XPath/impl/xpath_function.hpp>
#include <XPath/impl/xpath_step.hpp>
#include <XPath/impl/xpath_relational.hpp>
#include <XPath/impl/xpath_logical.hpp>
#include <XPath/impl/xpath_arithmetic.hpp>

/* To parameterise

DONE - xpath_arithmetic.hpp
DONE - xpath_ast.hpp
DONE - xpath_ast_ids.hpp
xpath_axis_enumerator.hpp
DONE - xpath_compile_context.hpp
xpath_execution_context.hpp
xpath_expression.hpp
xpath_function.hpp
xpath_function_holder.hpp
DONE - xpath_function_resolver.hpp
xpath_grammar.hpp
xpath_logical.hpp
DONE - xpath_namespace_context.hpp
DONE - xpath_namespace_node.hpp
xpath_node_test.hpp
xpath_object.hpp
xpath_parser.hpp
xpath_relational.hpp
DONE - xpath_resolver_holder.hpp
xpath_step.hpp
DONE - xpath_union.hpp
DONE - xpath_value.hpp
DONE - xpath_variable.hpp
DONE - xpath_variable_resolver.hpp

xpath_axis_enumerator.cpp
xpath_object.cpp
DONE - xpath_parser.cpp
*/
#endif
<|endoftext|>


<commit_before>#ifndef MINIMIZER_HPP_
#define MINIMIZER_HPP_

#include <vector>
#include <string>

#include "nucleotide.hpp"

namespace OLC
{

// Class representing the minimizer of a vector of nucleotides of a given length, while also storing the position of the
// start of the minimizer in the original vector. Operations on the minimizer are the same as if working with a vector of
// nucleotides
class Minimizer
{
  private:
    std::vector<Nucleotide> vector_;
    int position_;

  public:
    Minimizer(const std::vector<Nucleotide> &vector, const int position);
    void push_back(const Nucleotide &nucleotides);
    Nucleotide operator[](unsigned int index) const;
    std::size_t size() const;
    int getPosition() const;

    bool operator==(const Minimizer &other) const;
    std::string toValueString() const;
    std::string toNucleotideString() const;
};

bool operator<(const Minimizer &first, const Minimizer &second);

}

#endif
<commit_msg>minimizer: remove unnecessary method<commit_after>#ifndef MINIMIZER_HPP_
#define MINIMIZER_HPP_

#include <vector>
#include <string>

#include "nucleotide.hpp"

namespace OLC
{

// Class representing the minimizer of a vector of nucleotides of a given length, while also storing the position of the
// start of the minimizer in the original vector. Operations on the minimizer are the same as if working with a vector of
// nucleotides
class Minimizer
{
  private:
    std::vector<Nucleotide> vector_;
    int position_;

  public:
    Minimizer(const std::vector<Nucleotide> &vector, const int position);
    Nucleotide operator[](unsigned int index) const;
    std::size_t size() const;
    int getPosition() const;

    bool operator==(const Minimizer &other) const;
    std::string toValueString() const;
    std::string toNucleotideString() const;
};

bool operator<(const Minimizer &first, const Minimizer &second);

}

#endif
<|endoftext|>


<commit_before>///
/// @file  help.cpp
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

namespace {

const string helpMenu(
  "Usage: primecount x [OPTION]...\n"
  "Count the primes below x <= 10^31 using fast implementations of the\n"
  "combinatorial prime counting function.\n"
  "\n"
  "Options:\n"
  "\n"
  "  -d,    --deleglise_rivat  Count primes using Deleglise-Rivat algorithm\n"
  "         --legendre         Count primes using Legendre's formula\n"
  "         --lehmer           Count primes using Lehmer's formula\n"
  "  -l,    --lmo              Count primes using Lagarias-Miller-Odlyzko\n"
  "  -m,    --meissel          Count primes using Meissel's formula\n"
  "         --Li               Approximate pi(x) using the logarithmic integral\n"
  "         --Li_inverse       Approximate the nth prime using Li^-1(x)\n"
  "  -n,    --nthprime         Calculate the nth prime\n"
  "  -p,    --primesieve       Count primes using the sieve of Eratosthenes\n"
  "  -s[N], --status[=N]       Show computation progress 1%, 2%, 3%, ...\n"
  "                            [N] digits after decimal point e.g. N=1, 99.9%\n"
  "         --test             Run various correctness tests and exit\n"
  "         --time             Print the time elapsed in seconds\n"
  "  -t<N>, --threads=<N>      Set the number of threads, 1 <= N <= CPU cores\n"
  "  -v,    --version          Print version and license information\n"
  "  -h,    --help             Print this help menu\n"
  "\n"
  "Advanced Deleglise-Rivat options:\n"
  "\n"
  "  -a<N>, --alpha=<N>        Tuning factor, 1 <= alpha <= x^(1/6)\n"
  "         --P2               Only compute the 2nd partial sieve function\n"
  "         --S1               Only compute the ordinary leaves\n"
  "         --S2_trivial       Only compute the trivial special leaves\n"
  "         --S2_easy          Only compute the easy special leaves\n"
  "         --S2_hard          Only compute the hard special leaves\n"
  "\n"
  "Examples:\n"
  "\n"
  "  primecount 1e13\n"
  "  primecount 1e13 --nthprime --threads=4"
);

const string versionInfo(
  "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
  "Copyright (C) 2015 Kim Walisch\n"
  "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);

} // end namespace

namespace primecount {

void help()
{
  cout << helpMenu << endl;
  exit(1);
}

void version()
{
  cout << versionInfo << endl;
  exit(1);
}

} // namespace primecount
<commit_msg>Update year to 2016<commit_after>///
/// @file  help.cpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount.hpp>

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

namespace {

const string helpMenu(
  "Usage: primecount x [OPTION]...\n"
  "Count the primes below x <= 10^31 using fast implementations of the\n"
  "combinatorial prime counting function.\n"
  "\n"
  "Options:\n"
  "\n"
  "  -d,    --deleglise_rivat  Count primes using Deleglise-Rivat algorithm\n"
  "         --legendre         Count primes using Legendre's formula\n"
  "         --lehmer           Count primes using Lehmer's formula\n"
  "  -l,    --lmo              Count primes using Lagarias-Miller-Odlyzko\n"
  "  -m,    --meissel          Count primes using Meissel's formula\n"
  "         --Li               Approximate pi(x) using the logarithmic integral\n"
  "         --Li_inverse       Approximate the nth prime using Li^-1(x)\n"
  "  -n,    --nthprime         Calculate the nth prime\n"
  "  -p,    --primesieve       Count primes using the sieve of Eratosthenes\n"
  "  -s[N], --status[=N]       Show computation progress 1%, 2%, 3%, ...\n"
  "                            [N] digits after decimal point e.g. N=1, 99.9%\n"
  "         --test             Run various correctness tests and exit\n"
  "         --time             Print the time elapsed in seconds\n"
  "  -t<N>, --threads=<N>      Set the number of threads, 1 <= N <= CPU cores\n"
  "  -v,    --version          Print version and license information\n"
  "  -h,    --help             Print this help menu\n"
  "\n"
  "Advanced Deleglise-Rivat options:\n"
  "\n"
  "  -a<N>, --alpha=<N>        Tuning factor, 1 <= alpha <= x^(1/6)\n"
  "         --P2               Only compute the 2nd partial sieve function\n"
  "         --S1               Only compute the ordinary leaves\n"
  "         --S2_trivial       Only compute the trivial special leaves\n"
  "         --S2_easy          Only compute the easy special leaves\n"
  "         --S2_hard          Only compute the hard special leaves\n"
  "\n"
  "Examples:\n"
  "\n"
  "  primecount 1e13\n"
  "  primecount 1e13 --nthprime --threads=4"
);

const string versionInfo(
  "primecount " PRIMECOUNT_VERSION ", <https://github.com/kimwalisch/primecount>\n"
  "Copyright (C) 2016 Kim Walisch\n"
  "BSD 2-Clause License <http://opensource.org/licenses/BSD-2-Clause>"
);

} // end namespace

namespace primecount {

void help()
{
  cout << helpMenu << endl;
  exit(1);
}

void version()
{
  cout << versionInfo << endl;
  exit(1);
}

} // namespace primecount
<|endoftext|>


<commit_before>#include "main.h"

// --- Params --- //

NoiseParams noise_params;
WaterParams water_params;
LightParams light_params;
TextureParams texture_params;
WindowParams window_params{ WIDTH, HEIGHT };
GridParams grid_params;

// --- Scene Objects --- //

Grid grid;
Water water;
Box box;
Sky sky;

// --- Buffers --- //

Framebuffer fbw(WIDTH, HEIGHT);
Depthbuffer fb_water_depth(WIDTH, HEIGHT);

// --- Textures --- //

GLuint tex_height;
GLuint tex_mirror;
GLuint tex_water_depth;
GLuint tex_normal_map;

// --- Camera --- //
Camera camera(&window_params);
NAVIGATION_MODE navmode;
Bezier bezier;

// --- Other --- //

NoiseGenerator noise_generator(&tex_height, &noise_params);
bool ant_tw_entering_value = false;

// Gets called when the windows is resized.
void resize_callback(int width, int height) {
    window_params.width = width;
	window_params.height = height;

    glViewport(0, 0, width, height);
	fbw.resize(width, height);
	fb_water_depth.resize(width, height);

	camera.compute_projection_matrix();
}

void compute_height_map() {
	noise_generator.renderFractal();
	box.set_height_texture(tex_height);
	grid.set_height_texture(tex_height);
	water.set_height_texture(tex_height);
	water.set_mirror_texture(tex_mirror);
	water.set_normal_map(tex_normal_map);
}

void init(){

    // Sets background color.
    glClearColor(/*gray*/ .937,.937,.937, /*solid*/1.0);

    // Enable depth test.
    glEnable(GL_DEPTH_TEST);

	// Possible to specify the travel time in the last argument. Note: the bigger the slower.
	bezier.init(WIDTH, HEIGHT);

	initParams();
	initTextures();
	initSceneObjects();

	noise_generator.init();

	navmode = FREE;

	compute_height_map();

#ifdef WITH_ANTTWEAKBAR
	initAntTwBar(&grid_params, &window_params, &noise_params, &water_params, &texture_params);
#endif
	check_error_gl();
}

// Gets called for every frame.
void display(){
	opengp::update_title_fps("Terrain");

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	mat4 view_matrix = camera.get_view_matrix();
	mat4 view_matrix_mirrored = camera.get_view_matrix_mirrored(); // for water reflections

	if (navmode == BEZIER) {
		vec3 cam_pos(2.0f, 2.0f, 2.0f);
		vec3 cam_look(0.0f, 0.0f, 0.0f);
		vec3 cam_up(0.0f, 0.0f, 1.0f);

		float t = (glfwGetTime() - bezier.get_start_time()) / bezier.get_travel_time();

		if (t >= 1) {
			bezier.set_start_time(glfwGetTime());
			t = t - 1;
		}

		bezier.pos_curve_sample_point(t, cam_pos);
		bezier.cam_look_sample_point(t, cam_look);

		view_matrix = Eigen::lookAt(cam_pos, cam_look, cam_up);
	} else {
		// Allow minecraft like mouvements for all other modes
		camera.move();
	}

	// Render the water reflect
	fbw.bind();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	grid.draw(view_matrix_mirrored, camera.get_projection_matrix(), true);
	fbw.unbind();
	glViewport(0, 0, window_params.width, window_params.height);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	fb_water_depth.bind();
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	grid.draw(view_matrix, camera.get_projection_matrix(), false);
	fb_water_depth.unbind();

	grid.draw(view_matrix, camera.get_projection_matrix(), false);
	water.draw(view_matrix, camera.get_projection_matrix());
	box.draw(view_matrix, camera.get_projection_matrix());
	sky.draw(view_matrix, camera.get_projection_matrix());

	if (navmode == CAMERA_PATH) {

		// Display points
		bezier.draw_cam_pos_points(view_matrix, camera.get_projection_matrix());
		bezier.draw_cam_look_points(view_matrix, camera.get_projection_matrix());

		// Display bezier curves
		bezier.pos_curve_draw(view_matrix, camera.get_projection_matrix());
		bezier.cam_look_draw(view_matrix, camera.get_projection_matrix());
	}

#ifdef WITH_ANTTWEAKBAR
	TwDraw();
#endif
}

void cleanup(){
#ifdef WITH_ANTTWEAKBAR
    TwTerminate();
#endif
	bezier.cleanup();
}

int main(int, char**){
    glfwInitWindowSize(window_params.width, window_params.height);
    glfwCreateWindow("Terrain");
    glfwDisplayFunc(display);

	glfwSetWindowSizeCallback(OnWindowSize);
	glfwSetMouseButtonCallback(OnMouseButton);
	glfwSetMousePosCallback(OnMousePos);
	glfwSetMouseWheelCallback(OnMouseWheel);
	glfwSetKeyCallback(OnKey);
	glfwSetCharCallback(OnChar);

    init();
    glfwMainLoop();
    cleanup();
    return EXIT_SUCCESS;
}

// --- Helpers --- //

void initParams() {

	// --- Window ---
	window_params.width = WIDTH;
	window_params.height = HEIGHT;

	// --- Grid ---
	grid_params.resolution = 100;
	grid_params.length = 2;
	grid_params.width = 2;

	// --- Noise ---
	noise_params.noise_type = PERLIN_NOISE;
	noise_params.fractal_type = FBM;
	noise_params.noise_effect = NO_EFFECT;
	noise_params.fractal_effect = NO_EFFECT;
	noise_params.height = 1;
	noise_params.width = 1;
	noise_params.offset = 0.0f;
	noise_params.amplitude = 1.0f;
	noise_params.H = 1.2f;
	noise_params.lacunarity = 2;
	noise_params.octaves = 12;
	noise_params.seed = glfwGetTime();
	noise_params.seed -= floor(noise_params.seed);

	// --- Water ---
	water_params.height = 0;
	water_params.color = vec3(0.4f, 0.55f, 0.6f);
	water_params.depth_alpha_factor = 1.4f;
	water_params.depth_color_factor = 0.05f;
	water_params.transparency = 0.4f;

	water_params.reflection_factor = 0.25f;
	/*water_params.waves_speed = 0.04f;
	water_params.waves_tile_factor = 2.0;
	water_params.waves_amplitude = 1.0f;*/

	// --- Light ---
	light_params.Ia = vec3(0.7f, 0.7f, 0.7f);
	light_params.Id = vec3(0.3f, 0.3f, 0.3f);
	light_params.position = vec3(2.0f, 2.0f, 2.0f);

	// --- Texture ---
	texture_params.sand_min_height = -1;
	texture_params.sand_max_height = 0.15f;
	texture_params.grass_max_height = 1.0f;
	texture_params.sand_max_slope = 0.92f;
	texture_params.grass_max_slope = 0.9f;

	texture_params.grass_h_transition = 3;
	texture_params.grass_s_transition = 50;
	texture_params.sand_h_transition = 5;
	texture_params.sand_s_transition = 50;
}

void initSceneObjects() {
	box.init(&grid_params, &water_params, &noise_params);
	grid.init(&grid_params, &light_params, &texture_params);
	tex_mirror = fbw.init_texture();
	fbw.init(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE);
	tex_water_depth = fb_water_depth.init_texture();
	fb_water_depth.init();

	water.init(&grid_params, &water_params, &light_params);
	water.set_depth_texture(tex_water_depth);
	sky.init();

	check_error_gl();
}

void initTextures() {
	glGenTextures(1, &tex_normal_map);
	glBindTexture(GL_TEXTURE_2D, tex_normal_map);
	glfwLoadTexture2D("textures/water/tex_normal_map.tga", 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}

// --- Callbacks --- //

// Callback function called by GLFW when a mouse button is clicked
void GLFWCALL OnMouseButton(int glfwButton, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMouseButtonGLFW(glfwButton, glfwAction))   // Send event to AntTweakBar
	{
#endif
		if (navmode == BEZIER) {
			std::cout << "[Warning] No mouse interaction in Bezier mode.\n" << std::flush;
			return;
		}

		// Event not handled by AntTweakBar, we handle it ourselves
		camera.mouse_button(glfwButton, glfwAction);
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW when mouse has moved
void GLFWCALL OnMousePos(int mouseX, int mouseY)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMousePosGLFW(mouseX, mouseY))  // Send event to AntTweakBar
	{
#endif
		if (navmode == BEZIER) {
			return;
		}

		camera.mouse_pos(mouseX, mouseY);
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on mouse wheel event
void GLFWCALL OnMouseWheel(int pos)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMouseWheelGLFW(pos))   // Send event to AntTweakBar
	{
#endif
		// Nothing for the moment
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on key event
void GLFWCALL OnKey(int glfwKey, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	// The following lines fix the unwanted behavior where bezier mode is loaded when typing a '2' in any field of the AntTwBar.
	if (TwKeyTest(2, 0) || TwKeyTest(1, 0)) {
		ant_tw_entering_value = true;
	}
	if (ant_tw_entering_value && glfwKey != 294 /* enter */ && glfwKey != 295 /* delete */) {
		ant_tw_entering_value = false;
		return;
	}
	if (!TwEventKeyGLFW(glfwKey, glfwAction))  // Send event to AntTweakBar
	{
#endif

		if (glfwKey == GLFW_KEY_ESC && glfwAction == GLFW_PRESS) // Want to quit?
			glfwCloseWindow();
		else
		{
			camera.keyboard(glfwKey, glfwAction);

			if (glfwAction != GLFW_RELEASE) return; ///< only act on release

			switch (glfwKey){
			case '1':
				navmode = FREE;
				std::cout << "[Info] Running in free mode\n" << std::flush;
				twBarVisible(true);
				break;
			case '2':
				navmode = BEZIER;
				std::cout << "[Info] Running in bezier mode\n" << std::flush;
				bezier.set_start_time(glfwGetTime());
				twBarVisible(false);
				break;
			case '3':
				navmode = CAMERA_PATH;
				std::cout << "[Info] Running in camera path editing mode\n" << std::flush;
				twBarVisible(false);
				break;
			default:
				std::cout << "[Warning] No keyboard interaction in bezier mode.\n" << std::flush;
				break;
			}
		}
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on char event
void GLFWCALL OnChar(int glfwChar, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventCharGLFW(glfwChar, glfwAction))    // Send event to AntTweakBar
	{
#endif
		// Nothing for the moment
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW when window size changes
void GLFWCALL OnWindowSize(int width, int height)
{
#ifdef WITH_ANTTWEAKBAR
	// Send the new window size to AntTweakBar
	TwWindowSize(width, height);
#endif

	resize_callback(width, height);
}<commit_msg>Can move bezier points in CAMERA_PATH mode (key 3), some strange behavior but works globally<commit_after>#include "main.h"

// --- Params --- //

NoiseParams noise_params;
WaterParams water_params;
LightParams light_params;
TextureParams texture_params;
WindowParams window_params{ WIDTH, HEIGHT };
GridParams grid_params;

// --- Scene Objects --- //

Grid grid;
Water water;
Box box;
Sky sky;

// --- Buffers --- //

Framebuffer fbw(WIDTH, HEIGHT);
Depthbuffer fb_water_depth(WIDTH, HEIGHT);

// --- Textures --- //

GLuint tex_height;
GLuint tex_mirror;
GLuint tex_water_depth;
GLuint tex_normal_map;

// --- Camera --- //
Camera camera(&window_params);
NAVIGATION_MODE navmode;
Bezier bezier;

// --- Other --- //

NoiseGenerator noise_generator(&tex_height, &noise_params);
bool ant_tw_entering_value = false;

// Gets called when the windows is resized.
void resize_callback(int width, int height) {
    window_params.width = width;
	window_params.height = height;

    glViewport(0, 0, width, height);
	fbw.resize(width, height);
	fb_water_depth.resize(width, height);

	camera.compute_projection_matrix();
}

void compute_height_map() {
	noise_generator.renderFractal();
	box.set_height_texture(tex_height);
	grid.set_height_texture(tex_height);
	water.set_height_texture(tex_height);
	water.set_mirror_texture(tex_mirror);
	water.set_normal_map(tex_normal_map);
}

void init(){

    // Sets background color.
    glClearColor(/*gray*/ .937,.937,.937, /*solid*/1.0);

    // Enable depth test.
    glEnable(GL_DEPTH_TEST);

	// Possible to specify the travel time in the last argument. Note: the bigger the slower.
	bezier.init(WIDTH, HEIGHT);

	initParams();
	initTextures();
	initSceneObjects();

	noise_generator.init();

	navmode = FREE;

	compute_height_map();

#ifdef WITH_ANTTWEAKBAR
	initAntTwBar(&grid_params, &window_params, &noise_params, &water_params, &texture_params);
#endif
	check_error_gl();
}

// Gets called for every frame.
void display(){
	opengp::update_title_fps("Terrain");

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	mat4 view_matrix = camera.get_view_matrix();
	mat4 view_matrix_mirrored = camera.get_view_matrix_mirrored(); // for water reflections

	if (navmode == BEZIER) {
		vec3 cam_pos(2.0f, 2.0f, 2.0f);
		vec3 cam_look(0.0f, 0.0f, 0.0f);
		vec3 cam_up(0.0f, 0.0f, 1.0f);

		float t = (glfwGetTime() - bezier.get_start_time()) / bezier.get_travel_time();

		if (t >= 1) {
			bezier.set_start_time(glfwGetTime());
			t = t - 1;
		}

		bezier.pos_curve_sample_point(t, cam_pos);
		bezier.cam_look_sample_point(t, cam_look);

		view_matrix = Eigen::lookAt(cam_pos, cam_look, cam_up);
	} else {
		// Allow minecraft like mouvements for all other modes
		camera.move();
	}

	// Render the water reflect
	fbw.bind();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	grid.draw(view_matrix_mirrored, camera.get_projection_matrix(), true);
	fbw.unbind();
	glViewport(0, 0, window_params.width, window_params.height);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	fb_water_depth.bind();
	glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
	grid.draw(view_matrix, camera.get_projection_matrix(), false);
	fb_water_depth.unbind();

	grid.draw(view_matrix, camera.get_projection_matrix(), false);
	water.draw(view_matrix, camera.get_projection_matrix());
	box.draw(view_matrix, camera.get_projection_matrix());
	sky.draw(view_matrix, camera.get_projection_matrix());

	if (navmode == CAMERA_PATH) {

		// Display points
		bezier.draw_cam_pos_points(view_matrix, camera.get_projection_matrix());
		bezier.draw_cam_look_points(view_matrix, camera.get_projection_matrix());

		// Display bezier curves
		bezier.pos_curve_draw(view_matrix, camera.get_projection_matrix());
		bezier.cam_look_draw(view_matrix, camera.get_projection_matrix());
	}

#ifdef WITH_ANTTWEAKBAR
	TwDraw();
#endif
}

void cleanup(){
#ifdef WITH_ANTTWEAKBAR
    TwTerminate();
#endif
	bezier.cleanup();
}

int main(int, char**){
    glfwInitWindowSize(window_params.width, window_params.height);
    glfwCreateWindow("Terrain");
    glfwDisplayFunc(display);

	glfwSetWindowSizeCallback(OnWindowSize);
	glfwSetMouseButtonCallback(OnMouseButton);
	glfwSetMousePosCallback(OnMousePos);
	glfwSetMouseWheelCallback(OnMouseWheel);
	glfwSetKeyCallback(OnKey);
	glfwSetCharCallback(OnChar);

    init();
    glfwMainLoop();
    cleanup();
    return EXIT_SUCCESS;
}

// --- Helpers --- //

void initParams() {

	// --- Window ---
	window_params.width = WIDTH;
	window_params.height = HEIGHT;

	// --- Grid ---
	grid_params.resolution = 100;
	grid_params.length = 2;
	grid_params.width = 2;

	// --- Noise ---
	noise_params.noise_type = PERLIN_NOISE;
	noise_params.fractal_type = FBM;
	noise_params.noise_effect = NO_EFFECT;
	noise_params.fractal_effect = NO_EFFECT;
	noise_params.height = 1;
	noise_params.width = 1;
	noise_params.offset = 0.0f;
	noise_params.amplitude = 1.0f;
	noise_params.H = 1.2f;
	noise_params.lacunarity = 2;
	noise_params.octaves = 12;
	noise_params.seed = glfwGetTime();
	noise_params.seed -= floor(noise_params.seed);

	// --- Water ---
	water_params.height = 0;
	water_params.color = vec3(0.4f, 0.55f, 0.6f);
	water_params.depth_alpha_factor = 1.4f;
	water_params.depth_color_factor = 0.05f;
	water_params.transparency = 0.4f;

	water_params.reflection_factor = 0.25f;
	/*water_params.waves_speed = 0.04f;
	water_params.waves_tile_factor = 2.0;
	water_params.waves_amplitude = 1.0f;*/

	// --- Light ---
	light_params.Ia = vec3(0.7f, 0.7f, 0.7f);
	light_params.Id = vec3(0.3f, 0.3f, 0.3f);
	light_params.position = vec3(2.0f, 2.0f, 2.0f);

	// --- Texture ---
	texture_params.sand_min_height = -1;
	texture_params.sand_max_height = 0.15f;
	texture_params.grass_max_height = 1.0f;
	texture_params.sand_max_slope = 0.92f;
	texture_params.grass_max_slope = 0.9f;

	texture_params.grass_h_transition = 3;
	texture_params.grass_s_transition = 50;
	texture_params.sand_h_transition = 5;
	texture_params.sand_s_transition = 50;
}

void initSceneObjects() {
	box.init(&grid_params, &water_params, &noise_params);
	grid.init(&grid_params, &light_params, &texture_params);
	tex_mirror = fbw.init_texture();
	fbw.init(GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE);
	tex_water_depth = fb_water_depth.init_texture();
	fb_water_depth.init();

	water.init(&grid_params, &water_params, &light_params);
	water.set_depth_texture(tex_water_depth);
	sky.init();

	check_error_gl();
}

void initTextures() {
	glGenTextures(1, &tex_normal_map);
	glBindTexture(GL_TEXTURE_2D, tex_normal_map);
	glfwLoadTexture2D("textures/water/tex_normal_map.tga", 0);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}

// --- Callbacks --- //

// Callback function called by GLFW when a mouse button is clicked
void GLFWCALL OnMouseButton(int glfwButton, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMouseButtonGLFW(glfwButton, glfwAction))   // Send event to AntTweakBar
	{
#endif
		// Event not handled by AntTweakBar, we handle it ourselves

		if (navmode == BEZIER) {
			std::cout << "[Warning] No mouse interaction in Bezier mode.\n" << std::flush;
			return;
		}

		if (navmode == CAMERA_PATH) {
			if (glfwGetKey(GLFW_KEY_LSHIFT) == GLFW_PRESS) {
				camera.mouse_button(glfwButton, glfwAction);
			}
			else {
				bezier.selection_button(glfwButton, glfwAction, camera.get_view_matrix(), camera.get_projection_matrix());
			}
		}
		else {
			// FREE mode or default
			camera.mouse_button(glfwButton, glfwAction);
		}
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW when mouse has moved
void GLFWCALL OnMousePos(int mouseX, int mouseY)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMousePosGLFW(mouseX, mouseY))  // Send event to AntTweakBar
	{
#endif
		if (navmode == BEZIER) {
			return;
		}

		camera.mouse_pos(mouseX, mouseY);
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on mouse wheel event
void GLFWCALL OnMouseWheel(int pos)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventMouseWheelGLFW(pos))   // Send event to AntTweakBar
	{
#endif
		// Nothing for the moment
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on key event
void GLFWCALL OnKey(int glfwKey, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	// The following lines fix the unwanted behavior where bezier mode is loaded when typing a '2' in any field of the AntTwBar.
	if (TwKeyTest(2, 0) || TwKeyTest(1, 0)) {
		ant_tw_entering_value = true;
	}
	if (ant_tw_entering_value && glfwKey != 294 /* enter */ && glfwKey != 295 /* delete */) {
		ant_tw_entering_value = false;
		return;
	}
	if (!TwEventKeyGLFW(glfwKey, glfwAction))  // Send event to AntTweakBar
	{
#endif

		if (glfwKey == GLFW_KEY_ESC && glfwAction == GLFW_PRESS) // Want to quit?
			glfwCloseWindow();
		else
		{
			camera.keyboard(glfwKey, glfwAction);

			if (glfwAction != GLFW_RELEASE) return; ///< only act on release

			switch (glfwKey){
			case '1':
				navmode = FREE;
				std::cout << "[Info] Running in free mode\n" << std::flush;
				twBarVisible(true);
				break;
			case '2':
				navmode = BEZIER;
				std::cout << "[Info] Running in bezier mode\n" << std::flush;
				bezier.set_start_time(glfwGetTime());
				twBarVisible(false);
				break;
			case '3':
				navmode = CAMERA_PATH;
				std::cout << "[Info] Running in camera path editing mode\n" << std::flush;
				twBarVisible(false);
				break;
			default:
				std::cout << "[Warning] No keyboard interaction in bezier mode.\n" << std::flush;
				break;
			}
		}
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW on char event
void GLFWCALL OnChar(int glfwChar, int glfwAction)
{
#ifdef WITH_ANTTWEAKBAR
	if (!TwEventCharGLFW(glfwChar, glfwAction))    // Send event to AntTweakBar
	{
#endif
		// Nothing for the moment
#ifdef WITH_ANTTWEAKBAR
	}
#endif
}

// Callback function called by GLFW when window size changes
void GLFWCALL OnWindowSize(int width, int height)
{
#ifdef WITH_ANTTWEAKBAR
	// Send the new window size to AntTweakBar
	TwWindowSize(width, height);
#endif

	resize_callback(width, height);
}<|endoftext|>


<commit_before>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

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

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - 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.
   - Neither the name of the Mumble Developers 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 FOUNDATION 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.
*/

#include "mumble_pch.hpp"

#include "About.h"

#include "Global.h"
#include "MainWindow.h"
#include "licenses.h"

AboutDialog::AboutDialog(QWidget *p) : QDialog(p) {
	setWindowTitle(tr("About Mumble"));

	QTabWidget *qtwTab = new QTabWidget(this);
	QVBoxLayout *vblMain = new QVBoxLayout(this);

	QTextEdit *qteLicense=new QTextEdit(qtwTab);
	qteLicense->setReadOnly(true);
	qteLicense->setPlainText(QLatin1String(licenseMumble));

	QTextBrowser *qtb3rdPartyLicense = new QTextBrowser(qtwTab);
	qtb3rdPartyLicense->setReadOnly(true);
	qtb3rdPartyLicense->setOpenExternalLinks(true);

	for(int i = 0; !licenses3rdParties[i].isEmpty(); ++i)
	{
		qtb3rdPartyLicense->append(QString::fromLatin1("
%1 (%2)

%3
")
				.arg(QString::fromLatin1(licenses3rdParties[i].name))
				.arg(QString::fromLatin1(licenses3rdParties[i].url))
				.arg(QString::fromLatin1(licenses3rdParties[i].license)));
	}

	qtb3rdPartyLicense->moveCursor(QTextCursor::Start);

	QWidget *about=new QWidget(qtwTab);

	QLabel *icon=new QLabel(about);
	icon->setPixmap(g.mw->qiIcon.pixmap(g.mw->qiIcon.actualSize(QSize(128, 128))));

	QLabel *text=new QLabel(about);
	text->setOpenExternalLinks(true);
	text->setText(tr(
	                  "
Mumble (%1)
"
	                  "
Copyright %3 The Mumble team
"
	                  "
A voice-chat utility for gamers
"
	                  "
<tt>%2</tt>
"
	              ).arg(QLatin1String(MUMBLE_RELEASE)).arg(QLatin1String("http://www.mumble.info/")).arg(QLatin1String("2005-2014")));
	QHBoxLayout *qhbl=new QHBoxLayout(about);
	qhbl->addWidget(icon);
	qhbl->addWidget(text);

	qtwTab->addTab(about, tr("&About Mumble"));
	qtwTab->addTab(qteLicense, tr("&License"));
	qtwTab->addTab(qtb3rdPartyLicense, tr("3rd &party licenses"));

	QPushButton *okButton = new QPushButton(tr("OK"), this);
	connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));

	vblMain->addWidget(qtwTab);
	vblMain->addWidget(okButton);
}
<commit_msg>About: change 'The Mumble team' to 'The Mumble Developers', as used in our license.<commit_after>/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>

   All rights reserved.

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

   - Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
   - 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.
   - Neither the name of the Mumble Developers 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 FOUNDATION 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.
*/

#include "mumble_pch.hpp"

#include "About.h"

#include "Global.h"
#include "MainWindow.h"
#include "licenses.h"

AboutDialog::AboutDialog(QWidget *p) : QDialog(p) {
	setWindowTitle(tr("About Mumble"));

	QTabWidget *qtwTab = new QTabWidget(this);
	QVBoxLayout *vblMain = new QVBoxLayout(this);

	QTextEdit *qteLicense=new QTextEdit(qtwTab);
	qteLicense->setReadOnly(true);
	qteLicense->setPlainText(QLatin1String(licenseMumble));

	QTextBrowser *qtb3rdPartyLicense = new QTextBrowser(qtwTab);
	qtb3rdPartyLicense->setReadOnly(true);
	qtb3rdPartyLicense->setOpenExternalLinks(true);

	for(int i = 0; !licenses3rdParties[i].isEmpty(); ++i)
	{
		qtb3rdPartyLicense->append(QString::fromLatin1("
%1 (%2)

%3
")
				.arg(QString::fromLatin1(licenses3rdParties[i].name))
				.arg(QString::fromLatin1(licenses3rdParties[i].url))
				.arg(QString::fromLatin1(licenses3rdParties[i].license)));
	}

	qtb3rdPartyLicense->moveCursor(QTextCursor::Start);

	QWidget *about=new QWidget(qtwTab);

	QLabel *icon=new QLabel(about);
	icon->setPixmap(g.mw->qiIcon.pixmap(g.mw->qiIcon.actualSize(QSize(128, 128))));

	QLabel *text=new QLabel(about);
	text->setOpenExternalLinks(true);
	text->setText(tr(
		"
Mumble (%1)
"
		"
%3
"
		"
A voice-chat utility for gamers
"
		"
<tt>%2</tt>
"
	).arg(QLatin1String(MUMBLE_RELEASE))
	 .arg(QLatin1String("http://www.mumble.info/"))
	 .arg(QLatin1String("Copyright 2005-2015 The Mumble Developers")));
	QHBoxLayout *qhbl=new QHBoxLayout(about);
	qhbl->addWidget(icon);
	qhbl->addWidget(text);

	qtwTab->addTab(about, tr("&About Mumble"));
	qtwTab->addTab(qteLicense, tr("&License"));
	qtwTab->addTab(qtb3rdPartyLicense, tr("3rd &party licenses"));

	QPushButton *okButton = new QPushButton(tr("OK"), this);
	connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));

	vblMain->addWidget(qtwTab);
	vblMain->addWidget(okButton);
}
<|endoftext|>


<commit_before>#include "atlas_ph.h"
#include <SoftwareSerial.h>

AtlasPh::AtlasPh(int rxPin, int txPin)
{
	SoftwareSerial mySerial(rxPin, txPin);
	atlasSerial = & mySerial;

	Serial.begin(38400);
	atlasSerial->begin(38400);

	atlasSerial->print("E\r");
	delay(50);
	atlasSerial->print("E\r");
	delay(50);
}

float AtlasPh::getPh(int tempVal)
{
	atlasSerial->print("R\r");

	float phVal = 0.0;

	while (atlasSerial->available() > 0)
	{
		phVal = Serial.parseFloat();
	}

	return phVal;
}

void AtlasPh::setHighAlarmPh(char phVal)
{
	if (phVal > 8)
	{
		phVal = 8;
	}
	else if (phVal < 4)
	{
		phVal = 4;
	}

	highAlarmPh = (uint8_t)phVal;
}

void AtlasPh::setLowAlarmPh(char phVal)
{
	if (phVal > 8)
	{
		phVal = 8;
	}
	else if (phVal < 4)
	{
		phVal = 4;
	}

	lowAlarmPh = (uint8_t)phVal;
}<commit_msg>Added missing AtlasPh functions<commit_after>#include "atlas_ph.h"
#include <SoftwareSerial.h>

AtlasPh::AtlasPh(int rxPin, int txPin)
{
	SoftwareSerial mySerial(rxPin, txPin);
	atlasSerial = & mySerial;

	Serial.begin(38400);
	atlasSerial->begin(38400);

	atlasSerial->print("E\r");
	delay(50);
	atlasSerial->print("E\r");
	delay(50);
}

float AtlasPh::getPh(int tempVal)
{
	atlasSerial->print("R\r");

	float phVal = 0.0;

	while (atlasSerial->available() > 0)
	{
		phVal = Serial.parseFloat();
	}

	return phVal;
}

void AtlasPh::setHighAlarmPh(char phVal)
{
	if (phVal > 8)
	{
		phVal = 8;
	}
	else if (phVal < 4)
	{
		phVal = 4;
	}

	highAlarmPh = (uint8_t)phVal;
}

void AtlasPh::setLowAlarmPh(char phVal)
{
	if (phVal > 8)
	{
		phVal = 8;
	}
	else if (phVal < 4)
	{
		phVal = 4;
	}

	lowAlarmPh = (uint8_t)phVal;
}

char AtlasPh::getHighAlarmPh()
{
	return (char)highAlarmPh;
}

char AtlasPh::getLowAlarmPh()
{
	return (char)lowAlarmPh;
}<|endoftext|>


<commit_before>#include "dptrace.h"
#include "../logger.h"

TraceDPMatrix::IndexedTrans::IndexedTrans (const EvaluatedMachineState::Trans& t, StateIndex s, StateIndex d, InputToken i)
{
  init (t.logWeight, t.transIndex);
  src = s;
  dest = d;
  in = i;
}

TraceDPMatrix::TraceDPMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& moments, const TraceParams& traceParams, size_t bb) :
  eval (eval),
  modelParams (modelParams),
  moments (moments),
  traceParams (traceParams),
  coeffs (modelParams, traceParams, eval.outputTokenizer),
  outLen (moments.sample.size()),
  nStates (eval.nStates()),
  nOutToks (eval.outputTokenizer.tok2sym.size()),
  nColumns (outLen + 1),
  blockBytes (bb),
  blockSize (blockBytes ? max((OutputIndex)2,min((OutputIndex)(blockBytes / (nStates * sizeof(double))),(OutputIndex)nColumns)) : nColumns),
  nCheckpoints (1 + ((nColumns - 1) / blockSize))
{
  LogThisAt(7,"Creating " << (outLen+1) << "-sample * " << nStates << "-state matrix" << endl);
  LogThisAt(9,"Machine:" << endl << eval.toJsonString() << endl);

  nTrans = 0;
  transByOut.resize (nOutToks);
  for (StateIndex dest = 0; dest < nStates; ++dest)
    for (const auto& inTok_outStateTransMap: eval.state[dest].incoming)
      for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second)
	for (const auto& src_trans: outTok_stateTransMap.second) {
	  Assert (outTok_stateTransMap.first || (src_trans.first <= dest), "Input-blinded machine is not topologically sorted (transition from %d to %d has no output)", src_trans.first, dest);
	  transByOut[outTok_stateTransMap.first].push_back (IndexedTrans (src_trans.second, src_trans.first, dest, inTok_outStateTransMap.first));
	  ++nTrans;
	}

  columnStorage.resize (blockSize + nCheckpoints - 1, vguard<double> (nStates, -numeric_limits<double>::infinity()));
}
<commit_msg>smarter block sizes<commit_after>#include "dptrace.h"
#include "../logger.h"

TraceDPMatrix::IndexedTrans::IndexedTrans (const EvaluatedMachineState::Trans& t, StateIndex s, StateIndex d, InputToken i)
{
  init (t.logWeight, t.transIndex);
  src = s;
  dest = d;
  in = i;
}

size_t calcBlockSize (size_t storageColumns, size_t totalColumns) {
  const double s = pow ((double) storageColumns, 2) - 4*totalColumns;
  return s >= 0 ? ceil ((storageColumns + sqrt(s)) / 2) : 1;
}

TraceDPMatrix::TraceDPMatrix (const EvaluatedMachine& eval, const GaussianModelParams& modelParams, const TraceMoments& moments, const TraceParams& traceParams, size_t bb) :
  eval (eval),
  modelParams (modelParams),
  moments (moments),
  traceParams (traceParams),
  coeffs (modelParams, traceParams, eval.outputTokenizer),
  outLen (moments.sample.size()),
  nStates (eval.nStates()),
  nOutToks (eval.outputTokenizer.tok2sym.size()),
  nColumns (outLen + 1),
  blockBytes (bb),
  blockSize (blockBytes
	     ? max ((OutputIndex) 2,
		    min ((OutputIndex) nColumns,
			 (OutputIndex) calcBlockSize (blockBytes / (nStates * sizeof(double)), outLen)))
	     : nColumns),
  nCheckpoints (1 + ((nColumns - 1) / blockSize))
{
  LogThisAt(7,"Creating " << (outLen+1) << "-sample * " << nStates << "-state matrix" << endl);
  LogThisAt(9,"Machine:" << endl << eval.toJsonString() << endl);

  nTrans = 0;
  transByOut.resize (nOutToks);
  for (StateIndex dest = 0; dest < nStates; ++dest)
    for (const auto& inTok_outStateTransMap: eval.state[dest].incoming)
      for (const auto& outTok_stateTransMap: inTok_outStateTransMap.second)
	for (const auto& src_trans: outTok_stateTransMap.second) {
	  Assert (outTok_stateTransMap.first || (src_trans.first <= dest), "Input-blinded machine is not topologically sorted (transition from %d to %d has no output)", src_trans.first, dest);
	  transByOut[outTok_stateTransMap.first].push_back (IndexedTrans (src_trans.second, src_trans.first, dest, inTok_outStateTransMap.first));
	  ++nTrans;
	}

  columnStorage.resize (blockSize + nCheckpoints - 1, vguard<double> (nStates, -numeric_limits<double>::infinity()));
}
<|endoftext|>