/*
**************************************************************************
                                 description
                             --------------------
    copyright            : (C) 2002 by Andreas Zehender
    email                : zehender@kde.org
**************************************************************************

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


#include "pmblobcylinder.h"

#include "pmoutputdevice.h"
#include "pmxmlhelper.h"
#include "pmboxedit.h"
#include "pmmemento.h"
#include "pm3dcontrolpoint.h"
#include "pmdefaults.h"
#include "pmdistancecontrolpoint.h"
#include "pmblobcylinderedit.h"

#include <kdebug.h>
#include "pmglobals.h"

#include <klocale.h>


const double c_defaultRadius = 0.5;
const PMVector c_defaultEnd1 = PMVector ( 0, 0.5, 0 );
const PMVector c_defaultEnd2 = PMVector ( 0, -0.5, 0 );
const double c_defaultStrength = 1.0;

/** default cylinder structure */
PMViewStructure* PMBlobCylinder::s_pDefaultViewStructure = 0;
int PMBlobCylinder::s_vStep = c_defaultBlobCylinderVSteps;
int PMBlobCylinder::s_uStep = c_defaultBlobCylinderUSteps;
int PMBlobCylinder::s_parameterKey = 0;


PMBlobCylinder::PMBlobCylinder( )
      :Base( )
{
   m_end1 = c_defaultEnd1;
   m_end2 = c_defaultEnd2;
   m_radius = c_defaultRadius;
   m_strength = c_defaultStrength;
}

PMBlobCylinder::~PMBlobCylinder( )
{
}

QString PMBlobCylinder::description( ) const
{
   return i18n( "blob cylinder" );
}

void PMBlobCylinder::serialize( PMOutputDevice& dev ) const
{
   dev.objectBegin( "cylinder" );

   serializeName( dev );
   QString str1;
   str1.setNum( m_radius );
   dev.writeLine( m_end1.serialize( ) + ", " + m_end2.serialize( )
                  + ", " + str1 + "," );
   dev.writeLine( QString( "strength %1" ).arg( m_strength ) );
   
   Base::serialize( dev );
   dev.objectEnd( );
}

void PMBlobCylinder::serialize( QDomElement& e, QDomDocument& doc ) const
{
   e.setAttribute( "end_a", m_end1.serializeXML( ) );
   e.setAttribute( "end_b", m_end2.serializeXML( ) );
   e.setAttribute( "radius", m_radius );
   e.setAttribute( "strength", m_strength );
   Base::serialize( e, doc );
}

void PMBlobCylinder::readAttributes( const PMXMLHelper& h )
{
   m_end1 = h.vectorAttribute( "end_a", c_defaultEnd1 );
   m_end2 = h.vectorAttribute( "end_b", c_defaultEnd2 );
   m_radius = h.doubleAttribute( "radius", c_defaultRadius );
   m_strength = h.doubleAttribute( "strength", c_defaultStrength );
   Base::readAttributes( h );
}

bool PMBlobCylinder::isA( PMObjectType t ) const
{
   if( t == PMTBlobCylinder )
      return true;
   return Base::isA( t );
}

void PMBlobCylinder::setEnd1( const PMVector& p )
{
   if( p != m_end1 )
   {
      if( m_pMemento )
         m_pMemento->addData( PMTBlobCylinder, PMEnd1ID, m_end1 );
      m_end1 = p;
      m_end1.resize( 3 );
      setViewStructureChanged( );
   }
}

void PMBlobCylinder::setEnd2( const PMVector& p )
{
   if( p != m_end2 )
   {
      if( m_pMemento )
         m_pMemento->addData( PMTBlobCylinder, PMEnd2ID, m_end2 );
      m_end2 = p;
      m_end2.resize( 3 );
      setViewStructureChanged( );
   }
}

void PMBlobCylinder::setRadius( double radius )
{
   if( m_radius != radius )
   {
      if( m_pMemento )
        m_pMemento->addData( PMTBlobCylinder, PMRadiusID, m_radius );
      m_radius = radius;
      setViewStructureChanged( );
   }
}

void PMBlobCylinder::setStrength( double s )
{
   if( s != m_strength )
   {
      if( m_pMemento )
         m_pMemento->addData( PMTBlobCylinder, PMStrengthID, m_strength );
      m_strength = s;
   }
}

PMDialogEditBase* PMBlobCylinder::editWidget( QWidget* parent ) const
{
   return new PMBlobCylinderEdit( parent );
}

void PMBlobCylinder::restoreMemento( PMMemento* s )
{
   PMMementoDataIterator it( s );
   PMMementoData* data;

   for( ; it.current( ); ++it )
   {
      data = it.current( );
      if( data->objectType( ) == PMTBlobCylinder )
      {
         switch( data->valueID( ) )
         {
            case PMEnd1ID:
               setEnd1( data->vectorData( ) );
               break;
            case PMEnd2ID:
               setEnd2( data->vectorData( ) );
               break;
            case PMRadiusID:
               setRadius( data->doubleData( ) );
               break;
            case PMStrengthID:
               setStrength( data->doubleData( ) );
               break;
            default:
               kdError( PMArea ) << "Wrong ID in PMBlobCylinder::restoreMemento\n";
               break;
         }
      }
   }
   Base::restoreMemento( s );
}

bool PMBlobCylinder::isDefault( )
{
   if( ( m_end1 == c_defaultEnd1 ) && ( m_end2 == c_defaultEnd2 )
       && ( m_radius == c_defaultRadius ) )
      return true;
   return false;
}

void PMBlobCylinder::createViewStructure( )
{
   if( !m_pViewStructure )
   {
      m_pViewStructure = new PMViewStructure( defaultViewStructure ( ) );
      m_pViewStructure->points( ).detach( );
   }

   createPoints( m_pViewStructure->points( ), m_end1, m_end2, m_radius );
}

PMViewStructure* PMBlobCylinder::defaultViewStructure( ) const
{
   if( !s_pDefaultViewStructure )
   {
      int u, v;

      s_pDefaultViewStructure =
         new PMViewStructure( s_vStep * s_uStep * 2 + 2,
                              s_vStep * s_uStep * 4 + s_vStep );
      
      PMLineArray& lines = s_pDefaultViewStructure->lines( );
      
   
      // points
      createPoints( s_pDefaultViewStructure->points( ), c_defaultEnd1,
                    c_defaultEnd2, c_defaultRadius );

      int offset = 0;

      // horizontal lines
      for( u = 0; u < ( s_uStep * 2 ); u++ )
      {
         for( v = 0; v < ( s_vStep - 1 ); v++ )
            lines[offset + v] =
               PMLine( u * s_vStep + v + 1, u * s_vStep + v + 2 );
         lines[offset + s_vStep - 1] =
            PMLine( u * s_vStep + 1, u * s_vStep + s_vStep );
         
         offset += s_vStep;
      }

      // vertical lines
      // lines at the "north pole"
      for( v = 0; v < s_vStep; v++ )
         lines[offset + v] = PMLine( 0, v + 1 );
      offset += s_vStep;

      for( v = 0; v < s_vStep; v++ )
      {
         for( u = 0; u < ( 2 * s_uStep - 1 ); u++ )
         {
            lines[offset + u] =
               PMLine( u * s_vStep + v + 1, ( u + 1 ) * s_vStep + v + 1 );
         }
         offset += ( 2 * s_uStep - 1 );
      }
      // lines at the "south pole"
      for( v = 0; v < s_vStep; v++ )
         lines[offset + v] = PMLine( ( 2 * s_uStep - 1 ) * s_vStep + v + 1,
                                     2 * s_uStep * s_vStep + 1 );
      // offset += s_vStep;
   }
   return s_pDefaultViewStructure;
}

void PMBlobCylinder::createPoints( PMPointArray& points, const PMVector& end1,
                                   const PMVector& end2, double radius )
{
   double uRadStep = M_PI / s_uStep / 2.0;
   double vRadStep = 2 * M_PI / s_vStep;
   double du = uRadStep;

   if( radius < 0 )
      radius = -radius;
   
   PMVector pointAt = end2 - end1;
   double pl = pointAt.abs( );
   if( approxZero( pl ) )
      pointAt = PMVector( 0.0, 0.0, 1.0 );
   else
      pointAt /= pl;

   PMMatrix rotation = PMMatrix::rotation( pointAt, vRadStep );
   PMVector ortho = pointAt.orthogonal( );
   ortho /= ortho.abs( );

   points[0] = PMPoint( end1 - pointAt * radius );
   points[s_vStep * s_uStep * 2 + 1] = PMPoint( end2 + pointAt * radius );
   
   int u, v;
   for( u = 0; u < s_uStep; u++ )
   {
      PMVector end = ortho * radius * sin( du );
      PMVector pv = pointAt * radius * cos( du );
      PMVector e1 = end1 - pv;
      PMVector e2 = end2 + pv;

      for( v = 0; v < s_vStep; v++ )
      {
         points[u * s_vStep + v + 1] = PMPoint( e1 + end );
         points[s_vStep * s_uStep * 2 - ( u + 1 ) * s_vStep + v + 1]
            = PMPoint( e2 + end );
         end = rotation * end;
      }
      du += uRadStep;
   }
}

void PMBlobCylinder::controlPoints( PMControlPointList & list )
{
   PMVector center, angle1, angle2;
   center = m_end1 - m_end2;
   double pl = center.abs( );
   if( approxZero( pl ) )
      center = PMVector( 0.0, 1.0, 0.0 );
   else
      center /= pl;

   angle1 = center.orthogonal( );
   angle2 = PMVector::cross( center, angle1 );

   PM3DControlPoint* pb = new PM3DControlPoint( m_end1, PMEnd1ID, i18n( "End 1" ) );
   list.append( pb );
   list.append( new PM3DControlPoint( m_end2, PMEnd2ID, i18n( "End 2" ) ) );
   list.append( new PMDistanceControlPoint( pb, angle1, m_radius, PMRadiusID, i18n( "Radius (1)" ) ) );
   list.append( new PMDistanceControlPoint( pb, angle2, m_radius, PMRadiusID, i18n( "Radius (2)" ) ) );
}


void PMBlobCylinder::controlPointsChanged( PMControlPointList & list )
{
   PMControlPoint* p;
   bool pointChanged = false;
   bool radiusChanged = false;

   for( p = list.first( ); p; p = list.next( ) )
   {
      if( p->changed( ) )
      {
         switch( p->id( ) )
         {
            case PMEnd1ID:
               setEnd1( ( ( PM3DControlPoint *) p)->point( ) );
               pointChanged = true;
               break;
            case PMEnd2ID:
               setEnd2( ( ( PM3DControlPoint *) p)->point( ) );
               pointChanged = true;
               break;
            case PMRadiusID:
               setRadius( ( ( PMDistanceControlPoint *) p)->distance( ) );
               radiusChanged = true;
               break;
            default:
               kdError( PMArea ) << "Wrong ID in PMBlobCylinder::controlPointsChanged\n";
               break;
         }
      }
   }

   if( pointChanged )
   {
      PMVector center, angle1, angle2;
      bool firstPoint = true;

      center = m_end1 - m_end2;
      double pl = center.abs( );
      if( approxZero( pl ) )
         center = PMVector( 0.0, 1.0, 0.0 );
      else
        center /= pl;

      angle1 = center.orthogonal( );
      angle2 = PMVector::cross( center, angle1 );

      for( p = list.first( ); p; p = list.next( ) )
         if( p->id( ) == PMRadiusID )
         {
            if( firstPoint )
            {
               ( ( PMDistanceControlPoint *) p)->setDirection( angle1 );
               firstPoint = false;
            }
            else
               ( ( PMDistanceControlPoint *) p)->setDirection( angle2 );
         }
    }

   if( radiusChanged )
     for( p = list.first( ); p; p = list.next( ) )
        if( p->id( ) == PMRadiusID )
           ( ( PMDistanceControlPoint *) p)->setDistance( m_radius );
}

bool PMBlobCylinder::canInsert( PMObjectType t, const PMObject*,
                                const PMObjectList* ) const
{
   switch( t )
   {
      case PMTComment:
      case PMTRaw:
      case PMTTranslate:
      case PMTRotate:
      case PMTScale:
      case PMTMatrix:
      case PMTTexture:
      case PMTPigment:
      case PMTNormal:
      case PMTFinish:
         return true;
         break;
      default:
         break;
   }
   return false;
}

void PMBlobCylinder::setUSteps( int u )
{
   if( u >= 2 )
   {
      s_uStep = u;
      if( s_pDefaultViewStructure )
      {
         delete s_pDefaultViewStructure;
         s_pDefaultViewStructure = 0;
      }
   }
   else
      kdDebug( PMArea ) << "PMBlobCylinder::setUSteps: U must be greater than 1\n";
   s_parameterKey++;
}

void PMBlobCylinder::setVSteps( int v )
{
   if( v >= 4 )
   {
      s_vStep = v;
      if( s_pDefaultViewStructure )
      {
         delete s_pDefaultViewStructure;
         s_pDefaultViewStructure = 0;
      }
   }
   else
      kdDebug( PMArea ) << "PMBlobCylinder::setVSteps: V must be greater than 3\n";
   s_parameterKey++;
}

void PMBlobCylinder::cleanUp( ) const
{
   if( s_pDefaultViewStructure )
      delete s_pDefaultViewStructure;
   s_pDefaultViewStructure = 0;
   Base::cleanUp( );
}
