<commit_before>#include <vector>
#include <iostream>

#include <SFML/Graphics.hpp>

#include "Universe.hpp"
#include "Body.hpp"

#define MASS 10
#define BASE_LINE 2

using namespace sf;
using namespace std;

int main()
{
	RenderWindow window(VideoMode(800, 600), "Gravity Simulation by Johan");
	View view(FloatRect(0, 0, 400, 300));

	// Drawable elements
	Universe universe;
	VertexArray line(Lines, 2);
	CircleShape base_line(BASE_LINE);

	// Logic vars
	Clock timer;
	float delta_t(0);
	int mass(MASS);
	Vector2f mousePosition;
	Vector2f start, end;
	bool running = true;
	bool is_placing = false;
	bool is_moving = false;
	bool trace = false;
	bool control = false;
	bool shift = false;

	// Some inits
	line[0].color = Color::Blue;
	line[1].color = Color::Green;
	base_line.setFillColor(Color::Blue);
	window.setView(view);

	while (running)
	{
		Event evt;
		while (window.pollEvent(evt))
		{
			if (evt.type == Event::Closed)
			{
				running = false;
			}

			if (evt.type == Event::KeyPressed)
			{
				if (evt.key.code == Keyboard::Escape)
				{
					running = false;
				}

				switch (evt.key.code)
				{
                case Keyboard::PageUp:
				case Keyboard::Add:
					mass *= 10;
					if (mass < 0)
					{
						mass = MASS;
					}
					cout << "Mass is now " << mass << endl;
					break;

                case Keyboard::PageDown:
				case Keyboard::Subtract:
					if (mass > 10)
					{
						mass /= 10;
					}
					else
					{
						mass = MASS;
					}
					cout << "Mass is now " << mass << endl;
					break;

				case Keyboard::T:
					trace = !trace;
					cout << "Trace mode " << (trace ? "enabled" : "disabled") << endl;
					break;

				case Keyboard::Space:
                    if (is_placing)
                    {
                        cout << "Planet placement cancelled" << endl;
                    }

                    is_placing = false;
                    break;

                case Keyboard::LControl:
                	control = true;
                	break;

                case Keyboard::LShift:
                	shift = true;
                	break;
				default:
					break;
				}
			}

			if (evt.type == Event::KeyReleased)
			{
				switch (evt.key.code)
				{
				case Keyboard::LControl:
					control = false;

				case Keyboard::LShift:
					shift = false;

				default:
					break;
				}
			}

			if (evt.type == Event::MouseButtonPressed)
			{
                if (shift)
                {
                    universe.eraseAt(Vector2f(evt.mouseButton.x, evt.mouseButton.y));
                }
                else if (control)
                {
                	is_moving = true;
                }
                else
                {
                    is_placing = true;

                    line[0].position = window.mapPixelToCoords(Vector2i(evt.mouseButton.x, evt.mouseButton.y));
                    line[1].position = line[0].position;
                    start = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
                    end = start;

                    Vector2f base =
                    	window.mapPixelToCoords(Vector2i(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE));
                    base_line.setPosition(base);
                }
            }

			if (evt.type == Event::MouseMoved)
			{
				if (is_placing)
				{
					line[1].position = window.mapPixelToCoords(Vector2i(evt.mouseMove.x, evt.mouseMove.y));
					end = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
				}

				if (is_moving)
				{
					view.move(mousePosition - Vector2f(evt.mouseMove.x, evt.mouseMove.y));
					window.setView(view);
				}

				mousePosition = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
			}

			if (evt.type == Event::MouseButtonReleased)
			{
				if (is_placing)
				{
					is_placing = false;

					Vector2f direction = end - start;

					Body p(Vector2f(0, 0), mass, direction);

					p.position = Vector2f(line[0].position.x,
							line[0].position.y);;

					universe.addPlanet(p);
				}

				if (is_moving)
				{
					is_moving = false;
				}
			}
		}

		if (!trace)
		{
			window.clear();
		}

		// Delta T
		delta_t = timer.restart().asSeconds();

		// Vector Preview - wow - need an arrow - hard
		if (is_placing)
		{
			window.draw(line);
			window.draw(base_line);
		}

		// Planets
		universe.move(delta_t);
		universe.draw(window);

		window.display();

		sleep(milliseconds(3));
	}

	return 0;
}
<commit_msg>the view now adapts when the window is resized<commit_after>#include <vector>
#include <iostream>

#include <SFML/Graphics.hpp>

#include "Universe.hpp"
#include "Body.hpp"

#define MASS 10
#define BASE_LINE 2

using namespace sf;
using namespace std;

int main()
{
	unsigned int width(800), height(600);
	RenderWindow window(VideoMode(width, height), "Gravity Simulation by Johan");
	View view(FloatRect(0, 0, width, height));

	// Drawable elements
	Universe universe;
	VertexArray line(Lines, 2);
	CircleShape base_line(BASE_LINE);

	// Logic vars
	Clock timer;
	float delta_t(0);
	int mass(MASS);
	Vector2f mousePosition;
	Vector2f start, end;
	bool running = true;
	bool is_placing = false;
	bool is_moving = false;
	bool trace = false;
	bool control = false;
	bool shift = false;

	// Some inits
	line[0].color = Color::Blue;
	line[1].color = Color::Green;
	base_line.setFillColor(Color::Blue);
	window.setView(view);

	while (running)
	{
		Event evt;
		while (window.pollEvent(evt))
		{
			if (evt.type == Event::Closed)
			{
				running = false;
			}

			if (evt.type == Event::Resized)
			{
				view.setSize(evt.size.width, evt.size.height);
				window.setView(view);
			}

			if (evt.type == Event::KeyPressed)
			{
				if (evt.key.code == Keyboard::Escape)
				{
					running = false;
				}

				switch (evt.key.code)
				{
                case Keyboard::PageUp:
				case Keyboard::Add:
					mass *= 10;
					if (mass < 0)
					{
						mass = MASS;
					}
					cout << "Mass is now " << mass << endl;
					break;

                case Keyboard::PageDown:
				case Keyboard::Subtract:
					if (mass > 10)
					{
						mass /= 10;
					}
					else
					{
						mass = MASS;
					}
					cout << "Mass is now " << mass << endl;
					break;

				case Keyboard::T:
					trace = !trace;
					cout << "Trace mode " << (trace ? "enabled" : "disabled") << endl;
					break;

				case Keyboard::Space:
                    if (is_placing)
                    {
                        cout << "Planet placement cancelled" << endl;
                    }

                    is_placing = false;
                    break;

                case Keyboard::LControl:
                	control = true;
                	break;

                case Keyboard::LShift:
                	shift = true;
                	break;
				default:
					break;
				}
			}

			if (evt.type == Event::KeyReleased)
			{
				switch (evt.key.code)
				{
				case Keyboard::LControl:
					control = false;

				case Keyboard::LShift:
					shift = false;

				default:
					break;
				}
			}

			if (evt.type == Event::MouseButtonPressed)
			{
                if (shift)
                {
                    universe.eraseAt(Vector2f(evt.mouseButton.x, evt.mouseButton.y));
                }
                else if (control)
                {
                	is_moving = true;
                }
                else
                {
                    is_placing = true;

                    line[0].position = window.mapPixelToCoords(Vector2i(evt.mouseButton.x, evt.mouseButton.y));
                    line[1].position = line[0].position;
                    start = Vector2f(evt.mouseButton.x, evt.mouseButton.y);
                    end = start;

                    Vector2f base =
                    	window.mapPixelToCoords(Vector2i(evt.mouseButton.x - BASE_LINE, evt.mouseButton.y - BASE_LINE));
                    base_line.setPosition(base);
                }
            }

			if (evt.type == Event::MouseMoved)
			{
				if (is_placing)
				{
					line[1].position = window.mapPixelToCoords(Vector2i(evt.mouseMove.x, evt.mouseMove.y));
					end = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
				}

				if (is_moving)
				{
					view.move(mousePosition - Vector2f(evt.mouseMove.x, evt.mouseMove.y));
					window.setView(view);
				}

				mousePosition = Vector2f(evt.mouseMove.x, evt.mouseMove.y);
			}

			if (evt.type == Event::MouseButtonReleased)
			{
				if (is_placing)
				{
					is_placing = false;

					Vector2f direction = end - start;

					Body p(Vector2f(0, 0), mass, direction);

					p.position = Vector2f(line[0].position.x,
							line[0].position.y);;

					universe.addPlanet(p);
				}

				if (is_moving)
				{
					is_moving = false;
				}
			}

			if (evt.type == Event::MouseWheelMoved)
			{
				float factor = (evt.mouseWheel.delta < 1 ? 1.10 : 0.90);
				view.zoom(factor);
				window.setView(view);
			}
		}

		if (!trace)
		{
			window.clear();
		}

		// Delta T
		delta_t = timer.restart().asSeconds();

		// Vector Preview - wow - need an arrow - hard
		if (is_placing)
		{
			window.draw(line);
			window.draw(base_line);
		}

		// Planets
		universe.move(delta_t);
		universe.draw(window);

		window.display();

		sleep(milliseconds(3));
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
	This file is part of the CVD Library.

	Copyright (C) 2005 The Authors

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include <cvd/internal/io/bmp.h>

using namespace std;
#include <iostream>
#include <sstream>
#include <iomanip>
#include <setjmp.h>

namespace CVD
{
  namespace BMP
  {

    struct BMPHeader
    {
      unsigned long size;            //!< header size
      unsigned short reserved[2];        //!< reserved
      unsigned long dataOffset;      //!< offset to beginning of data
      unsigned long infoSize;        //!< size of info
      unsigned long width;           //!< width of image
      unsigned long height;          //!< height of image
      unsigned short planes;         //!< planes
      unsigned short bpp;            //!< colour depth
      unsigned long compression;     //!< compression type
      unsigned long dataSize;        //!< size of data
      unsigned long xPelsPerMeter;   //!< x resolution in pixels/meter
      unsigned long yPelsPerMeter;   //!< y resolution in pixels/meter
      unsigned long colors;          //!< number of specified colors in the map
      unsigned long importantColors; //!< number of important colors
    };

	void write_u4(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l))
		  << (unsigned char)(0xff & (l >> 8))
		  << (unsigned char)(0xff & (l >> 16))
		  << (unsigned char)(0xff & (l >> 24));
	}

	void write_u1(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l));
	}

	void write_u2(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l))
		  << (unsigned char)(0xff & (l >> 8));
	}

	inline	unsigned long  read_u4(istream& i)
	{
		//Data is little endian:
		unsigned long r =  i.get() | (i.get() << 8) | (i.get() << 16) | (i.get() << 12);
		if(i.eof())
			throw(Exceptions::Image_IO::MalformedImage("EOF in header."));

			return r;
	}

	inline	unsigned long  read_u2(istream& i)
	{
		//Data is little endian:
		unsigned long r =  i.get() | (i.get() << 8);
		if(i.eof())
			throw(Exceptions::Image_IO::MalformedImage("EOF in header."));

		return r;
	}

	BMPHeader read_header(istream& i)
	{
		//Read the header
		BMPHeader h;
		h.size = read_u4(i);
		h.reserved[0] = read_u2(i);
		h.reserved[1] = read_u2(i);
		h.dataOffset = read_u4(i);

		//Read the info block
		h.infoSize = read_u4(i);

		if(h.infoSize != 40)
		{

			string type;

			switch(h.infoSize)
			{
				case 40:
					type = "Windows 3.x style bitmap unsupported.";
					break;
				case 12:
					type = "OS/2 1.x style bitmap unsupported.";
					break;
				case 64:
					type = "OS/2 2.x style bitmap unsupported.";
					break;
				case 108:
					type = "Windows V4 (95/NT) style bitmap unsupported.";
					break;
				case 124:
					type = "Windows V5 (98/2000) style bitmap unsupported.";
					break;
				default:
				{
					ostringstream ts;
					ts << "unknown bitmap type (info size = " << h.infoSize << ")";
					type = ts.str();
				}
			}

			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", type));
		}
		h.width = read_u4(i);
		h.height = read_u4(i);
		h.planes = read_u2(i);
		h.bpp = read_u2(i);
		h.compression = read_u4(i);
		h.dataSize = read_u4(i);
		h.xPelsPerMeter = read_u4(i);
		h.yPelsPerMeter = read_u4(i);
		h.colors = read_u4(i);
		h.importantColors = read_u4(i);

		return h;
	}

	void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, ostream& out)
	{
		unsigned int rowSize = channels*width;
		if (rowSize%4)
		rowSize += 4-(rowSize%4);

		unsigned long dataSize = rowSize * height;
		unsigned long offset  =  14 + 40 +  (channels == 1 ? 1024 : 0);

		//Output header
		/*   0  */ out << "BM";
		/*   2  */ write_u4(out, offset + dataSize);  //File size
		/*   6  */ write_u2(out, 0); //Reserved
		/*   8  */ write_u2(out, 0); //Reserved
		/*  10  */ write_u4(out, offset); //Data offset

		//Output info
		/*  14  */ write_u4(out, 40);    //3.x style header size
		/*  18  */ write_u4(out, width);
		/*  22  */ write_u4(out, height);
		/*  26  */ write_u2(out, 1);    //Planes (always 1);
		/*  28  */ write_u2(out, channels*8); //Bpp
		/*  30  */ write_u4(out, 0); //Compression method
		/*  34  */ write_u4(out, dataSize);
		/*  38  */ write_u4(out, 0); //Pixels per meter (x)
		/*  42  */ write_u4(out, 0); //Pixels per meter (y)
		/*  46  */ write_u4(out, 0); //Number of colours (0 == 2^N)
		/*  50  */ write_u4(out, 0); //Number of important colora

		//Write the palette
		if (channels == 1)
		{
			for (unsigned int i=0; i<256;i++)
			{
				write_u1(out, i); //Blue
				write_u1(out, i); //Green
				write_u1(out, i); //Red
				write_u1(out, 0); //Reserved
			}
		}
	}

	void readBMPHeader(unsigned int& width, unsigned int& height, unsigned int& channels, unsigned int& compression, istream& in)
	{
		char tag[3]={0};
		in.read(tag,2);
		if (strcmp(tag, "BM") != 0)
			throw CVD::Exceptions::Image_IO::MalformedImage("BMP files must start with 'BM'");
		struct BMPHeader header = read_header(in);

		if(header.bpp == 8)
			channels = 1;
		else if(header.bpp == 24)
			channels = 3;
		else
			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", "image is not 8 or 24 bits per pixel."));

		compression = header.compression;
		if(compression != 0)
			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", "compressed images not supported."));

		width = header.width;
		height = header.height;
	}
  }
}
<commit_msg>Fix to remove multiple istream::get()'s in a multiple statement because the order of evaluation is not defined. This shows up in VS2010, release mode only.<commit_after>/*
	This file is part of the CVD Library.

	Copyright (C) 2005 The Authors

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Lesser General Public
	License as published by the Free Software Foundation; either
	version 2.1 of the License, or (at your option) any later version.

	This library is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
	Lesser General Public License for more details.

	You should have received a copy of the GNU Lesser General Public
	License along with this library; if not, write to the Free Software
	Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include <cvd/internal/io/bmp.h>

using namespace std;
#include <iostream>
#include <sstream>
#include <iomanip>
#include <setjmp.h>

namespace CVD
{
  namespace BMP
  {

    struct BMPHeader
    {
      unsigned long size;            //!< header size
      unsigned short reserved[2];        //!< reserved
      unsigned long dataOffset;      //!< offset to beginning of data
      unsigned long infoSize;        //!< size of info
      unsigned long width;           //!< width of image
      unsigned long height;          //!< height of image
      unsigned short planes;         //!< planes
      unsigned short bpp;            //!< colour depth
      unsigned long compression;     //!< compression type
      unsigned long dataSize;        //!< size of data
      unsigned long xPelsPerMeter;   //!< x resolution in pixels/meter
      unsigned long yPelsPerMeter;   //!< y resolution in pixels/meter
      unsigned long colors;          //!< number of specified colors in the map
      unsigned long importantColors; //!< number of important colors
    };

	void write_u4(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l))
		  << (unsigned char)(0xff & (l >> 8))
		  << (unsigned char)(0xff & (l >> 16))
		  << (unsigned char)(0xff & (l >> 24));
	}

	void write_u1(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l));
	}

	void write_u2(ostream& o, unsigned long l)
	{
		o << (unsigned char)(0xff & (l))
		  << (unsigned char)(0xff & (l >> 8));
	}

	inline	unsigned long  read_u4(istream& i)
	{
		//Data is little endian:
		//unsigned long r =  i.get() | (i.get() << 8) | (i.get() << 16) | (i.get() << 24 );
		int a = i.get();
		int b = i.get();
		int c = i.get();
		int d = i.get();
		unsigned long r = a | (b << 8) | (c<<16) | (d << 24);
		if(i.eof())
			throw(Exceptions::Image_IO::MalformedImage("EOF in header."));

			return r;
	}

	inline	unsigned long  read_u2(istream& i)
	{
		//Data is little endian:
		//unsigned long r =  i.get() | (i.get() << 8);
		int a = i.get();
		int b = i.get();
		unsigned long r = a | (b << 8);
		if(i.eof())
			throw(Exceptions::Image_IO::MalformedImage("EOF in header."));

		return r;
	}

	BMPHeader read_header(istream& i)
	{
		//Read the header
		BMPHeader h;
		h.size = read_u4(i);
		h.reserved[0] = read_u2(i);
		h.reserved[1] = read_u2(i);
		h.dataOffset = read_u4(i);

		//Read the info block
		h.infoSize = read_u4(i);

		if(h.infoSize != 40)
		{

			string type;

			switch(h.infoSize)
			{
				case 40:
					type = "Windows 3.x style bitmap unsupported.";
					break;
				case 12:
					type = "OS/2 1.x style bitmap unsupported.";
					break;
				case 64:
					type = "OS/2 2.x style bitmap unsupported.";
					break;
				case 108:
					type = "Windows V4 (95/NT) style bitmap unsupported.";
					break;
				case 124:
					type = "Windows V5 (98/2000) style bitmap unsupported.";
					break;
				default:
				{
					ostringstream ts;
					ts << "unknown bitmap type (info size = " << h.infoSize << ")";
					type = ts.str();
				}
			}

			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", type));
		}
		h.width = read_u4(i);
		h.height = read_u4(i);
		h.planes = read_u2(i);
		h.bpp = read_u2(i);
		h.compression = read_u4(i);
		h.dataSize = read_u4(i);
		h.xPelsPerMeter = read_u4(i);
		h.yPelsPerMeter = read_u4(i);
		h.colors = read_u4(i);
		h.importantColors = read_u4(i);

		return h;
	}

	void writeBMPHeader(unsigned int width, unsigned int height, unsigned int channels, ostream& out)
	{
		unsigned int rowSize = channels*width;
		if (rowSize%4)
		rowSize += 4-(rowSize%4);

		unsigned long dataSize = rowSize * height;
		unsigned long offset  =  14 + 40 +  (channels == 1 ? 1024 : 0);

		//Output header
		/*   0  */ out << "BM";
		/*   2  */ write_u4(out, offset + dataSize);  //File size
		/*   6  */ write_u2(out, 0); //Reserved
		/*   8  */ write_u2(out, 0); //Reserved
		/*  10  */ write_u4(out, offset); //Data offset

		//Output info
		/*  14  */ write_u4(out, 40);    //3.x style header size
		/*  18  */ write_u4(out, width);
		/*  22  */ write_u4(out, height);
		/*  26  */ write_u2(out, 1);    //Planes (always 1);
		/*  28  */ write_u2(out, channels*8); //Bpp
		/*  30  */ write_u4(out, 0); //Compression method
		/*  34  */ write_u4(out, dataSize);
		/*  38  */ write_u4(out, 0); //Pixels per meter (x)
		/*  42  */ write_u4(out, 0); //Pixels per meter (y)
		/*  46  */ write_u4(out, 0); //Number of colours (0 == 2^N)
		/*  50  */ write_u4(out, 0); //Number of important colora

		//Write the palette
		if (channels == 1)
		{
			for (unsigned int i=0; i<256;i++)
			{
				write_u1(out, i); //Blue
				write_u1(out, i); //Green
				write_u1(out, i); //Red
				write_u1(out, 0); //Reserved
			}
		}
	}

	void readBMPHeader(unsigned int& width, unsigned int& height, unsigned int& channels, unsigned int& compression, istream& in)
	{
		char tag[3]={0};
		in.read(tag,2);
		if (strcmp(tag, "BM") != 0)
			throw CVD::Exceptions::Image_IO::MalformedImage("BMP files must start with 'BM'");
		struct BMPHeader header = read_header(in);

		if(header.bpp == 8)
			channels = 1;
		else if(header.bpp == 24)
			channels = 3;
		else
			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", "image is not 8 or 24 bits per pixel."));

		compression = header.compression;
		if(compression != 0)
			throw(Exceptions::Image_IO::UnsupportedImageSubType("Windows BMP/DIB", "compressed images not supported."));

		width = header.width;
		height = header.height;
	}
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bmp.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2004-03-19 16:33:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <vector>
using namespace std;

#include <vcl/svapp.hxx>

#include "solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"

// ----------
// - BmpApp -
// ----------

class BmpApp : public BmpCreator
{
private:

    String          aOutputFileName;
    BYTE            cExitCode;

    BOOL            GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
    BOOL            GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );

    void            SetExitCode( BYTE cExit )
                    {
                        if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                            cExitCode = cExit;
                    }
    void            ShowUsage();

    virtual void    Message( const String& rText, BYTE cExitCode );

public:

                    BmpApp();
                    ~BmpApp();

    int             Start( const ::std::vector< String >& rArgs );
};

// -----------------------------------------------------------------------------

BmpApp::BmpApp()
{
}

// -----------------------------------------------------------------------------

BmpApp::~BmpApp()
{
}

// -----------------------------------------------------------------------

BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                bRet = TRUE;

                if( i < ( nCount - 1 ) )
                    rParam = rArgs[ i + 1 ];
                else
                    rParam = String();
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return bRet;
}

// -----------------------------------------------------------------------

BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                if( i < ( nCount - 1 ) )
                    rParams.push_back( rArgs[ i + 1 ] );
                else
                    rParams.push_back( String() );

                break;
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return( rParams.size() > 0 );
}

// -----------------------------------------------------------------------

void BmpApp::Message( const String& rText, BYTE cExit )
{
    if( EXIT_NOERROR != cExit )
        SetExitCode( cExit );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
    aText.Append( "\r\n" );
    fprintf( stderr, aText.GetBuffer() );
}

// -----------------------------------------------------------------------------

void BmpApp::ShowUsage()
{
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "   -i ...        name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "   -f            name of file, output should be written to" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR );
}

// -----------------------------------------------------------------------------

int BmpApp::Start( const ::std::vector< String >& rArgs )
{
    String aOutName;

    cExitCode = EXIT_NOERROR;

    if( rArgs.size() >= 6 )
    {
        LangInfo                aLangInfo;
        USHORT                  nCurCmd = 0;
        const String            aSrsName( rArgs[ nCurCmd++ ] );
        ::std::vector< String > aInDirVector;
        ByteString              aLangDir;

        aOutName = rArgs[ nCurCmd++ ];

        aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US );
        aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() );

        memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 );

        GetCommandOption( rArgs, 'f', aOutputFileName );
        GetCommandOptions( rArgs, 'i', aInDirVector );

        Create( aSrsName, aInDirVector, aOutName, aLangInfo );
    }
    else
    {
        ShowUsage();
        cExitCode = EXIT_COMMONERROR;
    }

    if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
    {
        SvFileStream    aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
        ByteString      aStr( "Successfully generated ImageList(s) in: " );

        aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
        aOStm.Close();
    }

    return cExitCode;
}

// --------
// - Main -
// --------

int main( int nArgCount, char* ppArgs[] )
{
#ifdef UNX
    static char aDisplayVar[ 1024 ];

    strcpy( aDisplayVar, "DISPLAY=" );
    putenv( aDisplayVar );
#endif

    ::std::vector< String > aArgs;
    BmpApp                  aBmpApp;

    InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );

    for( int i = 1; i < nArgCount; i++ )
        aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );

    return aBmpApp.Start( aArgs );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.14.562); FILE MERGED 2005/09/05 14:50:21 rt 1.14.562.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bmp.cxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 08:52:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <vector>
using namespace std;

#include <vcl/svapp.hxx>

#include "solar.hrc"
#include "filedlg.hxx"
#include "bmpcore.hxx"
#include "bmp.hrc"

// ----------
// - BmpApp -
// ----------

class BmpApp : public BmpCreator
{
private:

    String          aOutputFileName;
    BYTE            cExitCode;

    BOOL            GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rSwitchParam );
    BOOL            GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rSwitchParams );

    void            SetExitCode( BYTE cExit )
                    {
                        if( ( EXIT_NOERROR == cExitCode ) || ( cExit != EXIT_NOERROR ) )
                            cExitCode = cExit;
                    }
    void            ShowUsage();

    virtual void    Message( const String& rText, BYTE cExitCode );

public:

                    BmpApp();
                    ~BmpApp();

    int             Start( const ::std::vector< String >& rArgs );
};

// -----------------------------------------------------------------------------

BmpApp::BmpApp()
{
}

// -----------------------------------------------------------------------------

BmpApp::~BmpApp()
{
}

// -----------------------------------------------------------------------

BOOL BmpApp::GetCommandOption( const ::std::vector< String >& rArgs, const String& rSwitch, String& rParam )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ) && !bRet; i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                bRet = TRUE;

                if( i < ( nCount - 1 ) )
                    rParam = rArgs[ i + 1 ];
                else
                    rParam = String();
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return bRet;
}

// -----------------------------------------------------------------------

BOOL BmpApp::GetCommandOptions( const ::std::vector< String >& rArgs, const String& rSwitch, ::std::vector< String >& rParams )
{
    BOOL bRet = FALSE;

    for( int i = 0, nCount = rArgs.size(); ( i < nCount ); i++ )
    {
        String  aTestStr( '-' );

        for( int n = 0; ( n < 2 ) && !bRet; n++ )
        {
            aTestStr += rSwitch;

            if( aTestStr.CompareIgnoreCaseToAscii( rArgs[ i ] ) == COMPARE_EQUAL )
            {
                if( i < ( nCount - 1 ) )
                    rParams.push_back( rArgs[ i + 1 ] );
                else
                    rParams.push_back( String() );

                break;
            }

            if( 0 == n )
                aTestStr = '/';
        }
    }

    return( rParams.size() > 0 );
}

// -----------------------------------------------------------------------

void BmpApp::Message( const String& rText, BYTE cExit )
{
    if( EXIT_NOERROR != cExit )
        SetExitCode( cExit );

    ByteString aText( rText, RTL_TEXTENCODING_UTF8 );
    aText.Append( "\r\n" );
    fprintf( stderr, aText.GetBuffer() );
}

// -----------------------------------------------------------------------------

void BmpApp::ShowUsage()
{
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Usage:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmp srs_inputfile output_dir lang_dir lang_num -i input_dir [-i input_dir ][-f err_file]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Options:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "   -i ...        name of directory to be searched for input files [multiple occurence is possible]" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "   -f            name of file, output should be written to" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "Examples:" ) ), EXIT_NOERROR );
    Message( String( RTL_CONSTASCII_USTRINGPARAM( "    bmp /home/test.srs /home/out enus 01 -i /home/res -f /home/out/bmp.err" ) ), EXIT_NOERROR );
}

// -----------------------------------------------------------------------------

int BmpApp::Start( const ::std::vector< String >& rArgs )
{
    String aOutName;

    cExitCode = EXIT_NOERROR;

    if( rArgs.size() >= 6 )
    {
        LangInfo                aLangInfo;
        USHORT                  nCurCmd = 0;
        const String            aSrsName( rArgs[ nCurCmd++ ] );
        ::std::vector< String > aInDirVector;
        ByteString              aLangDir;

        aOutName = rArgs[ nCurCmd++ ];

        aLangDir = ByteString( rArgs[ nCurCmd++ ], RTL_TEXTENCODING_ASCII_US );
        aLangInfo.mnLangNum = static_cast< sal_uInt16 >( rArgs[ nCurCmd++ ].ToInt32() );

        memcpy( aLangInfo.maLangDir, aLangDir.GetBuffer(), aLangDir.Len() + 1 );

        GetCommandOption( rArgs, 'f', aOutputFileName );
        GetCommandOptions( rArgs, 'i', aInDirVector );

        Create( aSrsName, aInDirVector, aOutName, aLangInfo );
    }
    else
    {
        ShowUsage();
        cExitCode = EXIT_COMMONERROR;
    }

    if( ( EXIT_NOERROR == cExitCode ) && aOutputFileName.Len() && aOutName.Len() )
    {
        SvFileStream    aOStm( aOutputFileName, STREAM_WRITE | STREAM_TRUNC );
        ByteString      aStr( "Successfully generated ImageList(s) in: " );

        aOStm.WriteLine( aStr.Append( ByteString( aOutName, RTL_TEXTENCODING_UTF8 ) ) );
        aOStm.Close();
    }

    return cExitCode;
}

// --------
// - Main -
// --------

int main( int nArgCount, char* ppArgs[] )
{
#ifdef UNX
    static char aDisplayVar[ 1024 ];

    strcpy( aDisplayVar, "DISPLAY=" );
    putenv( aDisplayVar );
#endif

    ::std::vector< String > aArgs;
    BmpApp                  aBmpApp;

    InitVCL( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >() );

    for( int i = 1; i < nArgCount; i++ )
        aArgs.push_back( String( ppArgs[ i ], RTL_TEXTENCODING_ASCII_US ) );

    return aBmpApp.Start( aArgs );
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospray
#include "Data.h"
// stl
#include <sstream>

namespace ospray {

  Data::Data(size_t numItems, OSPDataType type, void *init, int flags)
    : numItems(numItems), numBytes(numItems * sizeOf(type)), type(type), flags(flags)
  {
    /* two notes here:
       a) i'm using embree's 'new' to enforce alignment
       b) i'm adding 16 bytes to size to enforce 4-float padding (which embree
          requires in some buffers
    */
    if (flags & OSP_DATA_SHARED_BUFFER) {
      Assert2(init != NULL, "shared buffer is NULL");
      data = init;
    } else {
      data = new unsigned char[numBytes+16];
      if (init)
        memcpy(data,init,numBytes);
      else if (type == OSP_OBJECT)
        bzero(data,numBytes);
    }

    managedObjectType = OSP_DATA;

    // std::cout << "checksum when creating data array" << std::endl;
    // PRINT(numBytes);
    // PRINT((int*)computeCheckSum(init,numBytes));
  }

  Data::~Data()
  {
    if (type == OSP_OBJECT) {
      Data **child = (Data **)data;
      for (int i=0;i<numItems;i++)
        if (child[i]) child[i]->refDec();
    }
    free(data);
  }

} // ::ospray
<commit_msg>bugfix: no longer freeing data associated with shared buffers (OSP_DATA_SHARED_BUFFER).<commit_after>// ======================================================================== //
// Copyright 2009-2014 Intel Corporation                                    //
//                                                                          //
// Licensed under the Apache License, Version 2.0 (the "License");          //
// you may not use this file except in compliance with the License.         //
// You may obtain a copy of the License at                                  //
//                                                                          //
//     http://www.apache.org/licenses/LICENSE-2.0                           //
//                                                                          //
// Unless required by applicable law or agreed to in writing, software      //
// distributed under the License is distributed on an "AS IS" BASIS,        //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and      //
// limitations under the License.                                           //
// ======================================================================== //

// ospray
#include "Data.h"
// stl
#include <sstream>

namespace ospray {

  Data::Data(size_t numItems, OSPDataType type, void *init, int flags)
    : numItems(numItems), numBytes(numItems * sizeOf(type)), type(type), flags(flags)
  {
    /* two notes here:
       a) i'm using embree's 'new' to enforce alignment
       b) i'm adding 16 bytes to size to enforce 4-float padding (which embree
          requires in some buffers
    */
    if (flags & OSP_DATA_SHARED_BUFFER) {
      Assert2(init != NULL, "shared buffer is NULL");
      data = init;
    } else {
      data = new unsigned char[numBytes+16];
      if (init)
        memcpy(data,init,numBytes);
      else if (type == OSP_OBJECT)
        bzero(data,numBytes);
    }

    managedObjectType = OSP_DATA;

    // std::cout << "checksum when creating data array" << std::endl;
    // PRINT(numBytes);
    // PRINT((int*)computeCheckSum(init,numBytes));
  }

  Data::~Data()
  {
    if (type == OSP_OBJECT) {
      Data **child = (Data **)data;
      for (int i=0;i<numItems;i++)
        if (child[i]) child[i]->refDec();
    }
    if (!(flags & OSP_DATA_SHARED_BUFFER)) free(data);
  }

} // ::ospray
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unoforou.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 09:32:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_UNOFOROU_HXX
#define _SVX_UNOFOROU_HXX

#ifndef _SVX_UNOEDSRC_HXX
#include <svx/unoedsrc.hxx>
#endif

#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif

#include <svx/editdata.hxx>

class Outliner;
class SdrObject;

//  SvxOutlinerForwarder - SvxTextForwarder fuer Outliner

class SVX_DLLPUBLIC SvxOutlinerForwarder : public SvxTextForwarder
{
private:
    Outliner&           rOutliner;
    SdrObject*          pSdrObject;

    /** this pointer may be null or point to an item set for the attribs of
        the selection maAttribsSelection */
    mutable SfxItemSet* mpAttribsCache;

    /** if we have a chached attribute item set, this is the selection of it */
    mutable ESelection  maAttribCacheSelection;

    /** this pointer may be null or point to an item set for the paragraph
        mnParaAttribsCache */
    mutable SfxItemSet* mpParaAttribsCache;

    /** if we have a cached para attribute item set, this is the paragraph of it */
    mutable USHORT      mnParaAttribsCache;

public:
                        SvxOutlinerForwarder( Outliner& rOutl, SdrObject* pSdrObj = 0 );
    virtual             ~SvxOutlinerForwarder();

    virtual USHORT      GetParagraphCount() const;
    virtual USHORT      GetTextLen( USHORT nParagraph ) const;
    virtual String      GetText( const ESelection& rSel ) const;
    virtual SfxItemSet  GetAttribs( const ESelection& rSel, BOOL bOnlyHardAttrib = 0 ) const;
    virtual SfxItemSet  GetParaAttribs( USHORT nPara ) const;
    virtual void        SetParaAttribs( USHORT nPara, const SfxItemSet& rSet );
    virtual void        GetPortions( USHORT nPara, SvUShorts& rList ) const;

    virtual USHORT      GetItemState( const ESelection& rSel, USHORT nWhich ) const;
    virtual USHORT      GetItemState( USHORT nPara, USHORT nWhich ) const;

    virtual void        QuickInsertText( const String& rText, const ESelection& rSel );
    virtual void        QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel );
    virtual void        QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel );
    virtual void        QuickInsertLineBreak( const ESelection& rSel );

    virtual SfxItemPool* GetPool() const;

    virtual XubString    CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor );
    virtual BOOL        IsValid() const;

    Outliner&           GetOutliner() const { return rOutliner; }

    virtual LanguageType    GetLanguage( USHORT, USHORT ) const;
    virtual USHORT          GetFieldCount( USHORT nPara ) const;
    virtual EFieldInfo      GetFieldInfo( USHORT nPara, USHORT nField ) const;
    virtual EBulletInfo     GetBulletInfo( USHORT nPara ) const;
    virtual Rectangle       GetCharBounds( USHORT nPara, USHORT nIndex ) const;
    virtual Rectangle       GetParaBounds( USHORT nPara ) const;
    virtual MapMode         GetMapMode() const;
    virtual OutputDevice*   GetRefDevice() const;
    virtual sal_Bool        GetIndexAtPoint( const Point&, USHORT& nPara, USHORT& nIndex ) const;
    virtual sal_Bool        GetWordIndices( USHORT nPara, USHORT nIndex, USHORT& nStart, USHORT& nEnd ) const;
    virtual sal_Bool        GetAttributeRun( USHORT& nStartIndex, USHORT& nEndIndex, USHORT nPara, USHORT nIndex ) const;
    virtual USHORT          GetLineCount( USHORT nPara ) const;
    virtual USHORT          GetLineLen( USHORT nPara, USHORT nLine ) const;
    virtual sal_Bool        Delete( const ESelection& );
    virtual sal_Bool        InsertText( const String&, const ESelection& );
    virtual sal_Bool        QuickFormatDoc( BOOL bFull=FALSE );
    virtual USHORT          GetDepth( USHORT nPara ) const;
    virtual sal_Bool        SetDepth( USHORT nPara, USHORT nNewDepth );

    /* this method flushes internal caches for this forwarder */
    void                flushCache();

    virtual const SfxItemSet*   GetEmptyItemSetPtr();

    // implementation functions for XParagraphAppend and XTextPortionAppend
    virtual void        AppendParagraph();
    virtual xub_StrLen  AppendTextPortion( USHORT nPara, const String &rText, const SfxItemSet &rSet );
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.36); FILE MERGED 2008/04/01 12:47:02 thb 1.4.36.2: #i85898# Stripping all external header guards 2008/03/31 14:18:21 rt 1.4.36.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: unoforou.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SVX_UNOFOROU_HXX
#define _SVX_UNOFOROU_HXX

#include <svx/unoedsrc.hxx>
#include "svx/svxdllapi.h"

#include <svx/editdata.hxx>

class Outliner;
class SdrObject;

//  SvxOutlinerForwarder - SvxTextForwarder fuer Outliner

class SVX_DLLPUBLIC SvxOutlinerForwarder : public SvxTextForwarder
{
private:
    Outliner&           rOutliner;
    SdrObject*          pSdrObject;

    /** this pointer may be null or point to an item set for the attribs of
        the selection maAttribsSelection */
    mutable SfxItemSet* mpAttribsCache;

    /** if we have a chached attribute item set, this is the selection of it */
    mutable ESelection  maAttribCacheSelection;

    /** this pointer may be null or point to an item set for the paragraph
        mnParaAttribsCache */
    mutable SfxItemSet* mpParaAttribsCache;

    /** if we have a cached para attribute item set, this is the paragraph of it */
    mutable USHORT      mnParaAttribsCache;

public:
                        SvxOutlinerForwarder( Outliner& rOutl, SdrObject* pSdrObj = 0 );
    virtual             ~SvxOutlinerForwarder();

    virtual USHORT      GetParagraphCount() const;
    virtual USHORT      GetTextLen( USHORT nParagraph ) const;
    virtual String      GetText( const ESelection& rSel ) const;
    virtual SfxItemSet  GetAttribs( const ESelection& rSel, BOOL bOnlyHardAttrib = 0 ) const;
    virtual SfxItemSet  GetParaAttribs( USHORT nPara ) const;
    virtual void        SetParaAttribs( USHORT nPara, const SfxItemSet& rSet );
    virtual void        GetPortions( USHORT nPara, SvUShorts& rList ) const;

    virtual USHORT      GetItemState( const ESelection& rSel, USHORT nWhich ) const;
    virtual USHORT      GetItemState( USHORT nPara, USHORT nWhich ) const;

    virtual void        QuickInsertText( const String& rText, const ESelection& rSel );
    virtual void        QuickInsertField( const SvxFieldItem& rFld, const ESelection& rSel );
    virtual void        QuickSetAttribs( const SfxItemSet& rSet, const ESelection& rSel );
    virtual void        QuickInsertLineBreak( const ESelection& rSel );

    virtual SfxItemPool* GetPool() const;

    virtual XubString    CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor );
    virtual BOOL        IsValid() const;

    Outliner&           GetOutliner() const { return rOutliner; }

    virtual LanguageType    GetLanguage( USHORT, USHORT ) const;
    virtual USHORT          GetFieldCount( USHORT nPara ) const;
    virtual EFieldInfo      GetFieldInfo( USHORT nPara, USHORT nField ) const;
    virtual EBulletInfo     GetBulletInfo( USHORT nPara ) const;
    virtual Rectangle       GetCharBounds( USHORT nPara, USHORT nIndex ) const;
    virtual Rectangle       GetParaBounds( USHORT nPara ) const;
    virtual MapMode         GetMapMode() const;
    virtual OutputDevice*   GetRefDevice() const;
    virtual sal_Bool        GetIndexAtPoint( const Point&, USHORT& nPara, USHORT& nIndex ) const;
    virtual sal_Bool        GetWordIndices( USHORT nPara, USHORT nIndex, USHORT& nStart, USHORT& nEnd ) const;
    virtual sal_Bool        GetAttributeRun( USHORT& nStartIndex, USHORT& nEndIndex, USHORT nPara, USHORT nIndex ) const;
    virtual USHORT          GetLineCount( USHORT nPara ) const;
    virtual USHORT          GetLineLen( USHORT nPara, USHORT nLine ) const;
    virtual sal_Bool        Delete( const ESelection& );
    virtual sal_Bool        InsertText( const String&, const ESelection& );
    virtual sal_Bool        QuickFormatDoc( BOOL bFull=FALSE );
    virtual USHORT          GetDepth( USHORT nPara ) const;
    virtual sal_Bool        SetDepth( USHORT nPara, USHORT nNewDepth );

    /* this method flushes internal caches for this forwarder */
    void                flushCache();

    virtual const SfxItemSet*   GetEmptyItemSetPtr();

    // implementation functions for XParagraphAppend and XTextPortionAppend
    virtual void        AppendParagraph();
    virtual xub_StrLen  AppendTextPortion( USHORT nPara, const String &rText, const SfxItemSet &rSet );
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
Name:       Isabell Jansson, Jonathan Bosson, Ronja Grosz
File name: 	SPH.cpp

SPH is responsible for orginization of a group of smooth particles.
*************************************************************************/

#include <string.h>
#include <cstdlib>
#include <stdio.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>

#include "../json/picojson.h"
#include "../particle/SPH.h"

#define EPSILON 0.000000000000001f

using namespace glm;

bool compareZ(Particle* left, Particle* right)
{
	return (left->getPosition().z < right->getPosition().z);
}

SPH::SPH()
{
	frameTimer = new timer;

	// load json parameters
	loadJson("json/scene_parameters.json");

	//scene.readOBJ(sceneName.c_str());
	//scene.printInfo();

	GLfloat randX, randY, randZ;
	vec3 newColor = vec3(1.0f,1.0f,1.0f);
	double randI, randJ, randK; //velocity vector values

	srand(time(0));

	water = new vector<Particle*>(particleCount);

	for(int i = 0; i < particleCount; ++i) {

		// random position
		randX = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5;
		randY = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5 + 1.6;
		randZ = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5;

		// random velocity
		randI = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;
		randJ = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;
		randK = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;

		water->at(i) = new Particle();
		water->at(i)->setPosition(randX, randY, randZ);
		water->at(i)->setColor(newColor);
		water->at(i)->setVelocity(dvec3(randI, randJ, randK));

		// find neighborhood
		// compute densities
		// compute ai

	}

	createVAO(particleCount);
	timeLastFrame = frameTimer->elapsed();
}

SPH::~SPH()
{
	for(int i = 0; i < particleCount; i++)
	{
		delete water->at(i);
	}
	delete water;
	delete frameTimer;

}

void SPH::setRadius(double rad) {
	particleRadius = rad;
}
void SPH::setMass(double mass) {
	particleMass = mass;
}
void SPH::setViscosity(double vis) {
	particleViscosity = vis;
}
double SPH::getRadius(){return particleRadius;}
double SPH::getMass(){return particleMass;}
double SPH::getViscosity(){return particleViscosity;}

void SPH::loadJson(string fileName)
{
	picojson::value params;
    ifstream paramStream (fileName);
    paramStream >> params;
    particleCount = (int)(params.get<picojson::object>()["particlesCount"].get<double>());
    maxTimestep = 1/params.get<picojson::object>()["fps"].get<double>();
    iterations = (int)(params.get<picojson::object>()["iterations"].get<double>());
    constantAcceleration = params.get<picojson::object>()["constantAcceleration"].get<double>();
    sceneName = params.get<picojson::object>()["sceneName"].get<std::string>();

    particleRadius = params.get<picojson::object>()["particleRadius"].get<double>();
    particleMass = params.get<picojson::object>()["particleMass"].get<double>();
    particleViscosity = params.get<picojson::object>()["particleViscosity"].get<double>();
}

// Update positions with a small timestep
void SPH::simulate(double timeStep)
{
	// Self-advection - Skipped for SPH

	// Calculate gravity, surface tension and viscosity
	calculateNonPressureForces();

	// adapt timestep according to CFL condition
	dT = adaptTimestep(timeStep);

	// predict velocities
	predictVelocities(dT);

	// correctDensityError

	// update positions
	for (int i = 0; i < particleCount; ++i) {
		water->at(i)->updatePosition(dT);
	}

	// update neighborhoods

	// compute densities and ai factors

	// correctDivergenceError

	// update velocities

}

// Compute non-pressure forces - advect, body forces (gravity) and viscosity
void SPH::calculateNonPressureForces()
{

	//dvec3 *particleVel;
	//dvec3 *neighborVel;
	//dvec3 particlePos;
	//dvec3 neighborPos;
	//double steps = 6;

	for(int i = 0; i < particleCount; ++i)
	{
		// Gravity
		water->at(i)->setForce(0.0, particleMass * constantAcceleration, 0.0);

		/*
		// Surface tension - skipped
		dvec3 currentPos = water->at(i)->getPosition();
		dvec3 currentVel = water->at(i)->getVelocity();
        float correctionFactor = 2.f * _restDensity / (density_i + density_j);
        forceCohesion += correctionFactor * (r / rn) * _kernel.surfaceTension(rn);
        forceCurvature += correctionFactor * (n_i - n_j);

		// Viscosity - skipped
		for(iterator of neighbor)
		{
			neighborPos = water->at(neighbors.at(j))->getPosition();
			neighborVel = water->at(neighbors.at(j))->getVelocity();

			if (density_j > 0.0001f) {
                viscosity -= (currentVel - neighborVel) * (_kernel.viscosityLaplace(rn) / density_j);
            }
		}
		*/
	}
}

double SPH::adaptTimestep(double timeStep)
{
	dvec3 val;
	double mag, dT, vMax = 0.0;

	for (int i = 0; i < particleCount; ++i)
	{
		val = water->at(i)->getVelocity();
		mag = dot(val, val);

		if (vMax < mag)
			vMax = mag;
	}
	dT = (particleRadius * 0.8 / vMax) - EPSILON;

	if (timeStep < dT)
		dT = timeStep;

	return dT;
}

// Predicts the velocity of the particle with its non-pressure forces and dirichlet boundary condition
void SPH::predictVelocities(double dT)
{
	dvec3 vel, pos, dPos;
	double x,y,z;
	for (int i = 0; i < particleCount; ++i) {
		vel = water->at(i)->getVelocity() + water->at(i)->getForce() * particleMass * dT;
		pos = water->at(i)->getPosition();

		// Dirichlet Boundary Condition
		x = pos.x;
		y = pos.y;
		z = pos.z;
		dPos = vel * dT;
		// is there solid in X?
		if(isSolid(x-dPos.x,y,z, 0) && vel.x < 0.0)
			vel.x = 0.0;
		else if(isSolid(x+dPos.x,y,z, 0) && vel.x > 0.0)
			vel.x = 0.0;
		// Y
		if(isSolid(x,y-dPos.y,z, 1) && vel.y < 0.0)
			vel.y = 0.0;
		else if(isSolid(x,y+dPos.y,z, 1) && vel.y > 0.0)
			vel.y = 0.0;
		// Z
		if(isSolid(x,y,z-dPos.z, 2) && vel.z < 0.0)
			vel.z = 0.0;
		else if(isSolid(x,y,z+dPos.z, 2) && vel.z > 0.0)
			vel.z = 0.0;

		water->at(i)->setVelocity(vel);
	}

}

// Check if (x,y,z) is inside the obj object
bool SPH::isSolid(double x, double y, double z, int c)
{

	// Cube
	if (sceneName == "cube") {
		switch (c) {
			case 0:
				if (x > 1.5 || x < -1.5)
					return true;
				break;
			case 1:
				if (y < 0.0)
					return true;
				break;
			case 2:
				if (z > 1.5 || z < -1.5)
					return true;
				break;
			default:
				return false;
		}
		return false;
	}

	// Two levels

	// Sphere
	else if (sceneName == "sphere") {
		double sqR = 4.0;
		switch (c) {
			case 0:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			case 1:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			case 2:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			default:
				return false;
		}
		return false;
	}

	// Default case, if our sceneName is something odd
	else
		return false;

}

//calculate density function
void SPH::calculateDensity()
{
	double distance = 0;

	glm::vec4 *particleVel;
	glm::vec4 *neighborVel;

	for(int i = 0; i < particleCount; i++)
	{
		dvec3 particlePos = water->at(i)->getPosition();
		for(int j = 0; j < particleCount; j++)
		{
			dvec3 neighborPos = water->at(j)->getPosition();
			//if(primaryPositionVector && secondaryPositionVector)
			//{
				distance = dot(particlePos - neighborPos, particlePos - neighborPos);
			//}

			if(distance <= H*H)
			{
				//if(primaryPositionVector && secondaryPositionVector)
				//{
					water->at(i)->calculateDensity(water->at(j));
				//}

				//delete secondaryPositionVector;
				delete particleVel;
				delete neighborVel;
			} else
			{
				//delete secondaryPositionVector;

				break;
			}

		}
		//delete primaryPositionVector;
	}
	for(int i = 0; i<particleCount; i++)
	{
		water->at(i)->clearNAN();
//		water->at(i)->printDensity();
	}

}

void SPH::display()
{

	GLfloat vertices[particleCount][3];
	GLfloat colors[particleCount][3];

	//this is used to log the elapsed time since the last frame
	double timeDiff = frameTimer->elapsed() - timeLastFrame;
	if (timeDiff - EPSILON > 0.0) {
		double t = 0.0;
		int iter = 0;
		// Propagate the solution until requested time is reached
		while (t < maxTimestep && iter < iterations) {
			simulate(maxTimestep);
			t += dT;
			iter++;
		}

		// "   " used as padding as sometimes we get 10 iterations, sometimes 9
		cout << "Iterations: " << iter << ", Timestep: " << t << "        " << '\r' << flush;

		// Render stuff
		for(int i = 0; i < particleCount; ++i) {
			vertices[i][0] = water->at(i)->getPosition().x;
			vertices[i][1] = water->at(i)->getPosition().y;
			vertices[i][2] = water->at(i)->getPosition().z;

			//tmp = water->at(i)->getColor();
			colors[i][0] = 0.7 - water->at(i)->getPosition().x;
			colors[i][1] = 0.7 - water->at(i)->getPosition().y;
			colors[i][2] = 0.7 - water->at(i)->getPosition().z;

		}

		// Bind the first VBO as being the active buffer and storing vertex attributes (coordinates)
	    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);

		// Copy the vertex data from diamond to our buffer
	    // 8 * sizeof(GLfloat) is the size of the diamond array, since it contains 8 GLfloat values
	    glBufferData(GL_ARRAY_BUFFER, 3 * particleCount * sizeof(GLfloat), vertices,/* 9 * sizeof(GLfloat), diamond, */ GL_STATIC_DRAW);

	    // Specify that our coordinate data is going into attribute index 0, and contains three floats per vertex
	    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

	    // Enable attribute index 0 as being used
	    glEnableVertexAttribArray(0);

	    // Bind the second VBO as being the active buffer and storing vertex attributes (colors)
	    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);

	    glBufferData(GL_ARRAY_BUFFER, 3 * particleCount * sizeof(GLfloat), colors, GL_STATIC_DRAW);

	    // Specify that our color data is going into attribute index 1, and contains three floats per vertex
	    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

	    // Enable attribute index 1 as being used
	    glEnableVertexAttribArray(1);
	}

	glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // make background black
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBindVertexArray(vao);

	glEnable(GL_PROGRAM_POINT_SIZE); //enable gl_PointSize in vertex shader

	glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);

	glDrawArrays(GL_POINTS, 0, particleCount);

	glDisable(GL_PROGRAM_POINT_SIZE);

	timeLastFrame = frameTimer->elapsed();
}

void SPH::createVAO ( int particles ) {
	// A VAO (Vertex Array Object) stores information of a complete rendered object.
	// It contains all VBOs (Vertex Buffer Objects)
	// A VBO stores information about the vertices.
	// Now we're using two VBOs, one for coordinates and one for colors

	// Allocate and bind Vertex Array Object to the handle vao
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Generate (one) new Vertex Buffer Object and get the associated id
	glGenBuffers(2, vbo);
}

void SPH::setTimer(timer *newTimer)
{
	frameTimer = newTimer;
}
<commit_msg>peer review of loading properties from a json file, adding some comments<commit_after>/*************************************************************************
Name:       Isabell Jansson, Jonathan Bosson, Ronja Grosz
File name: 	SPH.cpp

SPH is responsible for orginization of a group of smooth particles.
*************************************************************************/

#include <string.h>
#include <cstdlib>
#include <stdio.h>

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>

#include "../json/picojson.h"
#include "../particle/SPH.h"

#define EPSILON 0.000000000000001f

using namespace glm;

bool compareZ(Particle* left, Particle* right)
{
	return (left->getPosition().z < right->getPosition().z);
}

SPH::SPH()
{
	frameTimer = new timer;

	// load json parameters
	loadJson("json/scene_parameters.json");

	//scene.readOBJ(sceneName.c_str());
	//scene.printInfo();

	GLfloat randX, randY, randZ;
	vec3 newColor = vec3(1.0f,1.0f,1.0f);
	double randI, randJ, randK; //velocity vector values

	srand(time(0));

	water = new vector<Particle*>(particleCount);

	for(int i = 0; i < particleCount; ++i) {

		// random position
		randX = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5;
		randY = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5 + 1.6;
		randZ = ((float)rand()/(float)RAND_MAX) * 1.0 - 0.5;

		// random velocity
		randI = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;
		randJ = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;
		randK = (((double)rand()/(double)RAND_MAX) * 0.2) - 0.1;

		water->at(i) = new Particle();
		water->at(i)->setPosition(randX, randY, randZ);
		water->at(i)->setColor(newColor);
		water->at(i)->setVelocity(dvec3(randI, randJ, randK));

		// find neighborhood
		// compute densities
		// compute ai

	}

	createVAO(particleCount);
	timeLastFrame = frameTimer->elapsed();
}

SPH::~SPH()
{
	for(int i = 0; i < particleCount; i++)
	{
		delete water->at(i);
	}
	delete water;
	delete frameTimer;

}

void SPH::setRadius(double rad) {
	particleRadius = rad;
}
void SPH::setMass(double mass) {
	particleMass = mass;
}
void SPH::setViscosity(double vis) {
	particleViscosity = vis;
}
double SPH::getRadius(){return particleRadius;}
double SPH::getMass(){return particleMass;}
double SPH::getViscosity(){return particleViscosity;}

// Loads properties from json-file
void SPH::loadJson(string fileName)
{
	// Load scene properties
	picojson::value params;
    ifstream paramStream (fileName);
    paramStream >> params;
    particleCount = (int)(params.get<picojson::object>()["particlesCount"].get<double>());
    maxTimestep = 1/params.get<picojson::object>()["fps"].get<double>();
    iterations = (int)(params.get<picojson::object>()["iterations"].get<double>());
    constantAcceleration = params.get<picojson::object>()["constantAcceleration"].get<double>();
    sceneName = params.get<picojson::object>()["sceneName"].get<std::string>();

    // Load particle properties
    particleRadius = params.get<picojson::object>()["particleRadius"].get<double>();
    particleMass = params.get<picojson::object>()["particleMass"].get<double>();
    particleViscosity = params.get<picojson::object>()["particleViscosity"].get<double>();
}

// Update positions with a small timestep
void SPH::simulate(double timeStep)
{
	// Self-advection - Skipped for SPH

	// Calculate gravity, surface tension and viscosity
	calculateNonPressureForces();

	// adapt timestep according to CFL condition
	dT = adaptTimestep(timeStep);

	// predict velocities
	predictVelocities(dT);

	// correctDensityError

	// update positions
	for (int i = 0; i < particleCount; ++i) {
		water->at(i)->updatePosition(dT);
	}

	// update neighborhoods

	// compute densities and ai factors

	// correctDivergenceError

	// update velocities

}

// Compute non-pressure forces - advect, body forces (gravity) and viscosity
void SPH::calculateNonPressureForces()
{

	//dvec3 *particleVel;
	//dvec3 *neighborVel;
	//dvec3 particlePos;
	//dvec3 neighborPos;
	//double steps = 6;

	for(int i = 0; i < particleCount; ++i)
	{
		// Gravity
		water->at(i)->setForce(0.0, particleMass * constantAcceleration, 0.0);

		/*
		// Surface tension - skipped
		dvec3 currentPos = water->at(i)->getPosition();
		dvec3 currentVel = water->at(i)->getVelocity();
        float correctionFactor = 2.f * _restDensity / (density_i + density_j);
        forceCohesion += correctionFactor * (r / rn) * _kernel.surfaceTension(rn);
        forceCurvature += correctionFactor * (n_i - n_j);

		// Viscosity - skipped
		for(iterator of neighbor)
		{
			neighborPos = water->at(neighbors.at(j))->getPosition();
			neighborVel = water->at(neighbors.at(j))->getVelocity();

			if (density_j > 0.0001f) {
                viscosity -= (currentVel - neighborVel) * (_kernel.viscosityLaplace(rn) / density_j);
            }
		}
		*/
	}
}

double SPH::adaptTimestep(double timeStep)
{
	dvec3 val;
	double mag, dT, vMax = 0.0;

	for (int i = 0; i < particleCount; ++i)
	{
		val = water->at(i)->getVelocity();
		mag = dot(val, val);

		if (vMax < mag)
			vMax = mag;
	}
	dT = (particleRadius * 0.8 / vMax) - EPSILON;

	if (timeStep < dT)
		dT = timeStep;

	return dT;
}

// Predicts the velocity of the particle with its non-pressure forces and dirichlet boundary condition
void SPH::predictVelocities(double dT)
{
	dvec3 vel, pos, dPos;
	double x,y,z;
	for (int i = 0; i < particleCount; ++i) {
		vel = water->at(i)->getVelocity() + water->at(i)->getForce() * particleMass * dT;
		pos = water->at(i)->getPosition();

		// Dirichlet Boundary Condition
		x = pos.x;
		y = pos.y;
		z = pos.z;
		dPos = vel * dT;
		// is there solid in X?
		if(isSolid(x-dPos.x,y,z, 0) && vel.x < 0.0)
			vel.x = 0.0;
		else if(isSolid(x+dPos.x,y,z, 0) && vel.x > 0.0)
			vel.x = 0.0;
		// Y
		if(isSolid(x,y-dPos.y,z, 1) && vel.y < 0.0)
			vel.y = 0.0;
		else if(isSolid(x,y+dPos.y,z, 1) && vel.y > 0.0)
			vel.y = 0.0;
		// Z
		if(isSolid(x,y,z-dPos.z, 2) && vel.z < 0.0)
			vel.z = 0.0;
		else if(isSolid(x,y,z+dPos.z, 2) && vel.z > 0.0)
			vel.z = 0.0;

		water->at(i)->setVelocity(vel);
	}

}

// Check if (x,y,z) is inside the obj object
bool SPH::isSolid(double x, double y, double z, int c)
{

	// Cube
	if (sceneName == "cube") {
		switch (c) {
			case 0:
				if (x > 1.5 || x < -1.5)
					return true;
				break;
			case 1:
				if (y < 0.0)
					return true;
				break;
			case 2:
				if (z > 1.5 || z < -1.5)
					return true;
				break;
			default:
				return false;
		}
		return false;
	}

	// Two levels

	// Sphere
	else if (sceneName == "sphere") {
		double sqR = 4.0;
		switch (c) {
			case 0:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			case 1:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			case 2:
				if (x*x+y*y+z*z-sqR == 0.0)
					return true;
				break;
			default:
				return false;
		}
		return false;
	}

	// Default case, if our sceneName is something odd
	else
		return false;

}

//calculate density function
void SPH::calculateDensity()
{
	double distance = 0;

	glm::vec4 *particleVel;
	glm::vec4 *neighborVel;

	for(int i = 0; i < particleCount; i++)
	{
		dvec3 particlePos = water->at(i)->getPosition();
		for(int j = 0; j < particleCount; j++)
		{
			dvec3 neighborPos = water->at(j)->getPosition();
			//if(primaryPositionVector && secondaryPositionVector)
			//{
				distance = dot(particlePos - neighborPos, particlePos - neighborPos);
			//}

			if(distance <= H*H)
			{
				//if(primaryPositionVector && secondaryPositionVector)
				//{
					water->at(i)->calculateDensity(water->at(j));
				//}

				//delete secondaryPositionVector;
				delete particleVel;
				delete neighborVel;
			} else
			{
				//delete secondaryPositionVector;

				break;
			}

		}
		//delete primaryPositionVector;
	}
	for(int i = 0; i<particleCount; i++)
	{
		water->at(i)->clearNAN();
//		water->at(i)->printDensity();
	}

}

void SPH::display()
{

	GLfloat vertices[particleCount][3];
	GLfloat colors[particleCount][3];

	//this is used to log the elapsed time since the last frame
	double timeDiff = frameTimer->elapsed() - timeLastFrame;
	if (timeDiff - EPSILON > 0.0) {
		double t = 0.0;
		int iter = 0;
		// Propagate the solution until requested time is reached
		while (t < maxTimestep && iter < iterations) {
			simulate(maxTimestep);
			t += dT;
			iter++;
		}

		// "   " used as padding as sometimes we get 10 iterations, sometimes 9
		cout << "Iterations: " << iter << ", Timestep: " << t << "        " << '\r' << flush;

		// Render stuff
		for(int i = 0; i < particleCount; ++i) {
			vertices[i][0] = water->at(i)->getPosition().x;
			vertices[i][1] = water->at(i)->getPosition().y;
			vertices[i][2] = water->at(i)->getPosition().z;

			//tmp = water->at(i)->getColor();
			colors[i][0] = 0.7 - water->at(i)->getPosition().x;
			colors[i][1] = 0.7 - water->at(i)->getPosition().y;
			colors[i][2] = 0.7 - water->at(i)->getPosition().z;

		}

		// Bind the first VBO as being the active buffer and storing vertex attributes (coordinates)
	    glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);

		// Copy the vertex data from diamond to our buffer
	    // 8 * sizeof(GLfloat) is the size of the diamond array, since it contains 8 GLfloat values
	    glBufferData(GL_ARRAY_BUFFER, 3 * particleCount * sizeof(GLfloat), vertices,/* 9 * sizeof(GLfloat), diamond, */ GL_STATIC_DRAW);

	    // Specify that our coordinate data is going into attribute index 0, and contains three floats per vertex
	    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);

	    // Enable attribute index 0 as being used
	    glEnableVertexAttribArray(0);

	    // Bind the second VBO as being the active buffer and storing vertex attributes (colors)
	    glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);

	    glBufferData(GL_ARRAY_BUFFER, 3 * particleCount * sizeof(GLfloat), colors, GL_STATIC_DRAW);

	    // Specify that our color data is going into attribute index 1, and contains three floats per vertex
	    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, 0);

	    // Enable attribute index 1 as being used
	    glEnableVertexAttribArray(1);
	}

	glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // make background black
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glBindVertexArray(vao);

	glEnable(GL_PROGRAM_POINT_SIZE); //enable gl_PointSize in vertex shader

	glPolygonMode(GL_FRONT_AND_BACK, GL_POINT);

	glDrawArrays(GL_POINTS, 0, particleCount);

	glDisable(GL_PROGRAM_POINT_SIZE);

	timeLastFrame = frameTimer->elapsed();
}

void SPH::createVAO ( int particles ) {
	// A VAO (Vertex Array Object) stores information of a complete rendered object.
	// It contains all VBOs (Vertex Buffer Objects)
	// A VBO stores information about the vertices.
	// Now we're using two VBOs, one for coordinates and one for colors

	// Allocate and bind Vertex Array Object to the handle vao
	glGenVertexArrays(1, &vao);
	glBindVertexArray(vao);

	// Generate (one) new Vertex Buffer Object and get the associated id
	glGenBuffers(2, vbo);
}

void SPH::setTimer(timer *newTimer)
{
	frameTimer = newTimer;
}
<|endoftext|>


<commit_before>
/*
 * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL
 */

#include <QActiveResource.h>
#include <QDateTime>
#include <ruby.h>
#include <QDebug>

extern "C"
{
    typedef VALUE(*ARGS)(...);
    typedef int(*ITERATOR)(...);

    static VALUE rb_mQAR;
    static VALUE rb_cQARHash;
    static VALUE rb_cQARParamList;
    static VALUE rb_cQARResource;

    static QString to_s(VALUE value);

    /*
     * Hash
     */

    static VALUE hash_method_missing(VALUE self, VALUE method)
    {
        VALUE value = rb_hash_aref(self, method);

        if(value == Qnil)
        {
            static const ID symbol = rb_intern("method_missing");
            return rb_funcall(rb_cHash, symbol, 1, method);
        }

        return value;
    }

    /*
     * Resource
     */

    static void resource_mark(QActiveResource::Resource *) {}
    static void resource_free(QActiveResource::Resource *resource)
    {
        delete resource;
    }

    static VALUE resource_allocate(VALUE klass)
    {
        QActiveResource::Resource *resource = new QActiveResource::Resource;
        return Data_Wrap_Struct(klass, resource_mark, resource_free, resource);
    }

    static VALUE resource_initialize(VALUE self, VALUE base, VALUE resource)
    {
        QActiveResource::Resource *r = 0;
        Data_Get_Struct(self, QActiveResource::Resource, r);
        r->setBase(QString::fromUtf8(rb_string_value_ptr(&base)));
        r->setResource(QString::fromUtf8(rb_string_value_ptr(&resource)));
    }

    /*
     * ParamList
     */

    static VALUE param_list_mark(QActiveResource::ParamList *) {}
    static VALUE param_list_free(QActiveResource::ParamList *params)
    {
        delete params;
    }

    static VALUE param_list_allocate(VALUE klass)
    {
        QActiveResource::ParamList *params = new QActiveResource::ParamList();
        return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params);
    }

    static VALUE to_value(const QVariant &v)
    {
        switch(v.type())
        {
        case QVariant::Hash:
        {
            VALUE value = rb_hash_new();

            QHash<QString, QVariant> hash = v.toHash();

            for(QHash<QString, QVariant>::ConstIterator it = hash.begin(); it != hash.end(); ++it)
            {
                rb_hash_aset(value, ID2SYM(rb_intern(it.key().toUtf8())), to_value(it.value()));
            }

            return value;
        }
        case QVariant::List:
        {
            VALUE value = rb_ary_new();

            foreach(QVariant element, v.toList())
            {
                rb_ary_push(value, to_value(element));
            }

            return value;
        }
        case QVariant::Invalid:
            return Qnil;
        case QVariant::Bool:
            return v.toBool() ? Qtrue : Qfalse;
        case QVariant::Int:
            return rb_int_new(v.toInt());
        case QVariant::Double:
            return rb_float_new(v.toDouble());
        case QVariant::DateTime:
        {
            static const ID at = rb_intern("at");
            return rb_funcall(rb_cTime, at, 1, rb_int_new(v.toDateTime().toTime_t()));
        }
        default:
            return rb_str_new2(v.toString().toUtf8());
        }
    }

    static QString to_s(VALUE value)
    {
        static const ID id = rb_intern("to_s");
        VALUE s = rb_funcall(value, id, 0);
        return QString::fromUtf8(StringValuePtr(s));
    }

    static int hash_iterator(VALUE key, VALUE value, VALUE params)
    {
        QActiveResource::ParamList *params_pointer;
        Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);
        params_pointer->append(QActiveResource::Param(to_s(key), to_s(value)));
    }

    static VALUE resource_find(int argc, VALUE *argv, VALUE self)
    {
        QActiveResource::Resource *resource = 0;
        Data_Get_Struct(self, class QActiveResource::Resource, resource);

        VALUE params = param_list_allocate(rb_cData);

        if(argc >= 2 && TYPE(argv[1]) == T_HASH)
        {
            static const VALUE params_symbol = ID2SYM(rb_intern("params"));
            VALUE params_hash = rb_hash_aref(argv[1], params_symbol);

            if(params_hash != Qnil)
            {
                rb_hash_foreach(params_hash, (ITERATOR) hash_iterator, params);
            }

            static const VALUE follow_redirects_symbol = ID2SYM(rb_intern("follow_redirects"));
            VALUE follow_redirects = rb_hash_aref(argv[1], follow_redirects_symbol);
            resource->setFollowRedirects(follow_redirects == Qtrue);
        }

        QActiveResource::ParamList *params_pointer;
        Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);

        QString from;

        if(argc >= 1)
        {
            static const ID one = rb_intern("one");
            static const ID first = rb_intern("first");
            static const ID last = rb_intern("last");
            static const ID all = rb_intern("all");

            ID current = SYM2ID(argv[0]);

            if(current == one)
            {
                return to_value(resource->find(QActiveResource::FindOne, from, *params_pointer));
            }
            else if(current == first)
            {
                return to_value(resource->find(QActiveResource::FindFirst, from, *params_pointer));
            }
            else if(current == last)
            {
                return to_value(resource->find(QActiveResource::FindLast, from, *params_pointer));
            }
            else if(current != all)
            {
                return to_value(resource->find(to_s(argv[0])));
            }
        }

        QActiveResource::RecordList records =
            resource->find(QActiveResource::FindAll, from, *params_pointer);

        VALUE array = rb_ary_new2(records.length());

        for(int i = 0; i < records.length(); i++)
        {
            rb_ary_store(array, i, to_value(records[i]));
        }

        return array;
    }

    void Init_QAR(void)
    {
        rb_mQAR = rb_define_module("QAR");

        rb_cQARHash = rb_define_class_under(rb_mQAR, "Hash", rb_cHash);
        rb_define_method(rb_cQARHash, "method_missing", (ARGS) hash_method_missing, 1);

        rb_cQARParamList = rb_define_class_under(rb_mQAR, "ParamList", rb_cObject);
        rb_define_alloc_func(rb_cQARParamList, param_list_allocate);

        rb_cQARResource = rb_define_class_under(rb_mQAR, "Resource", rb_cObject);
        rb_define_alloc_func(rb_cQARResource, resource_allocate);
        rb_define_method(rb_cQARResource, "initialize", (ARGS) resource_initialize, 2);
        rb_define_method(rb_cQARResource, "find", (ARGS) resource_find, -1);
    }
}
<commit_msg>Reorganize code a little to separate class implementations and utility functions.<commit_after>
/*
 * Copyright (C) 2010, Directed Edge, Inc. | Licensed under the MPL and LGPL
 */

#include <QActiveResource.h>
#include <QDateTime>
#include <ruby.h>
#include <QDebug>

extern "C"
{
    typedef VALUE(*ARGS)(...);
    typedef int(*ITERATOR)(...);

    static VALUE rb_mQAR;
    static VALUE rb_cQARHash;
    static VALUE rb_cQARParamList;
    static VALUE rb_cQARResource;

    /*
     * helper functions
     */

    static QString to_s(VALUE value)
    {
        static const ID id = rb_intern("to_s");
        VALUE s = rb_funcall(value, id, 0);
        return QString::fromUtf8(StringValuePtr(s));
    }

    static VALUE to_value(const QVariant &v)
    {
        switch(v.type())
        {
        case QVariant::Hash:
        {
            VALUE value = rb_hash_new();

            QHash<QString, QVariant> hash = v.toHash();

            for(QHash<QString, QVariant>::ConstIterator it = hash.begin(); it != hash.end(); ++it)
            {
                rb_hash_aset(value, ID2SYM(rb_intern(it.key().toUtf8())), to_value(it.value()));
            }

            return value;
        }
        case QVariant::List:
        {
            VALUE value = rb_ary_new();

            foreach(QVariant element, v.toList())
            {
                rb_ary_push(value, to_value(element));
            }

            return value;
        }
        case QVariant::Invalid:
            return Qnil;
        case QVariant::Bool:
            return v.toBool() ? Qtrue : Qfalse;
        case QVariant::Int:
            return rb_int_new(v.toInt());
        case QVariant::Double:
            return rb_float_new(v.toDouble());
        case QVariant::DateTime:
        {
            static const ID at = rb_intern("at");
            return rb_funcall(rb_cTime, at, 1, rb_int_new(v.toDateTime().toTime_t()));
        }
        default:
            return rb_str_new2(v.toString().toUtf8());
        }
    }

    /*
     * Hash
     */

    static VALUE hash_method_missing(VALUE self, VALUE method)
    {
        VALUE value = rb_hash_aref(self, method);

        if(value == Qnil)
        {
            static const ID symbol = rb_intern("method_missing");
            return rb_funcall(rb_cHash, symbol, 1, method);
        }

        return value;
    }

    /*
     * Resource
     */

    static void resource_mark(QActiveResource::Resource *) {}
    static void resource_free(QActiveResource::Resource *resource)
    {
        delete resource;
    }

    static VALUE resource_allocate(VALUE klass)
    {
        QActiveResource::Resource *resource = new QActiveResource::Resource;
        return Data_Wrap_Struct(klass, resource_mark, resource_free, resource);
    }

    static VALUE resource_initialize(VALUE self, VALUE base, VALUE resource)
    {
        QActiveResource::Resource *r = 0;
        Data_Get_Struct(self, QActiveResource::Resource, r);
        r->setBase(QString::fromUtf8(rb_string_value_ptr(&base)));
        r->setResource(QString::fromUtf8(rb_string_value_ptr(&resource)));
    }

    /*
     * ParamList
     */

    static VALUE param_list_mark(QActiveResource::ParamList *) {}
    static VALUE param_list_free(QActiveResource::ParamList *params)
    {
        delete params;
    }

    static VALUE param_list_allocate(VALUE klass)
    {
        QActiveResource::ParamList *params = new QActiveResource::ParamList();
        return Data_Wrap_Struct(klass, param_list_mark, param_list_free, params);
    }

    static int params_hash_iterator(VALUE key, VALUE value, VALUE params)
    {
        QActiveResource::ParamList *params_pointer;
        Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);
        params_pointer->append(QActiveResource::Param(to_s(key), to_s(value)));
    }

    static VALUE resource_find(int argc, VALUE *argv, VALUE self)
    {
        QActiveResource::Resource *resource = 0;
        Data_Get_Struct(self, class QActiveResource::Resource, resource);

        VALUE params = param_list_allocate(rb_cData);

        if(argc >= 2 && TYPE(argv[1]) == T_HASH)
        {
            static const VALUE params_symbol = ID2SYM(rb_intern("params"));
            VALUE params_hash = rb_hash_aref(argv[1], params_symbol);

            if(params_hash != Qnil)
            {
                rb_hash_foreach(params_hash, (ITERATOR) params_hash_iterator, params);
            }

            static const VALUE follow_redirects_symbol = ID2SYM(rb_intern("follow_redirects"));
            VALUE follow_redirects = rb_hash_aref(argv[1], follow_redirects_symbol);
            resource->setFollowRedirects(follow_redirects == Qtrue);
        }

        QActiveResource::ParamList *params_pointer;
        Data_Get_Struct(params, QActiveResource::ParamList, params_pointer);

        QString from;

        if(argc >= 1)
        {
            static const ID one = rb_intern("one");
            static const ID first = rb_intern("first");
            static const ID last = rb_intern("last");
            static const ID all = rb_intern("all");

            ID current = SYM2ID(argv[0]);

            if(current == one)
            {
                return to_value(resource->find(QActiveResource::FindOne, from, *params_pointer));
            }
            else if(current == first)
            {
                return to_value(resource->find(QActiveResource::FindFirst, from, *params_pointer));
            }
            else if(current == last)
            {
                return to_value(resource->find(QActiveResource::FindLast, from, *params_pointer));
            }
            else if(current != all)
            {
                return to_value(resource->find(to_s(argv[0])));
            }
        }

        QActiveResource::RecordList records =
            resource->find(QActiveResource::FindAll, from, *params_pointer);

        VALUE array = rb_ary_new2(records.length());

        for(int i = 0; i < records.length(); i++)
        {
            rb_ary_store(array, i, to_value(records[i]));
        }

        return array;
    }

    void Init_QAR(void)
    {
        rb_mQAR = rb_define_module("QAR");

        rb_cQARHash = rb_define_class_under(rb_mQAR, "Hash", rb_cHash);
        rb_define_method(rb_cQARHash, "method_missing", (ARGS) hash_method_missing, 1);

        rb_cQARParamList = rb_define_class_under(rb_mQAR, "ParamList", rb_cObject);
        rb_define_alloc_func(rb_cQARParamList, param_list_allocate);

        rb_cQARResource = rb_define_class_under(rb_mQAR, "Resource", rb_cObject);
        rb_define_alloc_func(rb_cQARResource, resource_allocate);
        rb_define_method(rb_cQARResource, "initialize", (ARGS) resource_initialize, 2);
        rb_define_method(rb_cQARResource, "find", (ARGS) resource_find, -1);
    }
}
<|endoftext|>