source: trunk/gui/scripts/moleculeViewer.tcl @ 2743

Last change on this file since 2743 was 2743, checked in by gah, 13 years ago
File size: 23.1 KB
Line 
1# ----------------------------------------------------------------------
2#  COMPONENT: MoleculeViewer - view a molecule in 3D
3#
4#  This widget brings up a 3D representation of a molecule, which you
5#  can rotate.  It extracts atoms and bonds from the Rappture XML
6#  representation for a <molecule>.
7# ======================================================================
8#  AUTHOR:  Michael McLennan, Purdue University
9#  Copyright (c) 2004-2005  Purdue Research Foundation
10#
11#  See the file "license.terms" for information on usage and
12#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13# ======================================================================
14package require Itk
15package require vtk
16package require vtkinteraction
17package require BLT
18package require Img
19
20option add *MoleculeViewer.width 3i widgetDefault
21option add *MoleculeViewer.height 3i widgetDefault
22option add *MoleculeViewer.backdrop black widgetDefault
23
24itcl::class Rappture::MoleculeViewer {
25    inherit itk::Widget
26
27    itk_option define -backdrop backdrop Backdrop "black"
28    itk_option define -device device Device ""
29
30    constructor {tool args} {
31        # defined below
32    }
33    destructor {
34        # defined below
35    }
36
37    public method add {dataobj {settings ""}}
38    public method get {}
39    public method delete {args}
40    public method snap {w h}
41    public method parameters {title args} {
42        # do nothing
43    }
44    public method emblems {option}
45    public method download {option args}
46
47    protected method _clear {}
48    protected method _redraw {}
49    protected method _zoom {option}
50    protected method _move {option x y}
51    protected method _3dView {theta phi psi}
52    protected method _color2rgb {color}
53
54    private variable _dispatcher "" ;# dispatcher for !events
55
56    private variable _tool ""    ;# tool containing this viewer
57    private variable _dlist ""   ;# list of dataobj objects
58    private variable _dobj2raise ;# maps dataobj => raise flag
59    private variable _actors ""  ;# list of actors in renderer
60    private variable _label2atom ;# maps 2D text actor => underlying atom
61    private variable _view       ;# view params for 3D view
62    private variable _limits     ;# limits of x/y/z axes
63    private variable _click      ;# info used for _move operations
64    private variable _download "";# snapshot for download
65}
66                                                                               
67itk::usual MoleculeViewer {
68}
69
70# ----------------------------------------------------------------------
71# CONSTRUCTOR
72# ----------------------------------------------------------------------
73itcl::body Rappture::MoleculeViewer::constructor {tool args} {
74    set _tool $tool
75
76    Rappture::dispatcher _dispatcher
77    $_dispatcher register !redraw
78    $_dispatcher dispatch $this !redraw "[itcl::code $this _redraw]; list"
79    $_dispatcher register !render
80    $_dispatcher dispatch $this !render "$this-renWin Render; list"
81    $_dispatcher register !fixsize
82    $_dispatcher dispatch $this !fixsize \
83        "[itcl::code $this emblems fixPosition]; list"
84
85    itk_option add hull.width hull.height
86    pack propagate $itk_component(hull) no
87
88    vtkRenderWindow $this-renWin
89    vtkRenderer $this-ren
90    $this-renWin AddRenderer $this-ren
91
92    vtkRenderWindowInteractor $this-int
93    $this-int SetRenderWindow $this-renWin
94
95    vtkSphereSource $this-sphere
96    $this-sphere SetRadius 1.0
97    $this-sphere SetThetaResolution 18
98    $this-sphere SetPhiResolution 18
99
100    vtkPolyDataMapper $this-map
101    $this-map SetInput [$this-sphere GetOutput]
102
103    vtkCoordinate $this-xyzconv
104    $this-xyzconv SetCoordinateSystemToWorld
105
106    set _view(theta) 0
107    set _view(phi) 0
108    set _view(psi) 0
109
110    itk_component add controls {
111        frame $itk_interior.cntls
112    } {
113        usual
114        rename -background -controlbackground controlBackground Background
115    }
116    pack $itk_component(controls) -side right -fill y
117
118    itk_component add reset {
119        button $itk_component(controls).reset \
120            -borderwidth 1 -padx 1 -pady 1 \
121            -bitmap [Rappture::icon reset] \
122            -command [itcl::code $this _zoom reset]
123    } {
124        usual
125        ignore -borderwidth
126        rename -highlightbackground -controlbackground controlBackground Background
127    }
128    pack $itk_component(reset) -padx 4 -pady 4
129    Rappture::Tooltip::for $itk_component(reset) "Reset the view to the default zoom level"
130
131    itk_component add zoomin {
132        button $itk_component(controls).zin \
133            -borderwidth 1 -padx 1 -pady 1 \
134            -bitmap [Rappture::icon zoomin] \
135            -command [itcl::code $this _zoom in]
136    } {
137        usual
138        ignore -borderwidth
139        rename -highlightbackground -controlbackground controlBackground Background
140    }
141    pack $itk_component(zoomin) -padx 4 -pady 4
142    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
143
144    itk_component add zoomout {
145        button $itk_component(controls).zout \
146            -borderwidth 1 -padx 1 -pady 1 \
147            -bitmap [Rappture::icon zoomout] \
148            -command [itcl::code $this _zoom out]
149    } {
150        usual
151        ignore -borderwidth
152        rename -highlightbackground -controlbackground controlBackground Background
153    }
154    pack $itk_component(zoomout) -padx 4 -pady 4
155    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
156
157    itk_component add labels {
158        label $itk_component(controls).labels \
159            -borderwidth 1 -padx 1 -pady 1 \
160            -bitmap [Rappture::icon atoms]
161    } {
162        usual
163        ignore -borderwidth
164        rename -highlightbackground -controlbackground controlBackground Background
165    }
166    pack $itk_component(labels) -padx 4 -pady 8 -ipadx 1 -ipady 1
167    Rappture::Tooltip::for $itk_component(labels) "Show/hide the labels on atoms"
168    bind $itk_component(labels) <ButtonPress> \
169        [itcl::code $this emblems toggle]
170
171    #
172    # RENDERING AREA
173    #
174    itk_component add area {
175        frame $itk_interior.area
176    }
177    pack $itk_component(area) -expand yes -fill both
178    bind $itk_component(area) <Configure> \
179        [list $_dispatcher event -idle !fixsize]
180
181    itk_component add renderer {
182        vtkTkRenderWidget $itk_component(area).ren -rw $this-renWin
183    } {
184    }
185    pack $itk_component(renderer) -expand yes -fill both
186
187    eval itk_initialize $args
188
189    # prevent interactions -- use our own
190    blt::busy hold $itk_component(area) -cursor left_ptr
191    bind $itk_component(area)_Busy <ButtonPress> \
192        [itcl::code $this _move click %x %y]
193    bind $itk_component(area)_Busy <B1-Motion> \
194        [itcl::code $this _move drag %x %y]
195    bind $itk_component(area)_Busy <ButtonRelease> \
196        [itcl::code $this _move release %x %y]
197
198    emblems on
199
200    # create a photo for download snapshots
201    set _download [image create photo]
202}
203
204# ----------------------------------------------------------------------
205# DESTRUCTOR
206# ----------------------------------------------------------------------
207itcl::body Rappture::MoleculeViewer::destructor {} {
208    rename $this-renWin ""
209    rename $this-ren ""
210    rename $this-int ""
211    rename $this-sphere ""
212    rename $this-map ""
213    rename $this-xyzconv ""
214
215    image delete $_download
216}
217
218# ----------------------------------------------------------------------
219# USAGE: add <dataobj> ?<settings>?
220#
221# Clients use this to add a data object to the plot.  The optional
222# <settings> are used to configure the plot.  Allowed settings are
223# -color, -brightness, -width, -linestyle, and -raise. Only
224# -brightness and -raise do anything.
225# ----------------------------------------------------------------------
226itcl::body Rappture::MoleculeViewer::add {dataobj {settings ""}} {
227    array set params {
228        -color auto
229        -brightness 0
230        -width 1
231        -raise 0
232        -linestyle solid
233        -description ""
234        -param ""
235    }
236    foreach {opt val} $settings {
237        if {![info exists params($opt)]} {
238            error "bad settings \"$opt\": should be [join [lsort [array names params]] {, }]"
239        }
240        set params($opt) $val
241    }
242 
243    set pos [lsearch -exact $dataobj $_dlist]
244
245    if {$pos < 0} {
246        if {![Rappture::library isvalid $dataobj]} {
247            error "bad value \"$dataobj\": should be Rappture::library object"
248        }
249   
250        set emblem [$dataobj get components.molecule.about.emblems]
251        if {$emblem == "" || ![string is boolean $emblem] || !$emblem} {
252            emblems off
253        } else {
254            emblems on
255        }
256
257        lappend _dlist $dataobj
258        set _dobj2raise($dataobj) $params(-raise)
259
260        $_dispatcher event -idle !redraw
261    }
262}
263
264# ----------------------------------------------------------------------
265# USAGE: get
266#
267# Clients use this to query the list of objects being plotted, in
268# order from bottom to top of this result.
269# ----------------------------------------------------------------------
270itcl::body Rappture::MoleculeViewer::get {} {
271    # put the dataobj list in order according to -raise options
272    set dlist $_dlist
273    foreach obj $dlist {
274        if {[info exists _dobj2raise($obj)] && $_dobj2raise($obj)} {
275            set i [lsearch -exact $dlist $obj]
276            if {$i >= 0} {
277                set dlist [lreplace $dlist $i $i]
278                lappend dlist $obj
279            }
280        }
281    }
282    return $dlist
283}
284
285# ----------------------------------------------------------------------
286# USAGE: delete ?<dataobj> <dataobj> ...?
287#
288# Clients use this to delete a dataobj from the plot. If no dataobjs
289# are specified, then all dataobjs are deleted.
290# ----------------------------------------------------------------------
291itcl::body Rappture::MoleculeViewer::delete {args} {
292    if {[llength $args] == 0} {
293        set args $_dlist
294    }
295
296    # delete all specified dataobjs
297    set changed 0
298    foreach dataobj $args {
299        set pos [lsearch -exact $_dlist $dataobj]
300        if {$pos >= 0} {
301            set _dlist [lreplace $_dlist $pos $pos]
302            catch {unset _dobj2raise($dataobj)}
303            set changed 1
304        }
305    }
306
307    # if anything changed, then rebuild the plot
308    if {$changed} {
309        $_dispatcher event -idle !redraw
310    }
311}
312
313# ----------------------------------------------------------------------
314# USAGE: download coming
315# USAGE: download controls <downloadCommand>
316# USAGE: download now
317#
318# Clients use this method to create a downloadable representation
319# of the plot.  Returns a list of the form {ext string}, where
320# "ext" is the file extension (indicating the type of data) and
321# "string" is the data itself.
322# ----------------------------------------------------------------------
323itcl::body Rappture::MoleculeViewer::download {option args} {
324    switch $option {
325        coming {
326            if {[catch {blt::winop snap $itk_component(area) $_download}]} {
327                $_download configure -width 1 -height 1
328                $_download put #000000
329            }
330        }
331        controls {
332            # no controls for this download yet
333            return ""
334        }
335        now {
336            # Get the image data (as base64) and decode it back to binary.
337            # This is better than writing to temporary files.  When we switch
338            # to the BLT picture image it won't be necessary to decode the
339            # image data.
340            set bytes [$_download data -format "jpeg -quality 100"]
341            set bytes [Rappture::encoding::decode -as b64 $bytes]
342            return [list .jpg $bytes]
343        }
344        default {
345            error "bad option \"$option\": should be coming, controls, now"
346        }
347    }
348}
349
350# ----------------------------------------------------------------------
351# USAGE: _clear
352#
353# Used internally to clear the scene whenever it is about to change.
354# ----------------------------------------------------------------------
355itcl::body Rappture::MoleculeViewer::_clear {} {
356    foreach a $_actors {
357        $this-ren RemoveActor $a
358        rename $a ""
359    }
360    set _actors ""
361    catch {unset _label2atom}
362
363    foreach lim {xmin xmax ymin ymax zmin zmax} {
364        set _limits($lim) ""
365    }
366
367    $this-ren ResetCamera
368    $_dispatcher event -now !render
369}
370
371# ----------------------------------------------------------------------
372# USAGE: _redraw
373#
374# Used internally to rebuild the scene whenever options within this
375# widget change.  Destroys all actors and rebuilds them from scratch.
376# ----------------------------------------------------------------------
377itcl::body Rappture::MoleculeViewer::_redraw {} {
378    blt::busy hold $itk_component(hull)
379
380    _clear
381
382    set dev [lindex [get] end]
383    if {"" != $dev} {
384        set lib [Rappture::library standard]
385
386        set counter 0
387        foreach atom [$dev children -type atom components.molecule] {
388            set symbol [$dev get components.molecule.$atom.symbol]
389            set xyz [$dev get components.molecule.$atom.xyz]
390            regsub {,} $xyz {} xyz
391
392            # update overall limits for molecules along all axes
393            foreach axis {x y z} val $xyz {
394                if {"" == $_limits(${axis}min)} {
395                    set _limits(${axis}min) $val
396                    set _limits(${axis}max) $val
397                } else {
398                    if {$val < $_limits(${axis}min)} {
399                        set _limits(${axis}min) $val
400                    }
401                    if {$val > $_limits(${axis}max)} {
402                        set _limits(${axis}max) $val
403                    }
404                }
405            }
406
407            # create an actor for each atom
408            set aname $this-actor[incr counter]
409            vtkActor $aname
410            $aname SetMapper $this-map
411            eval $aname SetPosition $xyz
412            $this-ren AddActor $aname
413
414            set sfac 0.7
415            set scale [$lib get elements.($symbol).scale]
416            if {$scale != ""} {
417                $aname SetScale [expr {$sfac*$scale}]
418            }
419            set color [$lib get elements.($symbol).color]
420            if {$color != ""} {
421                eval [$aname GetProperty] SetColor [_color2rgb $color]
422            }
423
424            lappend _actors $aname
425
426            # create a label for each atom
427            set lname $this-label$counter
428            vtkTextActor $lname
429            $lname SetInput "$counter $symbol"
430            $lname ScaledTextOff
431
432            set tprop [$lname GetTextProperty]
433            $tprop SetJustificationToCentered
434            $tprop SetVerticalJustificationToCentered
435            $tprop ShadowOn
436            $tprop SetColor 1 1 1
437
438            set _label2atom($lname) $aname
439            lappend _actors $lname
440        }
441        if {[$itk_component(labels) cget -relief] == "sunken"} {
442            emblems on
443        }
444        _zoom reset
445    }
446    $this-ren ResetCamera
447    $_dispatcher event -idle !render
448
449    blt::busy release $itk_component(hull)
450}
451
452# ----------------------------------------------------------------------
453# USAGE: _zoom in
454# USAGE: _zoom out
455# USAGE: _zoom reset
456#
457# Called automatically when the user clicks on one of the zoom
458# controls for this widget.  Changes the zoom for the current view.
459# ----------------------------------------------------------------------
460itcl::body Rappture::MoleculeViewer::_zoom {option} {
461    switch -- $option {
462        in {
463            [$this-ren GetActiveCamera] Zoom 1.25
464        }
465        out {
466            [$this-ren GetActiveCamera] Zoom 0.8
467        }
468        reset {
469            $this-ren ResetCamera
470            [$this-ren GetActiveCamera] SetViewAngle 30
471            _3dView 45 45 0
472        }
473    }
474    $_dispatcher event -later !fixsize
475    $_dispatcher event -idle !render
476}
477
478# ----------------------------------------------------------------------
479# USAGE: _move click <x> <y>
480# USAGE: _move drag <x> <y>
481# USAGE: _move release <x> <y>
482#
483# Called automatically when the user clicks/drags/releases in the
484# plot area.  Moves the plot according to the user's actions.
485# ----------------------------------------------------------------------
486itcl::body Rappture::MoleculeViewer::_move {option x y} {
487    switch -- $option {
488        click {
489            blt::busy configure $itk_component(area) -cursor fleur
490            set _click(x) $x
491            set _click(y) $y
492            set _click(theta) $_view(theta)
493            set _click(phi) $_view(phi)
494            set _click(psi) $_view(psi)
495        }
496        drag {
497            if {[array size _click] == 0} {
498                _move click $x $y
499            } else {
500                set w [winfo width $itk_component(renderer)]
501                set h [winfo height $itk_component(renderer)]
502                if {$w <= 0 || $h <= 0} {
503                    return
504                }
505
506                if {[catch {
507                    # this fails sometimes for no apparent reason
508                    set dx [expr {double($x-$_click(x))/$w}]
509                    set dy [expr {double($y-$_click(y))/$h}]
510                }]} {
511                    return
512                }
513
514                #
515                # Rotate the camera in 3D
516                #
517                if {$_view(psi) > 90 || $_view(psi) < -90} {
518                    # when psi is flipped around, theta moves backwards
519                    set dy [expr {-$dy}]
520                }
521                set theta [expr {$_view(theta) - $dy*180}]
522                while {$theta < 0} { set theta [expr {$theta+180}] }
523                while {$theta > 180} { set theta [expr {$theta-180}] }
524                #if {$theta < 2} { set theta 2 }
525                #if {$theta > 178} { set theta 178 }
526
527                if {$theta > 45 && $theta < 135} {
528                    set phi [expr {$_view(phi) - $dx*360}]
529                    while {$phi < 0} { set phi [expr {$phi+360}] }
530                    while {$phi > 360} { set phi [expr {$phi-360}] }
531                    set psi $_view(psi)
532                } else {
533                    set phi $_view(phi)
534                    set psi [expr {$_view(psi) - $dx*360}]
535                    while {$psi < -180} { set psi [expr {$psi+360}] }
536                    while {$psi > 180} { set psi [expr {$psi-360}] }
537                }
538
539                _3dView $theta $phi $psi
540                emblems fixPosition
541                $_dispatcher event -idle !render
542
543                set _click(x) $x
544                set _click(y) $y
545            }
546        }
547        release {
548            _move drag $x $y
549            blt::busy configure $itk_component(area) -cursor left_ptr
550            catch {unset _click}
551        }
552        default {
553            error "bad option \"$option\": should be click, drag, release"
554        }
555    }
556}
557
558# ----------------------------------------------------------------------
559# USAGE: _3dView <theta> <phi> <psi>
560#
561# Used internally to change the position of the camera for 3D data
562# sets.  Sets the camera according to the angles <theta> (angle from
563# the z-axis) and <phi> (angle from the x-axis in the x-y plane).
564# Both angles are in degrees.
565# ----------------------------------------------------------------------
566itcl::body Rappture::MoleculeViewer::_3dView {theta phi psi} {
567    set deg2rad 0.0174532927778
568    set xp [expr {sin($theta*$deg2rad)*cos($phi*$deg2rad)}]
569    set yp [expr {sin($theta*$deg2rad)*sin($phi*$deg2rad)}]
570    set zp [expr {cos($theta*$deg2rad)}]
571
572    set blank 0
573    foreach lim {xmin xmax ymin ymax zmin zmax} {
574        if {"" == $_limits($lim)} {
575            set blank 1
576            break
577        }
578    }
579    if {$blank} {
580        set xm 0
581        set ym 0
582        set zm 0
583    } else {
584        set xm [expr {0.5*($_limits(xmax)+$_limits(xmin))}]
585        set ym [expr {0.5*($_limits(ymax)+$_limits(ymin))}]
586        set zm [expr {0.5*($_limits(zmax)+$_limits(zmin))}]
587    }
588
589    set cam [$this-ren GetActiveCamera]
590    set zoom [$cam GetViewAngle]
591    $cam SetViewAngle 30
592
593    $cam SetFocalPoint $xm $ym $zm
594    $cam SetPosition [expr {$xm-$xp}] [expr {$ym-$yp}] [expr {$zm+$zp}]
595    $cam ComputeViewPlaneNormal
596    $cam SetViewUp 0 0 1  ;# z-dir is up
597    $cam OrthogonalizeViewUp
598    $cam Azimuth $psi
599    $this-ren ResetCamera
600    $cam SetViewAngle $zoom
601
602    # fix up the labels so they sit over the new atom positions
603    emblems fixPosition
604
605    set _view(theta) $theta
606    set _view(phi) $phi
607    set _view(psi) $psi
608}
609
610# ----------------------------------------------------------------------
611# USAGE: emblems on
612# USAGE: emblems off
613# USAGE: emblems toggle
614# USAGE: emblems fixPosition
615#
616# Used internally to turn labels associated with atoms on/off, and to
617# update the positions of the labels so they sit on top of each atom.
618# ----------------------------------------------------------------------
619itcl::body Rappture::MoleculeViewer::emblems {option} {
620    switch -- $option {
621        on {
622            set state 1
623        }
624        off {
625            set state 0
626        }
627        toggle {
628            if {[$itk_component(labels) cget -relief] == "sunken"} {
629                set state 0
630            } else {
631                set state 1
632            }
633        }
634        fixPosition {
635            foreach lname [array names _label2atom] {
636                set aname $_label2atom($lname)
637                set xyz [$aname GetPosition]
638                eval $this-xyzconv SetValue $xyz
639                set xy [$this-xyzconv GetComputedViewportValue $this-ren]
640                eval $lname SetDisplayPosition $xy
641            }
642            return
643        }
644        default {
645            error "bad option \"$option\": should be on, off, toggle, fixPosition"
646        }
647    }
648
649    if {$state} {
650        $itk_component(labels) configure -relief sunken
651        foreach lname [array names _label2atom] {
652            catch {$this-ren AddActor2D $lname}
653        }
654        emblems fixPosition
655    } else {
656        $itk_component(labels) configure -relief raised
657        foreach lname [array names _label2atom] {
658            catch {$this-ren RemoveActor $lname}
659        }
660    }
661    $_dispatcher event -idle !render
662}
663
664# ----------------------------------------------------------------------
665# USAGE: _color2rgb color
666#
667# Used internally to convert a Tk color name into the r,g,b values
668# used in Vtk (scaled 0-1).
669# ----------------------------------------------------------------------
670itcl::body Rappture::MoleculeViewer::_color2rgb {color} {
671    foreach {r g b} [winfo rgb $itk_component(hull) $color] {}
672    set r [expr {$r/65535.0}]
673    set g [expr {$g/65535.0}]
674    set b [expr {$b/65535.0}]
675    return [list $r $g $b]
676}
677
678# ----------------------------------------------------------------------
679# OPTION: -backdrop
680# ----------------------------------------------------------------------
681itcl::configbody Rappture::MoleculeViewer::backdrop {
682    eval $this-ren SetBackground [_color2rgb $itk_option(-backdrop)]
683    $_dispatcher event -idle !render
684}
685
686# ----------------------------------------------------------------------
687# OPTION: -device
688# ----------------------------------------------------------------------
689itcl::configbody Rappture::MoleculeViewer::device {
690    if {"" != $itk_option(-device)
691          && ![Rappture::library isvalid $itk_option(-device)]} {
692        error "bad value \"$itk_option(-device)\": should be Rappture::library object"
693    }
694    delete
695
696    if {"" != $itk_option(-device)} {
697        add $itk_option(-device)
698        set state [$itk_option(-device) get components.molecule.about.emblems]
699        if {$state == "" || ![string is boolean $state] || !$state} {
700            emblems off
701        } else {
702            emblems on
703        }
704    }
705    $_dispatcher event -idle !redraw
706}
Note: See TracBrowser for help on using the repository browser.