File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.88: download - view: text, annotated - select for diffs
Sat Nov 26 01:35:26 2011 UTC (12 years, 5 months ago) by www
Branches: MAIN
CVS tags: language_hyphenation_merge, language_hyphenation, HEAD
Be able to adjust width and height, so you can use 1:1 aspect ratio

    1: # LearningOnline Network with CAPA
    2: # Functionplot responses
    3: #
    4: # $Id: functionplotresponse.pm,v 1.88 2011/11/26 01:35:26 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::functionplotresponse;
   30: use strict;
   31: use Apache::response();
   32: use Apache::lonlocal;
   33: use Apache::lonnet;
   34: use Apache::run;
   35: use LONCAPA;
   36:  
   37: BEGIN {
   38:   &Apache::lonxml::register('Apache::functionplotresponse',('functionplotresponse','backgroundplot','spline',
   39:                                                             'plotobject','plotvector',
   40:                                                             'functionplotvectorrule','functionplotvectorsumrule',
   41:                                                             'functionplotcustomrule',
   42:                                                             'functionplotrule','functionplotruleset',
   43:                                                             'functionplotelements'));
   44: }
   45: 
   46: #
   47: # There can be a number of applets on a page, each called ggbApplet_$id, 
   48: # where $id is the "_"-concatenated part and responseid
   49: #
   50: 
   51: sub geogebra_startcode {
   52:     my ($id,$width,$height)=@_;
   53:     $width=int(1.*$width);
   54:     $height=int(1.*$height);
   55:     unless ($width) { $width=700; }
   56:     unless ($height) { $height=400; }
   57:     return (<<ENDSTARTCODE);
   58: <applet name="ggbApplet_$id" code="geogebra.GeoGebraApplet" archive="geogebra.jar"
   59:          codebase="/adm/geogebra/"  width="$width" height="$height" MAYSCRIPT>
   60:        <param name="java_arguments" value="-Xmx512m -Djnlp.packEnabled=true"/>
   61: ENDSTARTCODE
   62: }
   63: 
   64: sub geogebra_endcode {
   65:     return &Apache::lonhtmlcommon::java_not_enabled()."</applet>\n";
   66: }
   67: 
   68: #
   69: # This is the internal GeoGebra bytecode which defines the spline functions
   70: #
   71: sub geogebra_spline_program {
   72:     return (<<ENDSPLINEPROGRAM);
   73: <param name="ggbBase64" value="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"/>
   74: ENDSPLINEPROGRAM
   75: }
   76: 
   77: #
   78: # The standard set of parameters inside <applet>
   79: #
   80: sub geogebra_default_parameters {
   81:    my ($id)=@_;
   82:    return(<<ENDDEFAULTPARAMETERS);
   83:         <param name="image" value="/adm/lonIcons/lonanim.gif"  />
   84:         <param name="boxborder" value="false"  />
   85:         <param name="centerimage" value="true"  />
   86: 	<param name="cache_archive" value="geogebra.jar, geogebra_main.jar, geogebra_gui.jar, geogebra_cas.jar, geogebra_export.jar, geogebra_algos.jar, geogebra_javascript.jar, geogebra_properties.jar, jlatexmath.jar, jlm_cyrillic.jar, jlm_greek.jar" />
   87: 	<param name="cache_version" value="4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0,4.0.1.0" />
   88:         <param name="framePossible" value="false" />
   89: 
   90:         <param name="showResetIcon" value="false" />
   91:         <param name="showAnimationButton" value="false" />
   92:         <param name="enableRightClick" value="false" />
   93:         <param name="errorDialogsActive" value="true" />
   94:         <param name="enableLabelDrags" value="false" />
   95:         <param name="showMenuBar" value="false" />
   96:         <param name="showToolBar" value="false" />
   97:         <param name="showToolBarHelp" value="false" />
   98:         <param name="showAlgebraInput" value="false" />
   99:         <param name="enableShiftDragZoom" value="false" />
  100:         <param name="allowRescaling" value="false" />
  101:         <param name="enableLabelDrags" value="false" />
  102:         <param name="ggbOnInitParam" value="applet_$id" />
  103: ENDDEFAULTPARAMETERS
  104: }
  105: 
  106: #
  107: # This subroutine is called by LON-CAPA at </problem>
  108: # Each applet on the page will call function ggbOnInit when it is done loading
  109: # This function in turn will call the respective function registered by start_init_script
  110: # Which one of the registered functions is called is determined by ggbOnInitParam, which GeoGebra passes to ggbOnInit
  111: #
  112: 
  113: sub init_script {
  114:    if ($#Apache::functionplotresponse::callscripts>=0) {
  115:       my $script='';
  116:       foreach my $id (@Apache::functionplotresponse::callscripts) {
  117:           $script.="if (param=='applet_$id') { loaded_$id=true; }\n";
  118:       }
  119:       $script.="if (".join(' && ',map { "loaded_$_" } (@Apache::functionplotresponse::callscripts)).
  120:                ") { setTimeout('ggbInitAll()',200) }";
  121:       my $calls=join("\n",map { "ggbInit_$_();" } (@Apache::functionplotresponse::callscripts)); 
  122:       return (<<ENDGGBINIT);
  123: <script type="text/javascript">
  124: // <![CDATA[
  125: // Function that each applet will call when loaded
  126: // It will pass "its" parameter
  127: // Set flags for when an applet is loaded, wait till all are loaded, and then some
  128: function ggbOnInit(param) {
  129: $script
  130: }
  131: function ggbInitAll() {
  132: $calls
  133: }
  134: // ]]>
  135: </script>
  136: ENDGGBINIT
  137:    }
  138: }
  139: 
  140: #
  141: # Each Geogebra applet is supposed to call this when parameters change
  142: # Changes the hidden fields on the web page
  143: #
  144: sub update_script {
  145:     my ($id)=@_;
  146:     return (<<ENDUPDATESCRIPT);
  147: <script type="text/javascript">
  148: // <![CDATA[
  149: function updatePointCoordinates_$id(coordinateName) {
  150:             var x = document.ggbApplet_$id.getXcoord(coordinateName);
  151:             var y = document.ggbApplet_$id.getYcoord(coordinateName);
  152:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_x"].value = x;
  153:             document.lonhomework.elements["HWVAL_$id\_" + coordinateName + "_y"].value = y;
  154:         }
  155: // ]]>
  156: </script>
  157: ENDUPDATESCRIPT
  158: }
  159: 
  160: #
  161: # Register the above update-handler for a variable
  162: #
  163: 
  164: sub update_register {
  165:    my ($id,$variable)=@_;
  166:    return "document.ggbApplet_$id.registerObjectUpdateListener('$variable','updatePointCoordinates_$id');\n";
  167: }
  168: 
  169: #
  170: # Set a point coordinate variable
  171: #
  172: sub set_point_coordinate {
  173:    my ($id,$variable,$x,$y,$fixed)=@_;
  174:    my $mult=($fixed?'a*':'');
  175: # Get rid of wild exponents, make sure it's a number
  176:    $x=1.*$x;
  177:    $y=1.*$y;
  178: # GeoGebra does not understand "E"
  179:    $x=~s/[e|E]/\*10\^/;
  180:    $x=~s/\+//;
  181:    $y=~s/[e|E]/\*10\^/;
  182:    $y=~s/\+//;
  183:    return (<<ENDSETVARIABLE);
  184: document.ggbApplet_$id.evalCommand("a=1");
  185: document.ggbApplet_$id.evalCommand("$variable=$mult($x,$y)");
  186: document.ggbApplet_$id.setLabelVisible("$variable",false);
  187: ENDSETVARIABLE
  188: }
  189: 
  190: #
  191: # Set a slope coordinate variable
  192: #
  193: sub set_slope_coordinate {
  194:    my ($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed)=@_;
  195:    my $xvariable=$variable.'x';
  196:    my $yvariable=$variable.'y';
  197:    my $domain=$xmax-$xmin;
  198:    my $range=$ymax-$ymin;
  199:    my $xinterval=$domain/100.;
  200:    my $yinterval=$range/200.;
  201:    my $mult=($fixed?'a*':'');
  202:    return (<<ENDSETSVARIABLE);
  203: document.ggbApplet_$id.evalCommand("a=1");
  204: document.ggbApplet_$id.evalCommand("$xvariable=Slider[$xinterval,$domain,$xinterval]");
  205: document.ggbApplet_$id.setVisible("$xvariable", false);
  206: document.ggbApplet_$id.evalCommand("$xvariable=$xrel");
  207: document.ggbApplet_$id.evalCommand("$yvariable=Slider[-$range,$range,$yinterval]");
  208: document.ggbApplet_$id.setVisible("$yvariable", false);
  209: document.ggbApplet_$id.evalCommand("$yvariable=$yrel");
  210: document.ggbApplet_$id.evalCommand("$variable=$mult($xvariable+x($pointname),$yvariable+y($pointname))");
  211: document.ggbApplet_$id.setLabelVisible("$variable", false);
  212: ENDSETSVARIABLE
  213: }
  214: 
  215: #
  216: # Input field name for a coordinate variable
  217: #
  218: 
  219: sub field_name {
  220:     my ($id,$variable,$name)=@_;
  221:     return "HWVAL_$id\_$variable\_$name";
  222: }
  223: 
  224: #
  225: # Generate an input field for a coordinate variable
  226: #
  227: 
  228: sub generate_input_field {
  229:     my ($id,$variable,$x,$y)=@_;
  230:     $Apache::functionplotresponse::inputfields.=
  231:        "<input type='hidden' name='".&field_name($id,$variable,'x')."' value='$x' />\n".
  232:        "<input type='hidden' name='".&field_name($id,$variable,'y')."' value='$y' />\n";
  233: }
  234: 
  235: #
  236: # Initialize a new point coordinate variable at set a listener on it
  237: #
  238: sub new_point_coordinate {
  239:     my ($id,$variable,$x,$y,$fixed)=@_;
  240:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
  241:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
  242:     }
  243:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
  244:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
  245:     }
  246:     &generate_input_field($id,$variable,$x,$y);
  247:     return &set_point_coordinate($id,$variable,$x,$y,$fixed).&update_register($id,$variable);
  248: }
  249: 
  250: #
  251: # Initialize a new slope coordinate variable at set a listener on it
  252: #
  253: sub new_slope_coordinate {
  254:     my ($id,$variable,$x,$y,$pointname,$xp,$yp,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
  255: #
  256: # $variable: name of the slope point
  257: # $x, $y: coordinates of the slope point
  258: # $pointname: name of the associated point point
  259: # $xp $yp: coordinates of the point point
  260: #
  261:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'x')})) {
  262:        $x=$Apache::functionplotresponse::previous{&field_name($id,$variable,'x')};
  263:     }
  264:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$variable,'y')})) {
  265:        $y=$Apache::functionplotresponse::previous{&field_name($id,$variable,'y')};
  266:     }
  267:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')})) {
  268:        $xp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'x')};
  269:     }
  270:     if (defined($Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')})) {
  271:        $yp=$Apache::functionplotresponse::previous{&field_name($id,$pointname,'y')};
  272:     }
  273: 
  274:     &generate_input_field($id,$variable,$x,$y);
  275:     my $xrel=$x-$xp;
  276:     my $yrel=$y-$yp;
  277:     return &set_slope_coordinate($id,$variable,$xrel,$yrel,$xmin,$xmax,$ymin,$ymax,$pointname,$fixed).&update_register($id,$variable);
  278: }
  279: 
  280: #
  281: # This registers the init-function call for ggbOnInit, which LON-CAPA will place at </problem>
  282: # It then starts the right headers
  283: #
  284: sub start_init_script {
  285:     my ($id)=@_;
  286: # Add id to the list of ggbInit_$id functions that need to be called
  287:     push(@Apache::functionplotresponse::callscripts,$id);
  288: # ... and open this function
  289:     return (<<ENDSTARTINIT);
  290: <script type="text/javascript">
  291: // <![CDATA[
  292: // variable that will eventually be passed back to the server
  293: var coordinateMap_$id = [];
  294: // flag for not loaded yet
  295: var loaded_$id=false;
  296: // Init-function for applet
  297: function ggbInit_$id() {
  298: ENDSTARTINIT
  299: }
  300: 
  301: #
  302: # This sets the axes inside ggbInit_$id
  303: #
  304: 
  305: sub axes_script {
  306:     my ($id,$xmin,$xmax,$ymin,$ymax,$xvisible,$yvisible,$gvisible)=@_;
  307:     return (<<ENDAXESSCRIPT);
  308:             // changes (xmin, xmax, ymin, ymax)
  309:             document.ggbApplet_$id.setCoordSystem($xmin,$xmax,$ymin,$ymax);
  310: 
  311:             // makes the (x,y) axis (in)visible
  312:             document.ggbApplet_$id.setAxesVisible($xvisible,$yvisible);
  313:             // makes the grid (in)visible
  314:             document.ggbApplet_$id.setGridVisible($gvisible);
  315: ENDAXESSCRIPT
  316: }
  317: 
  318: sub axes_label {
  319:     my ($id,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel)=@_;
  320:     unless ($xlabel || $ylabel) { return ''; }
  321:     my $return='document.ggbApplet_'.$id.'.evalCommand("topRight=Corner[3]");';
  322:     if ($xlabel) {
  323:       if (($ymin<0) && ($ymax>0)) {
  324:        $return.=(<<ENDXAXISLABELSCRIPT);
  325: document.ggbApplet_$id.evalCommand("Xlabel=(x(topRight)-AxisStepX[],AxisStepY[]/6)");
  326: document.ggbApplet_$id.setVisible("Xlabel",false);
  327: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", Xlabel]");
  328: ENDXAXISLABELSCRIPT
  329:       } else {
  330:        $return.=(<<ENDXOFFAXISLABEL);
  331: document.ggbApplet_$id.evalCommand("LowerRight=Corner[2]");
  332: document.ggbApplet_$id.evalCommand("Text[\\"$xlabel\\", (x(LowerRight) - AxisStepX[], y(LowerRight) + AxisStepY[] / 2)]");
  333: ENDXOFFAXISLABEL
  334:       }
  335:     }
  336:     if ($ylabel) {
  337:       if (($xmin<0) && ($xmax>0)) {
  338:        $return.=(<<ENDYAXISLABELSCRIPT);
  339: document.ggbApplet_$id.evalCommand("Ylabel=(AxisStepX[]/6,y(topRight)-AxisStepY[]/3)");
  340: document.ggbApplet_$id.setVisible("Ylabel",false);
  341: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", Ylabel]");
  342: ENDYAXISLABELSCRIPT
  343:       } else {
  344:        $return.=(<<ENDYOFFAXISLABEL);
  345: document.ggbApplet_$id.evalCommand("UpperLeft=Corner[4]");
  346: document.ggbApplet_$id.evalCommand("Text[\\"$ylabel\\", (x(UpperLeft) + AxisStepX[] / 5, y(UpperLeft) - AxisStepY[] / 1.8)]");
  347: ENDYOFFAXISLABEL
  348:       }
  349:     }
  350:     return $return;
  351: }
  352: 
  353: #
  354: # Subroutine to produce background and answer plots
  355: #
  356: 
  357: sub plot_script {
  358:    my ($id,$function,$fixed,$label,$color,$xmin,$xmax,$thickness)=@_;
  359:    $label=~s/\W//g;
  360:    if (($label) && ($label!~/^[A-Za-z]/)) {
  361:       $label='C'.$label;
  362:    }
  363:    my $visible=0;
  364:    if ($label) {
  365:       $visible="1";
  366:    } else {
  367:       $Apache::functionplotresponse::counter++;
  368:       $label='C'.$Apache::functionplotresponse::counter;
  369:    }
  370:    my $rc=0;
  371:    my $gc=0;
  372:    my $bc=0;
  373:    if ($color) {
  374:       my ($rh,$gh,$bh)=($color=~/(..)(..)(..)/);
  375:       $rc=hex($rh);
  376:       $gc=hex($gh);
  377:       $bc=hex($bh);
  378:    }
  379:    if ($fixed) {
  380:       return "document.ggbApplet_$id.evalCommand('$label=Function[$function,$xmin,$xmax]');\n".
  381:              ($visible?'':"document.ggbApplet_$id.setLabelVisible('$label', false);\n").
  382:              ($color?"document.ggbApplet_$id.setColor('$label',$rc,$gc,$bc);\n":'').
  383:              ($thickness?"document.ggbApplet_$id.setLineThickness('$label',$thickness);\n":'');
  384:    } else {
  385:        return "document.ggbApplet_$id.evalCommand('y=$function');\n";
  386:    }
  387: }
  388: 
  389: #
  390: # Subroutine to produce objects
  391: #
  392: 
  393: sub plotobject_script {
  394:    my ($id,$label,$x,$y)=@_;
  395:    unless ($label) {
  396:       $Apache::functionplotresponse::counter++;
  397:       $label='O'.$Apache::functionplotresponse::counter;
  398:    }
  399:    &generate_input_field($id,$label,$x,$y);
  400:    return "document.ggbApplet_$id.evalCommand('a=1');\n".
  401:           "document.ggbApplet_$id.setVisible('a', false);\n".
  402:           "document.ggbApplet_$id.setLabelVisible('a', false);\n".
  403:           "document.ggbApplet_$id.evalCommand('$label=a*($x,$y)');\n".
  404:           "document.ggbApplet_$id.setVisible('$label', true);\n".
  405:           "document.ggbApplet_$id.setLabelVisible('$label', true);\n";
  406: }
  407: 
  408: #
  409: # Subroutine to produce vectors
  410: #
  411: 
  412: sub plotvector_script {
  413:    my ($id,$label,$xs,$ys,$xe,$ye,$xmin,$xmax)=@_;
  414:    unless ($label) {
  415:       $Apache::functionplotresponse::counter++;
  416:       $label='V'.$Apache::functionplotresponse::counter;
  417:    }
  418:    my $startlabel=$label.'Start';
  419:    my $endlabel=$label.'End';
  420:    my $pointlabel=$label.'Point';
  421:    my $pointx=2.*($xmax-$xmin)+$xmax;
  422:    my $anglelabel=$label.'Angle';
  423:    return 
  424:        &new_point_coordinate($id,$startlabel,$xs,$ys,0).
  425:        &new_point_coordinate($id,$endlabel,$xe,$ye,0).
  426:        (<<ENDVECTOR);
  427: document.ggbApplet_$id.evalCommand("$label=Vector[$startlabel,$endlabel]");
  428: document.ggbApplet_$id.setLabelVisible("$label",true);
  429: document.ggbApplet_$id.setLineThickness("$label",8);
  430: document.ggbApplet_$id.evalCommand("$pointlabel=($pointx,y($startlabel))");
  431: document.ggbApplet_$id.evalCommand("$anglelabel=Angle[$pointlabel,$startlabel,$endlabel]");
  432: document.ggbApplet_$id.setLabelVisible("$anglelabel",true);
  433: document.ggbApplet_$id.setLabelStyle("$anglelabel",VALUE=2);
  434: ENDVECTOR
  435: }
  436: 
  437: #
  438: # Answer spline display
  439: # 
  440: # points: x,y,slope_x,slope_y
  441: 
  442: sub answer_spline_script {
  443:    my ($id,@points)=@_;
  444:    my $order=int(($#points+1)/4);
  445:    if ($order<2) { $order=2; }
  446:    if ($order>8) { $order=8; }
  447:    $Apache::functionplotresponse::counter++;
  448:    my $label='CSpline'.$Apache::functionplotresponse::counter;
  449:    my $output='document.ggbApplet_'.$id.'.evalCommand("'.$label.'=Spline'.$order.'[';
  450:    for (my $i=0;$i<=$#points;$i+=4) {
  451:       $output.="($points[$i],$points[$i+1]),($points[$i+2],$points[$i+3]),";
  452:    }
  453:    $output=~s/\,$//;
  454:    $output.=']");'."\n";
  455:    for (my $i=2; $i<2*$order; $i+=2) {
  456:        $output.='document.ggbApplet_'.$id.'.setColor("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",0,170,0);'."\n";
  457:    }
  458:    for (my $i=1; $i<2*$order; $i+=2) {
  459:        $output.='document.ggbApplet_'.$id.'.setVisible("'.$label.'_'.($i>=10?'{':'').$i.($i>=10?'}':'').'",false);'."\n";
  460:    }
  461: 
  462:    return $output;
  463: }
  464: 
  465: #
  466: # Subroutine that generates code for spline $label based on stored information
  467: #
  468: 
  469: sub generate_spline {
  470:    my ($id,$label,$xmin,$xmax,$ymin,$ymax,$fixed)=@_;
  471:    my $result='';
  472:    my $order=$Apache::functionplotresponse::splineorder{$label};
  473:    my $x=$Apache::functionplotresponse::splineinitx{$label};
  474:    my $y=$Apache::functionplotresponse::splineinity{$label};
  475:    my $sx=$Apache::functionplotresponse::splinescalex{$label};
  476:    my $sy=$Apache::functionplotresponse::splinescaley{$label};
  477:    my @coords=();
  478:    foreach my $i (1..$order) {
  479:        $result.=&new_point_coordinate($id,$label.'P'.$i,$x,$y,$fixed);
  480:        my $xp=$x;
  481:        $x+=$sx/(2.*($order-1));
  482:        push(@coords,$label.'P'.$i);
  483:        $result.=&new_slope_coordinate($id,$label.'S'.$i,$x,$y+$sy,$label.'P'.$i,$xp,$y,$xmin,$xmax,$ymin,$ymax,$fixed);
  484:        $x+=$sx/(2.*($order-1));
  485:        push(@coords,$label.'S'.$i);
  486:    }
  487:    $result.='document.ggbApplet_'.$id.'.evalCommand("Spline'.$order.'['.join(',',@coords).']");'."\n";
  488:    return $result;
  489: }
  490: 
  491: #
  492: # Object
  493: #
  494: 
  495: sub start_plotobject {
  496:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  497:    my $result='';
  498:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  499:    my $x=&Apache::lonxml::get_param('x',$parstack,$safeeval);
  500:    my $y=&Apache::lonxml::get_param('y',$parstack,$safeeval);
  501:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
  502:    $label=~s/\W//gs;
  503:    $label=ucfirst($label);
  504:    unless ($label) { $label="NewObject"; }
  505:    if ($target eq 'web') {
  506:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
  507:       unless (defined($x)) { $x=$xmin; }
  508:       unless (defined($y)) { $y=$ymin; }
  509:       $result.=&plotobject_script($internalid,$label,$x,$y);
  510:    } elsif ($target eq 'edit') {
  511:         $result=&Apache::edit::tag_start($target,$token,'Plot Object').
  512:              &Apache::edit::text_arg('Label on Plot:','label',
  513:                                      $token,'16').
  514:              &Apache::edit::text_arg('x:','x',
  515:                                      $token,'8').
  516:              &Apache::edit::text_arg('y:','y',
  517:                                      $token,'8').
  518:              &Apache::edit::end_row();
  519:   } elsif ($target eq 'modified') {
  520:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
  521:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','x','y');
  522:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  523:   }
  524:   return $result;
  525: }
  526: 
  527: sub end_plotobject {
  528:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  529:    my $result='';
  530:    if ($target eq 'edit') {
  531:        $result=&Apache::edit::end_table();
  532:    }
  533:    return $result;
  534: }
  535: 
  536: #
  537: # Vector
  538: #
  539: 
  540: sub start_plotvector {
  541:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  542:    my $result='';
  543:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  544:    my $tailx=&Apache::lonxml::get_param('tailx',$parstack,$safeeval);
  545:    my $taily=&Apache::lonxml::get_param('taily',$parstack,$safeeval);
  546:    my $tipx=&Apache::lonxml::get_param('tipx',$parstack,$safeeval);
  547:    my $tipy=&Apache::lonxml::get_param('tipy',$parstack,$safeeval);
  548: 
  549:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
  550:    $label=~s/\W//gs;
  551:    $label=ucfirst($label);
  552:    unless ($label) { $label="NewVector"; }
  553:    if ($target eq 'web') {
  554:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
  555:       unless (defined($tailx)) { $tailx=$xmin; }
  556:       unless (defined($taily)) { $taily=$ymin; }
  557:       unless (defined($tipx)) { $tipx=$xmin; }
  558:       unless (defined($tipy)) { $tipy=$ymin; }
  559:       $result.=&plotvector_script($internalid,$label,$tailx,$taily,$tipx,$tipy,$xmin,$xmax);
  560:    } elsif ($target eq 'edit') {
  561:         $result=&Apache::edit::tag_start($target,$token,'Plot Vector').
  562:              &Apache::edit::text_arg('Label on Plot:','label',
  563:                                      $token,'16').
  564:              &Apache::edit::text_arg('Tail x:','tailx',
  565:                                      $token,'8').
  566:              &Apache::edit::text_arg('Tail y:','taily',
  567:                                      $token,'8').
  568:              &Apache::edit::text_arg('Tip x:','tipx',
  569:                                      $token,'8').
  570:              &Apache::edit::text_arg('Tip y:','tipy',
  571:                                      $token,'8').
  572: 
  573:              &Apache::edit::end_row();
  574:   } elsif ($target eq 'modified') {
  575:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
  576:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','tipx','tipy');
  577:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  578:   }
  579:   return $result;
  580: }
  581: 
  582: sub end_plotvector {
  583:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  584:    my $result='';
  585:    if ($target eq 'edit') {
  586:        $result=&Apache::edit::end_table();
  587:    }
  588:    return $result;
  589: }
  590: 
  591: 
  592: 
  593: #
  594: # <backgroundplot function="..." fixed="yes/no" />
  595: #
  596: sub start_backgroundplot {
  597:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  598:    my $result='';
  599:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  600:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
  601:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
  602:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
  603:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
  604:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
  605:    $color=~s/[^a-fA-F0-9]//gs;
  606:    unless (length($color)==6) { $color=''; }
  607:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
  608:  
  609:    unless ($function) { $function="0"; }
  610:    if ($target eq 'web') {
  611:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
  612:       unless (defined($xinitial)) { $xinitial=$xmin; }
  613:       unless (defined($xfinal)) { $xfinal=$xmax; }
  614:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
  615:    } elsif ($target eq 'edit') {
  616:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
  617:              &Apache::edit::text_arg('Function:','function',
  618:                                      $token,'16').
  619:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
  620:                                      $token,'8').
  621:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  622:                                      $token,'8').
  623:              &Apache::edit::text_arg('Label on Plot:','label',
  624:                                      $token,'8').
  625:              &Apache::edit::text_arg('Color (hex code):','color',
  626:                                      $token,'8').
  627:              &Apache::edit::select_arg('Fixed location:','fixed',
  628:                                   ['yes','no'],$token).
  629:              &Apache::edit::end_row();
  630:   } elsif ($target eq 'modified') {
  631:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  632:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
  633:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  634:   }
  635:   return $result;
  636: }
  637: 
  638: sub end_backgroundplot {
  639:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  640:    my $result='';
  641:    if ($target eq 'edit') {
  642:        $result=&Apache::edit::end_table();
  643:    }
  644:    return $result;
  645: }
  646: 
  647: #
  648: # <functionplotrule ... />
  649: #
  650: sub start_functionplotrule {
  651:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  652:    my $result='';
  653:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  654:    $Apache::functionplotresponse::counter++;
  655:    if ($label=~/\W/) {
  656:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  657:    }
  658:    $label=~s/\W//gs;
  659:    unless ($label) {
  660:       $label='R'.$Apache::functionplotresponse::counter;
  661:    } else {
  662:       $label='R'.$label;
  663:    }
  664: 
  665:    if ($target eq 'grade') {
  666: # Simply remember - in order - for later
  667:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
  668:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
  669:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
  670:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
  671:       }
  672:       $beginninglabel=~s/\W//gs;
  673:       $endinglabel=~s/\W//gs;
  674:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
  675:       $relationship=~s/\W//gs;
  676:       $relationship=lc($relationship);
  677:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
  678:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
  679:           $relationship='eq';
  680:       }
  681:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
  682:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
  683:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
  684:          $derivative=0;
  685:       }
  686:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
  687:            $label,
  688:            $derivative,
  689:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
  690:            $beginninglabel,
  691:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
  692:            $endinglabel,
  693:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
  694:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
  695:            $relationship,
  696:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
  697:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
  698:           )));
  699:    } elsif ($target eq 'edit') {
  700:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Graph Rule').
  701:              &Apache::edit::text_arg('Index/Name:','index',
  702:                                      $token,'10').'&nbsp;'.
  703:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
  704:                                   [['0','Function itself'],
  705:                                    ['1','First derivative'],
  706:                                    ['2','Second derivative'],
  707:                                    ['-1','Integral']],$token).'<br />'.
  708:              &Apache::edit::text_arg('Initial x-value:','xinitial',
  709:                                       $token,'8').
  710:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
  711:                                                [['start','Start of Plot'],
  712:                                                 ['end','End of Plot']],$token,'8').'<br />'.
  713: 
  714:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  715:                                       $token,'8').
  716:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
  717:                                                [['end','End of Plot']],$token,'8').'<br />'.
  718:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
  719:                                      $token,'8').
  720:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
  721:                                      $token,'8').'<br />'.
  722:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
  723:                                   [['eq','equal'],
  724:                                    ['ne','not equal'],
  725:                                    ['ge','greater than or equal'],
  726:                                    ['gt','greater than'],
  727:                                    ['lt','less than'],
  728:                                    ['le','less than or equal']],$token).
  729:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
  730:                                                [['undef','not defined']],$token,'30').
  731:              &Apache::edit::text_arg('Percent error:','percenterror',
  732:                                      $token,'8').
  733:              &Apache::edit::end_row();
  734:   } elsif ($target eq 'modified') {
  735:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
  736:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
  737:     }
  738:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
  739:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
  740:     }
  741:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  742:                                                  $safeeval,'index','derivativeorder',
  743:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
  744:                                                            'minimumlength','maximumlength',
  745:                                                            'relationship','value','percenterror');
  746:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  747:    }
  748:    return $result;
  749: }
  750: 
  751: sub end_functionplotrule {
  752:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  753:    my $result='';
  754:    if ($target eq 'edit') {
  755:        $result=&Apache::edit::end_table();
  756:    }
  757:    return $result;
  758: }
  759: 
  760: 
  761: #
  762: # <functionplotvectorrule ... />
  763: #
  764: sub start_functionplotvectorrule {
  765:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  766:    my $result='';
  767:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  768:    $Apache::functionplotresponse::counter++;
  769:    if ($label=~/\W/) {
  770:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  771:    }
  772:    $label=~s/\W//gs;
  773:    unless ($label) {
  774:       $label='R'.$Apache::functionplotresponse::counter;
  775:    } else {
  776:       $label='R'.$label;
  777:    }
  778: 
  779:    if ($target eq 'grade') {
  780: # Simply remember - in order - for later
  781: 
  782:       my $id=$Apache::inputtags::response[-1];
  783:       my $partid=$Apache::inputtags::part;
  784:       my $internalid = $partid.'_'.$id;
  785: 
  786:       my $vector=&Apache::lonxml::get_param('vector',$parstack,$safeeval);
  787:       $vector=~s/\W//gs;
  788:       $vector=ucfirst($vector);
  789: 
  790:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  791:            $label,
  792:            'vector',
  793:            $internalid,
  794:            $vector,
  795:            &Apache::lonxml::get_param('attachpoint',$parstack,$safeeval),
  796:            &Apache::lonxml::get_param('notattachpoint',$parstack,$safeeval),
  797:            &Apache::lonxml::get_param('tailpoint',$parstack,$safeeval),
  798:            &Apache::lonxml::get_param('tippoint',$parstack,$safeeval),
  799:            &Apache::lonxml::get_param('nottailpoint',$parstack,$safeeval),
  800:            &Apache::lonxml::get_param('nottippoint',$parstack,$safeeval),
  801:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
  802:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
  803:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
  804:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
  805:           )));
  806:    } elsif ($target eq 'edit') {
  807:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Rule').
  808:              &Apache::edit::text_arg('Index/Name:','index',
  809:                                      $token,'10').'&nbsp;'.
  810:              &Apache::edit::text_arg('Vector:','vector',
  811:                                       $token,'16').'<br />'.
  812:              &Apache::edit::text_arg('Attached to object:','attachpoint',
  813:                                       $token,'16').
  814:              &Apache::edit::text_arg('Not attached to object:','notattachpoint',
  815:                                       $token,'16').'<br />'.
  816:              &Apache::edit::text_arg('Tail attached to object:','tailpoint',
  817:                                       $token,'16').
  818:              &Apache::edit::text_arg('Tip attached to object:','tippoint',
  819:                                       $token,'16').
  820:              &Apache::edit::text_arg('Tail not attached to object:','nottailpoint',
  821:                                       $token,'16').
  822:              &Apache::edit::text_arg('Tip not attached to object:','nottippoint',
  823:                                       $token,'16').'<br />'.
  824:              &Apache::edit::text_arg('Length:','length',
  825:                                      $token,'30').
  826:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
  827:                                      $token,'8').'<br />'.
  828:              &Apache::edit::text_arg('Angle:','angle',
  829:                                      $token,'30').
  830:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
  831:                                      $token,'8').
  832:              &Apache::edit::end_row();
  833:   } elsif ($target eq 'modified') {
  834:     $env{'form.'.&Apache::edit::html_element_name('vector')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('vector')});
  835:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  836:                                                  $safeeval,'index','vector','attachpoint','notattachpoint',
  837:                                                            'tailpoint','tippoint','nottailpoint','nottipoint',
  838:                                                            'length','angle',
  839:                                                            'lengtherror','angleerror');
  840:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  841:    }
  842:    return $result;
  843: }
  844: 
  845: sub end_functionplotvectorrule {
  846:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  847:    my $result='';
  848:    if ($target eq 'edit') {
  849:        $result=&Apache::edit::end_table();
  850:    }
  851:    return $result;
  852: }
  853: 
  854: #
  855: # <functionplotvectorsumrule ... />
  856: #
  857: sub start_functionplotvectorsumrule {
  858:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  859:    my $result='';
  860:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  861:    $Apache::functionplotresponse::counter++;
  862:    if ($label=~/\W/) {
  863:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  864:    }
  865:    $label=~s/\W//gs;
  866:    unless ($label) {
  867:       $label='R'.$Apache::functionplotresponse::counter;
  868:    } else {
  869:       $label='R'.$label;
  870:    }
  871:    if ($target eq 'grade') {
  872: # Simply remember - in order - for later
  873:       my $id=$Apache::inputtags::response[-1];
  874:       my $partid=$Apache::inputtags::part;
  875:       my $internalid = $partid.'_'.$id;
  876:       my $vectors=&Apache::lonxml::get_param('vectors',$parstack,$safeeval);
  877:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  878:            $label,
  879:            'sum',
  880:            $internalid,
  881:            $vectors,
  882:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
  883:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
  884:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
  885:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
  886:           )));
  887:    } elsif ($target eq 'edit') {
  888:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Sum Rule').
  889:              &Apache::edit::text_arg('Index/Name:','index',
  890:                                      $token,'10').'&nbsp;'.
  891:              &Apache::edit::text_arg('Comma-separated list of vectors:','vectors',
  892:                                       $token,'30').'<br />'.
  893:              &Apache::edit::text_arg('Sum vector length:','length',
  894:                                      $token,'30').
  895:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
  896:                                      $token,'8').'<br />'.
  897:              &Apache::edit::text_arg('Sum vector angle:','angle',
  898:                                      $token,'30').
  899:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
  900:                                      $token,'8').
  901:              &Apache::edit::end_row();
  902:    } elsif ($target eq 'modified') {
  903:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  904:                                                    $safeeval,'index','vectors',
  905:                                                              'length','angle',
  906:                                                              'lengtherror','angleerror');
  907:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  908:    }
  909:    return $result;
  910: }
  911: 
  912: sub end_functionplotvectorsumrule {
  913:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  914:    my $result='';
  915:    if ($target eq 'edit') {
  916:        $result=&Apache::edit::end_table();
  917:    }
  918:    return $result;
  919: }
  920: 
  921: #
  922: # <functionplotcustom ... />
  923: #
  924: sub start_functionplotcustomrule {
  925:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  926:    my $result='';
  927:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  928:    $Apache::functionplotresponse::counter++;
  929:    if ($label=~/\W/) {
  930:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  931:    }
  932:    $label=~s/\W//gs;
  933:    unless ($label) {
  934:       $label='R'.$Apache::functionplotresponse::counter;
  935:    } else {
  936:       $label='R'.$label;
  937:    }
  938:    &Apache::lonxml::register('Apache::response',('answer'));
  939:    if ($target eq 'edit') {
  940:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Custom Rule').
  941:              &Apache::edit::text_arg('Index/Name:','index',$token,'10').
  942:              &Apache::edit::end_row();
  943:   } elsif ($target eq 'modified') {
  944:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'index');
  945:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  946:    }
  947:    return $result;
  948: }
  949: 
  950: sub end_functionplotcustomrule {
  951:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  952:    my $result='';
  953:    if ($target eq 'edit') {
  954:       $result=&Apache::edit::end_table();
  955:    } elsif ($target eq 'grade') {
  956: # Simply remember - in order - for later
  957:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  958:       $Apache::functionplotresponse::counter++;
  959:       if ($label=~/\W/) {
  960:          &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  961:       }
  962:       $label=~s/\W//gs;
  963:       unless ($label) {
  964:          $label='R'.$Apache::functionplotresponse::counter;
  965:       } else {
  966:          $label='R'.$label;
  967:       }
  968:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  969:            $label,
  970:            'custom',
  971:            &escape($Apache::response::custom_answer[-1])
  972:           )));
  973:    }
  974:    &Apache::lonxml::deregister('Apache::response',('answer'));
  975:    return $result;
  976: }
  977: 
  978: 
  979: 
  980: #
  981: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
  982: #
  983: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
  984: #
  985: sub start_spline {
  986:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  987:    my $result='';
  988:    if ($target eq 'web') {
  989:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  990:       $Apache::functionplotresponse::counter++;
  991:       if ($label=~/\W/) {
  992:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
  993:       }
  994:       $label=~s/\W//gs;
  995:       unless ($label) { 
  996:          $label='S'.$Apache::functionplotresponse::counter; 
  997:       } else {
  998:          $label='S'.$label;
  999:       }
 1000:       if ($Apache::functionplotresponse::splineorder{$label}) {
 1001:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
 1002:       }
 1003: 
 1004:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
 1005:       if ($order<2) { $order=2; }
 1006:       if ($order>8) { $order=8; }
 1007:       $Apache::functionplotresponse::splineorder{$label}=$order;
 1008: 
 1009:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
 1010:       unless ($x) { $x=0; }
 1011:       $Apache::functionplotresponse::splineinitx{$label}=$x;
 1012: 
 1013:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
 1014:       unless ($y) { $y=0; }
 1015:       $Apache::functionplotresponse::splineinity{$label}=$y;
 1016: 
 1017:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
 1018:       unless ($sx) { $sx=$order; }
 1019:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
 1020: 
 1021:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
 1022:       unless ($sy) { $sy=2; }
 1023:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
 1024:    } elsif ($target eq 'edit') {
 1025:         $result=&Apache::edit::tag_start($target,$token,'Spline').
 1026:              &Apache::edit::text_arg('Index:','index',
 1027:                                      $token,'4').'&nbsp;'.
 1028:              &Apache::edit::select_arg('Order:','order',
 1029:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
 1030:              &Apache::edit::text_arg('Initial x-value:','initx',
 1031:                                      $token,'4').'&nbsp;'.
 1032:              &Apache::edit::text_arg('Initial y-value:','inity',
 1033:                                      $token,'4').'&nbsp;'.
 1034:              &Apache::edit::text_arg('Scale x:','scalex',
 1035:                                      $token,'4').'&nbsp;'.
 1036:              &Apache::edit::text_arg('Scale y:','scaley',
 1037:                                      $token,'4').
 1038:              &Apache::edit::end_row();
 1039:   } elsif ($target eq 'modified') {
 1040:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 1041:                                                  $safeeval,'index','order','initx','inity',
 1042:                                                            'scalex','scaley');
 1043:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
 1044:   }
 1045:   return $result;
 1046: }
 1047: 
 1048: sub end_spline {
 1049:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1050:    my $result='';
 1051:    if ($target eq 'edit') {
 1052:        $result=&Apache::edit::end_table();
 1053:    }
 1054:    return $result;
 1055: }
 1056:  
 1057: sub end_init_script {
 1058:     return (<<ENDENDINIT);
 1059: }
 1060: // ]]>
 1061: </script>
 1062: ENDENDINIT
 1063: }
 1064: 
 1065: #
 1066: # Storing and restoring spline coordinates from part answers
 1067: #
 1068: sub decode_previous_answer {
 1069:    my ($answer)=@_;
 1070:    foreach my $coordinate (split(/\,/,$answer)) {
 1071:       my ($key,$value)=split(/\=/,$coordinate);
 1072:       $Apache::functionplotresponse::previous{$key}=$value;
 1073:    }
 1074: }
 1075: 
 1076: sub get_answer_from_form_fields {
 1077:    my ($id)=@_;
 1078:    my $answer='';
 1079:    my %coords=();
 1080:    foreach my $field (keys(%env)) {
 1081:       if ($field=~/^form\.HWVAL\_$id/) {
 1082:          $field=~/^form\.(.*)$/;
 1083:          $coords{$1}=$env{$field};
 1084:       }
 1085:    }
 1086:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
 1087:    return ($answer,%coords);
 1088: }
 1089: 
 1090: #
 1091: # The following functions calculate the cubic-hermite splines server-side
 1092: #
 1093: 
 1094: sub cubic_hermite {
 1095:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1096:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
 1097:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
 1098: }
 1099: 
 1100: #
 1101: # d/dt(...)
 1102: # 
 1103: 
 1104: sub ddt_cubic_hermite {
 1105:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1106:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
 1107:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
 1108: }
 1109: 
 1110: #
 1111: # d^2/dt^2(...)
 1112: #
 1113: 
 1114: sub d2dt2_cubic_hermite {
 1115:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1116:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
 1117:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
 1118: }
 1119: 
 1120: #
 1121: # Array index calculation
 1122: #
 1123: sub array_index {
 1124:    my ($xmin,$xmax,$x)=@_;
 1125:    if ($x ne '') {
 1126:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
 1127:    } else {
 1128:       return undef;
 1129:    }
 1130: }
 1131: 
 1132: #
 1133: # Populate the arrays
 1134: #
 1135: 
 1136: sub populate_arrays {
 1137:     my ($id,$xmin,$xmax,$ymin,$ymax)=@_;
 1138:     for (my $i=0; $i<=400; $i++) {
 1139:        $Apache::functionplotresponse::actualxval[$i]=undef;
 1140:        $Apache::functionplotresponse::func[$i]=undef;
 1141:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
 1142:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
 1143:     }
 1144:     unless ($xmax>$xmin) { return 'no_func'; }
 1145: # Run over all splines in response
 1146:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
 1147:         my $xiold=-1;
 1148: # Run over all points in spline
 1149:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
 1150:             my $ni=$i+1;
 1151:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
 1152:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
 1153:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
 1154:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
 1155:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
 1156:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
 1157:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
 1158:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
 1159: # Run in small steps over spline parameter
 1160:             for (my $t=0; $t<=1; $t+=0.0001) {
 1161:                 my $xreal=&cubic_hermite($t,@xparms);
 1162:                 my $xi=&array_index($xmin,$xmax,$xreal);
 1163:                 if ($xi<$xiold) { return 'no_func'; }
 1164:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
 1165:                    $xiold=$xi;
 1166:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
 1167: # Function value
 1168:                    my $funcval=&cubic_hermite($t,@yparms);
 1169: 
 1170: # Do we already have a value for this point, and is it different from the new one?
 1171:                    if ((defined($Apache::functionplotresponse::func[$xi])) &&
 1172:                        (abs($Apache::functionplotresponse::func[$xi]-$funcval)>($ymax-$ymin)/100.)) { 
 1173:                        return 'no_func'; 
 1174:                    }
 1175: # Okay, remember the new point
 1176:                    $Apache::functionplotresponse::func[$xi]=$funcval;
 1177: 
 1178:                    if (defined($funcval)) {
 1179:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
 1180:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
 1181:                       }
 1182:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
 1183:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
 1184:                       }
 1185:                    }
 1186: # Chain rule
 1187: # dy/dx=dy/dt/(dx/dt)
 1188:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
 1189:                    if ($dxdt) {
 1190:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
 1191: # Second derivative
 1192:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
 1193:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
 1194:                          ($dxdt*$dxdt*$dxdt);
 1195:                    }
 1196:                 }
 1197:             }
 1198:         }
 1199:     }
 1200: }
 1201: 
 1202: #
 1203: # Implementation of <functionplotresponse>
 1204: #
 1205: 
 1206: sub start_functionplotresponse {
 1207:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1208:   my $result='';
 1209: # To remember the splines - somehow, they need to come last
 1210:   undef %Apache::functionplotresponse::splineorder;
 1211:   undef %Apache::functionplotresponse::splineinitx;
 1212:   undef %Apache::functionplotresponse::splineinity;
 1213:   undef %Apache::functionplotresponse::splinescalex;
 1214:   undef %Apache::functionplotresponse::splinescaley;
 1215: # Remember input fields, etc
 1216:   undef %Apache::functionplotresponse::previous;
 1217:   $Apache::functionplotresponse::inputfields='';
 1218:   $Apache::functionplotresponse::counter=0;
 1219: # Remember rules
 1220:   undef @Apache::functionplotresponse::functionplotrules;
 1221:   undef @Apache::functionplotresponse::functionplotvectorrules;
 1222: # Remember failed rules
 1223:   if ($target eq 'grade') {
 1224:      undef @Apache::functionplotresponse::failedrules;
 1225:   }
 1226: # Delete previous awards
 1227:   undef $Apache::functionplotresponse::awarddetail;
 1228: # Part and ID
 1229:   my $partid=$Apache::inputtags::part;
 1230:   my $id=&Apache::response::start_response($parstack,$safeeval);
 1231: # Internal ID to mark the applet and its coordinates
 1232:   my $internalid = $partid.'_'.$id;
 1233: # Previous answer
 1234:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
 1235: 
 1236: # Parameters of <functionplotresponse>
 1237:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
 1238:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1239:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1240:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1241:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
 1242:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
 1243:   if ($target eq 'edit') {
 1244:     $result.=&Apache::edit::start_table($token)
 1245:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
 1246:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1247:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1248:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1249:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
 1250:        .'</span></td>'
 1251:        ."<td>&nbsp;"
 1252:        .&Apache::edit::end_row()
 1253:        .&Apache::edit::start_spanning_row()
 1254:        ."\n";
 1255:     $result.=&Apache::edit::text_arg('Width (pixels):','width',
 1256:                                      $token,'6').'&nbsp;'.
 1257:              &Apache::edit::text_arg('Height (pixels):','height',
 1258:                                      $token,'6').'<br />'.
 1259:              &Apache::edit::text_arg('Label x-axis:','xlabel',
 1260:                                      $token,'6').'&nbsp;'.
 1261:              &Apache::edit::text_arg('Minimum x-value:','xmin',
 1262:                                      $token,'4').'&nbsp;'.
 1263:              &Apache::edit::text_arg('Maximum x-value:','xmax',
 1264:                                      $token,'4').'&nbsp;'.
 1265:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
 1266:                                   ['yes','no'],$token).'<br />'.
 1267:              &Apache::edit::text_arg('Label y-axis:','ylabel',
 1268:                                      $token,'6').'&nbsp;'.
 1269:              &Apache::edit::text_arg('Minimum y-value:','ymin',
 1270:                                      $token,'4').'&nbsp;'.
 1271:              &Apache::edit::text_arg('Maximum y-value:','ymax',
 1272:                                      $token,'4').'&nbsp;'.
 1273:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
 1274:                                   ['yes','no'],$token).'<br />'.
 1275:              &Apache::edit::select_arg('Grid visible:','gridvisible',
 1276:                                   ['yes','no'],$token).'<br />'.
 1277:              &Apache::edit::text_arg('Background plot(s) for answer (function(x):xmin:xmax,function(x):xmin:xmax,x1:y1:sx1:sy1:x2:y2:sx2:sy2,...):',
 1278:                                          'answerdisplay',$token,'50').
 1279:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
 1280:   } elsif ($target eq 'modified') {
 1281:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 1282:                                                  $safeeval,'width','height','xlabel','xmin','xmax','ylabel','ymin','ymax',
 1283:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
 1284:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 1285: 
 1286:   } elsif ($target eq 'meta') {
 1287:        $result=&Apache::response::meta_package_write('functionplotresponse');
 1288:   } elsif (($target eq 'answer') &&
 1289:             ($env{'form.answer_output_mode'} ne 'tex') &&
 1290:             ($Apache::lonhomework::viewgrades == 'F')) {
 1291:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
 1292:       my $windowopen=&Apache::lonhtmlcommon::javascript_docopen();
 1293:       my $start_page = &Apache::loncommon::start_page('Rules Log', undef,
 1294:                                                {'only_body' => 1,
 1295:                                                 'bgcolor'   => '#FFFFFF',
 1296:                                                 'js_ready'  => 1,});
 1297:       my $end_page = &Apache::loncommon::end_page({'js_ready' => 1,});
 1298:       $uname =~s/\W//g;
 1299:       $udom  =~s/\W//g;
 1300:       my $function_name =
 1301:                 join('_','LONCAPA_scriptvars',$uname,$udom,
 1302:                      $env{'form.counter'},$Apache::lonxml::curdepth);
 1303:       my $rules_var ="<script type=\"text/javascript\">
 1304: // <![CDATA[
 1305:     function $function_name() {newWindow=open('','new_W','width=500,height=500,scrollbars=1,resizable=yes');newWindow.$windowopen;newWindow.document.writeln('$start_page<pre>".
 1306:     $Apache::functionplotresponse::ruleslog.
 1307:     "<\\/pre>$end_page');newWindow.document.close();newWindow.focus()}
 1308: // ]]>
 1309: </script><a href=\"javascript:$function_name();void(0);\">".&mt('Rules Log')."</a><br />";
 1310:             &Apache::lonxml::add_script_result($rules_var);
 1311:         }
 1312: 
 1313:   return $result;
 1314: }
 1315: 
 1316: sub compare_rel {
 1317:    my ($relationship,$value,$realval,$tol)=@_;
 1318: # is the real value undefined?
 1319:    unless (defined($realval)) {
 1320: # the real value is not defined
 1321:       if ($relationship eq 'eq') {
 1322:          if ($value eq 'undef') {
 1323:             return 1;
 1324:          } else {
 1325:             return 0;
 1326:          }
 1327:       } elsif ($relationship eq 'ne') {
 1328:          if ($value eq 'undef') {
 1329:             return 0;
 1330:          } else {
 1331:             return 1;
 1332:          }
 1333:       } else {
 1334:          return 0;
 1335:       }
 1336:    }
 1337: 
 1338: # is the expected value undefined?
 1339:    if ($value eq 'undef') {
 1340: # but by now we know that the real value is defined
 1341:       return 0;
 1342:    }
 1343: 
 1344: # both are defined.
 1345:    if ($relationship eq 'gt') {
 1346:       return ($realval>$value);
 1347:    } elsif ($relationship eq 'ge') {
 1348:       return ($realval>$value-$tol);
 1349:    } elsif ($relationship eq 'lt') {
 1350:       return ($realval<$value);
 1351:    } elsif ($relationship eq 'le') {
 1352:       return ($realval<$value+$tol);
 1353:    } elsif ($relationship eq 'ne') {
 1354:       return (abs($value-$realval)>$tol);
 1355:    } else {
 1356:       return (abs($value-$realval)<$tol);
 1357:    }
 1358:    return 0;
 1359: }
 1360: 
 1361: sub addlog {
 1362:    my ($text)=@_;
 1363:    $text=~s/\'/\\\'/g;
 1364:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
 1365: }
 1366: 
 1367: sub actualval {
 1368:    my ($i,$xmin,$xmax)=@_;
 1369:    return $xmin+$i/400.*($xmax-$xmin);
 1370: }
 1371: 
 1372: sub fpr_val {
 1373:    my ($arg)=@_;
 1374:    return &actualval($Apache::functionplotresponse::functionplotrulelabels{$arg},
 1375:                      $Apache::functionplotresponse::fpr_xmin,
 1376:                      $Apache::functionplotresponse::fpr_xmax);
 1377: }
 1378: 
 1379: sub fpr_f {
 1380:    my ($arg)=@_;
 1381:    return $Apache::functionplotresponse::func[&array_index($Apache::functionplotresponse::fpr_xmin,
 1382:                                                            $Apache::functionplotresponse::fpr_xmax,
 1383:                                                            $arg)];
 1384: }
 1385: 
 1386: sub fpr_dfdx {
 1387:    my ($arg)=@_;
 1388:    return $Apache::functionplotresponse::dfuncdx[&array_index($Apache::functionplotresponse::fpr_xmin,
 1389:                                                               $Apache::functionplotresponse::fpr_xmax,
 1390:                                                               $arg)];
 1391: }
 1392: 
 1393: sub fpr_d2fdx2 {
 1394:    my ($arg)=@_;
 1395:    return $Apache::functionplotresponse::d2funcdx2[&array_index($Apache::functionplotresponse::fpr_xmin,
 1396:                                                                 $Apache::functionplotresponse::fpr_xmax,
 1397:                                                                 $arg)];
 1398: }
 1399: 
 1400: sub fpr_vectorcoords {
 1401:    my ($arg)=@_;
 1402:    $arg=~s/\W//gs;
 1403:    $arg=ucfirst($arg);
 1404:    my $id=$Apache::inputtags::response[-1];
 1405:    my $partid=$Apache::inputtags::part;
 1406:    my $internalid = $partid.'_'.$id;
 1407:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_x'},
 1408:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_x'},
 1409:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_y'},
 1410:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_y'});
 1411: }
 1412: 
 1413: sub fpr_objectcoords {
 1414:    my ($arg)=@_;
 1415:    $arg=~s/\W//gs;
 1416:    $arg=ucfirst($arg);
 1417:    my $id=$Apache::inputtags::response[-1];
 1418:    my $partid=$Apache::inputtags::part;
 1419:    my $internalid = $partid.'_'.$id;
 1420:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'_x'},
 1421:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'_y'});
 1422: }
 1423: 
 1424: sub fpr_vectorlength {
 1425:    my ($arg)=@_;
 1426:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
 1427:    return sqrt(($xe-$xs)*($xe-$xs)+($ye-$ys)*($ye-$ys));
 1428: }
 1429: 
 1430: sub fpr_vectorangle {
 1431:    my ($arg)=@_;
 1432:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
 1433:    my $angle=57.2957795*atan2(($ye-$ys),($xe-$xs));
 1434:    if ($angle<0) { $angle=360+$angle; }
 1435:    return $angle;
 1436: }
 1437: 
 1438: sub vectorcoords {
 1439:    my ($id,$label)=@_;
 1440:    return ($env{'form.HWVAL_'.$id.'_'.$label.'Start_x'},
 1441:            $env{'form.HWVAL_'.$id.'_'.$label.'End_x'},
 1442:            $env{'form.HWVAL_'.$id.'_'.$label.'Start_y'},
 1443:            $env{'form.HWVAL_'.$id.'_'.$label.'End_y'});
 1444: }
 1445: 
 1446: sub objectcoords {
 1447:    my ($id,$label)=@_;
 1448:    return ($env{'form.HWVAL_'.$id.'_'.$label.'_x'},
 1449:            $env{'form.HWVAL_'.$id.'_'.$label.'_y'});
 1450: }
 1451: 
 1452: sub attached {
 1453:    my ($id,$vector,$objects,$xmin,$xmax,$ymin,$ymax)=@_;
 1454:    my ($xs,$xe,$ys,$ye)=&vectorcoords($id,$vector);
 1455:    my $tolx=($xmax-$xmin)/100.;
 1456:    my $toly=($ymax-$ymin)/100.;
 1457:    my $tail=0;
 1458:    my $tip=0;
 1459:    foreach my $obj (split(/\s*\,\s*/,$objects)) {
 1460:       $obj=~s/\W//g;
 1461:       unless ($obj) { next; }
 1462:       $obj=ucfirst($obj);
 1463:       my ($xo,$yo)=&objectcoords($id,$obj);
 1464:       &addlog("Proximity $vector ($xs,$ys)-($xe,$ye) to $obj ($xo,$yo)");
 1465:       if ((abs($xs-$xo)<$tolx) && (abs($ys-$yo)<$toly)) {
 1466:          $tail=1;
 1467:          &addlog("Attached tail: $obj"); 
 1468:       }
 1469:       if ((abs($xe-$xo)<$tolx) && (abs($ye-$yo)<$toly)) { 
 1470:          $tip=1;
 1471:          &addlog("Attached tip: $obj"); 
 1472:       }
 1473:    }
 1474:    &addlog("Result tail:$tail tip:$tip");
 1475:    return($tail,$tip);
 1476: }
 1477: 
 1478:  
 1479: sub vectorangle {
 1480:    my ($x,$y)=@_;
 1481:    my $angle=57.2957795*atan2($y,$x);
 1482:    if ($angle<0) { $angle=360+$angle; }
 1483:    return $angle;
 1484: }
 1485: 
 1486: sub vectorlength {
 1487:    my ($x,$y)=@_;
 1488:    return sqrt($x*$x+$y*$y);
 1489: }
 1490: 
 1491: sub relvector {
 1492:    my ($xs,$xe,$ys,$ye)=@_;
 1493:    return ($xe-$xs,$ye-$ys);
 1494: }
 1495: 
 1496: sub plotvectorlength {
 1497:    return &vectorlength(&relvector(&vectorcoords(@_)));
 1498: }
 1499: 
 1500: sub plotvectorangle {
 1501:    return &vectorangle(&relvector(&vectorcoords(@_)));
 1502: }
 1503: 
 1504: 
 1505: #
 1506: # Evaluate a functionplotvectorrule
 1507: #
 1508: 
 1509: sub functionplotvectorrulecheck {
 1510:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1511:    &addlog("=================");
 1512:    my ($label,$type)=split(/\:/,$rule);
 1513:    if ($type eq 'vector') {
 1514:       return &vectorcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
 1515:    } elsif ($type eq 'sum') {
 1516:       return &sumcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
 1517:    } elsif ($type eq 'custom') {
 1518:       return &customcheck($rule,$safeeval);
 1519:    }
 1520: }
 1521: 
 1522: sub vectorcheck {
 1523:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1524:    my ($label,$type,$id,$vector,
 1525:        $attachpoint,$notattachpoint,
 1526:        $tailpoint,$tippoint,$nottailpoint,$nottippoint,
 1527:        $length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
 1528:    &addlog("Vector Rule $label for vector ".$vector);
 1529:    if ($length ne '') {
 1530:       &addlog("Checking for length $length with error $lengtherror");
 1531:       $length=&Apache::run::run($length,$safeeval);
 1532:       &addlog("Length evaluated to $length");
 1533:       my $thislength=&plotvectorlength($id,$vector);
 1534:       &addlog("Found length $thislength");
 1535:       if (abs($thislength-$length)>$lengtherror) {
 1536:          &setfailed($label);
 1537:          return 0;
 1538:       }
 1539:    }
 1540:    if ($angle ne '') {
 1541:       &addlog("Checking for angle $angle with error $angleerror");
 1542:       $angle=&Apache::run::run($angle,$safeeval);
 1543:       &addlog("Angle evaluated to $angle");
 1544:       my $thisangle=&plotvectorangle($id,$vector);
 1545:       &addlog("Found angle $thisangle");
 1546:       my $anglediff=abs($thisangle-$angle);
 1547:       &addlog("Angle difference: $anglediff");
 1548:       if ($anglediff>360.-$anglediff) {
 1549:          $anglediff=360.-$anglediff;
 1550:       }
 1551:       &addlog("Smallest angle difference: $anglediff");
 1552:       if ($anglediff>$angleerror) {
 1553:          &setfailed($label);
 1554:          return 0;
 1555:       }
 1556:    }
 1557:    if ($attachpoint ne '') {
 1558:       &addlog("Checking attached: ".$attachpoint);
 1559:       my ($tail,$tip)=&attached($id,$vector,$attachpoint,$xmin,$xmax,$ymin,$ymax);
 1560:       unless ($tail || $tip) {
 1561:          &setfailed($label);
 1562:          return 0;
 1563:       }
 1564:    }
 1565:    if ($notattachpoint ne '') {
 1566:       &addlog("Checking not attached: ".$notattachpoint);
 1567:       my ($tail,$tip)=&attached($id,$vector,$notattachpoint,$xmin,$xmax,$ymin,$ymax);
 1568:       if ($tail || $tip) {
 1569:          &setfailed($label);
 1570:          return 0;
 1571:       }
 1572:    }
 1573:    if ($tailpoint ne '') {
 1574:       &addlog("Checking tail: ".$tailpoint);
 1575:       my ($tail,$tip)=&attached($id,$vector,$tailpoint,$xmin,$xmax,$ymin,$ymax);
 1576:       unless ($tail) {
 1577:          &setfailed($label);
 1578:          return 0;
 1579:       }
 1580:    }
 1581:    if ($nottailpoint ne '') {
 1582:       &addlog("Checking not tail: ".$nottailpoint);
 1583:       my ($tail,$tip)=&attached($id,$vector,$nottailpoint,$xmin,$xmax,$ymin,$ymax);
 1584:       if ($tail) {
 1585:          &setfailed($label);
 1586:          return 0;
 1587:       }
 1588:    }
 1589:    if ($tippoint ne '') {
 1590:       &addlog("Checking tip: ".$tippoint);
 1591:       my ($tail,$tip)=&attached($id,$vector,$tippoint,$xmin,$xmax,$ymin,$ymax);
 1592:       unless ($tip) {
 1593:          &setfailed($label);
 1594:          return 0;
 1595:       }
 1596:    }
 1597:    if ($nottippoint ne '') {
 1598:       &addlog("Checking not tip: ".$nottippoint);
 1599:       my ($tail,$tip)=&attached($id,$vector,$nottippoint,$xmin,$xmax,$ymin,$ymax);
 1600:       if ($tip) {
 1601:          &setfailed($label);
 1602:          return 0;
 1603:       }
 1604:    }
 1605: 
 1606:    &addlog("Rule $label passed.");
 1607:    return 1;
 1608: }
 1609: 
 1610: sub sumcheck {
 1611:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1612:    my ($label,$type,$id,$vectors,$length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
 1613:    &addlog("Vector Sum Rule $label for vectors ".$vectors);
 1614:    my $sumx=0;
 1615:    my $sumy=0;
 1616:    foreach my $sv (split(/\s*\,\s*/,$vectors)) {
 1617:       my ($rx,$ry)=&relvector(&vectorcoords($id,$sv));
 1618:       $sumx+=$rx;
 1619:       $sumy+=$ry;
 1620:    }
 1621:    &addlog("Sum vector ($sumx,$sumy)");
 1622:    if ($length ne '') {
 1623:       &addlog("Checking length $length with error $lengtherror");
 1624:       $length=&Apache::run::run($length,$safeeval);
 1625:       &addlog("Evaluated to $length");
 1626:       my $thislength=&vectorlength($sumx,$sumy);
 1627:       &addlog("Actual length $thislength");
 1628:       if (abs($length-$thislength)>$lengtherror) {
 1629:                   &setfailed($label);
 1630:          return 0;
 1631:       }
 1632:    }
 1633:    if ($angle ne '') {
 1634:       &addlog("Checking angle $angle with error $angleerror");
 1635:       $angle=&Apache::run::run($angle,$safeeval);
 1636:       &addlog("Evaluated to $angle");
 1637:       my $thisangle=&vectorangle($sumx,$sumy);
 1638:       &addlog("Actual angle $thisangle");
 1639:       my $anglediff=abs($thisangle-$angle);
 1640:       &addlog("Angle difference: $anglediff");
 1641:       if ($anglediff>360.-$anglediff) {
 1642:          $anglediff=360.-$anglediff;
 1643:       }
 1644:       &addlog("Smallest angle difference: $anglediff");
 1645:       if ($anglediff>$angleerror) {
 1646:          &setfailed($label);
 1647:          return 0;
 1648:       }
 1649:    }
 1650:    &addlog("Rule $label passed.");
 1651:    return 1;
 1652: }
 1653: 
 1654: sub customcheck {
 1655:    my ($rule,$safeeval)=@_;
 1656:    my ($label,$type,$prg)=split(/\:/,$rule);
 1657:    &addlog("Custom Rule ".$label);
 1658:    my $result=&Apache::run::run(&unescape($prg),$safeeval);
 1659:    &addlog("Algorithm returned $result");
 1660:    unless ($result) {
 1661:       &setfailed($label);
 1662:       return 0;
 1663:    }
 1664:    &addlog("Rule $label passed.");
 1665:    return 1;
 1666: }
 1667: 
 1668: #
 1669: # Evaluate a functionplotrule
 1670: #
 1671:  
 1672: sub functionplotrulecheck {
 1673:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1674: 
 1675:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
 1676:       =split(/\:/,$rule);
 1677:    $percent=($percent>0?$percent:5);
 1678:    &addlog("=================");
 1679:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
 1680: #
 1681: # Evaluate the value
 1682: #
 1683:    if ($value=~/\D/) {
 1684:       $Apache::functionplotresponse::fpr_xmin=$xmin;
 1685:       $Apache::functionplotresponse::fpr_xmax=$xmax;
 1686:       $value=&Apache::run::run($value,$safeeval);
 1687:       &addlog("Value evaluated to $value");
 1688:    }
 1689: 
 1690: #
 1691: # Minimum and maximum lengths of the interval
 1692: #
 1693:    if ((defined($minimumlength)) || (defined($maximumlength))) {
 1694:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
 1695:    }
 1696:    my $li=0;
 1697:    my $lh=400;
 1698: 
 1699: # Special case: the upper boundary was not defined
 1700: # and needs to be set to the value where
 1701: # the condition is not true anymore => set flag
 1702: 
 1703:    my $findupper=0;
 1704:    if (($xfinal eq '')
 1705:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
 1706:     && ($xfinallabel)) {
 1707:        $findupper=1;
 1708:    }
 1709: 
 1710: # if a hard value is set for the boundaries, it overrides the label
 1711:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
 1712:       $li=&array_index($xmin,$xmax,$xinitial);
 1713:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
 1714:    }
 1715:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
 1716:       $lh=&array_index($xmin,$xmax,$xfinal);
 1717:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
 1718:    }
 1719: # if the label is defined, use it
 1720:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
 1721:       &addlog("Using lower label $xinitiallabel");
 1722:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
 1723:    } else {
 1724:       $li=&array_index($xmin,$xmax,$xinitial);
 1725:    }
 1726:    unless ($findupper) {
 1727:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
 1728:          &addlog("Using upper label $xfinallabel");
 1729:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
 1730:       } else {
 1731:          $lh=&array_index($xmin,$xmax,$xfinal);
 1732:       }
 1733:    }
 1734: # Basic sanity checks
 1735:    if ($li<0) { $li=0; }
 1736:    if ($lh>400) { $lh=400; }
 1737:    if (($li>$lh) || (!defined($lh))) {
 1738:        $lh=$li;
 1739:    }
 1740: 
 1741:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
 1742:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
 1743:    if ($findupper) {
 1744:       &addlog("Looking for label $xfinallabel");
 1745:    }
 1746:    my $tol=$percent*($ymax-$ymin)/100;
 1747:    if ($xmax>$xmin) {
 1748:       if ($derivative==2) {
 1749:          $tol=4.*$tol/($xmax-$xmin);
 1750:       } elsif ($derivative==1) {
 1751:          $tol=2.*$tol/($xmax-$xmin);
 1752:       } elsif ($derivative==-1) {
 1753:          $tol=$tol*($xmax-$xmin)/2.;
 1754:       }
 1755:    }
 1756:    my $integral=0;
 1757:    my $binwidth=($xmax-$xmin)/400.;
 1758:    if (($derivative<0) && (!$findupper)) {
 1759: # definite integral, calculate over whole length
 1760:      &addlog("Calculating definite integral");
 1761:      for (my $i=$li; $i<=$lh; $i++) {
 1762:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1763:      }
 1764:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
 1765:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
 1766:         &addlog("Rule $label failed.");
 1767:         &setfailed($label);
 1768:         return 0;
 1769:      } 
 1770:    } else {
 1771:      for (my $i=$li; $i<=$lh; $i++) {
 1772:         my $val;
 1773:         if ($derivative==2) {
 1774:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
 1775:         } elsif ($derivative==1) {
 1776:            $val=$Apache::functionplotresponse::dfuncdx[$i];
 1777:         } elsif ($derivative==-1) {
 1778:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1779:            $val=$integral;      
 1780:         } else {
 1781:            $val=$Apache::functionplotresponse::func[$i];
 1782:         }
 1783:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
 1784:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
 1785:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
 1786:            if (($findupper) && ($i>$li)) {
 1787: # Check lengths
 1788:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1789: # Successfully found a new label, set it
 1790:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
 1791:               &addlog("Rule $label passed, setting label $xfinallabel");
 1792:               return 1;
 1793:            } else {
 1794:               &addlog("Rule $label failed.");
 1795:               &setfailed($label);
 1796:               return 0; 
 1797:            }
 1798:         }
 1799:      }
 1800:    }
 1801: # Corner case where this makes sense: using start or stop as defined labels
 1802:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1803:    &addlog("Rule $label passed.");
 1804:    return 1;
 1805: }
 1806: 
 1807: #
 1808: # check for minimum and maximum lengths
 1809: #
 1810: 
 1811: sub checklength {
 1812:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
 1813:     unless (($minimumlength) || ($maximumlength)) { return 1; }
 1814:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
 1815:     if ($minimumlength) {
 1816:        if ($length<$minimumlength) {
 1817:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
 1818:           &setfailed($label);
 1819:           return 0;
 1820:        }
 1821:     }
 1822:     if ($maximumlength) {
 1823:        if ($length>$maximumlength) {
 1824:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
 1825:           &setfailed($label);
 1826:           return 0;
 1827:        }
 1828:     }
 1829:     return 1;
 1830: }
 1831: 
 1832: sub setfailed {
 1833:    my ($hintlabel)=@_;
 1834:    $hintlabel=~s/^R//;
 1835:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
 1836:    &addlog("Set hint condition $hintlabel");
 1837: }
 1838: 
 1839: sub start_functionplotruleset {
 1840:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1841:    if ($target eq 'edit') {
 1842:       return &Apache::edit::start_table($token).
 1843:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
 1844:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1845:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1846:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1847:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
 1848:        .'</span></td>'
 1849:        ."<td>&nbsp;"
 1850:        .&Apache::edit::end_row()
 1851:        .&Apache::edit::start_spanning_row()
 1852:        ."\n";
 1853:    }
 1854: }
 1855: 
 1856: sub end_functionplotruleset {
 1857:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1858:     my $id=$Apache::inputtags::response[-1];
 1859:     my $partid=$Apache::inputtags::part;
 1860:     my $internalid = $partid.'_'.$id;
 1861: 
 1862:     if ($target eq 'edit' ) {
 1863:         return &Apache::edit::end_table();
 1864:     }  elsif ($target eq 'grade'
 1865:          && &Apache::response::submitted()
 1866:          && $Apache::lonhomework::type ne 'exam') {
 1867: #
 1868: # Actually grade
 1869: #
 1870:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1871: 
 1872:         my $ad='';
 1873:         undef  %Apache::functionplotresponse::functionplotrulelabels;
 1874:         $Apache::functionplotresponse::ruleslog='';
 1875:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
 1876:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
 1877:         if (&populate_arrays($internalid,$xmin,$xmax,$ymin,$ymax) eq 'no_func') {
 1878:            $ad='NOT_FUNCTION';
 1879:         } else {
 1880:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
 1881:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
 1882:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
 1883:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
 1884: 
 1885: # We have a function that we can actually grade, go through the spline rules.
 1886:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
 1887:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
 1888:                  $ad='INCORRECT';
 1889:                  last;
 1890:               }
 1891:            }
 1892: # And now go through the vector rules
 1893:            foreach my $rule (@Apache::functionplotresponse::functionplotvectorrules) {
 1894:               unless (&functionplotvectorrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
 1895:                  $ad='INCORRECT';
 1896:                  last;
 1897:               }
 1898:            }
 1899: # If it's not wrong, it's correct 
 1900:            unless ($ad) { $ad='EXACT_ANS' };
 1901:         }
 1902:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
 1903:         &addlog("Assigned award detail: $ad");
 1904: # Store for later to be assigned at end_functionplotresponse
 1905:         $Apache::functionplotresponse::awarddetail=$ad;
 1906:      }
 1907: }
 1908: 
 1909: 
 1910: sub end_functionplotresponse {
 1911:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1912:   &Apache::response::end_response;
 1913: 
 1914:   my $result;
 1915:   my $id=$Apache::inputtags::response[-1];
 1916:   my $partid=$Apache::inputtags::part;
 1917:   my $internalid = $partid.'_'.$id;
 1918: 
 1919:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
 1920:     if ($target eq 'grade'
 1921:          && &Apache::response::submitted()
 1922:          && $Apache::lonhomework::type eq 'exam') {
 1923: 
 1924:         &Apache::response::scored_response($partid,$id);
 1925: 
 1926:     } elsif ($target eq 'grade'
 1927:          && &Apache::response::submitted()
 1928:          && $Apache::lonhomework::type ne 'exam') {
 1929:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
 1930:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
 1931:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
 1932: #
 1933: # Assign grade
 1934: #
 1935:         my $ad=$Apache::functionplotresponse::awarddetail;
 1936: #
 1937: # Store grading info
 1938: #
 1939:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
 1940:         &Apache::response::handle_previous(\%previous,$ad);
 1941:    } elsif ($target eq 'web') {
 1942:         undef @Apache::functionplotresponse::failedrules;
 1943:    }
 1944:    return $result;
 1945: }
 1946: 
 1947: sub end_functionplotelements {
 1948:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1949:   my $result='';
 1950:   my $id=$Apache::inputtags::response[-1];
 1951:   my $partid=$Apache::inputtags::part;
 1952:   my $internalid = $partid.'_'.$id;
 1953:   if ($target eq 'edit' ) {
 1954:      $result=&Apache::edit::end_table();
 1955:   } elsif ($target eq 'web') {
 1956:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1957: 
 1958: # Are we in show answer mode?
 1959:      my $showanswer=&Apache::response::show_answer();
 1960:      if ($showanswer) {
 1961: # Render answerdisplay
 1962:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
 1963:         if ($answerdisplay=~/\S/s) {
 1964:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
 1965:               my @components=split(/\s*\:\s*/,$plot);
 1966:               if ($#components<3) {
 1967: # Just a simple plot
 1968:                  my ($func,$xl,$xh)=@components;
 1969:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
 1970:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
 1971:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
 1972:               } else {
 1973: # This is a spline
 1974:                  $result.=&answer_spline_script($internalid,@components);
 1975:               }
 1976:            }
 1977:         }
 1978:      }
 1979:      my $fixed=0;
 1980:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
 1981: # Now is the time to render all of the stored splines
 1982:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1983:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
 1984:      }
 1985: # close the init script
 1986:      $result.=&end_init_script();
 1987: # register all splines in this response 
 1988:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
 1989:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
 1990:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1991:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
 1992:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
 1993:      }
 1994: # generate the input fields
 1995:      $result.=$Apache::functionplotresponse::inputfields;
 1996: # actually start the <applet>-tag
 1997:      $result.=&geogebra_startcode($internalid,
 1998:                                   &Apache::lonxml::get_param('width',$parstack,$safeeval,-2),
 1999:                                   &Apache::lonxml::get_param('height',$parstack,$safeeval,-2));
 2000: # load the spline bytecode
 2001:      $result.=&geogebra_spline_program();
 2002: # set default parameters
 2003:      $result.=&geogebra_default_parameters($internalid);
 2004: # close the <applet>-tag
 2005:      $result.=&geogebra_endcode();
 2006:   }
 2007:   return $result;
 2008: }
 2009: 
 2010: sub boundaries {
 2011:    my ($parstack,$safeeval,$level)=@_;
 2012:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
 2013:    $xmin=(defined($xmin)?$xmin:-10);
 2014:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
 2015:    $xmax=(defined($xmax)?$xmax:10);
 2016:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
 2017:    $ymin=(defined($ymin)?$ymin:-10);
 2018:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
 2019:    $ymax=(defined($ymax)?$ymax:10);
 2020:    if ($xmax<=$xmin) {
 2021:       $xmax=$xmin+20;
 2022:    }
 2023:    if ($ymax<=$ymin) {
 2024:       $ymax=$ymin+20;
 2025:    }
 2026:    return ($xmin,$xmax,$ymin,$ymax);
 2027: }
 2028: 
 2029: sub start_functionplotelements {
 2030:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2031:    my $result='';
 2032:    my $id=$Apache::inputtags::response[-1];
 2033:    my $partid=$Apache::inputtags::part;
 2034:    my $internalid = $partid.'_'.$id;
 2035: 
 2036:    if ($target eq 'edit') {
 2037:       return &Apache::edit::start_table($token).
 2038:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
 2039:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 2040:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 2041:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 2042:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
 2043:        .'</span></td>'
 2044:        ."<td>&nbsp;"
 2045:        .&Apache::edit::end_row()
 2046:        .&Apache::edit::start_spanning_row()
 2047:        ."\n";
 2048:    } elsif ($target eq 'web') {
 2049:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 2050:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2051:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2052:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2053:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
 2054:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
 2055: 
 2056: 
 2057: # paste in the update routine to receive stuff back from the applet
 2058:      $result.=&update_script($internalid);
 2059: # start the initscript for this applet
 2060:      $result.=&start_init_script($internalid);
 2061: # put the axis commands inside
 2062:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
 2063:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
 2064: # init script is left open
 2065:   }
 2066:   return $result;
 2067: }
 2068: 
 2069: 1;
 2070: 
 2071: __END__
 2072:  
 2073: =head1 NAME
 2074: 
 2075: Apache::functionplotresponse.pm;
 2076: 
 2077: =head1 SYNOPSIS
 2078: 
 2079: Handles tags associated with accepting function plots.
 2080: 
 2081: This is part of the LearningOnline Network with CAPA project
 2082: described at http://www.lon-capa.org.
 2083: 
 2084: =head1 HANDLER SUBROUTINE
 2085: 
 2086: start_functionplotresponse()
 2087: 
 2088: =head1 OTHER SUBROUTINES
 2089: 
 2090: =over
 2091: 
 2092: =item end_functionplotresponse()
 2093: 
 2094: =back
 2095: 
 2096: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>