source: trunk/gui/scripts/molvisviewer.tcl @ 2395

Last change on this file since 2395 was 2015, checked in by gah, 14 years ago

wrong vector method in parallelepiped

File size: 70.8 KB
Line 
1
2# ----------------------------------------------------------------------
3#  COMPONENT: molvisviewer - view a molecule in 3D
4#
5#  This widget brings up a 3D representation of a molecule
6#  It connects to the Molvis server running on a rendering farm,
7#  transmits data, and displays the results.
8# ======================================================================
9#  AUTHOR:  Michael McLennan, Purdue University
10#  Copyright (c) 2004-2005  Purdue Research Foundation
11#
12#  See the file "license.terms" for information on usage and
13#  redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
14# ======================================================================
15package require Itk
16package require BLT
17package require Img
18
19option add *MolvisViewer.width 4i widgetDefault
20option add *MolvisViewer.height 4i widgetDefault
21option add *MolvisViewer.foreground black widgetDefault
22option add *MolvisViewer.font -*-helvetica-medium-r-normal-*-12-* widgetDefault
23
24# must use this name -- plugs into Rappture::resources::load
25proc MolvisViewer_init_resources {} {
26    Rappture::resources::register \
27        molvis_server Rappture::MolvisViewer::SetServerList
28}
29
30set debug 0
31proc debug { args } {
32    global debug
33    if { $debug } {
34        puts stderr "[info level -1]: $args"
35    }
36}
37
38itcl::class Rappture::MolvisViewer {
39    inherit Rappture::VisViewer
40
41    itk_option define -device device Device ""
42
43    private variable _icon 0
44
45    private variable _mevent;           # info used for mouse event operations
46    private variable _rocker;           # info used for rock operations
47    private variable _dlist "";         # list of dataobj objects
48    private variable _dataobjs;         # data objects on server
49    private variable _dobj2transparency;# maps dataobj => transparency
50    private variable _dobj2raise;       # maps dataobj => raise flag 0/1
51
52    private variable _active;           # array of active models.
53    private variable _obj2models;       # array containing list of models
54                                        # for each data object.
55    private variable _view
56    private variable _click
57
58    private variable _model
59    private variable _mlist
60    private variable _mrep "ballnstick"
61
62    private variable _imagecache
63    private variable _state
64    private variable _labels  "default"
65    private variable _cacheid ""
66    private variable _cacheimage ""
67
68    private variable _delta1 10
69    private variable _delta2 2
70
71    private common _settings  ;         # Array of settings for all known
72                                        # widgets
73    private variable _initialized
74
75    private common _downloadPopup;      # Download options from popup
76    private variable _pdbdata;          # PDB data from run file sent to pymol
77    private common _hardcopy
78    private variable _nextToken 0
79    private variable _outbuf "";
80    private variable _buffering 0;
81    private variable _resizePending 0;
82    private variable _width
83    private variable _height
84    private variable _restore 1;        # Restore camera settings
85    private variable _cell 0;           # Restore camera settings
86
87    constructor { hostlist args } {
88        Rappture::VisViewer::constructor $hostlist
89    } {
90        # defined below
91    }
92    destructor {
93        # defined below
94    }
95    public proc SetServerList { namelist } {
96        Rappture::VisViewer::SetServerList "pymol" $namelist
97    }
98    private method BuildSettingsTab {}
99    private method DoResize {}
100    private method EventuallyResize { w h }
101    private method GetImage { widget }
102    private method ReceiveImage { size cacheid frame rock }
103    private method WaitIcon { option widget }
104    private method DownloadPopup { popup command }
105    private method EnableDownload { popup what }
106
107    protected method Map {}
108    protected method Pan {option x y}
109    protected method Rebuild { }
110    protected method Rotate {option x y}
111    protected method SendCmd { string }
112    protected method Unmap {}
113    protected method Update { args }
114    protected method Vmouse  {option b m x y}
115    protected method Vmouse2 {option b m x y}
116    protected method Zoom {option {factor 10}}
117
118    public method Connect {}
119    public method Disconnect {}
120    public method ResetView {}
121    public method add {dataobj {options ""}}
122    public method delete {args}
123    public method download {option args}
124    public method get {}
125    public method isconnected {}
126    public method labels {option {model "all"}}
127    public method parameters {title args} {
128        # do nothing
129    }
130    public method snap { w h }
131    private method Opacity {option}
132    private method SphereScale {option {models "all"} }
133    private method StickRadius {option {models "all"} }
134    private method OrthoProjection {option}
135    private method Representation {option {model "all"} }
136    private method CartoonTrace {option {model "all"}}
137    private method ComputeParallelepipedVertices { dataobj }
138    private method Cell {option}
139    private method Rock {option}
140}
141
142itk::usual MolvisViewer {
143    keep -background -foreground -cursor -font
144}
145
146# ----------------------------------------------------------------------
147# CONSTRUCTOR
148# ----------------------------------------------------------------------
149itcl::body Rappture::MolvisViewer::constructor {hostlist args} {
150    # Register events to the dispatcher.  Base class expects !rebuild
151    # event to be registered.
152
153    # Rebuild
154    $_dispatcher register !rebuild
155    $_dispatcher dispatch $this !rebuild "[itcl::code $this Rebuild]; list"
156
157    # Resize event
158    $_dispatcher register !resize
159    $_dispatcher dispatch $this !resize "[itcl::code $this DoResize]; list"
160
161    # Rocker
162    $_dispatcher register !rocker
163    $_dispatcher dispatch $this !rocker "[itcl::code $this Rock step]; list"
164    # Mouse Event
165    $_dispatcher register !mevent
166    $_dispatcher dispatch $this !mevent "[itcl::code $this _mevent]; list"
167    $_dispatcher register !pngtimeout
168    $_dispatcher register !waiticon
169
170    array set _downloadPopup {
171        format draft
172    }
173
174    # Populate the slave interpreter with commands to handle responses from
175    # the visualization server.
176    $_parser alias image [itcl::code $this ReceiveImage]
177
178    set _rocker(dir) 1
179    set _rocker(client) 0
180    set _rocker(server) 0
181    set _rocker(on) 0
182    set _state(server) 1
183    set _state(client) 1
184    set _hostlist $hostlist
185    set _restore 1
186
187    array set _view {
188        theta   45
189        phi     45
190        psi     0
191        vx      0
192        vy      0
193        vz      0
194        zoom    0
195        mx      0
196        my      0
197        mz      0
198        x       0
199        y       0
200        z       0
201        width   0
202        height  0
203    }
204
205    # Setup default settings for widget.
206    array set _settings [subst {
207        $this-spherescale 0.25
208        $this-stickradius 0.14
209        $this-cartoontrace no
210        $this-model     ballnstick
211        $this-modelimg  [Rappture::icon ballnstick]
212        $this-opacity   1.0
213        $this-ortho     no
214        $this-rock      no
215        $this-showlabels no
216        $this-showcell  yes
217        $this-showlabels-initialized no
218    }]
219   
220    itk_component add 3dview {
221        label $itk_component(plotarea).vol -image $_image(plot) \
222            -highlightthickness 0 -borderwidth 0
223    } {
224        usual
225        ignore -highlightthickness -borderwidth  -background
226    }
227
228    set f [$itk_component(main) component controls]
229    itk_component add reset {
230        button $f.reset -borderwidth 1 -padx 1 -pady 1 \
231            -highlightthickness 0 \
232            -image [Rappture::icon reset-view] \
233            -command [itcl::code $this ResetView]
234    } {
235        usual
236        ignore -highlightthickness
237    }
238    pack $itk_component(reset) -padx 1 -pady 2
239    Rappture::Tooltip::for $itk_component(reset) \
240        "Reset the view to the default zoom level"
241
242    itk_component add zoomin {
243        button $f.zin -borderwidth 1 -padx 1 -pady 1 \
244            -highlightthickness 0 \
245            -image [Rappture::icon zoom-in] \
246            -command [itcl::code $this Zoom in]
247    } {
248        usual
249        ignore -highlightthickness
250    }
251    pack $itk_component(zoomin) -padx 2 -pady 2
252    Rappture::Tooltip::for $itk_component(zoomin) "Zoom in"
253
254    itk_component add zoomout {
255        button $f.zout -borderwidth 1 -padx 1 -pady 1 \
256            -highlightthickness 0 \
257            -image [Rappture::icon zoom-out] \
258            -command [itcl::code $this Zoom out]
259    } {
260        usual
261        ignore -highlightthickness
262    }
263    pack $itk_component(zoomout) -padx 2 -pady 2
264    Rappture::Tooltip::for $itk_component(zoomout) "Zoom out"
265
266    itk_component add labels {
267        Rappture::PushButton $f.labels \
268            -onimage [Rappture::icon molvis-labels-view] \
269            -offimage [Rappture::icon molvis-labels-view] \
270            -command [itcl::code $this labels update] \
271            -variable [itcl::scope _settings($this-showlabels)]
272    }
273    $itk_component(labels) deselect
274    Rappture::Tooltip::for $itk_component(labels) \
275        "Show/hide the labels on atoms"
276    pack $itk_component(labels) -padx 2 -pady {6 2}
277
278    itk_component add rock {
279        Rappture::PushButton $f.rock \
280            -onimage [Rappture::icon molvis-rock-view] \
281            -offimage [Rappture::icon molvis-rock-view] \
282            -command [itcl::code $this Rock toggle] \
283            -variable [itcl::scope _settings($this-rock)]
284    }
285    pack $itk_component(rock) -padx 2 -pady 2
286    Rappture::Tooltip::for $itk_component(rock) "Rock model back and forth"
287
288    itk_component add ortho {
289        label $f.ortho -borderwidth 1 -padx 1 -pady 1 \
290            -relief "raised" -image [Rappture::icon molvis-3dpers]
291    }
292    pack $itk_component(ortho) -padx 2 -pady 2 -ipadx 1 -ipady 1
293    Rappture::Tooltip::for $itk_component(ortho) \
294        "Use orthoscopic projection"
295
296    bind $itk_component(ortho) <ButtonPress> \
297        [itcl::code $this OrthoProjection toggle]
298
299    BuildSettingsTab
300
301    # HACK ALERT. Initially force a requested width of the 3dview label.
302
303    # It's a chicken-and-the-egg problem.  The size of the 3dview label is set
304    # from the size of the image retrieved from the server.  But the size of
305    # the image is specified by the viewport which is the size of the label.
306    # The fly-in-the-ointment is that it takes a non-trival amount of time to
307    # get the first image back from the server.  In the meantime the idletasks
308    # have already kicked in.  We end up with a 1x1 viewport and image.
309
310    # So the idea is to force a ridiculously big requested width on the label
311    # (that's why we're using the blt::table to manage the geometry).  It has
312    # to be big, because we don't know how big the user may want to stretch
313    # the window.  This at least forces the sidebarframe to give the 3dview
314    # the maximum size available, which is perfect for an initially closed
315    # sidebar.
316
317    blt::table $itk_component(plotarea) \
318        0,0 $itk_component(3dview) -fill both -reqwidth 10000
319    #
320    # RENDERING AREA
321    #
322
323    set _image(id) ""
324
325    # set up bindings for rotation
326    if 0 {
327        bind $itk_component(3dview) <ButtonPress-1> \
328            [itcl::code $this Rotate click %x %y]
329        bind $itk_component(3dview) <B1-Motion> \
330            [itcl::code $this Rotate drag %x %y]
331        bind $itk_component(3dview) <ButtonRelease-1> \
332            [itcl::code $this Rotate release %x %y]
333    } else {
334        bind $itk_component(3dview) <ButtonPress-1> \
335            [itcl::code $this Vmouse click %b %s %x %y]
336        bind $itk_component(3dview) <B1-Motion> \
337            [itcl::code $this Vmouse drag 1 %s %x %y]
338        bind $itk_component(3dview) <ButtonRelease-1> \
339            [itcl::code $this Vmouse release %b %s %x %y]
340    }
341
342    bind $itk_component(3dview) <ButtonPress-2> \
343        [itcl::code $this Pan click %x %y]
344    bind $itk_component(3dview) <B2-Motion> \
345        [itcl::code $this Pan drag %x %y]
346    bind $itk_component(3dview) <ButtonRelease-2> \
347        [itcl::code $this Pan release %x %y]
348
349    bind $itk_component(3dview) <KeyPress-Left> \
350        [itcl::code $this Pan set -10 0]
351    bind $itk_component(3dview) <KeyPress-Right> \
352        [itcl::code $this Pan set 10 0]
353    bind $itk_component(3dview) <KeyPress-Up> \
354        [itcl::code $this Pan set 0 -10]
355    bind $itk_component(3dview) <KeyPress-Down> \
356        [itcl::code $this Pan set 0 10]
357    bind $itk_component(3dview) <Shift-KeyPress-Left> \
358        [itcl::code $this Pan set -50 0]
359    bind $itk_component(3dview) <Shift-KeyPress-Right> \
360        [itcl::code $this Pan set 50 0]
361    bind $itk_component(3dview) <Shift-KeyPress-Up> \
362        [itcl::code $this Pan set 0 -50]
363    bind $itk_component(3dview) <Shift-KeyPress-Down> \
364        [itcl::code $this Pan set 0 50]
365    bind $itk_component(3dview) <KeyPress-Prior> \
366        [itcl::code $this Zoom out 2]
367    bind $itk_component(3dview) <KeyPress-Next> \
368        [itcl::code $this Zoom in 2]
369
370    bind $itk_component(3dview) <Enter> "focus $itk_component(3dview)"
371
372
373    if {[string equal "x11" [tk windowingsystem]]} {
374        bind $itk_component(3dview) <4> [itcl::code $this Zoom out 2]
375        bind $itk_component(3dview) <5> [itcl::code $this Zoom in 2]
376    }
377
378    # set up bindings to bridge mouse events to server
379    #bind $itk_component(3dview) <ButtonPress> \
380    #   [itcl::code $this Vmouse2 click %b %s %x %y]
381    #bind $itk_component(3dview) <ButtonRelease> \
382    #    [itcl::code $this Vmouse2 release %b %s %x %y]
383    #bind $itk_component(3dview) <B1-Motion> \
384    #    [itcl::code $this Vmouse2 drag 1 %s %x %y]
385    #bind $itk_component(3dview) <B2-Motion> \
386    #    [itcl::code $this Vmouse2 drag 2 %s %x %y]
387    #bind $itk_component(3dview) <B3-Motion> \
388    #    [itcl::code $this Vmouse2 drag 3 %s %x %y]
389    #bind $itk_component(3dview) <Motion> \
390    #    [itcl::code $this Vmouse2 move 0 %s %x %y]
391
392    bind $itk_component(3dview) <Configure> \
393        [itcl::code $this EventuallyResize %w %h]
394    bind $itk_component(3dview) <Unmap> \
395        [itcl::code $this Unmap]
396    bind $itk_component(3dview) <Map> \
397        [itcl::code $this Map]
398
399    eval itk_initialize $args
400    Connect
401}
402
403itcl::body Rappture::MolvisViewer::BuildSettingsTab {} {
404    set fg [option get $itk_component(hull) font Font]
405
406    set inner [$itk_component(main) insert end \
407        -title "Settings" \
408        -icon [Rappture::icon wrench]]
409    $inner configure -borderwidth 4
410
411    label $inner.drawinglabel -text "Molecule Representation" \
412        -font "Arial 9 bold"
413
414    label $inner.pict -image $_settings($this-modelimg)
415
416    radiobutton $inner.bstick -text "balls and sticks" \
417        -command [itcl::code $this Representation ballnstick all] \
418        -variable Rappture::MolvisViewer::_settings($this-model) \
419        -value ballnstick -font "Arial 9" -pady 0
420    Rappture::Tooltip::for $inner.bstick \
421        "Display atoms (balls) and connections (sticks) "
422
423    radiobutton $inner.spheres -text "spheres" \
424        -command [itcl::code $this Representation spheres all] \
425        -variable Rappture::MolvisViewer::_settings($this-model) \
426        -value spheres -font "Arial 9" -pady 0
427    Rappture::Tooltip::for $inner.spheres \
428        "Display atoms as spheres. Do not display bonds."
429
430    radiobutton $inner.sticks -text "sticks" \
431        -command [itcl::code $this Representation sticks all] \
432        -variable Rappture::MolvisViewer::_settings($this-model) \
433        -value sticks -font "Arial 9" -pady 0
434    Rappture::Tooltip::for $inner.sticks \
435        "Display bonds as sticks. Do not display atoms."
436
437    radiobutton $inner.lines -text "lines" \
438        -command [itcl::code $this Representation lines all] \
439        -variable [itcl::scope _settings($this-model)] \
440        -value lines -font "Arial 9" -pady 0
441    Rappture::Tooltip::for $inner.lines \
442        "Display bonds as lines. Do not display atoms."
443
444    radiobutton $inner.cartoon -text "cartoon" \
445        -command [itcl::code $this Representation cartoon all] \
446        -variable [itcl::scope _settings($this-model)] \
447        -value cartoon -font "Arial 9" -pady 0
448    Rappture::Tooltip::for $inner.cartoon \
449        "Display cartoon representation of bonds (sticks)."
450
451    scale $inner.spherescale -width 10 -font "Arial 9 bold" \
452        -from 0.1 -to 2.0 -resolution 0.05 -label "Sphere Scale" \
453        -showvalue true -orient horizontal \
454        -command [itcl::code $this SphereScale] \
455        -variable Rappture::MolvisViewer::_settings($this-spherescale)
456    $inner.spherescale set $_settings($this-spherescale)
457    Rappture::Tooltip::for $inner.spherescale \
458        "Adjust scale of atoms (spheres or balls). 1.0 is the full VDW radius."
459
460    scale $inner.stickradius -width 10 -font "Arial 9 bold" \
461        -from 0.1 -to 1.0 -resolution 0.025 -label "Stick Radius" \
462        -showvalue true -orient horizontal \
463        -command [itcl::code $this StickRadius] \
464        -variable Rappture::MolvisViewer::_settings($this-stickradius)
465    Rappture::Tooltip::for $inner.stickradius \
466        "Adjust scale of bonds (sticks)."
467    $inner.stickradius set $_settings($this-stickradius)
468
469    checkbutton $inner.labels -text "Show labels on atoms" \
470        -command [itcl::code $this labels update] \
471        -variable [itcl::scope _settings($this-showlabels)] \
472        -font "Arial 9 bold"
473    Rappture::Tooltip::for $inner.labels \
474        "Display atom symbol and serial number."
475
476    checkbutton $inner.rock -text "Rock model back and forth" \
477        -command [itcl::code $this Rock toggle] \
478        -variable Rappture::MolvisViewer::_settings($this-rock) \
479        -font "Arial 9 bold"
480    Rappture::Tooltip::for $inner.rock \
481        "Rotate the object back and forth around the y-axis."
482
483    checkbutton $inner.ortho -text "Orthoscopic projection" \
484        -command [itcl::code $this OrthoProjection update] \
485        -variable Rappture::MolvisViewer::_settings($this-ortho) \
486         -font "Arial 9 bold"
487    Rappture::Tooltip::for $inner.ortho \
488        "Toggle between orthoscopic/perspective projection modes."
489
490    checkbutton $inner.cartoontrace -text "Cartoon Trace" \
491        -command [itcl::code $this CartoonTrace update] \
492        -variable [itcl::scope _settings($this-cartoontrace)] \
493        -font "Arial 9 bold"
494    Rappture::Tooltip::for $inner.cartoontrace \
495        "Set cartoon representation of bonds (sticks)."
496
497    checkbutton $inner.cell -text "Parallelepiped" \
498        -command [itcl::code $this Cell toggle] \
499        -font "Arial 9 bold"
500    $inner.cell select
501
502    label $inner.spacer
503    blt::table $inner \
504        0,0 $inner.drawinglabel -anchor w -columnspan 4 \
505        1,1 $inner.pict -anchor w -rowspan 5 \
506        1,2 $inner.bstick -anchor w -columnspan 2 \
507        2,2 $inner.spheres -anchor w -columnspan 2 \
508        3,2 $inner.sticks -anchor w -columnspan 2 \
509        4,2 $inner.lines -anchor w -columnspan 2 \
510        5,2 $inner.cartoon -anchor w -columnspan 2 \
511        6,0 $inner.labels -anchor w -columnspan 4 -pady {1 0} \
512        7,0 $inner.rock -anchor w -columnspan 4 -pady {1 0} \
513        8,0 $inner.ortho -anchor w -columnspan 4 -pady {1 0} \
514        9,0 $inner.cartoontrace -anchor w -columnspan 4 -pady {1 0} \
515        10,0 $inner.cell -anchor w -columnspan 4 -pady {1 0} \
516        11,1 $inner.spherescale -fill x -columnspan 4 -pady {1 0} \
517        12,1 $inner.stickradius -fill x -columnspan 4 -pady {1 0} \
518
519    blt::table configure $inner c0 -resize expand -width 2
520    blt::table configure $inner c1 c2 -resize none
521    blt::table configure $inner c3 -resize expand
522    blt::table configure $inner r* -resize none
523    blt::table configure $inner r13 -resize expand
524}
525
526# ----------------------------------------------------------------------
527# DESTRUCTOR
528# ----------------------------------------------------------------------
529itcl::body Rappture::MolvisViewer::destructor {} {
530    VisViewer::Disconnect
531
532    image delete $_image(plot)
533    array unset _settings $this-*
534}
535
536# ----------------------------------------------------------------------
537# USAGE: download coming
538# USAGE: download controls <downloadCommand>
539# USAGE: download now
540#
541# Clients use this method to create a downloadable representation
542# of the plot.  Returns a list of the form {ext string}, where
543# "ext" is the file extension (indicating the type of data) and
544# "string" is the data itself.
545# ----------------------------------------------------------------------
546itcl::body Rappture::MolvisViewer::download {option args} {
547    switch $option {
548        coming {}
549        controls {
550            set popup .molvisviewerdownload
551            if { ![winfo exists .molvisviewerdownload] } {
552                set inner [DownloadPopup $popup [lindex $args 0]]
553            } else {
554                set inner [$popup component inner]
555            }
556            set _downloadPopup(image_controls) $inner.image_frame
557            set num [llength [get]]
558            set num [expr {($num == 1) ? "1 result" : "$num results"}]
559            set word [Rappture::filexfer::label downloadWord]
560            $inner.summary configure -text "$word $num in the following format:"
561            update idletasks ;          # Fix initial sizes
562            return $popup
563        }
564        now {
565
566            set popup .molvisviewerdownload
567            if {[winfo exists .molvisviewerdownload]} {
568                $popup deactivate
569            }
570            switch -- $_downloadPopup(format) {
571                "image" {
572                    return [$this GetImage [lindex $args 0]]
573                }
574                "pdb" {
575                    return [list .pdb $_pdbdata]
576                }
577            }
578        }
579        default {
580            error "bad option \"$option\": should be coming, controls, now"
581        }
582    }
583}
584
585#
586# isconnected --
587#
588#       Indicates if we are currently connected to the visualization server.
589#
590itcl::body Rappture::MolvisViewer::isconnected {} {
591    return [VisViewer::IsConnected]
592}
593
594
595#
596# Connect --
597#
598#       Establishes a connection to a new visualization server.
599#
600itcl::body Rappture::MolvisViewer::Connect {} {
601    global readyForNextFrame
602    set readyForNextFrame 1
603    if { [isconnected] } {
604        return 1
605    }
606    set hosts [GetServerList "pymol"]
607    if { "" == $hosts } {
608        return 0
609    }
610    set _restore 1
611    set result [VisViewer::Connect $hosts]
612    if { $result } {
613        $_dispatcher event -idle !rebuild
614    }
615    return $result
616}
617
618#
619# Disconnect --
620#
621#       Clients use this method to disconnect from the current rendering
622#       server.
623#
624itcl::body Rappture::MolvisViewer::Disconnect {} {
625    VisViewer::Disconnect
626
627    # disconnected -- no more data sitting on server
628    catch { after cancel $_rocker(afterid) }
629    catch { after cancel $_mevent(afterid) }
630    array unset _dataobjs
631    array unset _model
632    array unset _mlist
633    array unset _imagecache
634
635    set _state(server) 1
636    set _state(client) 1
637    set _outbuf ""
638    global readyForNextFrame
639    set readyForNextFrame 1
640}
641
642itcl::body Rappture::MolvisViewer::SendCmd { cmd } {
643    debug "in SendCmd ($cmd)\n"
644
645    if { $_buffering } {
646        # Just buffer the commands. Don't send them yet.
647        if { $_state(server) != $_state(client) } {
648            append _outbuf "frame -defer $_state(client)\n"
649            set _state(server) $_state(client)
650        }
651        if { $_rocker(server) != $_rocker(client) } {
652            append _outbuf "rock -defer $_rocker(client)\n"
653            set _rocker(server) $_rocker(client)
654        }
655        append _outbuf "$cmd\n"
656    } else {
657        if { $_state(server) != $_state(client) } {
658            if { ![SendBytes "frame -defer $_state(client)\n"] } {
659                set _state(server) $_state(client)
660            }
661        }
662        if { $_rocker(server) != $_rocker(client) } {
663            if { ![SendBytes "rock -defer $_rocker(client)\n"] } {
664                set _rocker(server) $_rocker(client)
665            }
666        }
667        SendBytes "$cmd\n"
668    }
669}
670
671#
672# ReceiveImage -bytes <size>
673#
674#     Invoked automatically whenever the "image" command comes in from
675#     the rendering server.  Indicates that binary image data with the
676#     specified <size> will follow.
677#
678set count 0
679itcl::body Rappture::MolvisViewer::ReceiveImage { size cacheid frame rock } {
680    global readyForNextFrame
681    set readyForNextFrame 1
682    set tag "$frame,$rock"
683    global count
684    incr count
685    if { $cacheid != $_cacheid } {
686        array unset _imagecache
687        set _cacheid $cacheid
688    }
689    #debug "reading $size bytes from proxy\n"
690    set data [ReceiveBytes $size]
691    #debug "success: reading $size bytes from proxy\n"
692    if { $cacheid == "print" } {
693        # $frame is the token that we sent to the proxy.
694        set _hardcopy($this-$frame) $data
695    } else {
696        set _imagecache($tag) $data
697        #debug "CACHED: $tag,$cacheid"
698        $_image(plot) configure -data $data
699        set _image(id) $tag
700    }
701}
702
703
704# ----------------------------------------------------------------------
705# USAGE: Rebuild
706#
707# Called automatically whenever something changes that affects the
708# data in the widget.  Clears any existing data and rebuilds the
709# widget to display new data.
710# ----------------------------------------------------------------------
711itcl::body Rappture::MolvisViewer::Rebuild {} {
712    debug "in rebuild"
713    set changed 0
714
715    # Turn on buffering of commands to the server.  We don't want to
716    # be preempted by a server disconnect/reconnect (that automatically
717    # generates a new call to Rebuild).   
718    #blt::bltdebug 100
719    set _buffering 1
720    set _cell 0
721
722    if { $_restore } {
723        set _rocker(server) 0
724        set _cacheid 0
725        SendCmd "raw -defer {set auto_color,0}"
726        SendCmd "raw -defer {set auto_show_lines,0}"
727    }
728    set dlist [get]
729    foreach dataobj $dlist {
730        set model [$dataobj get components.molecule.model]
731        if {"" == $model } {
732            set model "molecule"
733            scan $dataobj "::libraryObj%d" suffix
734            set model $model$suffix
735        }
736        lappend _obj2models($dataobj) $model
737        set state [$dataobj get components.molecule.state]
738        if {"" == $state} {
739            set state $_state(server)
740        }
741        if { ![info exists _mlist($model)] } {  # new, turn on
742            set _mlist($model) 2
743        } elseif { $_mlist($model) == 1 } {     # on, leave on
744            set _mlist($model) 3
745        } elseif { $_mlist($model) == 0 } {     # off, turn on
746            set _mlist($model) 2
747        }
748        if { ![info exists _dataobjs($model-$state)] } {
749            set data1      ""
750            set serial    1
751
752            foreach _atom [$dataobj children -type atom components.molecule] {
753                set symbol [$dataobj get components.molecule.$_atom.symbol]
754                set xyz [$dataobj get components.molecule.$_atom.xyz]
755                regsub {,} $xyz {} xyz
756                scan $xyz "%f %f %f" x y z
757                set recname  "ATOM  "
758                set altLoc   ""
759                set resName  ""
760                set chainID  ""
761                set Seqno    ""
762                set occupancy  1
763                set tempFactor 0
764                set recID      ""
765                set segID      ""
766                set element    ""
767                set charge     ""
768                set atom $symbol
769                set line [format "%6s%5d %4s%1s%3s %1s%5s   %8.3f%8.3f%8.3f%6.2f%6.2f%8s\n" $recname $serial $atom $altLoc $resName $chainID $Seqno $x $y $z $occupancy $tempFactor $recID]
770                append data1 $line
771                incr serial
772            }
773            if {"" != $data1} {
774                # Save the PDB data in case the user wants to later save it.
775                set _pdbdata $data1
776                set nBytes [string length $data1]
777
778                # We know we're buffered here, so append the "loadpdb" command
779                # with the data payload immediately afterwards.
780                SendCmd "loadpdb -defer follows $model $state $nBytes"
781                append _outbuf $data1
782                set _dataobjs($model-$state)  1
783            }
784            # note that pdb files always overwrite xyz files
785            set data2 [$dataobj get components.molecule.pdb]
786            if {"" != $data2} {
787                # Save the PDB data in case the user wants to later save it.
788                set _pdbdata $data2
789                set nBytes [string length $data2]
790
791                # We know we're buffered here, so append the "loadpdb" command
792                # with the data payload immediately afterwards.
793                SendCmd "loadpdb -defer follows $model $state $nBytes"
794                append _outbuf $data2
795                set _dataobjs($model-$state)  1
796            }
797            # lammps dump file overwrites pdb file (change this?)
798            set lammpstypemap [$dataobj get components.molecule.lammpstypemap]
799            set lammpsdata [$dataobj get components.molecule.lammps]
800            if {"" != $lammpsdata} {
801                set data3 ""
802                set modelcount 0
803                foreach lammpsline [split $lammpsdata "\n"] {
804                    if {[scan $lammpsline "%d %d %f %f %f" id type x y z] == 5} {
805                        set recname  "ATOM  "
806                        set altLoc   ""
807                        set resName  ""
808                        set chainID  ""
809                        set Seqno    ""
810                        set occupancy  1
811                        set tempFactor 0
812                        set recID      ""
813                        set segID      ""
814                        set element    ""
815                        set charge     ""
816                        if { "" == $lammpstypemap} {
817                            set atom $type
818                        } else {
819                            set atom [lindex $lammpstypemap [expr {$type - 1}]]
820                            if { "" == $atom} {
821                              set atom $type
822                            }
823                        }
824                        set pdbline [format "%6s%5d %4s%1s%3s %1s%5s   %8.3f%8.3f%8.3f%6.2f%6.2f%8s\n" $recname $id $atom $altLoc $resName $chainID $Seqno $x $y $z $occupancy $tempFactor $recID]
825                        append data3 $pdbline
826                    }
827                    # only read first model
828                    if {[regexp "^ITEM: ATOMS" $lammpsline]} {
829                      incr modelcount
830                      if {$modelcount > 1} {
831                        break
832                      }
833                    }
834                }
835                if {"" != $data3} {
836                    # Save the PDB data in case the user wants to later save it.
837                    set _pdbdata $data3
838                    set nBytes [string length $data3]
839
840                    # We know we're buffered here, so append the "loadpdb"
841                    # command with the data payload immediately afterwards.
842                    SendCmd "loadpdb -defer follows $model $state $nBytes"
843                    append _outbuf $data3
844                }
845                set _dataobjs($model-$state) 1
846            }
847        }
848        if { ![info exists _model($model-transparency)] } {
849            set _model($model-transparency) ""
850        }
851        if { ![info exists _model($model-rep)] } {
852            set _model($model-rep) ""
853            set _model($model-newrep) $_mrep
854        }
855        if { $_model($model-transparency) != $_dobj2transparency($dataobj) } {
856            set _model($model-newtransparency) $_dobj2transparency($dataobj)
857        }
858        if { $_dobj2transparency($dataobj) == "ghost"} {
859            array unset _active $model
860        } else {
861            set _active($model) $dataobj
862        }
863        set vector [$dataobj get components.parallelepiped.vector]
864        if { $vector != "" } {
865            set vertices [ComputeParallelepipedVertices $dataobj]
866            SendCmd "raw -defer {verts = \[$vertices\]\n}"
867            SendCmd "raw -defer {run \$PYMOL_PATH/rappture/box.py\n}"
868            SendCmd "raw -defer {draw_box(verts)\n}"
869            set _cell 1
870        }
871    }
872       
873    # enable/disable models as required (0=off->off, 1=on->off, 2=off->on,
874    # 3=on->on)
875
876    foreach model [array names _mlist] {
877        if { $_mlist($model) == 1 } {
878            SendCmd "disable -defer $model"
879            set _mlist($model) 0
880            set changed 1
881        } elseif { $_mlist($model) == 2 } {
882            set _mlist($model) 1
883            SendCmd "enable -defer $model"
884            set changed 1
885        } elseif { $_mlist($model) == 3 } {
886            set _mlist($model) 1
887        }
888        if { $_mlist($model) == 1 } {
889            if {  [info exists _model($model-newtransparency)] ||
890                  [info exists _model($model-newrep)] } {
891                if { ![info exists _model($model-newrep)] } {
892                    set _model($model-newrep) $_model($model-rep)
893                }
894                if { ![info exists _model($model-newtransparency)] } {
895                    set _model($model-newtransparency) $_model($model-transparency)
896                }
897                set rep $_model($model-newrep)
898                set transp $_model($model-newtransparency)
899                SendCmd "representation -defer -model $model $rep"
900                set changed 1
901                set _model($model-transparency) $_model($model-newtransparency)
902                set _model($model-rep) $_model($model-newrep)
903                catch {
904                    unset _model($model-newtransparency)
905                    unset _model($model-newrep)
906                }
907            }
908        }
909
910    }
911
912    if { $changed } {
913        array unset _imagecache
914    }
915    if { $dlist == "" } {
916        set _state(server) 1
917        set _state(client) 1
918        SendCmd "frame 1"
919        set flush 1
920    } elseif { ![info exists _imagecache($state,$_rocker(client))] } {
921        set _state(server) $state
922        set _state(client) $state
923        SendCmd "frame $state"
924        set flush 1
925    } else {
926        set _state(client) $state
927        Update
928        set flush 0
929    }
930    if { $_restore } {
931        # Set or restore viewing parameters.  We do this for the first
932        # model and assume this works for everything else.
933        set w  [winfo width $itk_component(3dview)]
934        set h  [winfo height $itk_component(3dview)]
935        SendCmd [subst {
936            reset
937            screen $w $h
938            rotate $_view(mx) $_view(my) $_view(mz)
939            pan $_view(x) $_view(y)
940            zoom $_view(zoom)
941        }]
942        debug "rebuild: rotate $_view(mx) $_view(my) $_view(mz)"
943
944        SendCmd "raw -defer {zoom complete=1}"
945        set _restore 0
946    }
947    if { $changed } {
948        # Default settings for all models.
949        SphereScale update
950        StickRadius update
951        labels update
952        Opacity update
953        CartoonTrace update
954        Cell update
955        OrthoProjection update
956        Representation update
957    }
958    set inner [$itk_component(main) panel "Settings"]
959    if { $_cell } {
960        $inner.cell configure -state normal
961    } else {
962        $inner.cell configure -state disabled
963    }
964    if { $flush } {
965        global readyForNextFrame
966        set readyForNextFrame 0;        # Don't advance to the next frame
967                                        # until we get an image.
968        SendCmd "bmp";                  # Flush the results.
969    }
970    set _buffering 0;                   # Turn off buffering.
971
972    blt::busy hold $itk_component(hull)
973
974    # Actually write the commands to the server socket. 
975    # If it fails, we don't care.  We're finished here.
976    SendBytes $_outbuf;                 
977    set _outbuf "";                     # Clear the buffer.             
978    blt::busy release $itk_component(hull)
979
980    debug "exiting rebuild"
981}
982
983itcl::body Rappture::MolvisViewer::Unmap { } {
984    # Pause rocking loop while unmapped (saves CPU time)
985    Rock pause
986
987    # Blank image, mark current image dirty
988    # This will force reload from cache, or remain blank if cache is cleared
989    # This prevents old image from briefly appearing when a new result is added
990    # by result viewer
991
992    #$_image(plot) blank
993    set _image(id) ""
994}
995
996itcl::body Rappture::MolvisViewer::Map { } {
997    if { [isconnected] } {
998        # Resume rocking loop if it was on
999        Rock unpause
1000        # Rebuild image if modified, or redisplay cached image if not
1001        $_dispatcher event -idle !rebuild
1002    }
1003}
1004
1005itcl::body Rappture::MolvisViewer::DoResize { } {
1006    SendCmd "screen $_width $_height"
1007    $_image(plot) configure -width $_width -height $_height
1008    # Immediately invalidate cache, defer update until mapped
1009    array unset _imagecache
1010    set _resizePending 0
1011}
1012   
1013itcl::body Rappture::MolvisViewer::EventuallyResize { w h } {
1014    set _width $w
1015    set _height $h
1016    if { !$_resizePending } {
1017        $_dispatcher event -idle !resize
1018        set _resizePending 1
1019    }
1020}
1021
1022# ----------------------------------------------------------------------
1023# USAGE: $this Pan click x y
1024#        $this Pan drag x y
1025#        $this Pan release x y
1026#
1027# Called automatically when the user clicks on one of the zoom
1028# controls for this widget.  Changes the zoom for the current view.
1029# ----------------------------------------------------------------------
1030itcl::body Rappture::MolvisViewer::Pan {option x y} {
1031    if { $option == "set" } {
1032        set dx $x
1033        set dy $y
1034        set _view(x) [expr $_view(x) + $dx]
1035        set _view(y) [expr $_view(y) + $dy]
1036        SendCmd "pan $dx $dy"
1037        return
1038    }
1039    if { ![info exists _mevent(x)] } {
1040        set option "click"
1041    }
1042    if { $option == "click" } {
1043        $itk_component(3dview) configure -cursor hand1
1044    }
1045    if { $option == "drag" || $option == "release" } {
1046        set dx [expr $x - $_mevent(x)]
1047        set dy [expr $y - $_mevent(y)]
1048        set _view(x) [expr $_view(x) + $dx]
1049        set _view(y) [expr $_view(y) + $dy]
1050        SendCmd "pan $dx $dy"
1051    }
1052    set _mevent(x) $x
1053    set _mevent(y) $y
1054    if { $option == "release" } {
1055        $itk_component(3dview) configure -cursor ""
1056    }
1057}
1058
1059# ----------------------------------------------------------------------
1060# USAGE: Zoom in
1061# USAGE: Zoom out
1062# USAGE: Zoom reset
1063#
1064# Called automatically when the user clicks on one of the zoom
1065# controls for this widget.  Changes the zoom for the current view.
1066# ----------------------------------------------------------------------
1067itcl::body Rappture::MolvisViewer::Zoom {option {factor 10}} {
1068    switch -- $option {
1069        "in" {
1070            set _view(zoom) [expr $_view(zoom) + $factor]
1071            SendCmd "zoom $factor"
1072        }
1073        "out" {
1074            set _view(zoom) [expr $_view(zoom) - $factor]
1075            SendCmd "zoom -$factor"
1076        }
1077        "reset" {
1078            set _view(zoom) 0
1079            SendCmd "reset"
1080        }
1081    }
1082}
1083
1084itcl::body Rappture::MolvisViewer::Update { args } {
1085    set tag "$_state(client),$_rocker(client)"
1086    if { $_image(id) != "$tag" } {
1087        if { [info exists _imagecache($tag)] } {
1088            $_image(plot) configure -data $_imagecache($tag)
1089            set _image(id) "$tag"
1090        }
1091    }
1092}
1093
1094# ----------------------------------------------------------------------
1095# USAGE: Rock on|off|toggle
1096# USAGE: Rock pause|unpause|step
1097#
1098# Used to control the "rocking" model for the molecule being displayed.
1099# Clients should use only the on/off/toggle options; the rest are for
1100# internal control of the rocking motion.
1101# ----------------------------------------------------------------------
1102itcl::body Rappture::MolvisViewer::Rock { option } {
1103    # cancel any pending rocks
1104    if { [info exists _rocker(afterid)] } {
1105        after cancel $_rocker(afterid)
1106        unset _rocker(afterid)
1107    }
1108    if { ![winfo viewable $itk_component(3dview)] } {
1109        return
1110    }
1111    set _rocker(on) $_settings($this-rock)
1112    if { $option == "step"} {
1113        if { $_rocker(client) >= 10 } {
1114            set _rocker(dir) -1
1115        } elseif { $_rocker(client) <= -10 } {
1116            set _rocker(dir) 1
1117        }
1118        set _rocker(client) [expr {$_rocker(client) + $_rocker(dir)}]
1119        if { ![info exists _imagecache($_state(server),$_rocker(client))] } {
1120            set _rocker(server) $_rocker(client)
1121            SendCmd "rock $_rocker(client)"
1122        }
1123        Update
1124    }
1125    if { $_rocker(on) && $option != "pause" } {
1126         set _rocker(afterid) [after 200 [itcl::code $this Rock step]]
1127    }
1128}
1129
1130
1131itcl::body Rappture::MolvisViewer::Vmouse2 {option b m x y} {
1132    set now [clock clicks -milliseconds]
1133    set vButton [expr $b - 1]
1134    set vModifier 0
1135    set vState 1
1136
1137    if { $m & 1 }      { set vModifier [expr $vModifier | 1 ] }
1138    if { $m & 4 }      { set vModifier [expr $vModifier | 2 ] }
1139    if { $m & 131072 } { set vModifier [expr $vModifier | 4 ] }
1140
1141    if { $option == "click"   } { set vState 0 }
1142    if { $option == "release" } { set vState 1 }
1143    if { $option == "drag"    } { set vState 2 }
1144    if { $option == "move"    } { set vState 3 }
1145
1146    if { $vState == 2 || $vState == 3} {
1147        set diff 0
1148
1149        catch { set diff [expr $now - $_mevent(time)] }
1150        if {$diff < 75} { # 75ms between motion updates
1151            return
1152        }
1153    }
1154    SendCmd "vmouse $vButton $vModifier $vState $x $y"
1155    set _mevent(time) $now
1156}
1157
1158itcl::body Rappture::MolvisViewer::Vmouse {option b m x y} {
1159    set now  [clock clicks -milliseconds]
1160    # cancel any pending delayed dragging events
1161    if { [info exists _mevent(afterid)] } {
1162        after cancel $_mevent(afterid)
1163        unset _mevent(afterid)
1164    }
1165
1166    if { ![info exists _mevent(x)] } {
1167        set option "click"
1168    }
1169    if { $option == "click" } {
1170        $itk_component(3dview) configure -cursor fleur
1171    }
1172    if { $option == "drag" || $option == "release" } {
1173        set diff 0
1174         catch { set diff [expr $now - $_mevent(time) ] }
1175         if {$diff < 25 && $option == "drag" } { # 75ms between motion updates
1176             set _mevent(afterid) [after [expr 25 - $diff] [itcl::code $this Vmouse drag $b $m $x $y]]
1177             return
1178         }
1179        set w [winfo width $itk_component(3dview)]
1180        set h [winfo height $itk_component(3dview)]
1181        if {$w <= 0 || $h <= 0} {
1182            return
1183        }
1184        set x1 [expr double($w) / 3]
1185        set x2 [expr $x1 * 2]
1186        set y1 [expr double($h) / 3]
1187        set y2 [expr $y1 * 2]
1188        set dx [expr $x - $_mevent(x)]
1189        set dy [expr $y - $_mevent(y)]
1190        set mx 0
1191        set my 0
1192        set mz 0
1193
1194        if { $_mevent(x) < $x1 } {
1195            set mz $dy
1196        } elseif { $_mevent(x) < $x2 } {
1197            set mx $dy
1198        } else {
1199            set mz [expr -$dy]
1200        }
1201
1202        if { $_mevent(y) < $y1 } {
1203            set mz [expr -$dx]
1204        } elseif { $_mevent(y) < $y2 } {
1205            set my $dx
1206        } else {
1207            set mz $dx
1208        }
1209        # Accumlate movements
1210        set _view(mx) [expr {$_view(mx) + $mx}]
1211        set _view(my) [expr {$_view(my) + $my}]
1212        set _view(mz) [expr {$_view(mz) + $mz}]
1213        SendCmd "rotate $mx $my $mz"
1214        debug "_vmmouse: rotate $_view(mx) $_view(my) $_view(mz)"
1215    }
1216    set _mevent(x) $x
1217    set _mevent(y) $y
1218    set _mevent(time) $now
1219    if { $option == "release" } {
1220        $itk_component(3dview) configure -cursor ""
1221    }
1222}
1223
1224# ----------------------------------------------------------------------
1225# USAGE: Rotate click <x> <y>
1226# USAGE: Rotate drag <x> <y>
1227# USAGE: Rotate release <x> <y>
1228#
1229# Called automatically when the user clicks/drags/releases in the
1230# plot area.  Moves the plot according to the user's actions.
1231# ----------------------------------------------------------------------
1232itcl::body Rappture::MolvisViewer::Rotate {option x y} {
1233    set now  [clock clicks -milliseconds]
1234    #update idletasks
1235    # cancel any pending delayed dragging events
1236    if { [info exists _mevent(afterid)] } {
1237        after cancel $_mevent(afterid)
1238        unset _mevent(afterid)
1239    }
1240    switch -- $option {
1241        click {
1242            $itk_component(3dview) configure -cursor fleur
1243            set _click(x) $x
1244            set _click(y) $y
1245            set _click(theta) $_view(theta)
1246            set _click(phi) $_view(phi)
1247        }
1248        drag {
1249            if {[array size _click] == 0} {
1250                Rotate click $x $y
1251            } else {
1252                set w [winfo width $itk_component(3dview)]
1253                set h [winfo height $itk_component(3dview)]
1254                if {$w <= 0 || $h <= 0} {
1255                    return
1256                }
1257#         set diff 0
1258#          catch { set diff [expr $now - $_mevent(time) ] }
1259#          if {$diff < 175 && $option == "drag" } { # 75ms between motion updates
1260#              set _mevent(afterid) [after [expr 175 - $diff] [itcl::code $this Rotate drag $x $y]]
1261#              return
1262#          }
1263
1264                if {[catch {
1265                    # this fails sometimes for no apparent reason
1266                    set dx [expr {double($x-$_click(x))/$w}]
1267                    set dy [expr {double($y-$_click(y))/$h}]
1268                }]} {
1269                    return
1270                }
1271
1272                #
1273                # Rotate the camera in 3D
1274                #
1275                if {$_view(psi) > 90 || $_view(psi) < -90} {
1276                    # when psi is flipped around, theta moves backwards
1277                    set dy [expr {-$dy}]
1278                }
1279                set theta [expr {$_view(theta) - $dy*180}]
1280                while {$theta < 0} { set theta [expr {$theta+180}] }
1281                while {$theta > 180} { set theta [expr {$theta-180}] }
1282
1283                if {abs($theta) >= 30 && abs($theta) <= 160} {
1284                    set phi [expr {$_view(phi) - $dx*360}]
1285                    while {$phi < 0} { set phi [expr {$phi+360}] }
1286                    while {$phi > 360} { set phi [expr {$phi-360}] }
1287                    set psi $_view(psi)
1288                } else {
1289                    set phi $_view(phi)
1290                    set psi [expr {$_view(psi) - $dx*360}]
1291                    while {$psi < -180} { set psi [expr {$psi+360}] }
1292                    while {$psi > 180} { set psi [expr {$psi-360}] }
1293                }
1294                array set _view [subst {
1295                    theta $theta
1296                    phi $phi
1297                    psi $psi
1298                }]
1299                foreach { vx vy vz } [Euler2XYZ $theta $phi $psi] break
1300                set a [expr $vx - $_view(vx)]
1301                set a [expr -$a]
1302                set b [expr $vy - $_view(vy)]
1303                set c [expr $vz - $_view(vz)]
1304                array set _view [subst {
1305                    vx $vx
1306                    vy $vy
1307                    vz $vz
1308                }]
1309                SendCmd "rotate $a $b $c"
1310                debug "Rotate $x $y: rotate $_view(vx) $_view(vy) $_view(vz)"
1311                set _click(x) $x
1312                set _click(y) $y
1313            }
1314        }
1315        release {
1316            Rotate drag $x $y
1317            $itk_component(3dview) configure -cursor ""
1318            catch {unset _click}
1319        }
1320        default {
1321            error "bad option \"$option\": should be click, drag, release"
1322        }
1323    }
1324    set _mevent(time) $now
1325}
1326
1327# ----------------------------------------------------------------------
1328# USAGE: Representation spheres|ballnstick|lines|sticks
1329#
1330# Used internally to change the molecular representation used to render
1331# our scene.
1332# ----------------------------------------------------------------------
1333itcl::body Rappture::MolvisViewer::Representation {option {model "all"} } {
1334    if { $option == $_mrep } {
1335        return
1336    }
1337    if { $option == "update" } {
1338        set option $_settings($this-model)
1339    }
1340    if { $option == "sticks" } {
1341        set _settings($this-modelimg) [Rappture::icon lines]
1342    }  else {
1343        set _settings($this-modelimg) [Rappture::icon $option]
1344    }
1345    set inner [$itk_component(main) panel "Settings"]
1346    $inner.pict configure -image $_settings($this-modelimg)
1347
1348    # Save the current option to set all radiobuttons -- just in case.
1349    # This method gets called without the user clicking on a radiobutton.
1350    set _settings($this-model) $option
1351    set _mrep $option
1352
1353    if { $model == "all" } {
1354        set models [array names _mlist]
1355    } else {
1356        set models $model
1357    }
1358
1359    foreach model $models {
1360        if { [info exists _model($model-rep)] } {
1361            if { $_model($model-rep) != $option } {
1362                set _model($model-newrep) $option
1363            } else {
1364                catch { unset _model($model-newrep) }
1365            }
1366        }
1367    }
1368    if { [isconnected] } {
1369        SendCmd "representation -model $model $option"
1370        #$_dispatcher event -idle !rebuild
1371    }
1372}
1373
1374
1375# ----------------------------------------------------------------------
1376# USAGE: OrthoProjection on|off|toggle
1377# USAGE: OrthoProjection update
1378#
1379# Used internally to turn labels associated with atoms on/off, and to
1380# update the positions of the labels so they sit on top of each atom.
1381# ----------------------------------------------------------------------
1382itcl::body Rappture::MolvisViewer::OrthoProjection {option} {
1383    switch -- $option {
1384        "orthoscopic" {
1385            set ortho 1
1386        }
1387        "perspective" {
1388            set ortho 0
1389        }
1390        "toggle" {
1391            set ortho [expr {$_settings($this-ortho) == 0}]
1392        }
1393        "update" {
1394            set ortho $_settings($this-ortho)
1395        }
1396        default {
1397            error "bad option \"$option\": should be on, off, toggle, or update"
1398        }
1399    }
1400    if { $ortho == $_settings($this-ortho) && $option != "update"} {
1401        # nothing to do
1402        return
1403    }
1404    if { $ortho } {
1405        $itk_component(ortho) configure -image [Rappture::icon molvis-3dorth]
1406        Rappture::Tooltip::for $itk_component(ortho) \
1407            "Use perspective projection"
1408        set _settings($this-ortho) 1
1409        SendCmd "orthoscopic on"
1410    } else {
1411        $itk_component(ortho) configure -image [Rappture::icon molvis-3dpers]
1412        Rappture::Tooltip::for $itk_component(ortho) \
1413            "Use orthoscopic projection"
1414        set _settings($this-ortho) 0
1415        SendCmd "orthoscopic off"
1416    }
1417}
1418
1419# ----------------------------------------------------------------------
1420# USAGE: Cell on|off|toggle
1421#
1422# Used internally to turn labels associated with atoms on/off, and to
1423# update the positions of the labels so they sit on top of each atom.
1424# ----------------------------------------------------------------------
1425itcl::body Rappture::MolvisViewer::Cell {option} {
1426    switch -- $option {
1427        "on" - "off" {
1428            set cell $option
1429        }
1430        "toggle" {
1431            set cell [expr {$_settings($this-showcell) == 0}]
1432        }
1433        "update" {
1434            set cell $_settings($this-showcell)
1435        }
1436        default {
1437            error "bad option \"$option\": should be on, off, toggle, or update"
1438        }
1439    }
1440    if { $cell == $_settings($this-showcell) && $option != "update"} {
1441        # nothing to do
1442        return
1443    }
1444    if { $cell } {
1445        Rappture::Tooltip::for $itk_component(ortho) \
1446            "Hide the cell."
1447        set _settings($this-showcell) 1
1448        SendCmd "raw {show everything,unitcell}"
1449    } else {
1450        Rappture::Tooltip::for $itk_component(ortho) \
1451            "Show the cell."
1452        set _settings($this-showcell) 0
1453        SendCmd "raw {hide everything,unitcell}"
1454    }
1455}
1456
1457
1458# ----------------------------------------------------------------------
1459# USAGE: add <dataobj> ?<settings>?
1460#
1461# Clients use this to add a data object to the plot.  The optional
1462# <settings> are used to configure the plot.  Allowed settings are
1463# -color, -brightness, -width, -linestyle, and -raise. Only
1464# -brightness and -raise do anything.
1465# ----------------------------------------------------------------------
1466itcl::body Rappture::MolvisViewer::add { dataobj {options ""}} {
1467    array set params {
1468        -color          auto
1469        -brightness     0
1470        -width          1
1471        -raise          0
1472        -linestyle      solid
1473        -description    ""
1474        -param          ""
1475    }
1476
1477    foreach {opt val} $options {
1478        if {![info exists params($opt)]} {
1479            error "bad settings \"$opt\": should be [join [lsort [array names params]] {, }]"
1480        }
1481        set params($opt) $val
1482    }
1483
1484    set pos [lsearch -exact $dataobj $_dlist]
1485
1486    if {$pos < 0} {
1487        if {![Rappture::library isvalid $dataobj]} {
1488            error "bad value \"$dataobj\": should be Rappture::library object"
1489        }
1490
1491        if { !$_settings($this-showlabels-initialized) } {
1492            set showlabels [$dataobj get components.molecule.about.emblems]
1493            if { $showlabels != "" && [string is boolean $showlabels] } {
1494                set _settings($this-showlabels) $showlabels
1495            }
1496        }
1497
1498        lappend _dlist $dataobj
1499        if { $params(-brightness) >= 0.5 } {
1500            set _dobj2transparency($dataobj) "ghost"
1501        } else {
1502            set _dobj2transparency($dataobj) "normal"
1503        }
1504        set _dobj2raise($dataobj) $params(-raise)
1505        debug "setting parameters for $dataobj\n"
1506
1507        if { [isconnected] } {
1508            $_dispatcher event -idle !rebuild
1509        }
1510    }
1511}
1512
1513#
1514# ResetView
1515#
1516itcl::body Rappture::MolvisViewer::ResetView {} {
1517    array set _view {
1518        theta   45
1519        phi     45
1520        psi     0
1521        mx      0
1522        my      0
1523        mz      0
1524        x       0
1525        y       0
1526        z       0
1527        zoom    0
1528        width   0
1529        height  0
1530    }
1531    SendCmd "reset"
1532    SendCmd "rotate $_view(mx) $_view(my) $_view(mz)"
1533    debug "ResetView: rotate $_view(mx) $_view(my) $_view(mz)"
1534    SendCmd "pan $_view(x) $_view(y)"
1535    SendCmd "zoom $_view(zoom)"
1536}
1537
1538# ----------------------------------------------------------------------
1539# USAGE: get
1540#
1541# Clients use this to query the list of objects being plotted, in
1542# order from bottom to top of this result.
1543# ----------------------------------------------------------------------
1544itcl::body Rappture::MolvisViewer::get {} {
1545    # put the dataobj list in order according to -raise options
1546    set dlist $_dlist
1547    foreach obj $dlist {
1548        if {[info exists _dobj2raise($obj)] && $_dobj2raise($obj)} {
1549            set i [lsearch -exact $dlist $obj]
1550            if {$i >= 0} {
1551                set dlist [lreplace $dlist $i $i]
1552                lappend dlist $obj
1553            }
1554        }
1555    }
1556    return $dlist
1557}
1558
1559# ----------------------------------------------------------------------
1560# USAGE: delete ?<dataobj> <dataobj> ...?
1561#
1562# Clients use this to delete a dataobj from the plot. If no dataobjs
1563# are specified, then all dataobjs are deleted.
1564# ----------------------------------------------------------------------
1565itcl::body Rappture::MolvisViewer::delete { args } {
1566    if {[llength $args] == 0} {
1567        set args $_dlist
1568    }
1569
1570    # delete all specified dataobjs
1571    set changed 0
1572    foreach dataobj $args {
1573        set pos [lsearch -exact $_dlist $dataobj]
1574        if {$pos >= 0} {
1575            set _dlist [lreplace $_dlist $pos $pos]
1576            if { [info exists _obj2models($dataobj)] } {
1577                foreach model $_obj2models($dataobj) {
1578                    array unset _active $model
1579                }
1580            }
1581            array unset _obj2models $dataobj
1582            array unset _dobj2transparency $dataobj
1583            array unset _dobj2color $dataobj
1584            array unset _dobj2width $dataobj
1585            array unset _dobj2dashes $dataobj
1586            array unset _dobj2raise $dataobj
1587            set changed 1
1588        }
1589    }
1590
1591    # if anything changed, then rebuild the plot
1592    if {$changed} {
1593        if { [isconnected] } {
1594            $_dispatcher event -idle !rebuild
1595        }
1596    }
1597}
1598
1599# ----------------------------------------------------------------------
1600# OPTION: -device
1601# ----------------------------------------------------------------------
1602itcl::configbody Rappture::MolvisViewer::device {
1603    if {$itk_option(-device) != "" } {
1604
1605        if {![Rappture::library isvalid $itk_option(-device)]} {
1606            error "bad value \"$itk_option(-device)\": should be Rappture::library object"
1607        }
1608        $this delete
1609        $this add $itk_option(-device)
1610    } else {
1611        $this delete
1612    }
1613
1614    if { [isconnected] } {
1615        $_dispatcher event -idle !rebuild
1616    }
1617}
1618
1619
1620
1621itcl::body Rappture::MolvisViewer::WaitIcon  { option widget } {
1622    switch -- $option {
1623        "start" {
1624            $_dispatcher dispatch $this !waiticon \
1625                "[itcl::code $this WaitIcon "next" $widget] ; list"
1626            set _icon 0
1627            $widget configure -image [Rappture::icon bigroller${_icon}]
1628            $_dispatcher event -after 100 !waiticon
1629        }
1630        "next" {
1631            incr _icon
1632            if { $_icon >= 8 } {
1633                set _icon 0
1634            }
1635            $widget configure -image [Rappture::icon bigroller${_icon}]
1636            $_dispatcher event -after 100 !waiticon
1637        }
1638        "stop" {
1639            $_dispatcher cancel !waiticon
1640        }
1641    }
1642}
1643           
1644itcl::body Rappture::MolvisViewer::GetImage { widget } {
1645    set token "print[incr _nextToken]"
1646    set var ::Rappture::MolvisViewer::_hardcopy($this-$token)
1647    set $var ""
1648
1649    set controls $_downloadPopup(image_controls)
1650    set combo $controls.size_combo
1651    set size [$combo translate [$combo value]]
1652    switch -- $size {
1653        "standard" {
1654            set width 1200
1655            set height 1200
1656        }
1657        "highquality" {
1658            set width 2400
1659            set height 2400
1660        }
1661        "draft" {
1662            set width 400
1663            set height 400
1664        }
1665        default {
1666            error "unknown image size [$inner.image_size_combo value]"
1667        }
1668    }
1669    # Setup an automatic timeout procedure.
1670    $_dispatcher dispatch $this !pngtimeout "set $var {} ; list"
1671   
1672    set popup .molvisviewerprint
1673    if { ![winfo exists $popup] } {
1674        Rappture::Balloon $popup -title "Generating file..."
1675        set inner [$popup component inner]
1676        label $inner.title -text "Generating hardcopy." -font "Arial 10 bold"
1677        label $inner.please -text "This may take a minute." -font "Arial 10"
1678        label $inner.icon -image [Rappture::icon bigroller0]
1679        button $inner.cancel -text "Cancel" -font "Arial 10 bold" \
1680            -command [list set $var ""]
1681        blt::table $inner \
1682            0,0 $inner.title -columnspan 2 \
1683            1,0 $inner.please -anchor w \
1684            1,1 $inner.icon -anchor e  \
1685            2,0 $inner.cancel -columnspan 2
1686        blt::table configure $inner r0 -pady 4
1687        blt::table configure $inner r2 -pady 4
1688        bind $inner.cancel <KeyPress-Return> [list $inner.cancel invoke]
1689    } else {
1690        set inner [$popup component inner]
1691    }
1692    set combo $controls.bgcolor_combo
1693    set bgcolor [$combo translate [$combo value]]
1694   
1695    $_dispatcher event -after 60000 !pngtimeout
1696    WaitIcon start $inner.icon
1697    grab set -local $inner
1698    focus $inner.cancel
1699   
1700    SendCmd "print $token $width $height $bgcolor"
1701
1702    $popup activate $widget below
1703    # We wait here for either
1704    #  1) the png to be delivered or
1705    #  2) timeout or 
1706    #  3) user cancels the operation.
1707    tkwait variable $var
1708
1709    # Clean up.
1710    $_dispatcher cancel !pngtimeout
1711    WaitIcon stop $inner.icon
1712    grab release $inner
1713    $popup deactivate
1714    update
1715
1716    if { $_hardcopy($this-$token) != "" } {
1717        set combo $controls.type_combo
1718        set type [$combo translate [$combo value]]
1719        switch -- $type {
1720            "jpg" {
1721                set img [image create photo -data $_hardcopy($this-$token)]
1722                set bytes [$img data -format "jpeg -quality 100"]
1723                set bytes [Rappture::encoding::decode -as b64 $bytes]
1724                return [list .jpg $bytes]
1725            }
1726            "gif" {
1727                set img [image create photo -data $_hardcopy($this-$token)]
1728                set bytes [$img data -format "gif"]
1729                set bytes [Rappture::encoding::decode -as b64 $bytes]
1730                return [list .gif $bytes]
1731            }
1732            "png" {
1733                return [list .png $_hardcopy($this-$token)]
1734            }
1735        }
1736    }
1737    return ""
1738}
1739
1740# ----------------------------------------------------------------------
1741# USAGE: SphereScale radius ?model?
1742#        SphereScale update ?model?
1743#
1744# Used internally to change the molecular atom scale used to render
1745# our scene. 
1746#
1747# Note: Only sets the specified radius for active models.  If the model
1748#       is inactive, then it overridden with the value "0.1".
1749# ----------------------------------------------------------------------
1750
1751itcl::body Rappture::MolvisViewer::SphereScale { option {models "all"} } {
1752    if { $option == "update" } {
1753        set radius $_settings($this-spherescale)
1754    } elseif { [string is double $option] } {
1755        set radius $option
1756        if { ($radius < 0.1) || ($radius > 2.0) } {
1757            error "bad atom size \"$radius\""
1758        }
1759    } else {
1760        error "bad option \"$option\""
1761    }
1762    set _settings($this-spherescale) $radius
1763    if { $models == "all" } {
1764        SendCmd "spherescale -model all $radius"
1765        return
1766    }
1767    set overrideradius [expr $radius * 0.8]
1768    SendCmd "spherescale -model all $overrideradius"
1769    foreach model $models {
1770        if { [info exists _active($model)] } {
1771            SendCmd "spherescale -model $model $radius"
1772        }
1773    }
1774}
1775
1776# ----------------------------------------------------------------------
1777# USAGE: StickRadius radius ?models?
1778#        StickRadius update ?models?
1779#
1780# Used internally to change the stick radius used to render
1781# our scene.
1782#
1783# Note: Only sets the specified radius for active models.  If the model
1784#       is inactive, then it overridden with the value "0.25".
1785# ----------------------------------------------------------------------
1786
1787itcl::body Rappture::MolvisViewer::StickRadius { option {models "all"} } {
1788    if { $option == "update" } {
1789        set radius $_settings($this-stickradius)
1790    } elseif { [string is double $option] } {
1791        set radius $option
1792        if { ($radius < 0.1) || ($radius > 2.0) } {
1793            error "bad stick radius \"$radius\""
1794        }
1795    } else {
1796        error "bad option \"$option\""
1797    }
1798    set _settings($this-stickradius) $radius
1799    if { $models == "all" } {
1800        SendCmd "stickradius -model all $radius"
1801        return
1802    }
1803    set overrideradius [expr $radius * 0.8]
1804    SendCmd "stickradius -model all $overrideradius"
1805    foreach model $models {
1806        if { [info exists _active($model)] } {
1807            SendCmd "stickradius -model $model $radius"
1808        }
1809    }
1810}
1811
1812# ----------------------------------------------------------------------
1813# USAGE: Opacity value ?models?
1814#        Opacity update ?models?
1815#
1816# Used internally to change the opacity (transparency) used to render
1817# our scene.
1818#
1819# Note: Only sets the specified transparency for active models.  If the model
1820#       is inactive, then it overridden with the value "0.75".
1821# ----------------------------------------------------------------------
1822
1823itcl::body Rappture::MolvisViewer::Opacity { option } {
1824    if { $option == "update" } {
1825        set opacity $_settings($this-opacity)
1826    } elseif { [string is double $option] } {
1827        set opacity $option
1828        if { ($opacity < 0.0) || ($opacity > 1.0) } {
1829            error "bad opacity \"$opacity\""
1830        }
1831    } else {
1832        error "bad option \"$option\""
1833    }
1834    set _settings($this-opacity) $opacity
1835    set transparency [expr 1.0 - $opacity]
1836    set models [array names _active]
1837    if { [llength $models] == 0 } {
1838        SendCmd "transparency -model all $transparency"
1839        return
1840    }
1841    set overridetransparency 0.60
1842    SendCmd "transparency -model all $overridetransparency"
1843    foreach model $models {
1844        SendCmd "transparency -model $model $transparency"
1845    }
1846}
1847
1848# ----------------------------------------------------------------------
1849# USAGE: labels on|off|toggle
1850# USAGE: labels update
1851#
1852# Used internally to turn labels associated with atoms on/off, and to
1853# update the positions of the labels so they sit on top of each atom.
1854# ----------------------------------------------------------------------
1855itcl::body Rappture::MolvisViewer::labels {option {models "all"}} {
1856    set showlabels $_settings($this-showlabels)
1857    if { $option == "update" } {
1858        set showlabels $_settings($this-showlabels)
1859    } elseif { [string is boolean $option] } {
1860        set showlabels $option
1861    } else {
1862        error "bad option \"$option\""
1863    }
1864    set _settings($this-showlabels) $showlabels
1865    if { $models == "all" } {
1866        SendCmd "label -model all $showlabels"
1867        return
1868    }
1869    SendCmd "label -model all off"
1870    if { $showlabels } {
1871        foreach model $models {
1872            if { [info exists _active($model)] } {
1873                SendCmd "label -model $model $showlabels"
1874            }
1875        }
1876    }
1877}
1878
1879# ----------------------------------------------------------------------
1880# USAGE: CartoonTrace on|off|toggle
1881# USAGE: CartoonTrace update
1882#
1883# Used internally to turn labels associated with atoms on/off, and to
1884# update the positions of the labels so they sit on top of each atom.
1885# ----------------------------------------------------------------------
1886itcl::body Rappture::MolvisViewer::CartoonTrace {option {models "all"}} {
1887    set trace $_settings($this-cartoontrace)
1888    if { $option == "update" } {
1889        set trace $_settings($this-cartoontrace)
1890    } elseif { [string is boolean $option] } {
1891        set trace $option
1892    } else {
1893        error "bad option \"$option\""
1894    }
1895    set _settings($this-cartoontrace) $trace
1896    if { $models == "all" } {
1897        SendCmd "cartoontrace -model all $trace"
1898        return
1899    }
1900    SendCmd "cartoontrace -model all off"
1901    if { $trace } {
1902        foreach model $models {
1903            if { [info exists _active($model)] } {
1904                SendCmd "cartoontrace -model $model $trace"
1905            }
1906        }
1907    }
1908}
1909
1910itcl::body Rappture::MolvisViewer::DownloadPopup { popup command } {
1911    Rappture::Balloon $popup \
1912        -title "[Rappture::filexfer::label downloadWord] as..."
1913    set inner [$popup component inner]
1914    label $inner.summary -text "" -anchor w -font "Arial 11 bold"
1915    radiobutton $inner.pdb_button -text "PDB Protein Data Bank Format File" \
1916        -variable [itcl::scope _downloadPopup(format)] \
1917        -command [itcl::code $this EnableDownload $popup pdb] \
1918        -font "Arial 10 " \
1919        -value pdb 
1920    Rappture::Tooltip::for $inner.pdb_button \
1921        "Save as PDB Protein Data Bank format file."
1922    radiobutton $inner.image_button -text "Image File" \
1923        -variable [itcl::scope _downloadPopup(format)] \
1924        -command [itcl::code $this EnableDownload $popup image] \
1925        -font "Arial 10 " \
1926        -value image
1927    Rappture::Tooltip::for $inner.image_button \
1928        "Save as digital image."
1929
1930    set controls [frame $inner.image_frame -bd 2 -relief groove]
1931    label $controls.size_label -text "Size:" \
1932        -font "Arial 9"
1933    set img $_image(plot)
1934    set res "[image width $img]x[image height $img]"
1935    Rappture::Combobox $controls.size_combo -width 20 -editable no
1936    $controls.size_combo choices insert end \
1937        "draft"  "Draft (400x400)"         \
1938        "standard"  "Standard (1200x1200)"          \
1939        "highquality"  "High Quality (2400x2400)"
1940
1941    label $controls.bgcolor_label -text "Background:" \
1942        -font "Arial 9"
1943    Rappture::Combobox $controls.bgcolor_combo -width 20 -editable no
1944    $controls.bgcolor_combo choices insert end \
1945        "black"  "Black" \
1946        "white"  "White" \
1947        "none"  "Transparent (PNG only)"         
1948
1949    label $controls.type_label -text "Type:" \
1950        -font "Arial 9"
1951    Rappture::Combobox $controls.type_combo -width 20 -editable no
1952    $controls.type_combo choices insert end \
1953        "jpg"  "JPEG Joint Photographic Experts Group Format (*.jpg)" \
1954        "png"  "PNG Portable Network Graphics Format (*.png)"         
1955
1956    button $inner.go -text [Rappture::filexfer::label download] \
1957        -command $command
1958
1959    blt::table $controls \
1960        1,0 $controls.size_label -anchor e \
1961        1,1 $controls.size_combo -anchor w -fill x \
1962        2,0 $controls.bgcolor_label -anchor e \
1963        2,1 $controls.bgcolor_combo -anchor w -fill x \
1964        3,0 $controls.type_label -anchor e \
1965        3,1 $controls.type_combo -anchor w -fill x 
1966    blt::table configure $controls r0 -height 16
1967    blt::table configure $controls -padx 4 -pady {0 6}
1968    blt::table $inner \
1969        0,0 $inner.summary -cspan 2 \
1970        1,0 $inner.pdb_button -cspan 2 -anchor w \
1971        2,0 $inner.image_button -cspan 2 -rspan 2 -anchor nw -ipadx 2 -ipady 2 \
1972        3,1 $controls -fill both \
1973        6,0 $inner.go -cspan 2 -pady 5
1974    blt::table configure $inner c0 -width 11
1975    blt::table configure $inner r2 -height 11
1976    #blt::table configure $inner c1 -width 8
1977    raise $inner.image_button
1978    $inner.pdb_button invoke
1979    $controls.bgcolor_combo value "Black"
1980    $controls.size_combo value "Draft (400x400)"
1981    $controls.type_combo value  "PNG Portable Network Graphics Format (*.png)"
1982    return $inner
1983}
1984
1985itcl::body Rappture::MolvisViewer::EnableDownload { popup what } {
1986    set inner [$popup component inner]
1987    switch -- $what {
1988        "pdb" {
1989            foreach w [winfo children $inner.image_frame] {
1990                $w configure -state disabled
1991            }
1992        }
1993        "image" {
1994            foreach w [winfo children $inner.image_frame] {
1995                $w configure -state normal
1996            }
1997        }
1998        default {
1999            error "unknown type of download"
2000        }
2001    }
2002}
2003
2004itcl::body Rappture::MolvisViewer::snap { w h } {
2005    if { $w <= 0 || $h <= 0 } {
2006        set w [image width $_image(plot)]
2007        set h [image height $_image(plot)]
2008    }
2009    set tag "$_state(client),$_rocker(client)"
2010    if { $_image(id) != "$tag" } {
2011        while { ![info exists _imagecache($tag)] } {
2012            update idletasks
2013            update
2014            after 100
2015        }
2016        if { [info exists _imagecache($tag)] } {
2017            $_image(plot) configure -data $_imagecache($tag)
2018            set _image(id) "$tag"
2019        }
2020    }
2021    set img [image create picture -width $w -height $h]
2022    $img resample $_image(plot)
2023    return $img
2024}
2025
2026# FIXME: Handle 2D vectors
2027itcl::body Rappture::MolvisViewer::ComputeParallelepipedVertices { dataobj } {
2028    # Create a vector for every 3D point
2029    blt::vector point0(3) point1(3) point2(3) point3(3) point4(3) point5(3) \
2030        point6(3) point7(3) origin(3) scale(3)
2031
2032    set count 0
2033    set parent [$dataobj element -as object "components.parallelepiped"]
2034    foreach child [$parent children] {
2035        if { ![string match "vector*" $child] } {
2036            continue
2037        }
2038        incr count
2039        set values [$parent get $child]
2040        regexp -all {,} $values { } values
2041        point$count set $values
2042    }
2043    itcl::delete object $parent
2044    if { $count < 1 || $count > 3 } {
2045        error "bad number of vectors supplied to parallelepiped"
2046    }
2047    point0 set { 0.0 0.0 0.0 }
2048    point4 expr {point2 + point1}
2049    point5 expr {point4 + point3}
2050    point6 expr {point2 + point3}
2051    point7 expr {point1 + point3}
2052
2053    set values [$dataobj get components.parallelepiped.scale]
2054    set n [llength $values]
2055    scale set { 1.0 1.0 1.0 }
2056    if { $n == 1 } {
2057        set scale(0:2) [lindex $values 0]
2058    } elseif { $n == 2 } {
2059        set scale(0:1) [lindex $values 0]
2060    } elseif { $n == 3 } {
2061        scale set $values
2062    }
2063    set values [$dataobj get components.parallelepiped.origin]
2064    set n [llength $values]
2065    origin set { 0.0 0.0 0.0 }
2066    if { $n == 1 } {
2067        set origin(0) [lindex $values 0]
2068    } elseif { $n == 2 } {
2069        set origin(0) [lindex $values 0]
2070        set origin(1) [lindex $values 1]
2071    } elseif { $n == 3 } {
2072        origin set $values
2073    }
2074
2075    # Scale and translate points
2076    for { set i 0 } { $i < 8 } { incr i } {
2077        point${i} expr "(point${i} * scale) + origin"
2078    }
2079
2080    # Generate vertices as a string for PyMOL
2081    set vertices ""
2082    foreach n { 0 1 0 2 0 3 1 4 2 4 2 6 1 7 3 7 5 7 4 5 3 6 5 } {
2083        set values [point${n} range 0 end]
2084        append vertices "\[ [join $values {, }] \], \\\n"
2085    }
2086    set values [point6 range 0 end]
2087    append vertices "\[ [join $values {, }] \]  \\\n"
2088    blt::vector destroy point0 point1 point2 point3 point4 point5 point6 \
2089        point7 origin scale
2090    return $vertices
2091}
Note: See TracBrowser for help on using the repository browser.