summaryrefslogtreecommitdiffstats
path: root/tdescreensaver/kdesavers/pendulum.cpp
blob: 83f77d70c9761b078ac73f15103f76968317c138 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//============================================================================
//
// KPendulum screen saver for TDE
//
// The screen saver displays a physically realistic simulation of a two-part
// pendulum.
//
// Developed by Georg Drenkhahn, georg-d@users.sourceforge.net
//
// $Id$
//
/*
 * Copyright (C) 2004 Georg Drenkhahn
 *
 * KRotation is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 2 as published by the
 * Free Software Foundation.
 *
 * KRotation 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02110-1301 USA
 */
//============================================================================

// std. C++ headers
#include <cstdlib>

// TQt headers
#include <tqlineedit.h>
#include <tqspinbox.h>
#include <tqvalidator.h>
#include <tqcolordialog.h>
#include <tqpushbutton.h>
#include <tqtooltip.h>
// TDE headers
#include <tdelocale.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <tdemessagebox.h>

#include "sspreviewarea.h"

// pendulum.moc includes pendulum.h
#include "pendulum.moc"

#define KPENDULUM_VERSION "1.1"

// libtdescreensaver interface
extern "C"
{
   /// application name for libtdescreensaver interface
   KDE_EXPORT const char *kss_applicationName = "kpendulum.kss";
   /// application description for libtdescreensaver interface
   KDE_EXPORT const char *kss_description = I18N_NOOP("Simulation of\
 a two-part pendulum");
   /// application version for libtdescreensaver interface
   KDE_EXPORT const char *kss_version = KPENDULUM_VERSION;

   /// function to create screen saver object
   KDE_EXPORT KScreenSaver* kss_create(WId id)
   {
      return new KPendulumSaver(id);
   }

   /// function to create setup dialog for screen saver
   KDE_EXPORT TQDialog* kss_setup()
   {
      return new KPendulumSetup();
   }
}

//-----------------------------------------------------------------------------
// PendulumOdeSolver
//-----------------------------------------------------------------------------

PendulumOdeSolver::PendulumOdeSolver(
   const double &_t,
   const double &_dt,
   std::valarray<double> &_y,
   const double &_eps,
   const double &_m1,
   const double &_m2,
   const double &_l1,
   const double &_l2,
   const double &_g)
   : RkOdeSolver<double>(_t,_y,_dt,_eps),
     A(1.0/(_m2*_l1*_l1)),
     B1(_m2*_l1*_l2),           // constants for faster numeric calculation
     B(1.0/B1),                 // derived from m1,m2,l1,l2,g
     C((_m1+_m2)/(_m2*_m2*_l2*_l2)),
     D(_g*(_m1+_m2)*_l1),
     E(_g*_m2*_l2),
     M((_m1+_m2)/_m2)
{
}

std::valarray<double> PendulumOdeSolver::f(
   const double &x,
   const std::valarray<double> &y) const
{
   (void)x; // unused

   const double& q1 = y[0];
   const double& q2 = y[1];
   const double& p1 = y[2];
   const double& p2 = y[3];

   const double cosDq = std::cos(q1-q2);
   const double iden  = 1.0/(M - cosDq*cosDq); // invers denominator
   const double dq1dt = (A*p1 - B*cosDq*p2)*iden;
   const double dq2dt = (C*p2 - B*cosDq*p1)*iden;

   std::valarray<double> ypr(y.size());
   ypr[0] = dq1dt;
   ypr[1] = dq2dt;

   const double K = B1 * dq1dt*dq2dt * std::sin(q1-q2);
   ypr[2] = -K - D * std::sin(q1);
   ypr[3] =  K - E * std::sin(q2);

   return ypr;
}

//-----------------------------------------------------------------------------
// Rotation: screen saver widget
//-----------------------------------------------------------------------------

PendulumGLWidget::PendulumGLWidget(TQWidget* parent, const char* name)
   : TQGLWidget(parent, name),
     eyeR(30),                  // eye coordinates (polar)
     eyeTheta(M_PI*0.45),
     eyePhi(0),
     lightR(eyeR),              // light coordinates (polar)
     lightTheta(M_PI*0.25),
     lightPhi(M_PI*0.25),
     quadM1(gluNewQuadric()),
     m_barColor(KPendulumSaver::barColorDefault),
     m_m1Color(KPendulumSaver::m1ColorDefault),
     m_m2Color(KPendulumSaver::m2ColorDefault)
{
}

PendulumGLWidget::~PendulumGLWidget(void)
{
   gluDeleteQuadric(quadM1);
}

void PendulumGLWidget::setEyePhi(double phi)
{
   eyePhi = phi;
   while (eyePhi < 0)      eyePhi += 2.*M_PI;
   while (eyePhi > 2*M_PI) eyePhi -= 2.*M_PI;

   // get the view port
   static GLint vp[4];
   glGetIntegerv(GL_VIEWPORT, vp);
   // calc new perspective, a resize event is simulated here
   resizeGL(static_cast<int>(vp[2]), static_cast<int>(vp[3]));
}

void PendulumGLWidget::setAngles(const double& q1, const double& q2)
{
   ang1 = static_cast<GLfloat>(q1*180./M_PI);
   ang2 = static_cast<GLfloat>(q2*180./M_PI);
}

void PendulumGLWidget::setMasses(const double& m1, const double& m2)
{
   sqrtm1 = static_cast<GLfloat>(sqrt(m1));
   sqrtm2 = static_cast<GLfloat>(sqrt(m2));
}

void PendulumGLWidget::setLengths(const double& _l1, const double& _l2)
{
   l1 = static_cast<GLfloat>(_l1);
   l2 = static_cast<GLfloat>(_l2);
}

void PendulumGLWidget::setBarColor(const TQColor& c)
{
   if (c.isValid())
   {
      m_barColor = c;
   }
}

void PendulumGLWidget::setM1Color(const TQColor& c)
{
   if (c.isValid())
   {
      m_m1Color = c;
   }
}
void PendulumGLWidget::setM2Color(const TQColor& c)
{
   if (c.isValid())
   {
      m_m2Color = c;
   }
}

/* --------- protected methods ----------- */

void PendulumGLWidget::initializeGL(void)
{
   qglClearColor(TQColor(black)); // set color to clear the background

   glClearDepth(1);             // depth buffer setup
   glEnable(GL_DEPTH_TEST);     // depth testing
   glDepthFunc(GL_LEQUAL);      // type of depth test

   glShadeModel(GL_SMOOTH);     // smooth color shading in poygons

   // nice perspective calculation
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

   // set up the light
   glEnable(GL_LIGHTING);
   glEnable(GL_LIGHT0);
   glEnable(GL_LIGHT1);

   glMatrixMode(GL_MODELVIEW);           // select modelview matrix
   glLoadIdentity();
   // set positon of light0
   GLfloat lightPos[4]=
      {(GLfloat)(lightR * sin(lightTheta) * sin(lightPhi)),
       (GLfloat)(lightR * sin(lightTheta) * cos(lightPhi)),
       (GLfloat)(lightR * cos(lightTheta)),
       0};
   glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
   // set positon of light1
   lightPos[0] = lightR * sin(lightTheta) * sin(lightPhi+M_PI);
   lightPos[1] = lightR * sin(lightTheta) * cos(lightPhi+M_PI);
   glLightfv(GL_LIGHT1, GL_POSITION, lightPos);

   // only for lights #>0
   GLfloat spec[]={1,1,1,1};
   glLightfv(GL_LIGHT1, GL_SPECULAR, spec);
   glLightfv(GL_LIGHT1, GL_DIFFUSE, spec);

   // enable setting the material colour by glColor()
   glEnable(GL_COLOR_MATERIAL);

   GLfloat emi[4] = {.13, .13, .13, 1};
   glMaterialfv(GL_FRONT, GL_EMISSION, emi);
}

void PendulumGLWidget::paintGL(void)
{
   // clear color and depth buffer
   glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

   glMatrixMode(GL_MODELVIEW);           // select modelview matrix

   glLoadIdentity();

   static const GLfloat width     = 2.0;
   static const GLfloat masswidth = 1.0;
   static const int noOfSlices    = 20;

   // top axis, left (x>0)
   glTranslatef(0.5*width, 0, 0);
   glRotatef(90, 0, 1, 0);
   qglColor(m_barColor);
   gluCylinder(quadM1, 0.2, 0.2, 5, 10, 1);
   gluSphere(quadM1, 0.2, 10, 10);
   // top axis, right
   glLoadIdentity();
   glTranslatef(-0.5*width, 0, 0);
   glRotatef(-90, 0, 1, 0);
   gluCylinder(quadM1, 0.2, 0.2, 5, 10, 1);
   gluSphere(quadM1, 0.2, 10, 10);
   // 1. part, left
   glLoadIdentity();
   glRotatef(ang1, 1, 0, 0);
   glPushMatrix();
   glTranslatef(0.5*width, 0, -l1);
   gluCylinder(quadM1, 0.2, 0.2, l1, 10, 1);
   glPopMatrix();

   // 1. part, right
   glPushMatrix();
   glTranslatef(-0.5*width, 0, -l1);
   gluCylinder(quadM1, 0.2, 0.2, l1, 10, 1);
   // 1. part, bottom
   glRotatef(90, 0, 1, 0);
   gluSphere(quadM1, 0.2, 10, 10); // bottom corner 1
   gluCylinder(quadM1, 0.2, 0.2, width, 10, 1); // connection
   glTranslatef(0, 0, 0.5*(width-masswidth));
   qglColor(m_m1Color);
   gluCylinder(quadM1, sqrtm1, sqrtm1, masswidth, noOfSlices, 1); // mass 1
   gluQuadricOrientation(quadM1, GLU_INSIDE);
   gluDisk(quadM1, 0, sqrtm1, noOfSlices,1); // bottom of mass
   gluQuadricOrientation(quadM1, GLU_OUTSIDE);
   glTranslatef(0, 0, masswidth);
   gluDisk(quadM1, 0, sqrtm1, noOfSlices,1); // top of mass

   glTranslatef(0, 0, 0.5*(width-masswidth));
   qglColor(m_barColor);
   gluSphere(quadM1, 0.2, 10, 10); // bottom corner 2
   glPopMatrix();

   // 2. pendulum bar
   glLoadIdentity();
   glTranslatef(0, l1*std::sin(ang1*M_PI/180.), -l1*std::cos(ang1*M_PI/180.));
   glRotatef(ang2, 1, 0, 0);
   glTranslatef(0, 0, -l2);
   qglColor(m_barColor);
   gluCylinder(quadM1, 0.2, 0.2, l2, 10, 1);

   // mass 2
   glRotatef(90, 0, 1, 0);
   glTranslatef(0, 0, -0.5*masswidth);
   qglColor(m_m2Color);
   gluCylinder(quadM1, sqrtm2, sqrtm2, masswidth, noOfSlices, 1);
   gluQuadricOrientation(quadM1, GLU_INSIDE);
   gluDisk(quadM1, 0, sqrtm2, noOfSlices,1); // bottom of mass
   gluQuadricOrientation(quadM1, GLU_OUTSIDE);
   glTranslatef(0, 0, masswidth);
   gluDisk(quadM1, 0, sqrtm2, noOfSlices,1); // top of mass

   glFlush();
}

void PendulumGLWidget::resizeGL(int w, int h)
{
   // Prevent a divide by zero
   if (h == 0) h = 1;

   // set the new view port
   glViewport(0, 0, static_cast<GLint>(w), static_cast<GLint>(h));

   // set up projection matrix
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   // Perspective view
   gluPerspective(40.0f,
                  static_cast<GLdouble>(w)/static_cast<GLdouble>(h),
                  1.0, 100.0f);

   // Viewing transformation, position for better view
   // Theta is polar angle 0<Theta<Pi
   gluLookAt(
      eyeR * sin(eyeTheta) * sin(eyePhi),
      eyeR * sin(eyeTheta) * cos(eyePhi),
      eyeR * cos(eyeTheta),
      0,0,0,
      0,0,1);
}

//-----------------------------------------------------------------------------
// KPendulumSaver: screen saver class
//-----------------------------------------------------------------------------

KPendulumSaver::KPendulumSaver(WId id) :
   KScreenSaver(id),
   solver(0),
   m_massRatio(massRatioDefault),
   m_lengthRatio(lengthRatioDefault),
   m_g(gDefault),
   m_E(EDefault),
   m_persChangeInterval(persChangeIntervalDefault)
{
   setEraseColor(black);
   erase();                     // erase area
   glArea = new PendulumGLWidget(this); // create gl widget
   glArea->setEyePhi(eyePhiDefault);

   readSettings();              // read global settings into pars
   initData();                  // init solver and glArea with read settings

   embed(glArea);               // embed gl widget and resize it
   glArea->show();              // show gl widget

   // set up and start cyclic timer
   timer = new TQTimer(this);
   timer->start(deltaT, TRUE);
   connect(timer, TQT_SIGNAL(timeout()), this, TQT_SLOT(doTimeStep()));
}

KPendulumSaver::~KPendulumSaver()
{
   // time, rotation are automatically deleted with parent KPendulumSaver
   delete solver;
}


void KPendulumSaver::readSettings()
{
   // read configuration settings from config file
   TDEConfig *config = TDEGlobal::config();
   config->setGroup("Settings");

   // internal saver parameters are set to stored values or left at their
   // default values if stored values are out of range
   setMassRatio(
      config->readDoubleNumEntry(
         "mass ratio",
         KPendulumSaver::massRatioDefault));
   setLengthRatio(
      config->readDoubleNumEntry(
         "length ratio",
         KPendulumSaver::lengthRatioDefault));
   setG(
      config->readDoubleNumEntry(
         "g",
         KPendulumSaver::gDefault));
   setE(
      config->readDoubleNumEntry(
         "E",
         KPendulumSaver::EDefault));
   setPersChangeInterval(
      config->readUnsignedNumEntry(
         "perspective change interval",
         KPendulumSaver::persChangeIntervalDefault));

   // set the colours
   setBarColor(config->readColorEntry("bar color", &barColorDefault));
   setM1Color( config->readColorEntry("m1 color",  &m1ColorDefault));
   setM2Color( config->readColorEntry("m2 color",  &m2ColorDefault));
}

void KPendulumSaver::initData()
{
   const double m1plusm2 = 2;   // m1+m2
   const double m2 = m_massRatio * m1plusm2;
   const double m1 = m1plusm2 - m2;
   glArea->setMasses(m1, m2);
   glArea->setAngles(0, 0);

   const double l1plusl2 = 9;   // l1+l2
   const double l2 = m_lengthRatio * l1plusl2;
   const double l1 = l1plusl2 - l2;
   glArea->setLengths(l1, l2);

   // kinetic energy of m2 and m1
   const double kin_energy = m_E * m_g * (l1*m1 + (m1+m2)*(l1+l2));
   // angular velocity for 1. and 2. pendulum
   const double qp = sqrt(2.*kin_energy/((m1+m2)*l1*l1 + m2*l2*l2 + m2*l1*l2));

   // assemble initial y for solver
   std::valarray<double> y(4);
   y[0] = 0;                    // q1
   y[1] = 0;                    // q2
   y[2] = (m1+m2)*l1*l1*qp + 0.5*m2*l1*l2*qp; // p1
   y[3] = m2*l2*l2*qp + 0.5*m2*l1*l2*qp; // p2

   // delete old solver
   if (solver!=0) delete solver;
   // init new solver
   solver = new PendulumOdeSolver(
      0.0,                      // t
      0.01,                     // first dt step size estimation
      y,
      1e-5,                     // eps
      m1,
      m2,
      l1,
      l2,
      m_g);
}


void KPendulumSaver::setBarColor(const TQColor& c)
{
   glArea->setBarColor(c);
}
TQColor KPendulumSaver::barColor(void) const
{
   return glArea->barColor();
}

const TQColor KPendulumSaver::barColorDefault(255, 255, 127);

void KPendulumSaver::setM1Color(const TQColor& c)
{
   glArea->setM1Color(c);
}
TQColor KPendulumSaver::m1Color(void) const
{
   return glArea->m1Color();
}

const TQColor KPendulumSaver::m1ColorDefault(170,   0, 127);

void KPendulumSaver::setM2Color(const TQColor& c)
{
   glArea->setM2Color(c);
}
TQColor KPendulumSaver::m2Color(void) const
{
   return glArea->m2Color();
}

const TQColor KPendulumSaver::m2ColorDefault( 85, 170, 127);


void KPendulumSaver::setMassRatio(const double& massRatio)
{
   // range check is not neccessary in normal operation because validators check
   // the values at input.  But the validators do not check for corrupted
   // settings read from disk.
   if (massRatio >= massRatioLimitLower
       && massRatio <= massRatioLimitUpper
       && m_massRatio != massRatio)
   {
      m_massRatio = massRatio;
      if (timer!=0)
      {
         initData();
      }
   }
}

const double KPendulumSaver::massRatioLimitLower = 0.01;
const double KPendulumSaver::massRatioLimitUpper = 0.99;
const double KPendulumSaver::massRatioDefault    = 0.5;

void KPendulumSaver::setLengthRatio(const double& lengthRatio)
{
   if (lengthRatio >= lengthRatioLimitLower
       && lengthRatio <= lengthRatioLimitUpper
       && m_lengthRatio != lengthRatio)
   {
      m_lengthRatio = lengthRatio;
      if (timer!=0)
      {
         initData();
      }
   }
}

const double KPendulumSaver::lengthRatioLimitLower = 0.01;
const double KPendulumSaver::lengthRatioLimitUpper = 0.99;
const double KPendulumSaver::lengthRatioDefault    = 0.5;

void KPendulumSaver::setG(const double& g)
{
   if (g >= gLimitLower
       && g <= gLimitUpper
       && m_g != g)
   {
      m_g = g;
      if (timer!=0)
      {
         initData();
      }
   }
}

const double KPendulumSaver::gLimitLower = 0.1;
const double KPendulumSaver::gLimitUpper = 300.0;
const double KPendulumSaver::gDefault    = 40.0;

void KPendulumSaver::setE(const double& E)
{
   if (E >= ELimitLower
       && E <= ELimitUpper
       && m_E != E)
   {
      m_E = E;
      if (timer!=0)
      {
         initData();
      }
   }
}

const double KPendulumSaver::ELimitLower = 0.0;
const double KPendulumSaver::ELimitUpper = 5.0;
const double KPendulumSaver::EDefault    = 1.2;

void KPendulumSaver::setPersChangeInterval(
   const unsigned int& persChangeInterval)
{
   if (persChangeInterval >= persChangeIntervalLimitLower
       && persChangeInterval <= persChangeIntervalLimitUpper
       && m_persChangeInterval != persChangeInterval)
   {
      m_persChangeInterval = persChangeInterval;
      // do not restart simulation here
   }
}

const double KPendulumSaver::eyePhiDefault = 0.25*M_PI;


void KPendulumSaver::doTimeStep()
{
   /* time (in seconds) of perspective change.
    * - t<0: no change yet
    * - t=0: change starts
    * - 0<t<moving time: change takes place
    * - t=moving time: end of the change */
   static double persChangeTime = -5;

   // integrate a step ahead
   solver->integrate(0.001*deltaT);

   // read new y from solver
   const std::valarray<double> y = solver->Y();

   // tell glArea the new coordinates/angles of the pendulum
   glArea->setAngles(y[0], y[1]);

   // handle perspective change
   persChangeTime += 0.001*deltaT;
   if (persChangeTime > 0)
   {
      // phi value at the start of a perspective change
      static double eyePhi0     = eyePhiDefault;
      // phi value at the end of a perspective change
      static double eyePhi1     = 0.75*M_PI;
      static double deltaEyePhi = eyePhi1-eyePhi0;

      // movement acceleration/deceleration
      const double a = 3;
      // duration of the change period
      const double movingTime = 2.*sqrt(fabs(deltaEyePhi)/a);

      // new current phi of eye
      double eyePhi = persChangeTime < 0.5*movingTime ?
         // accelerating phase
         eyePhi0 + (deltaEyePhi>0?1:-1)
         * 0.5*a*persChangeTime*persChangeTime:
         // decellerating phase
         eyePhi1 - (deltaEyePhi>0?1:-1)
         * 0.5*a*(movingTime-persChangeTime)*(movingTime-persChangeTime);

      if (persChangeTime>movingTime)
      {  // perspective change has finished
         // set new time till next change
         persChangeTime = -double(m_persChangeInterval);
         eyePhi0 = eyePhi = eyePhi1;
         // find new phi value with angleLimit < phi < Pi-angleLimit or
         // Pi+angleLimit < phi < 2*Pi-angleLimit
         const double angleLimit = M_PI*0.2;
         for (eyePhi1 = 0;
              eyePhi1<angleLimit
                 || (eyePhi1<M_PI+angleLimit && eyePhi1>M_PI-angleLimit)
                 || eyePhi1>2*M_PI-angleLimit;
              eyePhi1 = double(rand())/RAND_MAX * 2*M_PI)
         {}
         // new delta phi for next change
         deltaEyePhi = eyePhi1 - eyePhi0;
         // find shortest perspective change
         if (deltaEyePhi < -M_PI) deltaEyePhi += 2*M_PI;
      }

      glArea->setEyePhi(eyePhi); // set new perspective
   }

   glArea->updateGL();          // repaint scenery
   timer->start(deltaT, TRUE);  // restart timer
}

// public slot of KPendulumSaver, forward resize event to public slot of glArea
// to allow the resizing of the gl area withing the setup dialog
void KPendulumSaver::resizeGlArea(TQResizeEvent* e)
{
   glArea->resize(e->size());
}

//-----------------------------------------------------------------------------
// KPendulumSetup: dialog to setup screen saver parameters
//-----------------------------------------------------------------------------

KPendulumSetup::KPendulumSetup(TQWidget* parent, const char* name)
   : KPendulumSetupUi(parent, name),
     // create saver and give it the WinID of the preview area
     saver(new KPendulumSaver(preview->winId()))
{
   // the dialog should block, no other control center input should be possible
   // until the dialog is closed
   setModal(TRUE);

   // create input validators
   mEdit->setValidator(new TQDoubleValidator(
                          KPendulumSaver::massRatioLimitLower,
                          KPendulumSaver::massRatioLimitUpper,
                          5, mEdit));
   lEdit->setValidator(new TQDoubleValidator(
                          KPendulumSaver::lengthRatioLimitLower,
                          KPendulumSaver::lengthRatioLimitUpper,
                          5, lEdit));
   gEdit->setValidator(new TQDoubleValidator(
                          KPendulumSaver::gLimitLower,
                          KPendulumSaver::gLimitUpper,
                          5, gEdit));
   eEdit->setValidator(new TQDoubleValidator(
                          KPendulumSaver::ELimitLower,
                          KPendulumSaver::ELimitUpper,
                          5, eEdit));

   // set input limits for the perspective change interval time
   persSpinBox->setMinValue(KPendulumSaver::persChangeIntervalLimitLower);
   persSpinBox->setMaxValue(KPendulumSaver::persChangeIntervalLimitUpper);

   // set tool tips of editable fields
   TQToolTip::add(
      mEdit,
      i18n("Ratio of 2nd mass to sum of both masses.\nValid values from %1 to %2.")
      .arg(KPendulumSaver::massRatioLimitLower, 0, 'f', 2)
      .arg(KPendulumSaver::massRatioLimitUpper, 0, 'f', 2));
   TQToolTip::add(
      lEdit,
      i18n("Ratio of 2nd pendulum part length to the sum of both part lengths.\nValid values from %1 to %2.")
      .arg(KPendulumSaver::lengthRatioLimitLower, 0, 'f', 2)
      .arg(KPendulumSaver::lengthRatioLimitUpper, 0, 'f', 2));
   TQToolTip::add(
      gEdit,
      i18n("Gravitational constant in arbitrary units.\nValid values from %1 to %2.")
      .arg(KPendulumSaver::gLimitLower, 0, 'f', 2)
      .arg(KPendulumSaver::gLimitUpper, 0, 'f', 2));
   TQToolTip::add(
      eEdit,
      i18n("Energy in units of the maximum potential energy of the given configuration.\nValid values from %1 to %2.")
      .arg(KPendulumSaver::ELimitLower, 0, 'f', 2)
      .arg(KPendulumSaver::ELimitUpper, 0, 'f', 2));
   TQToolTip::add(
      persSpinBox,
      i18n("Time in seconds after which a random perspective change occurs.\nValid values from %1 to %2.")
      .arg(KPendulumSaver::persChangeIntervalLimitLower)
      .arg(KPendulumSaver::persChangeIntervalLimitUpper));

   // init preview area
   preview->setBackgroundColor(black);
   preview->show();    // otherwise saver does not get correct size

   // read settings from saver and update GUI elements with these values, saver
   // has read settings in its constructor

   // set editable fields with stored values as defaults
   TQString text;
   text.setNum(saver->massRatio());
   mEdit->setText(text);
   text.setNum(saver->lengthRatio());
   lEdit->setText(text);
   text.setNum(saver->g());
   gEdit->setText(text);
   text.setNum(saver->E());
   eEdit->setText(text);

   persSpinBox->setValue(saver->persChangeInterval());

   barColorButton->setPaletteBackgroundColor(saver->barColor());
   m1ColorButton->setPaletteBackgroundColor(saver->m1Color());
   m2ColorButton->setPaletteBackgroundColor(saver->m2Color());

   // if the preview area is resized it emmits the resized() event which is
   // caught by the saver.  The embedded GlArea is resized to fit into the
   // preview area.
   connect(preview, TQT_SIGNAL(resized(TQResizeEvent*)),
           saver,   TQT_SLOT(resizeGlArea(TQResizeEvent*)));
}

KPendulumSetup::~KPendulumSetup()
{
   delete saver;
}

// Ok pressed - save settings and exit
void KPendulumSetup::okButtonClickedSlot()
{
   TDEConfig* config = TDEGlobal::config();
   config->setGroup("Settings");

   config->writeEntry("mass ratio",   saver->massRatio());
   config->writeEntry("length ratio", saver->lengthRatio());
   config->writeEntry("g",            saver->g());
   config->writeEntry("E",            saver->E());
   config->writeEntry("perspective change interval",
                      saver->persChangeInterval());
   config->writeEntry("bar color",    saver->barColor());
   config->writeEntry("m1 color",     saver->m1Color());
   config->writeEntry("m2 color",     saver->m2Color());

   config->sync();
   accept();
}

void KPendulumSetup::aboutButtonClickedSlot()
{
   KMessageBox::about(this, i18n("\
<h3>KPendulum Screen Saver for TDE</h3>\
<p>Simulation of a two-part pendulum</p>\
<p>Copyright (c) Georg&nbsp;Drenkhahn 2004</p>\
<p><tt>georg-d@users.sourceforge.net</tt></p>"));
}

void KPendulumSetup::mEditLostFocusSlot(void)
{
   if (mEdit->hasAcceptableInput())
   {
      saver->setMassRatio(mEdit->text().toDouble());
   }
   else
   {  // write current setting back into input field
      TQString text;
      text.setNum(saver->massRatio());
      mEdit->setText(text);
   }
}
void KPendulumSetup::lEditLostFocusSlot(void)
{
   if (lEdit->hasAcceptableInput())
   {
      saver->setLengthRatio(lEdit->text().toDouble());
   }
   else
   {  // write current setting back into input field
      TQString text;
      text.setNum(saver->lengthRatio());
      lEdit->setText(text);
   }
}
void KPendulumSetup::gEditLostFocusSlot(void)
{
   if (gEdit->hasAcceptableInput())
   {
      saver->setG(gEdit->text().toDouble());
   }
   else
   {  // write current setting back into input field
      TQString text;
      text.setNum(saver->g());
      gEdit->setText(text);
   }
}
void KPendulumSetup::eEditLostFocusSlot(void)
{
   if (eEdit->hasAcceptableInput())
   {
      saver->setE(eEdit->text().toDouble());
   }
   else
   {  // write current setting back into input field
      TQString text;
      text.setNum(saver->E());
      eEdit->setText(text);
   }
}
void KPendulumSetup::persChangeEnteredSlot(int t)
{
   saver->setPersChangeInterval(t);
}

void KPendulumSetup::barColorButtonClickedSlot(void)
{
   TQColor color = TQColorDialog::getColor(
      saver->barColor(), this, "bar color dialog");
   if (color.isValid())
   {
      saver->setBarColor(color);
      barColorButton->setPaletteBackgroundColor(color);
   }
}
void KPendulumSetup::m1ColorButtonClickedSlot(void)
{
   TQColor color = TQColorDialog::getColor(
      saver->m1Color(), this, "mass 1 color dialog");
   if (color.isValid())
   {
      saver->setM1Color(color);
      m1ColorButton->setPaletteBackgroundColor(color);
   }
}
void KPendulumSetup::m2ColorButtonClickedSlot(void)
{
   TQColor color = TQColorDialog::getColor(
      saver->m2Color(), this, "mass 2 color dialog");
   if (color.isValid())
   {
      saver->setM2Color(color);
      m2ColorButton->setPaletteBackgroundColor(color);
   }
}