<commit_before>#include "PolycrystalReducedIC.h"
#include "IndirectSort.h"
#include "MooseRandom.h"

template<>
InputParameters validParams<PolycrystalReducedIC>()
{
  InputParameters params = validParams<InitialCondition>();
  params.addRequiredParam<unsigned int>("crys_num","Number of order parameters");
  params.addRequiredParam<unsigned int>("grain_num","Number of grains being represented by the order parameters");
  params.addRequiredParam<unsigned int>("crys_index", "The index for the current order parameter");

  params.addParam<unsigned int>("rand_seed",12444,"The random seed");

  params.addParam<bool>("cody_test",false,"Use set grain center points for Cody's test. Grain num MUST equal 10");

  params.addParam<bool>("columnar_3D",false,"3D microstructure will be columnar in the z-direction?");

  return params;
}

PolycrystalReducedIC::PolycrystalReducedIC(const std::string & name,
                             InputParameters parameters)
  :InitialCondition(name, parameters),
   _mesh(_fe_problem.mesh()),
   _nl(_fe_problem.getNonlinearSystem()),
   _op_num(getParam<unsigned int>("crys_num")),
   _grain_num(getParam<unsigned int>("grain_num")),
   _op_index(getParam<unsigned int>("crys_index")),
   _rand_seed(getParam<unsigned int>("rand_seed")),
   _cody_test(getParam<bool>("cody_test")),
   _columnar_3D(getParam<bool>("columnar_3D"))
{
}

void
PolycrystalReducedIC::initialSetup()
{
 //Set up domain bounds with mesh tools
  for (unsigned int i = 0; i < LIBMESH_DIM; i++)
  {
    _bottom_left(i) = _mesh.getMinInDimension(i);
    _top_right(i) = _mesh.getMaxInDimension(i);
  }
  _range = _top_right - _bottom_left;

  if (_op_num > _grain_num)
     mooseError("ERROR in PolycrystalReducedIC: Number of order parameters (crys_num) can't be larger than the number of grains (grain_num)");

  if (_cody_test)
    if (_op_num != 5 || _grain_num != 10)
      mooseError("ERROR in PolycrystalReducedIC: Numbers aren't correct for Cody's test.");

  MooseRandom::seed(_rand_seed);

  //Randomly generate the centers of the individual grains represented by the Voronoi tesselation
  _centerpoints.resize(_grain_num);
  _assigned_op.resize(_grain_num);
  std::vector<Real> distances(_grain_num);

  std::vector<Point> holder;

  if (_cody_test)
  {
    holder.resize(_grain_num);
    holder[0] = Point(0.2,0.85,0.0);
    holder[1] = Point(0.50,0.85,0.0);
    holder[2] = Point(0.8,0.85,0.0);

    holder[3] = Point(0.2,0.5,0.0);
    holder[4] = Point(0.50,0.5,0.0);
    holder[5] = Point(0.8,0.5,0.0);

    holder[6] = Point(0.1,0.1,0.0);
    holder[7] = Point(0.50,0.05,0.0);
    holder[8] = Point(0.9,0.1,0.0);

    holder[9] = Point(0.50,0.1,0.0);
  }

  //Assign actual center point positions
  for (unsigned int grain=0; grain<_grain_num; grain++)
  {
    for (unsigned int i = 0; i<LIBMESH_DIM; i++)
    {
      if (_cody_test)
        _centerpoints[grain](i) = _bottom_left(i) + _range(i)*holder[grain](i);
      else
        _centerpoints[grain](i) = _bottom_left(i) + _range(i)*MooseRandom::rand();
    }
    if (_columnar_3D)
        _centerpoints[grain](2) = _bottom_left(2) + _range(2)*0.5;
  }

  //Assign grains to each order parameter
  if (_cody_test)
  {
    _assigned_op[0] = 0;
    _assigned_op[1] = 0;
    _assigned_op[2] = 0;
    _assigned_op[3] = 1;
    _assigned_op[4] = 1;
    _assigned_op[5] = 1;
    _assigned_op[6] = 2;
    _assigned_op[7] = 3;
    _assigned_op[8] = 2;
    _assigned_op[9] = 4;
  }
  else

    for (unsigned int grain=0; grain<_grain_num; grain++) //Assign grains to specific order parameters in a way that maximized the distance
    {
      std::vector<int> min_op_ind;
      std::vector<Real> min_op_dist;
      min_op_ind.resize(_op_num);
      min_op_dist.resize(_op_num);
      std::fill(min_op_dist.begin() , min_op_dist.end(), 1.0e6*_top_right(1));
      //Determine the distance to the closest center assigned to each order parameter
      for (unsigned int i=0; i<grain; i++) //These shouldn't run for grain = 0
      {

        Real dist =  _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
        if (min_op_dist[_assigned_op[i]] > dist)
        {
          min_op_dist[_assigned_op[i]] = dist;
          min_op_ind[_assigned_op[i]] = i;
        }
      }
      //Assign the current center point to the order parameter that is furthest away.
      Real mx;
      if (grain == 0)
        _assigned_op[grain] = 0;
      else
      {
        mx = 0.0;
        unsigned int mx_ind = 1e6;
        for (unsigned int i = 0; i < _op_num; i++) //Find index of max
          if (mx < min_op_dist[i])
          {
            mx = min_op_dist[i];
            mx_ind = i;
          }
        _assigned_op[grain] = mx_ind;
      }
      //std::cout << "For grain " << grain << ", center point = " << _centerpoints[grain](0) << " " << _centerpoints[grain](1) << "\n";
      //std::cout << "Max index is " << _assigned_op[grain] << ", with a max distance of " << mx << "\n";
    }
}

Real
PolycrystalReducedIC::value(const Point & p)
{
  // Assumption: We are going to assume that all variables are periodic together
//  _mesh.initPeriodicDistanceForVariable(_nl, _var.number());

  Real min_distance = 1e10;
  Real val = 0.0;
  unsigned int min_index = _grain_num + 1;
  //Loops through all of the grain centers and finds the center that is closest to the point p
  for (unsigned int grain=0; grain<_grain_num; grain++)
  {
    Point cp = p;
    if (_columnar_3D)
      cp(2) = _centerpoints[grain](2);

    Real distance = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], cp);

    if (min_distance > distance)
    {
      min_distance = distance;
      min_index = grain;
    }

  }

  if (min_index > _grain_num)
    mooseError("ERROR in PolycrystalReducedIC: didn't find minimum values");

  //If the current order parameter index (_op_index) is equal to the min_index, set the value to 1.0
  if (_assigned_op[min_index] == _op_index) //Make sure that the _op_index goes from 0 to _op_num-1
    val = 1.0;

  if (val > 1)
    val = 1.0;

  if (val < 0.0)
    val = 0.0;

  return val;

}

<commit_msg>fixed columnar grain ic<commit_after>#include "PolycrystalReducedIC.h"
#include "IndirectSort.h"
#include "MooseRandom.h"

template<>
InputParameters validParams<PolycrystalReducedIC>()
{
  InputParameters params = validParams<InitialCondition>();
  params.addRequiredParam<unsigned int>("crys_num","Number of order parameters");
  params.addRequiredParam<unsigned int>("grain_num","Number of grains being represented by the order parameters");
  params.addRequiredParam<unsigned int>("crys_index", "The index for the current order parameter");

  params.addParam<unsigned int>("rand_seed",12444,"The random seed");

  params.addParam<bool>("cody_test",false,"Use set grain center points for Cody's test. Grain num MUST equal 10");

  params.addParam<bool>("columnar_3D",false,"3D microstructure will be columnar in the z-direction?");

  return params;
}

PolycrystalReducedIC::PolycrystalReducedIC(const std::string & name,
                             InputParameters parameters)
  :InitialCondition(name, parameters),
   _mesh(_fe_problem.mesh()),
   _nl(_fe_problem.getNonlinearSystem()),
   _op_num(getParam<unsigned int>("crys_num")),
   _grain_num(getParam<unsigned int>("grain_num")),
   _op_index(getParam<unsigned int>("crys_index")),
   _rand_seed(getParam<unsigned int>("rand_seed")),
   _cody_test(getParam<bool>("cody_test")),
   _columnar_3D(getParam<bool>("columnar_3D"))
{
}

void
PolycrystalReducedIC::initialSetup()
{
 //Set up domain bounds with mesh tools
  for (unsigned int i = 0; i < LIBMESH_DIM; i++)
  {
    _bottom_left(i) = _mesh.getMinInDimension(i);
    _top_right(i) = _mesh.getMaxInDimension(i);
  }
  _range = _top_right - _bottom_left;

  if (_op_num > _grain_num)
     mooseError("ERROR in PolycrystalReducedIC: Number of order parameters (crys_num) can't be larger than the number of grains (grain_num)");

  if (_cody_test)
    if (_op_num != 5 || _grain_num != 10)
      mooseError("ERROR in PolycrystalReducedIC: Numbers aren't correct for Cody's test.");

  MooseRandom::seed(_rand_seed);

  //Randomly generate the centers of the individual grains represented by the Voronoi tesselation
  _centerpoints.resize(_grain_num);
  _assigned_op.resize(_grain_num);
  std::vector<Real> distances(_grain_num);

  std::vector<Point> holder;

  if (_cody_test)
  {
    holder.resize(_grain_num);
    holder[0] = Point(0.2,0.85,0.0);
    holder[1] = Point(0.50,0.85,0.0);
    holder[2] = Point(0.8,0.85,0.0);

    holder[3] = Point(0.2,0.5,0.0);
    holder[4] = Point(0.50,0.5,0.0);
    holder[5] = Point(0.8,0.5,0.0);

    holder[6] = Point(0.1,0.1,0.0);
    holder[7] = Point(0.50,0.05,0.0);
    holder[8] = Point(0.9,0.1,0.0);

    holder[9] = Point(0.50,0.1,0.0);
  }

  //Assign actual center point positions
  for (unsigned int grain=0; grain<_grain_num; grain++)
  {
    for (unsigned int i = 0; i<LIBMESH_DIM; i++)
    {
      if (_cody_test)
        _centerpoints[grain](i) = _bottom_left(i) + _range(i)*holder[grain](i);
      else
        _centerpoints[grain](i) = _bottom_left(i) + _range(i)*MooseRandom::rand();
    }
    if (_columnar_3D)
        _centerpoints[grain](2) = _bottom_left(2) + _range(2)*0.5;
  }

  //Assign grains to each order parameter
  if (_cody_test)
  {
    _assigned_op[0] = 0;
    _assigned_op[1] = 0;
    _assigned_op[2] = 0;
    _assigned_op[3] = 1;
    _assigned_op[4] = 1;
    _assigned_op[5] = 1;
    _assigned_op[6] = 2;
    _assigned_op[7] = 3;
    _assigned_op[8] = 2;
    _assigned_op[9] = 4;
  }
  else

    for (unsigned int grain=0; grain<_grain_num; grain++) //Assign grains to specific order parameters in a way that maximized the distance
    {
      std::vector<int> min_op_ind;
      std::vector<Real> min_op_dist;
      min_op_ind.resize(_op_num);
      min_op_dist.resize(_op_num);
      std::fill(min_op_dist.begin() , min_op_dist.end(), 1.0e6*_top_right(1));
      //Determine the distance to the closest center assigned to each order parameter
      for (unsigned int i=0; i<grain; i++) //These shouldn't run for grain = 0
      {

        Real dist =  _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], _centerpoints[i]);
        if (min_op_dist[_assigned_op[i]] > dist)
        {
          min_op_dist[_assigned_op[i]] = dist;
          min_op_ind[_assigned_op[i]] = i;
        }
      }
      //Assign the current center point to the order parameter that is furthest away.
      Real mx;
      if (grain == 0)
        _assigned_op[grain] = 0;
      else
      {
        mx = 0.0;
        unsigned int mx_ind = 1e6;
        for (unsigned int i = 0; i < _op_num; i++) //Find index of max
          if (mx < min_op_dist[i])
          {
            mx = min_op_dist[i];
            mx_ind = i;
          }
        _assigned_op[grain] = mx_ind;
      }
      //std::cout << "For grain " << grain << ", center point = " << _centerpoints[grain](0) << " " << _centerpoints[grain](1) << "\n";
      //std::cout << "Max index is " << _assigned_op[grain] << ", with a max distance of " << mx << "\n";
    }
}

Real
PolycrystalReducedIC::value(const Point & p)
{
  // Assumption: We are going to assume that all variables are periodic together
//  _mesh.initPeriodicDistanceForVariable(_nl, _var.number());

  Real min_distance = _top_right(0)*1e5;
  Real val = 0.0;
  unsigned int min_index = _grain_num + 100;
  //Loops through all of the grain centers and finds the center that is closest to the point p
  for (unsigned int grain=0; grain<_grain_num; grain++)
  {
    Real distance = _mesh.minPeriodicDistance(_var.number(), _centerpoints[grain], p);

    if (min_distance > distance)
    {
      min_distance = distance;
      min_index = grain;
    }

  }

  if (min_index > _grain_num)
    mooseError("ERROR in PolycrystalReducedIC: didn't find minimum values");

  //If the current order parameter index (_op_index) is equal to the min_index, set the value to 1.0
  if (_assigned_op[min_index] == _op_index) //Make sure that the _op_index goes from 0 to _op_num-1
    val = 1.0;

  if (val > 1)
    val = 1.0;

  if (val < 0.0)
    val = 0.0;

  return val;

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: test_member.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 03:47:48 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#include <iostream>
#include <string>

using namespace std;

class Aint
{
    int n;

public:

    Aint():n(0)
        {
            cout << "ctor Aint()" << endl;
        }
    Aint(int _n):n(_n)
        {
            cout << "ctor Aint(int(" << _n << "))" << endl;
        }
    int getA() {return n;}
    ~Aint()
        {
            cout << "dtor Aint()" << endl;
        }

};

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

class B
{
    Aint a;
    Aint b;
    std::string aStr;

public:

    B()
            :a(2)
        {
            cout << "ctor B()" << endl;
        }
    B(int _a)
            :a(_a)
        {
            cout << "ctor B(int)" << endl;
        }

    void foo()
        {
            cout << "a.getA() := " << a.getA() << endl;
            cout << "b.getA() := " << b.getA() << endl;
        }

};

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    B b(4);
    b.foo();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.3.52); FILE MERGED 2008/03/31 13:06:10 rt 1.3.52.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: test_member.cxx,v $
 * $Revision: 1.4 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_testshl2.hxx"
#include <iostream>
#include <string>

using namespace std;

class Aint
{
    int n;

public:

    Aint():n(0)
        {
            cout << "ctor Aint()" << endl;
        }
    Aint(int _n):n(_n)
        {
            cout << "ctor Aint(int(" << _n << "))" << endl;
        }
    int getA() {return n;}
    ~Aint()
        {
            cout << "dtor Aint()" << endl;
        }

};

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

class B
{
    Aint a;
    Aint b;
    std::string aStr;

public:

    B()
            :a(2)
        {
            cout << "ctor B()" << endl;
        }
    B(int _a)
            :a(_a)
        {
            cout << "ctor B(int)" << endl;
        }

    void foo()
        {
            cout << "a.getA() := " << a.getA() << endl;
            cout << "b.getA() := " << b.getA() << endl;
        }

};

// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
    B b(4);
    b.foo();
}
<|endoftext|>


<commit_before>char volume_tf_mip_frag[] = "uniform sampler3D baseTexture;\n"
                            "\n"
                            "uniform sampler1D tfTexture;\n"
                            "uniform float tfScale;\n"
                            "uniform float tfOffset;\n"
                            "\n"
                            "uniform float SampleDensityValue;\n"
                            "uniform float TransparencyValue;\n"
                            "uniform float AlphaFuncValue;\n"
                            "\n"
                            "varying vec4 cameraPos;\n"
                            "varying vec4 vertexPos;\n"
                            "varying mat4 texgen;\n"
                            "varying vec4 baseColor;\n"
                            "\n"
                            "void main(void)\n"
                            "{ \n"
                            "    vec3 t0 = (texgen * vertexPos).xyz;\n"
                            "    vec3 te = (texgen * cameraPos).xyz;\n"
                            "\n"
                            "    if (te.x>=0.0 && te.x<=1.0 &&\n"
                            "        te.y>=0.0 && te.y<=1.0 &&\n"
                            "        te.z>=0.0 && te.z<=1.0)\n"
                            "    {\n"
                            "        // do nothing... te inside volume\n"
                            "    }\n"
                            "    else\n"
                            "    {\n"
                            "        if (te.x<0.0)\n"
                            "        {\n"
                            "            float r = -te.x / (t0.x-te.x);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.x>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.x) / (t0.x-te.x);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.y<0.0)\n"
                            "        {\n"
                            "            float r = -te.y / (t0.y-te.y);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.y>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.y) / (t0.y-te.y);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.z<0.0)\n"
                            "        {\n"
                            "            float r = -te.z / (t0.z-te.z);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.z>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.z) / (t0.z-te.z);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "    }\n"
                            "\n"
                            "    const float max_iteratrions = 2048.0;\n"
                            "    float num_iterations = ceil(length(te-t0)/SampleDensityValue);\n"
                            "    if (num_iterations<2.0) num_iterations = 2.0;\n"
                            "    \n"
                            "    if (num_iterations>max_iteratrions) \n"
                            "    {\n"
                            "        num_iterations = max_iteratrions;\n"
                            "    }\n"
                            "\n"
                            "    vec3 deltaTexCoord=(te-t0)/float(num_iterations-1.0);\n"
                            "    vec3 texcoord = t0;\n"
                            "\n"
                            "    vec4 fragColor = vec4(0.0, 0.0, 0.0, 0.0); \n"
                            "    while(num_iterations>0.0)\n"
                            "    {\n"
                            "        float v = texture3D( baseTexture, texcoord).s * tfScale + tfOffset;\n"
                            "        vec4 color = texture1D( tfTexture, v);\n"
                            "        if (fragColor.w<color.w)\n"
                            "        {\n"
                            "            fragColor = color;\n"
                            "        }\n"
                            "        texcoord += deltaTexCoord; \n"
                            "\n"
                            "        --num_iterations;\n"
                            "    }\n"
                            "\n"
                            "    fragColor.w *= TransparencyValue;\n"
                            "    if (fragColor.w>1.0) fragColor.w = 1.0;\n"
                            "\n"
                            "    fragColor *= baseColor;\n"
                            "\n"
                            "    if (fragColor.w<AlphaFuncValue) discard;\n"
                            "    gl_FragColor = fragColor;\n"
                            "}\n"
                            "\n";
<commit_msg>Fixed error in the computation of tex coords of Maximum Intensity Projection + Transfer Function rendering.<commit_after>char volume_tf_mip_frag[] = "uniform sampler3D baseTexture;\n"
                            "\n"
                            "uniform sampler1D tfTexture;\n"
                            "uniform float tfScale;\n"
                            "uniform float tfOffset;\n"
                            "\n"
                            "uniform float SampleDensityValue;\n"
                            "uniform float TransparencyValue;\n"
                            "uniform float AlphaFuncValue;\n"
                            "\n"
                            "varying vec4 cameraPos;\n"
                            "varying vec4 vertexPos;\n"
                            "varying mat4 texgen;\n"
                            "varying vec4 baseColor;\n"
                            "\n"
                            "void main(void)\n"
                            "{\n"
                            "    vec4 t0 = vertexPos;\n"
                            "    vec4 te = cameraPos;\n"
                            "\n"
                            "    if (te.x>=0.0 && te.x<=1.0 &&\n"
                            "        te.y>=0.0 && te.y<=1.0 &&\n"
                            "        te.z>=0.0 && te.z<=1.0)\n"
                            "    {\n"
                            "        // do nothing... te inside volume\n"
                            "    }\n"
                            "    else\n"
                            "    {\n"
                            "        if (te.x<0.0)\n"
                            "        {\n"
                            "            float r = -te.x / (t0.x-te.x);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.x>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.x) / (t0.x-te.x);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.y<0.0)\n"
                            "        {\n"
                            "            float r = -te.y / (t0.y-te.y);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.y>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.y) / (t0.y-te.y);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.z<0.0)\n"
                            "        {\n"
                            "            float r = -te.z / (t0.z-te.z);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "\n"
                            "        if (te.z>1.0)\n"
                            "        {\n"
                            "            float r = (1.0-te.z) / (t0.z-te.z);\n"
                            "            te = te + (t0-te)*r;\n"
                            "        }\n"
                            "    }\n"
                            "\n"
                            "    t0 = t0 * texgen;\n"
                            "    te = te * texgen;\n"
                            "\n"
                            "    const float max_iteratrions = 2048.0;\n"
                            "    float num_iterations = ceil(length((te-t0).xyz)/SampleDensityValue);\n"
                            "    if (num_iterations<2.0) num_iterations = 2.0;\n"
                            "\n"
                            "    if (num_iterations>max_iteratrions)\n"
                            "    {\n"
                            "        num_iterations = max_iteratrions;\n"
                            "    }\n"
                            "\n"
                            "    vec3 deltaTexCoord=(te-t0).xyz/float(num_iterations-1.0);\n"
                            "    vec3 texcoord = t0.xyz;\n"
                            "\n"
                            "    vec4 fragColor = vec4(0.0, 0.0, 0.0, 0.0);\n"
                            "    while(num_iterations>0.0)\n"
                            "    {\n"
                            "        float v = texture3D( baseTexture, texcoord).s * tfScale + tfOffset;\n"
                            "        vec4 color = texture1D( tfTexture, v);\n"
                            "        if (fragColor.w<color.w)\n"
                            "        {\n"
                            "            fragColor = color;\n"
                            "        }\n"
                            "        texcoord += deltaTexCoord;\n"
                            "\n"
                            "        --num_iterations;\n"
                            "    }\n"
                            "\n"
                            "    fragColor.w *= TransparencyValue;\n"
                            "    if (fragColor.w>1.0) fragColor.w = 1.0;\n"
                            "\n"
                            "    fragColor *= baseColor;\n"
                            "\n"
                            "    if (fragColor.w<AlphaFuncValue) discard;\n"
                            "    gl_FragColor = fragColor;\n"
                            "}\n"
                            "\n";
<|endoftext|>


<commit_before>#include "service.h"
#include <string>
#include <fstream>
#include <locale>
#include <iostream>

typedef std::string string;
typedef std::string::iterator string_iterator;

// Utility function to skip white space. Returns an iterator at the
// first non-white-space position (or at end).
static string_iterator skipws(string_iterator i, string_iterator end)
{
    using std::locale;
    using std::isspace;

    while (i != end) {
      if (! isspace(*i, locale::classic())) {
        break;
      }
      ++i;
    }
    return i;
}

// Read a setting name.
static string read_setting_name(string_iterator & i, string_iterator end)
{
    using std::locale;
    using std::ctype;
    using std::use_facet;

    const ctype<char> & facet = use_facet<ctype<char> >(locale::classic());

    string rval;
    // Allow alphabetical characters, and dash (-) in setting name
    while (i != end && (*i == '-' || facet.is(ctype<char>::alpha, *i))) {
        rval += *i;
        ++i;
    }
    return rval;
}

// Read a setting value
// Try to allow quoted strings:
static string read_setting_value(string_iterator & i, string_iterator end)
{
    using std::locale;
    using std::isspace;

    i = skipws(i, end);

    string rval;

    while (i != end) {
        char c = *i;
        if (c == '\"') {
            // quoted string
            ++i;
            while (i != end) {
                c = *i;
                if (c == '\"') break;
                if (c == '\n') {
                    // TODO error here.
                }
                else if (c == '\\') {
                    // A backslash escapes the following character.
                    ++i;
                    if (i != end) {
                        c = *i;
                        rval += c;
                    }
                }
                else {
                    rval += c;
                }
                ++i;
            }
            if (i == end) {
                // String wasn't terminated
                // TODO error here
                break;
            }
        }
        else if (c == '\\') {
            // A backslash escapes the next character
            ++i;
            if (i != end) {
                rval += *i;
            }
            else {
                // TODO error here
            }
        }
        else if (isspace(c, locale::classic())) {
            i = skipws(i, end);
            if (i == end) break;
            if (*i == '#') break; // comment
            rval += ' ';  // collapse ws to a single space
            continue;
        }
        else if (c == '#') {
            // hmm... comment? Probably, though they should have put a space
            // before it really. TODO throw an exception, and document
            // that '#' for comments must be preceded by space, and in values
            // must be quoted.
            break;
        }
        else {
            rval += c;
        }
        ++i;
    }

    return rval;
}

// Find a service record, or load it from file. If the service has
// dependencies, load those also.
//
// Might throw a ServiceLoadExc exception if a dependency cycle is found or if another
// problem occurs (I/O error, service description not found etc).
ServiceRecord * ServiceSet::loadServiceRecord(const char * name)
{
    using std::string;
    using std::ifstream;
    using std::ios;
    using std::ios_base;
    using std::locale;
    using std::isspace;

    // First try and find an existing record...
    ServiceRecord * rval = findService(string(name));
    if (rval != 0) {
        if (rval->isDummy()) {
            throw ServiceCyclicDependency(name);
        }
        return rval;
    }

    // Couldn't find one. Have to load it.
    string service_filename = service_dir;
    if (*(service_filename.rbegin()) != '/') {
        service_filename += '/';
    }
    service_filename += name;

    string command;
    int service_type = SVC_PROCESS;
    std::list<ServiceRecord *> depends_on;
    std::list<ServiceRecord *> depends_soft;
    string logfile;

    // TODO catch I/O exceptions, wrap & re-throw?
    string line;
    bool auto_restart = false;
    ifstream service_file;
    service_file.exceptions(ios::badbit | ios::failbit);

    try {
        service_file.open(service_filename.c_str(), ios::in);
    }
    catch (std::ios_base::failure &exc) {
        throw ServiceNotFound(name);
    }

    // Add a dummy service record now to prevent cyclic dependencies
    rval = new ServiceRecord(this, string(name));
    records.push_back(rval);

    // getline can set failbit if it reaches end-of-file, we don't want an exception in that case:
    service_file.exceptions(ios::badbit);

    while (! (service_file.rdstate() & ios::eofbit)) {
        getline(service_file, line);
        string::iterator i = line.begin();
        string::iterator end = line.end();

        i = skipws(i, end);
        if (i != end) {
            if (*i == '#') {
                continue;  // comment line
            }
            string setting = read_setting_name(i, end);
            i = skipws(i, end);
            if (i == end || (*i != '=' && *i != ':')) {
                throw ServiceDescriptionExc(name, "Badly formed line.");
            }
            i = skipws(++i, end);

            if (setting == "command") {
                command = read_setting_value(i, end);
            }
            else if (setting == "depends-on") {
                string dependency_name = read_setting_value(i, end);
                depends_on.push_back(loadServiceRecord(dependency_name.c_str()));
            }
            else if (setting == "waits-for") {
                string dependency_name = read_setting_value(i, end);
                depends_soft.push_back(loadServiceRecord(dependency_name.c_str()));
            }
            else if (setting == "logfile") {
                logfile = read_setting_value(i, end);
            }
            else if (setting == "restart") {
                string restart = read_setting_value(i, end);
                auto_restart = (restart == "yes" || restart == "true");
            }
            else if (setting == "type") {
                string type_str = read_setting_value(i, end);
                if (type_str == "scripted") {
                    service_type = SVC_SCRIPTED;
                }
                else if (type_str == "process") {
                    service_type = SVC_PROCESS;
                }
                else if (type_str == "internal") {
                    service_type = SVC_INTERNAL;
                }
                else {
                    throw ServiceDescriptionExc(name, "Service type must be \"scripted\""
                        " or \"process\" or \"internal\"");
                }
            }
            else {
                throw ServiceDescriptionExc(name, "Unknown setting: " + setting);
            }
        }
    }

    service_file.close();
    // TODO check we actually have all the settings - type, command

    // Now replace the dummy service record with a real record:
    for (auto iter = records.begin(); iter != records.end(); iter++) {
        if (*iter == rval) {
            // We've found the dummy record
            delete rval;
            rval = new ServiceRecord(this, string(name), service_type, command,
                    & depends_on, & depends_soft);
            rval->setLogfile(logfile);
            rval->setAutoRestart(auto_restart);
            *iter = rval;
            break;
        }
    }

    return rval;
}
<commit_msg>Augment read_setting_value so that it can return the position (start and end) of each part of the setting value.<commit_after>#include "service.h"
#include <string>
#include <fstream>
#include <locale>
#include <iostream>

typedef std::string string;
typedef std::string::iterator string_iterator;

// Utility function to skip white space. Returns an iterator at the
// first non-white-space position (or at end).
static string_iterator skipws(string_iterator i, string_iterator end)
{
    using std::locale;
    using std::isspace;

    while (i != end) {
      if (! isspace(*i, locale::classic())) {
        break;
      }
      ++i;
    }
    return i;
}

// Read a setting name.
static string read_setting_name(string_iterator & i, string_iterator end)
{
    using std::locale;
    using std::ctype;
    using std::use_facet;

    const ctype<char> & facet = use_facet<ctype<char> >(locale::classic());

    string rval;
    // Allow alphabetical characters, and dash (-) in setting name
    while (i != end && (*i == '-' || facet.is(ctype<char>::alpha, *i))) {
        rval += *i;
        ++i;
    }
    return rval;
}

// Read a setting value
//
// In general a setting value is a single-line string. It may contain multiple parts
// separated by white space (which is normally collapsed). A hash mark - # - denotes
// the end of the value and the beginning of a comment (it should be preceded by
// whitespace).
//
// Part of a value may be quoted using double quote marks, which prevents collapse
// of whitespace and interpretation of most special characters (the quote marks will
// not be considered part of the value). A backslash can precede a character (such
// as '#' or '"' or another backslash) to remove its special meaning. Newline
// characters are not allowed in values and cannot be quoted.
//
// This function expects the string to be in an ASCII-compatible, single byte
// encoding (the "classic" locale).
static string read_setting_value(string_iterator & i, string_iterator end,
        std::list<std::pair<int,int>> * part_positions = nullptr)
{
    using std::locale;
    using std::isspace;

    i = skipws(i, end);

    string rval;
    bool new_part = true;
    int part_start;

    while (i != end) {
        char c = *i;
        if (c == '\"') {
            if (new_part) {
                part_start = rval.length();
                new_part = false;
            }
            // quoted string
            ++i;
            while (i != end) {
                c = *i;
                if (c == '\"') break;
                if (c == '\n') {
                    // TODO error here.
                }
                else if (c == '\\') {
                    // A backslash escapes the following character.
                    ++i;
                    if (i != end) {
                        c = *i;
                        if (c == '\n') {
                            // TODO error here.
                        }
                        rval += c;
                    }
                }
                else {
                    rval += c;
                }
                ++i;
            }
            if (i == end) {
                // String wasn't terminated
                // TODO error here
                break;
            }
        }
        else if (c == '\\') {
            if (new_part) {
                part_start = rval.length();
                new_part = false;
            }
            // A backslash escapes the next character
            ++i;
            if (i != end) {
                rval += *i;
            }
            else {
                // TODO error here
            }
        }
        else if (isspace(c, locale::classic())) {
            if (! new_part && part_positions != nullptr) {
                part_positions->emplace_back(part_start, rval.length());
                new_part = true;
            }
            i = skipws(i, end);
            if (i == end) break;
            if (*i == '#') break; // comment
            rval += ' ';  // collapse ws to a single space
            continue;
        }
        else if (c == '#') {
            // hmm... comment? Probably, though they should have put a space
            // before it really. TODO throw an exception, and document
            // that '#' for comments must be preceded by space, and in values
            // must be quoted.
            break;
        }
        else {
            if (new_part) {
                part_start = rval.length();
                new_part = false;
            }
            rval += c;
        }
        ++i;
    }

    return rval;
}

// Find a service record, or load it from file. If the service has
// dependencies, load those also.
//
// Might throw a ServiceLoadExc exception if a dependency cycle is found or if another
// problem occurs (I/O error, service description not found etc).
ServiceRecord * ServiceSet::loadServiceRecord(const char * name)
{
    using std::string;
    using std::ifstream;
    using std::ios;
    using std::ios_base;
    using std::locale;
    using std::isspace;

    // First try and find an existing record...
    ServiceRecord * rval = findService(string(name));
    if (rval != 0) {
        if (rval->isDummy()) {
            throw ServiceCyclicDependency(name);
        }
        return rval;
    }

    // Couldn't find one. Have to load it.
    string service_filename = service_dir;
    if (*(service_filename.rbegin()) != '/') {
        service_filename += '/';
    }
    service_filename += name;

    string command;
    int service_type = SVC_PROCESS;
    std::list<ServiceRecord *> depends_on;
    std::list<ServiceRecord *> depends_soft;
    string logfile;

    // TODO catch I/O exceptions, wrap & re-throw?
    string line;
    bool auto_restart = false;
    ifstream service_file;
    service_file.exceptions(ios::badbit | ios::failbit);

    try {
        service_file.open(service_filename.c_str(), ios::in);
    }
    catch (std::ios_base::failure &exc) {
        throw ServiceNotFound(name);
    }

    // Add a dummy service record now to prevent cyclic dependencies
    rval = new ServiceRecord(this, string(name));
    records.push_back(rval);

    // getline can set failbit if it reaches end-of-file, we don't want an exception in that case:
    service_file.exceptions(ios::badbit);

    while (! (service_file.rdstate() & ios::eofbit)) {
        getline(service_file, line);
        string::iterator i = line.begin();
        string::iterator end = line.end();

        i = skipws(i, end);
        if (i != end) {
            if (*i == '#') {
                continue;  // comment line
            }
            string setting = read_setting_name(i, end);
            i = skipws(i, end);
            if (i == end || (*i != '=' && *i != ':')) {
                throw ServiceDescriptionExc(name, "Badly formed line.");
            }
            i = skipws(++i, end);

            if (setting == "command") {
                command = read_setting_value(i, end);
            }
            else if (setting == "depends-on") {
                string dependency_name = read_setting_value(i, end);
                depends_on.push_back(loadServiceRecord(dependency_name.c_str()));
            }
            else if (setting == "waits-for") {
                string dependency_name = read_setting_value(i, end);
                depends_soft.push_back(loadServiceRecord(dependency_name.c_str()));
            }
            else if (setting == "logfile") {
                logfile = read_setting_value(i, end);
            }
            else if (setting == "restart") {
                string restart = read_setting_value(i, end);
                auto_restart = (restart == "yes" || restart == "true");
            }
            else if (setting == "type") {
                string type_str = read_setting_value(i, end);
                if (type_str == "scripted") {
                    service_type = SVC_SCRIPTED;
                }
                else if (type_str == "process") {
                    service_type = SVC_PROCESS;
                }
                else if (type_str == "internal") {
                    service_type = SVC_INTERNAL;
                }
                else {
                    throw ServiceDescriptionExc(name, "Service type must be \"scripted\""
                        " or \"process\" or \"internal\"");
                }
            }
            else {
                throw ServiceDescriptionExc(name, "Unknown setting: " + setting);
            }
        }
    }

    service_file.close();
    // TODO check we actually have all the settings - type, command

    // Now replace the dummy service record with a real record:
    for (auto iter = records.begin(); iter != records.end(); iter++) {
        if (*iter == rval) {
            // We've found the dummy record
            delete rval;
            rval = new ServiceRecord(this, string(name), service_type, command,
                    & depends_on, & depends_soft);
            rval->setLogfile(logfile);
            rval->setAutoRestart(auto_restart);
            *iter = rval;
            break;
        }
    }

    return rval;
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>"
//

#include "MarbleTestPlugin.h"

#include <QtGui/QColor>
#include <QtGui/QPixmap>

#include "MarbleDirs.h"
#include "GeoPainter.h"
#include "GeoDataPoint.h"

QStringList MarbleTestPlugin::backendTypes() const
{
    return QStringList( "test" );
}

QString MarbleTestPlugin::renderPolicy() const
{
    return QString( "ALWAYS" );
}

QString MarbleTestPlugin::renderPosition() const
{
    return QString( "ALWAYS_ON_TOP" );
}

QString MarbleTestPlugin::name() const
{
    return QString( "Test Plugin" );
}

QString MarbleTestPlugin::nameId() const
{
    return QString( "test-plugin" );
}

QString MarbleTestPlugin::description() const
{
    return QString( "This is a simple test plugin." );
}

QIcon MarbleTestPlugin::icon () const
{
    return QIcon();
}

void MarbleTestPlugin::initialize ()
{
}

bool MarbleTestPlugin::isInitialized () const
{
    return true;
}

bool MarbleTestPlugin::render( GeoPainter *painter, ViewportParams *viewport, GeoSceneLayer * layer )
{
    painter->autoMapQuality();

    GeoDataPoint northpole1( 0.0, 90.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint northpole2( 0.0, 90.0, 3000000.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 255, 255, 255, 255 ) );

    painter->drawLine( northpole1, northpole2 );

    GeoDataPoint madrid( -3.7, 40.4, 0.0, GeoDataPoint::Degree );
    GeoDataPoint flensburg( 9.4, 54.8, 0.0, GeoDataPoint::Degree );
    GeoDataPoint linkoeping( 15.6, 58.4, 0.0, GeoDataPoint::Degree );
    GeoDataPoint istanbul( 28.0, 41.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint moscow( 37.6, 55.75, 0.0, GeoDataPoint::Degree );
    GeoDataPoint brasilia( -47.9, -15.75, 0.0, GeoDataPoint::Degree );
    GeoDataPoint orbit( 105.6, 0.0, 3000000.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 200, 200, 200, 255 ) );
    static const GeoDataPoint points[5] = {
        madrid,
        flensburg,
        linkoeping,
        istanbul,
        moscow
    };

    painter->drawPolyline( points, 5 );

    painter->setPen( QColor( 99, 198, 99, 255 ) );
    painter->setBrush( QColor( 99, 198, 99, 80 ) );
    painter->drawEllipse( flensburg, 30, 30 );

    painter->drawText( flensburg, "Torsten" );

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    painter->setBrush( QColor( 198, 99, 99, 80 ) );
    painter->drawEllipse( linkoeping, 40, 40 );

    painter->drawText( linkoeping, "Inge" );

    painter->setPen( QColor( 99, 99, 198, 255 ) );
    painter->setBrush( QColor( 99, 99, 198, 80 ) );
    painter->drawEllipse( orbit, 20, 20 );

    painter->drawText( orbit, "Claudiu" );

    painter->drawPixmap( istanbul, QPixmap( MarbleDirs::path( "bitmaps/earth_apollo.jpg" ) ) );

    painter->drawImage( brasilia, QImage( MarbleDirs::path( "bitmaps/earth_apollo.jpg" ) ) );

    painter->setPen( QColor( 99, 198, 198, 255 ) );
    QBrush brush( QColor( 99, 198, 198, 80 ) );
    painter->setBrush( brush );

    painter->drawRect( madrid, 30, 30 );

    painter->setPen( QColor( 198, 99, 198, 255 ) );
    brush.setColor( QColor( 198, 99, 198, 180 ) );
    brush.setStyle( Qt::DiagCrossPattern );
    painter->setBrush( brush );

    painter->drawRoundRect( moscow, 40, 40 );

    GeoDataPoint m1(-180.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m2(-170.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m3(-160.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m4(-150.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m5(-140.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m6(-130.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m7(-120.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m8(-110.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m9(-100.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m10(-90.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m11(-80.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m12(-70.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m13(-60.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m14(-50.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m15(-40.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m16(-30.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m17(-20.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m18(-10.0, 0.0, 3000000.0, GeoDataPoint::Degree );

    GeoDataPoint m19(0.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m20(10.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m21(20.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m22(30.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m23(40.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m24(50.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m25(60.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m26(70.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m27(80.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m28(90.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m29(100.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m30(110.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m31(120.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m32(130.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m33(140.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m34(150.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m35(160.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m36(170.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m37(180.0, 0.0, 3000000.0, GeoDataPoint::Degree );

    static const GeoDataPoint ring[37] = {
        m1, m2, m3, m4, m5, m6, m7, m8, m9,
        m10, m11, m12, m13, m14, m15, m16, m17, m18, m19,
        m20, m21, m22, m23, m24, m25, m26, m27, m28, m29,
        m30, m31, m32, m33, m34, m35, m36, m37
    };

    painter->drawPolyline( ring, 37 );

    GeoDataPoint t1(0.0, 90.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint t2(-45.0, 60.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint t3(-135.0, 60.0, 0.0, GeoDataPoint::Degree );

    static const GeoDataPoint triangle[3] = {
        t1, t2, t3
    };

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    brush.setColor( QColor( 198, 99, 99, 180 ) );
    brush.setStyle( Qt::FDiagPattern );
    painter->setBrush( brush );

    painter->drawPolygon( triangle, 3 );

    GeoDataPoint sotm(-8.6, 52.66, 0.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    brush.setColor( QColor( 255, 255, 255, 200 ) );
    brush.setStyle( Qt::SolidPattern );
    painter->setBrush( brush );

    painter->drawAnnotation (  sotm, "State of the Map,\n  12-13 July 2008,\n" );

    return true;
}

Q_EXPORT_PLUGIN2(MarbleTestPlugin, MarbleTestPlugin)

#include "MarbleTestPlugin.moc"
<commit_msg>- Some advertizing for aK^WAkademy 2008<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2008 Torsten Rahn <tackat@kde.org>"
//

#include "MarbleTestPlugin.h"

#include <QtGui/QColor>
#include <QtGui/QPixmap>
#include <QtGui/QRadialGradient>
#include "MarbleDirs.h"
#include "GeoPainter.h"
#include "GeoDataPoint.h"

QStringList MarbleTestPlugin::backendTypes() const
{
    return QStringList( "test" );
}

QString MarbleTestPlugin::renderPolicy() const
{
    return QString( "ALWAYS" );
}

QString MarbleTestPlugin::renderPosition() const
{
    return QString( "ALWAYS_ON_TOP" );
}

QString MarbleTestPlugin::name() const
{
    return QString( "Test Plugin" );
}

QString MarbleTestPlugin::nameId() const
{
    return QString( "test-plugin" );
}

QString MarbleTestPlugin::description() const
{
    return QString( "This is a simple test plugin." );
}

QIcon MarbleTestPlugin::icon () const
{
    return QIcon();
}

void MarbleTestPlugin::initialize ()
{
}

bool MarbleTestPlugin::isInitialized () const
{
    return true;
}

bool MarbleTestPlugin::render( GeoPainter *painter, ViewportParams *viewport, GeoSceneLayer * layer )
{
    painter->autoMapQuality();

    GeoDataPoint northpole1( 0.0, 90.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint northpole2( 0.0, 90.0, 3000000.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 255, 255, 255, 255 ) );

    painter->drawLine( northpole1, northpole2 );

    GeoDataPoint madrid( -3.7, 40.4, 0.0, GeoDataPoint::Degree );
    GeoDataPoint flensburg( 9.4, 54.8, 0.0, GeoDataPoint::Degree );
    GeoDataPoint linkoeping( 15.6, 58.4, 0.0, GeoDataPoint::Degree );
    GeoDataPoint istanbul( 28.0, 41.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint moscow( 37.6, 55.75, 0.0, GeoDataPoint::Degree );
    GeoDataPoint brasilia( -47.9, -15.75, 0.0, GeoDataPoint::Degree );
    GeoDataPoint orbit( 105.6, 0.0, 3000000.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 200, 200, 200, 255 ) );
    static const GeoDataPoint points[5] = {
        madrid,
        flensburg,
        linkoeping,
        istanbul,
        moscow
    };

    painter->drawPolyline( points, 5 );

    painter->setPen( QColor( 99, 198, 99, 255 ) );
    painter->setBrush( QColor( 99, 198, 99, 80 ) );
    painter->drawEllipse( flensburg, 30, 30 );

    painter->drawText( flensburg, "Torsten" );

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    painter->setBrush( QColor( 198, 99, 99, 80 ) );
    painter->drawEllipse( linkoeping, 40, 40 );

    painter->drawText( linkoeping, "Inge" );

    painter->setPen( QColor( 99, 99, 198, 255 ) );
    painter->setBrush( QColor( 99, 99, 198, 80 ) );
    painter->drawEllipse( orbit, 20, 20 );

    painter->drawText( orbit, "Claudiu" );

    painter->drawPixmap( istanbul, QPixmap( MarbleDirs::path( "bitmaps/earth_apollo.jpg" ) ) );

    painter->drawImage( brasilia, QImage( MarbleDirs::path( "bitmaps/earth_apollo.jpg" ) ) );

    painter->setPen( QColor( 99, 198, 198, 255 ) );
    QBrush brush( QColor( 99, 198, 198, 80 ) );
    painter->setBrush( brush );

    painter->drawRect( madrid, 30, 30 );

    painter->setPen( QColor( 198, 99, 198, 255 ) );
    brush.setColor( QColor( 198, 99, 198, 180 ) );
    brush.setStyle( Qt::DiagCrossPattern );
    painter->setBrush( brush );

    painter->drawRoundRect( moscow, 40, 40 );

    GeoDataPoint m1(-180.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m2(-170.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m3(-160.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m4(-150.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m5(-140.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m6(-130.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m7(-120.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m8(-110.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m9(-100.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m10(-90.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m11(-80.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m12(-70.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m13(-60.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m14(-50.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m15(-40.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m16(-30.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m17(-20.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m18(-10.0, 0.0, 3000000.0, GeoDataPoint::Degree );

    GeoDataPoint m19(0.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m20(10.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m21(20.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m22(30.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m23(40.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m24(50.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m25(60.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m26(70.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m27(80.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m28(90.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m29(100.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m30(110.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m31(120.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m32(130.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m33(140.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m34(150.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m35(160.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m36(170.0, 0.0, 3000000.0, GeoDataPoint::Degree );
    GeoDataPoint m37(180.0, 0.0, 3000000.0, GeoDataPoint::Degree );

    static const GeoDataPoint ring[37] = {
        m1, m2, m3, m4, m5, m6, m7, m8, m9,
        m10, m11, m12, m13, m14, m15, m16, m17, m18, m19,
        m20, m21, m22, m23, m24, m25, m26, m27, m28, m29,
        m30, m31, m32, m33, m34, m35, m36, m37
    };

    painter->drawPolyline( ring, 37 );

    GeoDataPoint t1(0.0, 90.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint t2(-45.0, 60.0, 0.0, GeoDataPoint::Degree );
    GeoDataPoint t3(-135.0, 60.0, 0.0, GeoDataPoint::Degree );

    static const GeoDataPoint triangle[3] = {
        t1, t2, t3
    };

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    brush.setColor( QColor( 198, 99, 99, 180 ) );
    brush.setStyle( Qt::FDiagPattern );
    painter->setBrush( brush );

    painter->drawPolygon( triangle, 3 );

    GeoDataPoint sotm(-8.6, 52.66, 0.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 198, 99, 99, 255 ) );
    brush.setColor( QColor( 255, 255, 255, 200 ) );
    brush.setStyle( Qt::SolidPattern );
    painter->setBrush( brush );

    painter->drawAnnotation (  sotm, "State of the Map,\n  12-13 July 2008,\n OSM conference" );

    GeoDataPoint akademy2008(4.5, 51.1, 0.0, GeoDataPoint::Degree );

    painter->setPen( QColor( 99, 99, 0 ) );

    QRadialGradient radialGrad(QPointF(100, 100), 100);
    radialGrad.setColorAt(0, QColor( 198, 198, 198, 200 ) );
    radialGrad.setColorAt(0.5, QColor( 199, 198, 99, 200  ) );
    radialGrad.setColorAt( 1, Qt::white );
    radialGrad.setSpread( QGradient::ReflectSpread );

    QBrush gradientBrush( radialGrad );
//    brush.setStyle( Qt::SolidPattern );
    painter->setBrush( gradientBrush );

    painter->drawAnnotation (  akademy2008, "Akademy 2008,\n  9-15 August 2008,\n KDE conference", QSize(130, 120), 10, 30, 15, 15 );

    return true;
}

Q_EXPORT_PLUGIN2(MarbleTestPlugin, MarbleTestPlugin)

#include "MarbleTestPlugin.moc"
<|endoftext|>


<commit_before>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct File
{
    char** lines;
    int lineCount;
    char* startData;
    char* filename;
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct SourceCodeData
{
    uint32_t line;
    File file;  // TODO: support more files
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* readFileFromDisk(const char* file, size_t* size)
{
    size_t fileSize;
    char* data;
    FILE* f = fopen(file, "rb");

    if (!f)
    {
        printf("sourcecode_plugin: Unable to open file %s\n", file);
        return 0;
    }

    fseek(f, 0, SEEK_END);
    fileSize = (size_t)ftell(f);
    fseek(f, 0, SEEK_SET);

    // pad the size a bit so we make sure to have the data null terminated
    data = (char*)malloc(fileSize + 16);
    data[fileSize] = 0;

    if ((fread((void*)data, 1, fileSize, f)) != fileSize)
    {
        free(data);
        fclose(f);
        printf("sourcecode_plugin: Unable to read the whole file %s to memory\n", file);
        return 0;
    }

    *size = fileSize;
    fclose(f);

    return data;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Do not read whole file to memory?
// TODO: Have a cache of files

void parseFile(File* file, const char* filename)
{
    char* target;
    char* targetEnd;
    char** lines;
    size_t size;
    int lineCount = 0;

    if (file->filename)
    {
        if (!strcmp(filename, file->filename))
            return;
    }

    if (!(target = (char*)readFileFromDisk(filename, &size)))
        return;

    if (file->startData)
    {
        free(file->lines);
        free(file->startData);
        free(file->filename);
    }

    file->startData = target;
    targetEnd = target + size;

    // so this is really waste of memory but will do for now

    file->lines = lines = (char**)malloc(sizeof(char*) * size);
    lines[0] = target;
    lineCount++;

    while (target < targetEnd)
    {
        if (*target == '\r')
            *target++ = 0;

        if (*target == '\n')
        {
            *target++ = 0;
            lines[lineCount++] = target;
        }

        target++;
    }

	*target++ = 0;

    file->filename = strdup(filename);
    file->lineCount = lineCount;

    printf("found %d lines in %s\n", lineCount, filename);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)serviceFunc;
    (void)uiFuncs;
    SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
    memset(userData, 0, sizeof(SourceCodeData));

    // TODO: Temp testing code

    parseFile(&userData->file, "examples/crashing_native/crash2.c");

    return userData;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void destroyInstance(void* userData)
{
    free(userData);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void setExceptionLocation(SourceCodeData* data, PDReader* inEvents)
{
    const char* filename;
    uint32_t line;

    // TODO: How to show this? Tell user to switch to disassembly view?

    if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
        return;

    if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
        return;

    printf("filename %s\n", filename);

    parseFile(&data->file, filename);

    data->line = line;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Count how many numbers we have in lineCount

int countNumbers(int maxLineCount)
{
    int count = 0;

    while (maxLineCount != 0)
    {
        maxLineCount /= 10;
        count++;
    }

    return count;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This code will calculate the width of the max line count in the file and use that as the width
// for the line area

static float calcLineAreaWidth(PDUI* uiFuncs, int lineCount)
{
    char lineBuffer[128];
    sprintf(lineBuffer, "%d", lineCount);
    return uiFuncs->getTextWidth(lineBuffer, 0);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLineAreaBG(PDUI* uiFuncs, float areaWidth)
{
    PDVec2 pos = uiFuncs->getCursorPos();
    PDRect rect = { pos.x - 4, pos.y - 14, areaWidth + 4, -1 };
    uiFuncs->fillRect(rect, PD_COLOR_32(100, 100, 100, 127));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLineArea(PDUI* uiFuncs, int offset, int lineCount, int maxLineCount)
{
    char formatString[64];
    int numCount = countNumbers(maxLineCount);
    sprintf(formatString, "%%%dd", numCount);

    for (int i = 0; i < lineCount; ++i)
    {
        uiFuncs->text(formatString, offset + i + 1);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLines(PDUI* uiFuncs, SourceCodeData* data, float lineStart, int offset, int lineCount)
{
    const char** lines = (const char**)data->file.lines;

    for (int i = offset; i < lineCount; ++i)
    {
        uiFuncs->setCursorPosX(lineStart);

        if ((i + 1) == (int)data->line)
        {
            PDRect rect;
            PDVec2 pos = uiFuncs->getCursorPos();
            rect.x = pos.x;
            rect.y = pos.y - 11;
            rect.width = -1;
            rect.height = 14;
            uiFuncs->fillRect(rect, PD_COLOR_32(200, 0, 0, 127));
        }

        uiFuncs->text(lines[i]);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void showInUI(SourceCodeData* data, PDUI* uiFuncs)
{
    uiFuncs->columns(1, "sourceview", true);

    // calculate the range we can show

    PDVec2 textStart = uiFuncs->getCursorPos();
    PDVec2 windowSize = uiFuncs->getWindowSize();
    windowSize.y -= textStart.y;

    const float fontHeight = uiFuncs->getFontHeight();
    int drawableLineCount = (int)(windowSize.y / fontHeight);

    int lineCount = data->file.lineCount;

    // Draw the line

    float areaWidth = calcLineAreaWidth(uiFuncs, lineCount) + 4;

    // if we are fully with in the drawing range we just render as is

    if (lineCount < drawableLineCount)
    {
        drawLineAreaBG(uiFuncs, areaWidth);
        drawLineArea(uiFuncs, 0, lineCount, lineCount);

        uiFuncs->setCursorPos(textStart);

        drawLines(uiFuncs, data, areaWidth + 10, 0, lineCount);
    }
    else
    {
        // We want the breakline to be in the center of the screen so calculate the pos as such

		int lineStart = (int)data->line - drawableLineCount / 2;

		if (lineStart < 0)
			lineStart = 0;

		// Make sure we don't draw too many lines

		if (lineStart + drawableLineCount > lineCount)
			drawableLineCount = lineCount;

        drawLineAreaBG(uiFuncs, areaWidth);
        drawLineArea(uiFuncs, lineStart, drawableLineCount, lineCount);

        uiFuncs->setCursorPos(textStart);

        drawLines(uiFuncs, data, areaWidth + 10, lineStart, drawableLineCount);
    }

    (void)textStart;

    // Draw line column

    uiFuncs->setCursorPos(textStart);

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
    uint32_t event;

    (void)uiFuncs;

    SourceCodeData* data = (SourceCodeData*)userData;

    while ((event = PDRead_getEvent(inEvents)) != 0)
    {
        switch (event)
        {
            case PDEventType_setExceptionLocation:
            {
                setExceptionLocation(data, inEvents);
                break;
            }
        }
    }

    showInUI(data, uiFuncs);

    PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
    PDWrite_u8(writer, "dummy", 0); // TODO: Remove me
    PDWrite_eventEnd(writer);

    //uiFuncs->button("test test");
    //uiFuncs->text("funy text %f", 12.02f);

    return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static PDViewPlugin plugin =
{
    "Source Code View",
    createInstance,
    destroyInstance,
    update,
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

extern "C"
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
    {
        registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<commit_msg>Removed spam<commit_after>#include <pd_view.h>
#include <pd_backend.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct File
{
    char** lines;
    int lineCount;
    char* startData;
    char* filename;
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

struct SourceCodeData
{
    uint32_t line;
    File file;  // TODO: support more files
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* readFileFromDisk(const char* file, size_t* size)
{
    size_t fileSize;
    char* data;
    FILE* f = fopen(file, "rb");

    if (!f)
    {
        printf("sourcecode_plugin: Unable to open file %s\n", file);
        return 0;
    }

    fseek(f, 0, SEEK_END);
    fileSize = (size_t)ftell(f);
    fseek(f, 0, SEEK_SET);

    // pad the size a bit so we make sure to have the data null terminated
    data = (char*)malloc(fileSize + 16);
    data[fileSize] = 0;

    if ((fread((void*)data, 1, fileSize, f)) != fileSize)
    {
        free(data);
        fclose(f);
        printf("sourcecode_plugin: Unable to read the whole file %s to memory\n", file);
        return 0;
    }

    *size = fileSize;
    fclose(f);

    return data;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TODO: Do not read whole file to memory?
// TODO: Have a cache of files

void parseFile(File* file, const char* filename)
{
    char* target;
    char* targetEnd;
    char** lines;
    size_t size;
    int lineCount = 0;

    if (file->filename)
    {
        if (!strcmp(filename, file->filename))
            return;
    }

    if (!(target = (char*)readFileFromDisk(filename, &size)))
        return;

    if (file->startData)
    {
        free(file->lines);
        free(file->startData);
        free(file->filename);
    }

    file->startData = target;
    targetEnd = target + size;

    // so this is really waste of memory but will do for now

    file->lines = lines = (char**)malloc(sizeof(char*) * size);
    lines[0] = target;
    lineCount++;

    while (target < targetEnd)
    {
        if (*target == '\r')
            *target++ = 0;

        if (*target == '\n')
        {
            *target++ = 0;
            lines[lineCount++] = target;
        }

        target++;
    }

	*target++ = 0;

    file->filename = strdup(filename);
    file->lineCount = lineCount;

    printf("found %d lines in %s\n", lineCount, filename);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void* createInstance(PDUI* uiFuncs, ServiceFunc* serviceFunc)
{
    (void)serviceFunc;
    (void)uiFuncs;
    SourceCodeData* userData = (SourceCodeData*)malloc(sizeof(SourceCodeData));
    memset(userData, 0, sizeof(SourceCodeData));

    // TODO: Temp testing code

    parseFile(&userData->file, "examples/crashing_native/crash2.c");

    return userData;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void destroyInstance(void* userData)
{
    free(userData);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void setExceptionLocation(SourceCodeData* data, PDReader* inEvents)
{
    const char* filename;
    uint32_t line;

    // TODO: How to show this? Tell user to switch to disassembly view?

    if (PDRead_findString(inEvents, &filename, "filename", 0) == PDReadStatus_notFound)
        return;

    if (PDRead_findU32(inEvents, &line, "line", 0) == PDReadStatus_notFound)
        return;

    parseFile(&data->file, filename);

    data->line = line;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Count how many numbers we have in lineCount

int countNumbers(int maxLineCount)
{
    int count = 0;

    while (maxLineCount != 0)
    {
        maxLineCount /= 10;
        count++;
    }

    return count;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// This code will calculate the width of the max line count in the file and use that as the width
// for the line area

static float calcLineAreaWidth(PDUI* uiFuncs, int lineCount)
{
    char lineBuffer[128];
    sprintf(lineBuffer, "%d", lineCount);
    return uiFuncs->getTextWidth(lineBuffer, 0);
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLineAreaBG(PDUI* uiFuncs, float areaWidth)
{
    PDVec2 pos = uiFuncs->getCursorPos();
    PDRect rect = { pos.x - 4, pos.y - 14, areaWidth + 4, -1 };
    uiFuncs->fillRect(rect, PD_COLOR_32(100, 100, 100, 127));
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLineArea(PDUI* uiFuncs, int offset, int lineCount, int maxLineCount)
{
    char formatString[64];
    int numCount = countNumbers(maxLineCount);
    sprintf(formatString, "%%%dd", numCount);

    for (int i = 0; i < lineCount; ++i)
    {
        uiFuncs->text(formatString, offset + i + 1);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void drawLines(PDUI* uiFuncs, SourceCodeData* data, float lineStart, int offset, int lineCount)
{
    const char** lines = (const char**)data->file.lines;

    for (int i = offset; i < lineCount; ++i)
    {
        uiFuncs->setCursorPosX(lineStart);

        if ((i + 1) == (int)data->line)
        {
            PDRect rect;
            PDVec2 pos = uiFuncs->getCursorPos();
            rect.x = pos.x;
            rect.y = pos.y - 11;
            rect.width = -1;
            rect.height = 14;
            uiFuncs->fillRect(rect, PD_COLOR_32(200, 0, 0, 127));
        }

        uiFuncs->text(lines[i]);
    }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static void showInUI(SourceCodeData* data, PDUI* uiFuncs)
{
    uiFuncs->columns(1, "sourceview", true);

    // calculate the range we can show

    PDVec2 textStart = uiFuncs->getCursorPos();
    PDVec2 windowSize = uiFuncs->getWindowSize();
    windowSize.y -= textStart.y;

    const float fontHeight = uiFuncs->getFontHeight();
    int drawableLineCount = (int)(windowSize.y / fontHeight);

    int lineCount = data->file.lineCount;

    // Draw the line

    float areaWidth = calcLineAreaWidth(uiFuncs, lineCount) + 4;

    // if we are fully with in the drawing range we just render as is

    if (lineCount < drawableLineCount)
    {
        drawLineAreaBG(uiFuncs, areaWidth);
        drawLineArea(uiFuncs, 0, lineCount, lineCount);

        uiFuncs->setCursorPos(textStart);

        drawLines(uiFuncs, data, areaWidth + 10, 0, lineCount);
    }
    else
    {
        // We want the breakline to be in the center of the screen so calculate the pos as such

		int lineStart = (int)data->line - drawableLineCount / 2;

		if (lineStart < 0)
			lineStart = 0;

		// Make sure we don't draw too many lines

		if (lineStart + drawableLineCount > lineCount)
			drawableLineCount = lineCount;

        drawLineAreaBG(uiFuncs, areaWidth);
        drawLineArea(uiFuncs, lineStart, drawableLineCount, lineCount);

        uiFuncs->setCursorPos(textStart);

        drawLines(uiFuncs, data, areaWidth + 10, lineStart, drawableLineCount);
    }

    (void)textStart;

    // Draw line column

    uiFuncs->setCursorPos(textStart);

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static int update(void* userData, PDUI* uiFuncs, PDReader* inEvents, PDWriter* writer)
{
    uint32_t event;

    (void)uiFuncs;

    SourceCodeData* data = (SourceCodeData*)userData;

    while ((event = PDRead_getEvent(inEvents)) != 0)
    {
        switch (event)
        {
            case PDEventType_setExceptionLocation:
            {
                setExceptionLocation(data, inEvents);
                break;
            }
        }
    }

    showInUI(data, uiFuncs);

    PDWrite_eventBegin(writer, PDEventType_getExceptionLocation);
    PDWrite_u8(writer, "dummy", 0); // TODO: Remove me
    PDWrite_eventEnd(writer);

    //uiFuncs->button("test test");
    //uiFuncs->text("funy text %f", 12.02f);

    return 0;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

static PDViewPlugin plugin =
{
    "Source Code View",
    createInstance,
    destroyInstance,
    update,
};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

extern "C"
{

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    PD_EXPORT void InitPlugin(RegisterPlugin* registerPlugin, void* privateData)
    {
        registerPlugin(PD_VIEW_API_VERSION, &plugin, privateData);
    }

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}

<|endoftext|>


<commit_before>#include <bravo/argv_parser.h>

using namespace bravo;

class cmd_line_parser : public argv_parser
{
public:
    cmd_line_parser()
    {
        flag_defs["o"]          = AP_REQUIRED_ARG;
        flag_defs["output"]     = AP_REQUIRED_ARG;
        flag_defs["h"]          = AP_NO_ARG;
        flag_defs["help"]       = AP_NO_ARG;
        flag_defs["v"]          = AP_NO_ARG;
        flag_defs["version"]    = AP_NO_ARG;
        flag_defs["verbose"]    = AP_NO_ARG;

        usage_ = "usage:\nbaretta url";
    }
};

cmd_line_parser cmd_line;

int main(int argc, const char *argv[])
{
    cmd_line.parse(argc,argv);

    return 0;
}
<commit_msg>Added license info.<commit_after>/*******************************************************************************
 MIT License

 Copyright (c) 2017 Mark Elrod

 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 <bravo/argv_parser.h>

using namespace bravo;

class cmd_line_parser : public argv_parser
{
public:
    cmd_line_parser()
    {
        flag_defs["o"]          = AP_REQUIRED_ARG;
        flag_defs["output"]     = AP_REQUIRED_ARG;
        flag_defs["h"]          = AP_NO_ARG;
        flag_defs["help"]       = AP_NO_ARG;
        flag_defs["v"]          = AP_NO_ARG;
        flag_defs["version"]    = AP_NO_ARG;
        flag_defs["verbose"]    = AP_NO_ARG;

        usage_ = "usage:\nbaretta url";
    }
};

cmd_line_parser cmd_line;

int main(int argc, const char *argv[])
{
    cmd_line.parse(argc,argv);

    return 0;
}
<|endoftext|>