File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.92: download - view: text, annotated - select for diffs
Tue Feb 28 15:46:55 2012 UTC (12 years, 3 months ago) by www
Branches: MAIN
CVS tags: HEAD
Nail down vectors after problem is no longer answerable

    1: # LearningOnline Network with CAPA
    2: # Functionplot responses
    3: #
    4: # $Id: functionplotresponse.pm,v 1.92 2012/02/28 15:46:55 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,$fixed)=@_;
  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,$fixed).
  425:        &new_point_coordinate($id,$endlabel,$xe,$ye,$fixed).
  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:       my $fixed=0;
  560:       if ((&Apache::response::show_answer()) || (&Apache::response::check_status()>=2)) { $fixed=1; }
  561:       $result.=&plotvector_script($internalid,$label,$tailx,$taily,$tipx,$tipy,$xmin,$xmax,$fixed);
  562:    } elsif ($target eq 'edit') {
  563:         $result=&Apache::edit::tag_start($target,$token,'Plot Vector').
  564:              &Apache::edit::text_arg('Label on Plot:','label',
  565:                                      $token,'16').
  566:              &Apache::edit::text_arg('Tail x:','tailx',
  567:                                      $token,'8').
  568:              &Apache::edit::text_arg('Tail y:','taily',
  569:                                      $token,'8').
  570:              &Apache::edit::text_arg('Tip x:','tipx',
  571:                                      $token,'8').
  572:              &Apache::edit::text_arg('Tip y:','tipy',
  573:                                      $token,'8').
  574: 
  575:              &Apache::edit::end_row();
  576:   } elsif ($target eq 'modified') {
  577:     $env{'form.'.&Apache::edit::html_element_name('label')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('label')});
  578:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'label','tailx','taily','tipx','tipy');
  579:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  580:   }
  581:   return $result;
  582: }
  583: 
  584: sub end_plotvector {
  585:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  586:    my $result='';
  587:    if ($target eq 'edit') {
  588:        $result=&Apache::edit::end_table();
  589:    }
  590:    return $result;
  591: }
  592: 
  593: 
  594: 
  595: #
  596: # <backgroundplot function="..." fixed="yes/no" />
  597: #
  598: sub start_backgroundplot {
  599:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  600:    my $result='';
  601:    my $internalid = $Apache::inputtags::part.'_'.$Apache::inputtags::response[-1];
  602:    my $function=&Apache::lonxml::get_param('function',$parstack,$safeeval);
  603:    my $xinitial=&Apache::lonxml::get_param('xinitial',$parstack,$safeeval);
  604:    my $xfinal=&Apache::lonxml::get_param('xfinal',$parstack,$safeeval);
  605:    my $label=&Apache::lonxml::get_param('label',$parstack,$safeeval);
  606:    my $color=&Apache::lonxml::get_param('color',$parstack,$safeeval);
  607:    $color=~s/[^a-fA-F0-9]//gs;
  608:    unless (length($color)==6) { $color=''; }
  609:    my $fixed=(&Apache::lonxml::get_param('fixed',$parstack,$safeeval)=~/on|true|yes|1/i?1:0);
  610:  
  611:    unless ($function) { $function="0"; }
  612:    if ($target eq 'web') {
  613:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-3);
  614:       unless (defined($xinitial)) { $xinitial=$xmin; }
  615:       unless (defined($xfinal)) { $xfinal=$xmax; }
  616:       $result.=&plot_script($internalid,$function,$fixed,$label,$color,$xinitial,$xfinal);
  617:    } elsif ($target eq 'edit') {
  618:         $result=&Apache::edit::tag_start($target,$token,'Background Function Plot').
  619:              &Apache::edit::text_arg('Function:','function',
  620:                                      $token,'16').
  621:              &Apache::edit::text_arg('Initial x-value (optional):','xinitial',
  622:                                      $token,'8').
  623:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  624:                                      $token,'8').
  625:              &Apache::edit::text_arg('Label on Plot:','label',
  626:                                      $token,'8').
  627:              &Apache::edit::text_arg('Color (hex code):','color',
  628:                                      $token,'8').
  629:              &Apache::edit::select_arg('Fixed location:','fixed',
  630:                                   ['yes','no'],$token).
  631:              &Apache::edit::end_row();
  632:   } elsif ($target eq 'modified') {
  633:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  634:                                                  $safeeval,'function','label','xinitial','xfinal','color','fixed');
  635:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  636:   }
  637:   return $result;
  638: }
  639: 
  640: sub end_backgroundplot {
  641:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  642:    my $result='';
  643:    if ($target eq 'edit') {
  644:        $result=&Apache::edit::end_table();
  645:    }
  646:    return $result;
  647: }
  648: 
  649: #
  650: # <functionplotrule ... />
  651: #
  652: sub start_functionplotrule {
  653:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  654:    my $result='';
  655:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  656:    $Apache::functionplotresponse::counter++;
  657:    if ($label=~/\W/) {
  658:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  659:    }
  660:    $label=~s/\W//gs;
  661:    unless ($label) {
  662:       $label='R'.$Apache::functionplotresponse::counter;
  663:    } else {
  664:       $label='R'.$label;
  665:    }
  666: 
  667:    if ($target eq 'grade') {
  668: # Simply remember - in order - for later
  669:       my $beginninglabel=&Apache::lonxml::get_param('xinitiallabel',$parstack,$safeeval);
  670:       my $endinglabel=&Apache::lonxml::get_param('xfinallabel',$parstack,$safeeval);
  671:       if (($beginninglabel=~/\W/) || ($endinglabel=~/W/)) {
  672:           &Apache::lonxml::warning(&mt('Rule labels must be alphanumeric.'));
  673:       }
  674:       $beginninglabel=~s/\W//gs;
  675:       $endinglabel=~s/\W//gs;
  676:       my $relationship=&Apache::lonxml::get_param('relationship',$parstack,$safeeval);
  677:       $relationship=~s/\W//gs;
  678:       $relationship=lc($relationship);
  679:       unless ($relationship=~/^(eq|ge|gt|le|lt|ne)$/) {
  680:           &Apache::lonxml::warning(&mt('Rule relationship not defined.'));
  681:           $relationship='eq';
  682:       }
  683:       my $derivative=&Apache::lonxml::get_param('derivativeorder',$parstack,$safeeval);
  684:       unless (($derivative==-1) || ($derivative==0) || ($derivative==1) || ($derivative==2)) {
  685:          &Apache::lonxml::warning(&mt('Rule derivative not defined.'));
  686:          $derivative=0;
  687:       }
  688:       push(@Apache::functionplotresponse::functionplotrules,join(':',(
  689:            $label,
  690:            $derivative,
  691:            &Apache::lonxml::get_param('xinitial',$parstack,$safeeval),
  692:            $beginninglabel,
  693:            &Apache::lonxml::get_param('xfinal',$parstack,$safeeval),
  694:            $endinglabel,
  695:            &Apache::lonxml::get_param('minimumlength',$parstack,$safeeval),
  696:            &Apache::lonxml::get_param('maximumlength',$parstack,$safeeval),
  697:            $relationship,
  698:            &Apache::lonxml::get_param('value',$parstack,$safeeval),
  699:            &Apache::lonxml::get_param('percenterror',$parstack,$safeeval)
  700:           )));
  701:    } elsif ($target eq 'edit') {
  702:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Graph Rule').
  703:              &Apache::edit::text_arg('Index/Name:','index',
  704:                                      $token,'10').'&nbsp;'.
  705:              &Apache::edit::select_arg(&mt('Function:'),'derivativeorder',
  706:                                   [['0','Function itself'],
  707:                                    ['1','First derivative'],
  708:                                    ['2','Second derivative'],
  709:                                    ['-1','Integral']],$token).'<br />'.
  710:              &Apache::edit::text_arg('Initial x-value:','xinitial',
  711:                                       $token,'8').
  712:              &Apache::edit::select_or_text_arg('Initial x-value label:','xinitiallabel',
  713:                                                [['start','Start of Plot'],
  714:                                                 ['end','End of Plot']],$token,'8').'<br />'.
  715: 
  716:              &Apache::edit::text_arg('Final x-value (optional):','xfinal',
  717:                                       $token,'8').
  718:              &Apache::edit::select_or_text_arg('Final x-value label (optional):','xfinallabel',
  719:                                                [['end','End of Plot']],$token,'8').'<br />'.
  720:              &Apache::edit::text_arg('Minimum length for range (optional):','minimumlength',
  721:                                      $token,'8').
  722:              &Apache::edit::text_arg('Maximum length for range (optional):','maximumlength',
  723:                                      $token,'8').'<br />'.
  724:              &Apache::edit::select_or_text_arg(&mt('Relationship:'),'relationship',
  725:                                   [['eq','equal'],
  726:                                    ['ne','not equal'],
  727:                                    ['ge','greater than or equal'],
  728:                                    ['gt','greater than'],
  729:                                    ['lt','less than'],
  730:                                    ['le','less than or equal']],$token).
  731:              $result.= &Apache::edit::select_or_text_arg('Value:','value',
  732:                                                [['undef','not defined']],$token,'30').
  733:              &Apache::edit::text_arg('Percent error:','percenterror',
  734:                                      $token,'8').
  735:              &Apache::edit::end_row();
  736:   } elsif ($target eq 'modified') {
  737:     if (($env{'form.'.&Apache::edit::html_element_name('xinitial')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xinitiallabel')} eq 'start')) {
  738:        $env{'form.'.&Apache::edit::html_element_name('xinitiallabel')}='';
  739:     }
  740:     if (($env{'form.'.&Apache::edit::html_element_name('xfinal')} ne '') && ($env{'form.'.&Apache::edit::html_element_name('xfinallabel')} eq 'end')) {
  741:        $env{'form.'.&Apache::edit::html_element_name('xfinallabel')}='';
  742:     }
  743:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  744:                                                  $safeeval,'index','derivativeorder',
  745:                                                            'xinitial','xinitiallabel','xfinal','xfinallabel',
  746:                                                            'minimumlength','maximumlength',
  747:                                                            'relationship','value','percenterror');
  748:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  749:    }
  750:    return $result;
  751: }
  752: 
  753: sub end_functionplotrule {
  754:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  755:    my $result='';
  756:    if ($target eq 'edit') {
  757:        $result=&Apache::edit::end_table();
  758:    }
  759:    return $result;
  760: }
  761: 
  762: 
  763: #
  764: # <functionplotvectorrule ... />
  765: #
  766: sub start_functionplotvectorrule {
  767:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  768:    my $result='';
  769:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  770:    $Apache::functionplotresponse::counter++;
  771:    if ($label=~/\W/) {
  772:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  773:    }
  774:    $label=~s/\W//gs;
  775:    unless ($label) {
  776:       $label='R'.$Apache::functionplotresponse::counter;
  777:    } else {
  778:       $label='R'.$label;
  779:    }
  780: 
  781:    if ($target eq 'grade') {
  782: # Simply remember - in order - for later
  783: 
  784:       my $id=$Apache::inputtags::response[-1];
  785:       my $partid=$Apache::inputtags::part;
  786:       my $internalid = $partid.'_'.$id;
  787: 
  788:       my $vector=&Apache::lonxml::get_param('vector',$parstack,$safeeval);
  789:       $vector=~s/\W//gs;
  790:       $vector=ucfirst($vector);
  791: 
  792:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  793:            $label,
  794:            'vector',
  795:            $internalid,
  796:            $vector,
  797:            &Apache::lonxml::get_param('attachpoint',$parstack,$safeeval),
  798:            &Apache::lonxml::get_param('notattachpoint',$parstack,$safeeval),
  799:            &Apache::lonxml::get_param('tailpoint',$parstack,$safeeval),
  800:            &Apache::lonxml::get_param('tippoint',$parstack,$safeeval),
  801:            &Apache::lonxml::get_param('nottailpoint',$parstack,$safeeval),
  802:            &Apache::lonxml::get_param('nottippoint',$parstack,$safeeval),
  803:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
  804:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
  805:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
  806:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
  807:           )));
  808:    } elsif ($target eq 'edit') {
  809:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Rule').
  810:              &Apache::edit::text_arg('Index/Name:','index',
  811:                                      $token,'10').'&nbsp;'.
  812:              &Apache::edit::text_arg('Vector:','vector',
  813:                                       $token,'16').'<br />'.
  814:              &Apache::edit::text_arg('Attached to object:','attachpoint',
  815:                                       $token,'16').
  816:              &Apache::edit::text_arg('Not attached to object:','notattachpoint',
  817:                                       $token,'16').'<br />'.
  818:              &Apache::edit::text_arg('Tail attached to object:','tailpoint',
  819:                                       $token,'16').
  820:              &Apache::edit::text_arg('Tip attached to object:','tippoint',
  821:                                       $token,'16').
  822:              &Apache::edit::text_arg('Tail not attached to object:','nottailpoint',
  823:                                       $token,'16').
  824:              &Apache::edit::text_arg('Tip not attached to object:','nottippoint',
  825:                                       $token,'16').'<br />'.
  826:              &Apache::edit::text_arg('Length:','length',
  827:                                      $token,'30').
  828:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
  829:                                      $token,'8').'<br />'.
  830:              &Apache::edit::text_arg('Angle:','angle',
  831:                                      $token,'30').
  832:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
  833:                                      $token,'8').
  834:              &Apache::edit::end_row();
  835:   } elsif ($target eq 'modified') {
  836:     $env{'form.'.&Apache::edit::html_element_name('vector')}=ucfirst($env{'form.'.&Apache::edit::html_element_name('vector')});
  837:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  838:                                                  $safeeval,'index','vector','attachpoint','notattachpoint',
  839:                                                            'tailpoint','tippoint','nottailpoint','nottipoint',
  840:                                                            'length','angle',
  841:                                                            'lengtherror','angleerror');
  842:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  843:    }
  844:    return $result;
  845: }
  846: 
  847: sub end_functionplotvectorrule {
  848:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  849:    my $result='';
  850:    if ($target eq 'edit') {
  851:        $result=&Apache::edit::end_table();
  852:    }
  853:    return $result;
  854: }
  855: 
  856: #
  857: # <functionplotvectorsumrule ... />
  858: #
  859: sub start_functionplotvectorsumrule {
  860:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  861:    my $result='';
  862:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  863:    $Apache::functionplotresponse::counter++;
  864:    if ($label=~/\W/) {
  865:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  866:    }
  867:    $label=~s/\W//gs;
  868:    unless ($label) {
  869:       $label='R'.$Apache::functionplotresponse::counter;
  870:    } else {
  871:       $label='R'.$label;
  872:    }
  873:    if ($target eq 'grade') {
  874: # Simply remember - in order - for later
  875:       my $id=$Apache::inputtags::response[-1];
  876:       my $partid=$Apache::inputtags::part;
  877:       my $internalid = $partid.'_'.$id;
  878:       my $vectors=&Apache::lonxml::get_param('vectors',$parstack,$safeeval);
  879:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  880:            $label,
  881:            'sum',
  882:            $internalid,
  883:            $vectors,
  884:            &Apache::lonxml::get_param('length',$parstack,$safeeval),
  885:            &Apache::lonxml::get_param('angle',$parstack,$safeeval),
  886:            &Apache::lonxml::get_param('lengtherror',$parstack,$safeeval),
  887:            &Apache::lonxml::get_param('angleerror',$parstack,$safeeval),
  888:           )));
  889:    } elsif ($target eq 'edit') {
  890:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Vector Sum Rule').
  891:              &Apache::edit::text_arg('Index/Name:','index',
  892:                                      $token,'10').'&nbsp;'.
  893:              &Apache::edit::text_arg('Comma-separated list of vectors:','vectors',
  894:                                       $token,'30').'<br />'.
  895:              &Apache::edit::text_arg('Sum vector length:','length',
  896:                                      $token,'30').
  897:              &Apache::edit::text_arg('Absolute error length:','lengtherror',
  898:                                      $token,'8').'<br />'.
  899:              &Apache::edit::text_arg('Sum vector angle:','angle',
  900:                                      $token,'30').
  901:              &Apache::edit::text_arg('Absolute error angle:','angleerror',
  902:                                      $token,'8').
  903:              &Apache::edit::end_row();
  904:    } elsif ($target eq 'modified') {
  905:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,
  906:                                                    $safeeval,'index','vectors',
  907:                                                              'length','angle',
  908:                                                              'lengtherror','angleerror');
  909:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  910:    }
  911:    return $result;
  912: }
  913: 
  914: sub end_functionplotvectorsumrule {
  915:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  916:    my $result='';
  917:    if ($target eq 'edit') {
  918:        $result=&Apache::edit::end_table();
  919:    }
  920:    return $result;
  921: }
  922: 
  923: #
  924: # <functionplotcustom ... />
  925: #
  926: sub start_functionplotcustomrule {
  927:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  928:    my $result='';
  929:    my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  930:    $Apache::functionplotresponse::counter++;
  931:    if ($label=~/\W/) {
  932:       &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  933:    }
  934:    $label=~s/\W//gs;
  935:    unless ($label) {
  936:       $label='R'.$Apache::functionplotresponse::counter;
  937:    } else {
  938:       $label='R'.$label;
  939:    }
  940:    &Apache::lonxml::register('Apache::response',('answer'));
  941:    if ($target eq 'edit') {
  942:         $result=&Apache::edit::tag_start($target,$token,'Function Plot Custom Rule').
  943:              &Apache::edit::text_arg('Index/Name:','index',$token,'10').
  944:              &Apache::edit::end_row();
  945:   } elsif ($target eq 'modified') {
  946:       my $constructtag=&Apache::edit::get_new_args($token,$parstack,$safeeval,'index');
  947:       if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
  948:    }
  949:    return $result;
  950: }
  951: 
  952: sub end_functionplotcustomrule {
  953:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  954:    my $result='';
  955:    if ($target eq 'edit') {
  956:       $result=&Apache::edit::end_table();
  957:    } elsif ($target eq 'grade') {
  958: # Simply remember - in order - for later
  959:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  960:       $Apache::functionplotresponse::counter++;
  961:       if ($label=~/\W/) {
  962:          &Apache::lonxml::warning(&mt('Rule indices should only contain alphanumeric characters.'));
  963:       }
  964:       $label=~s/\W//gs;
  965:       unless ($label) {
  966:          $label='R'.$Apache::functionplotresponse::counter;
  967:       } else {
  968:          $label='R'.$label;
  969:       }
  970:       push(@Apache::functionplotresponse::functionplotvectorrules,join(':',(
  971:            $label,
  972:            'custom',
  973:            &escape($Apache::response::custom_answer[-1])
  974:           )));
  975:    }
  976:    &Apache::lonxml::deregister('Apache::response',('answer'));
  977:    return $result;
  978: }
  979: 
  980: 
  981: 
  982: #
  983: # <spline index="..." order="1,2,3,4" initx="..." inity="..." scalex="..." scaley="..." />
  984: #
  985: # Unfortunately, GeoGebra seems to want all splines after everything else, so we need to store them
  986: #
  987: sub start_spline {
  988:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
  989:    my $result='';
  990:    if ($target eq 'web') {
  991:       my $label=&Apache::lonxml::get_param('index',$parstack,$safeeval);
  992:       $Apache::functionplotresponse::counter++;
  993:       if ($label=~/\W/) {
  994:          &Apache::lonxml::warning(&mt('Spline indices should only contain alphanumeric characters.'));
  995:       }
  996:       $label=~s/\W//gs;
  997:       unless ($label) { 
  998:          $label='S'.$Apache::functionplotresponse::counter; 
  999:       } else {
 1000:          $label='S'.$label;
 1001:       }
 1002:       if ($Apache::functionplotresponse::splineorder{$label}) {
 1003:          &Apache::lonxml::error(&mt('Spline indices must be unique.'));
 1004:       }
 1005: 
 1006:       my $order=&Apache::lonxml::get_param('order',$parstack,$safeeval);
 1007:       if ($order<2) { $order=2; }
 1008:       if ($order>8) { $order=8; }
 1009:       $Apache::functionplotresponse::splineorder{$label}=$order;
 1010: 
 1011:       my $x=&Apache::lonxml::get_param('initx',$parstack,$safeeval);
 1012:       unless ($x) { $x=0; }
 1013:       $Apache::functionplotresponse::splineinitx{$label}=$x;
 1014: 
 1015:       my $y=&Apache::lonxml::get_param('inity',$parstack,$safeeval);
 1016:       unless ($y) { $y=0; }
 1017:       $Apache::functionplotresponse::splineinity{$label}=$y;
 1018: 
 1019:       my $sx=&Apache::lonxml::get_param('scalex',$parstack,$safeeval);
 1020:       unless ($sx) { $sx=$order; }
 1021:       $Apache::functionplotresponse::splinescalex{$label}=$sx;
 1022: 
 1023:       my $sy=&Apache::lonxml::get_param('scaley',$parstack,$safeeval);
 1024:       unless ($sy) { $sy=2; }
 1025:       $Apache::functionplotresponse::splinescaley{$label}=$sy;
 1026:    } elsif ($target eq 'edit') {
 1027:         $result=&Apache::edit::tag_start($target,$token,'Spline').
 1028:              &Apache::edit::text_arg('Index:','index',
 1029:                                      $token,'4').'&nbsp;'.
 1030:              &Apache::edit::select_arg('Order:','order',
 1031:                                   ['2','3','4','5','6','7','8'],$token).'&nbsp;'.
 1032:              &Apache::edit::text_arg('Initial x-value:','initx',
 1033:                                      $token,'4').'&nbsp;'.
 1034:              &Apache::edit::text_arg('Initial y-value:','inity',
 1035:                                      $token,'4').'&nbsp;'.
 1036:              &Apache::edit::text_arg('Scale x:','scalex',
 1037:                                      $token,'4').'&nbsp;'.
 1038:              &Apache::edit::text_arg('Scale y:','scaley',
 1039:                                      $token,'4').
 1040:              &Apache::edit::end_row();
 1041:   } elsif ($target eq 'modified') {
 1042:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 1043:                                                  $safeeval,'index','order','initx','inity',
 1044:                                                            'scalex','scaley');
 1045:     if ($constructtag) { $result=&Apache::edit::rebuild_tag($token); }
 1046:   }
 1047:   return $result;
 1048: }
 1049: 
 1050: sub end_spline {
 1051:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1052:    my $result='';
 1053:    if ($target eq 'edit') {
 1054:        $result=&Apache::edit::end_table();
 1055:    }
 1056:    return $result;
 1057: }
 1058:  
 1059: sub end_init_script {
 1060:     return (<<ENDENDINIT);
 1061: }
 1062: // ]]>
 1063: </script>
 1064: ENDENDINIT
 1065: }
 1066: 
 1067: #
 1068: # Storing and restoring spline coordinates from part answers
 1069: #
 1070: sub decode_previous_answer {
 1071:    my ($answer)=@_;
 1072:    foreach my $coordinate (split(/\,/,$answer)) {
 1073:       my ($key,$value)=split(/\=/,$coordinate);
 1074:       $Apache::functionplotresponse::previous{$key}=$value;
 1075:    }
 1076: }
 1077: 
 1078: sub get_answer_from_form_fields {
 1079:    my ($id)=@_;
 1080:    my $answer='';
 1081:    my %coords=();
 1082:    foreach my $field (keys(%env)) {
 1083:       if ($field=~/^form\.HWVAL\_$id/) {
 1084:          $field=~/^form\.(.*)$/;
 1085:          $coords{$1}=$env{$field};
 1086:       }
 1087:    }
 1088:    $answer=join(',',map { $_.'='.$coords{$_} } (sort(keys(%coords))));
 1089:    return ($answer,%coords);
 1090: }
 1091: 
 1092: #
 1093: # The following functions calculate the cubic-hermite splines server-side
 1094: #
 1095: 
 1096: sub cubic_hermite {
 1097:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1098:    return (2.*$t*$t*$t-3.*$t*$t+1.)*$p1 + 3.*($t*$t*$t-2.*$t*$t+$t)*($s1-$p1)+
 1099:           (-2.*$t*$t*$t+3.*$t*$t)  *$p2 + 3.*($t*$t*$t-$t*$t)      *($s2-$p2);
 1100: }
 1101: 
 1102: #
 1103: # d/dt(...)
 1104: # 
 1105: 
 1106: sub ddt_cubic_hermite {
 1107:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1108:    return (6.*$t*$t-6.*$t) *$p1 + 3.*(3.*$t*$t-4.*$t+1.)*($s1-$p1)+
 1109:           (-6.*$t*$t+6.*$t)*$p2 + 3.*(3.*$t*$t-2.*$t)   *($s2-$p2);
 1110: }
 1111: 
 1112: #
 1113: # d^2/dt^2(...)
 1114: #
 1115: 
 1116: sub d2dt2_cubic_hermite {
 1117:    my ($t,$p1,$s1,$p2,$s2)=@_;
 1118:    return (12.*$t-6.) *$p1 + 3.*(6.*$t-4.)*($s1-$p1)+
 1119:           (-12.*$t+6.)*$p2 + 3.*(6.*$t-2.)*($s2-$p2);
 1120: }
 1121: 
 1122: #
 1123: # Array index calculation
 1124: #
 1125: sub array_index {
 1126:    my ($xmin,$xmax,$x)=@_;
 1127:    if ($x ne '') {
 1128:       return int(($x-$xmin)/($xmax-$xmin)*400.+0.5);
 1129:    } else {
 1130:       return undef;
 1131:    }
 1132: }
 1133: 
 1134: #
 1135: # Populate the arrays
 1136: #
 1137: 
 1138: sub populate_arrays {
 1139:     my ($id,$xmin,$xmax,$ymin,$ymax)=@_;
 1140:     for (my $i=0; $i<=400; $i++) {
 1141:        $Apache::functionplotresponse::actualxval[$i]=undef;
 1142:        $Apache::functionplotresponse::func[$i]=undef;
 1143:        $Apache::functionplotresponse::dfuncdx[$i]=undef;
 1144:        $Apache::functionplotresponse::d2funcd2x[$i]=undef;
 1145:     }
 1146:     unless ($xmax>$xmin) { return 'no_func'; }
 1147: # Run over all splines in response
 1148:     foreach my $label (split(/\,/,$env{"form.HWVAL_AllSplines_$id"})) {
 1149:         my $xiold=-1;
 1150: # Run over all points in spline
 1151:         for (my $i=1; $i<$env{"form.HWVAL_SplineOrder_".$id."_".$label}; $i++) {
 1152:             my $ni=$i+1;
 1153:             my @xparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_x'},
 1154:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_x'},
 1155:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_x'},
 1156:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_x'});
 1157:             my @yparms=($env{'form.HWVAL_'.$id.'_'.$label.'P'.$i.'_y'},
 1158:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$i.'_y'},
 1159:                         $env{'form.HWVAL_'.$id.'_'.$label.'P'.$ni.'_y'},
 1160:                         $env{'form.HWVAL_'.$id.'_'.$label.'S'.$ni.'_y'});
 1161: # Run in small steps over spline parameter
 1162:             for (my $t=0; $t<=1; $t+=0.0001) {
 1163:                 my $xreal=&cubic_hermite($t,@xparms);
 1164:                 my $xi=&array_index($xmin,$xmax,$xreal);
 1165:                 if ($xi<$xiold) { return 'no_func'; }
 1166:                 if (($xi>$xiold) && ($xi>=0) && ($xi<=400)) {
 1167:                    $xiold=$xi;
 1168:                    $Apache::functionplotresponse::actualxval[$xi]=$xreal;
 1169: # Function value
 1170:                    my $funcval=&cubic_hermite($t,@yparms);
 1171: 
 1172: # Do we already have a value for this point, and is it different from the new one?
 1173:                    if ((defined($Apache::functionplotresponse::func[$xi])) &&
 1174:                        (abs($Apache::functionplotresponse::func[$xi]-$funcval)>($ymax-$ymin)/100.)) { 
 1175:                        return 'no_func'; 
 1176:                    }
 1177: # Okay, remember the new point
 1178:                    $Apache::functionplotresponse::func[$xi]=$funcval;
 1179: 
 1180:                    if (defined($funcval)) {
 1181:                       if ($xi<$Apache::functionplotresponse::functionplotrulelabels{'start'}) {
 1182:                          $Apache::functionplotresponse::functionplotrulelabels{'start'}=$xi;
 1183:                       }
 1184:                       if ($xi>$Apache::functionplotresponse::functionplotrulelabels{'end'}) {
 1185:                          $Apache::functionplotresponse::functionplotrulelabels{'end'}=$xi;
 1186:                       }
 1187:                    }
 1188: # Chain rule
 1189: # dy/dx=dy/dt/(dx/dt)
 1190:                    my $dxdt=&ddt_cubic_hermite($t,@xparms);
 1191:                    if ($dxdt) {
 1192:                       $Apache::functionplotresponse::dfuncdx[$xi]=&ddt_cubic_hermite($t,@yparms)/$dxdt;
 1193: # Second derivative
 1194:                       $Apache::functionplotresponse::d2funcdx2[$xi]=
 1195:                          ($dxdt*&d2dt2_cubic_hermite($t,@yparms)-&ddt_cubic_hermite($t,@yparms)*&d2dt2_cubic_hermite($t,@xparms))/
 1196:                          ($dxdt*$dxdt*$dxdt);
 1197:                    }
 1198:                 }
 1199:             }
 1200:         }
 1201:     }
 1202: }
 1203: 
 1204: #
 1205: # Implementation of <functionplotresponse>
 1206: #
 1207: 
 1208: sub start_functionplotresponse {
 1209:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1210:   my $result='';
 1211: # To remember the splines - somehow, they need to come last
 1212:   undef %Apache::functionplotresponse::splineorder;
 1213:   undef %Apache::functionplotresponse::splineinitx;
 1214:   undef %Apache::functionplotresponse::splineinity;
 1215:   undef %Apache::functionplotresponse::splinescalex;
 1216:   undef %Apache::functionplotresponse::splinescaley;
 1217: # Remember input fields, etc
 1218:   undef %Apache::functionplotresponse::previous;
 1219:   $Apache::functionplotresponse::inputfields='';
 1220:   $Apache::functionplotresponse::counter=0;
 1221: # Remember rules
 1222:   undef @Apache::functionplotresponse::functionplotrules;
 1223:   undef @Apache::functionplotresponse::functionplotvectorrules;
 1224: # Remember failed rules
 1225:   if ($target eq 'grade') {
 1226:      undef @Apache::functionplotresponse::failedrules;
 1227:   }
 1228: # Delete previous awards
 1229:   undef $Apache::functionplotresponse::awarddetail;
 1230: # Part and ID
 1231:   my $partid=$Apache::inputtags::part;
 1232:   my $id=&Apache::response::start_response($parstack,$safeeval);
 1233: # Internal ID to mark the applet and its coordinates
 1234:   my $internalid = $partid.'_'.$id;
 1235: # Previous answer
 1236:   &decode_previous_answer($Apache::lonhomework::history{"resource.$partid.$id.submission"});
 1237: 
 1238: # Parameters of <functionplotresponse>
 1239:   my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval);
 1240:   my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1241:   my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1242:   my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval)=~/on|true|yes|1/i?'true':'false');
 1243:   my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval);
 1244:   my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval);
 1245:   if ($target eq 'edit') {
 1246:     $result.=&Apache::edit::start_table($token)
 1247:        .'<tr><td><span class="LC_nobreak">'.&mt('Function Plot Question').'</span></td>'
 1248:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1249:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1250:        .&Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1251:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Question','Function Plot Responses')
 1252:        .'</span></td>'
 1253:        ."<td>&nbsp;"
 1254:        .&Apache::edit::end_row()
 1255:        .&Apache::edit::start_spanning_row()
 1256:        ."\n";
 1257:     $result.=&Apache::edit::text_arg('Width (pixels):','width',
 1258:                                      $token,'6').'&nbsp;'.
 1259:              &Apache::edit::text_arg('Height (pixels):','height',
 1260:                                      $token,'6').'<br />'.
 1261:              &Apache::edit::text_arg('Label x-axis:','xlabel',
 1262:                                      $token,'6').'&nbsp;'.
 1263:              &Apache::edit::text_arg('Minimum x-value:','xmin',
 1264:                                      $token,'4').'&nbsp;'.
 1265:              &Apache::edit::text_arg('Maximum x-value:','xmax',
 1266:                                      $token,'4').'&nbsp;'.
 1267:              &Apache::edit::select_arg('x-axis visible:','xaxisvisible',
 1268:                                   ['yes','no'],$token).'<br />'.
 1269:              &Apache::edit::text_arg('Label y-axis:','ylabel',
 1270:                                      $token,'6').'&nbsp;'.
 1271:              &Apache::edit::text_arg('Minimum y-value:','ymin',
 1272:                                      $token,'4').'&nbsp;'.
 1273:              &Apache::edit::text_arg('Maximum y-value:','ymax',
 1274:                                      $token,'4').'&nbsp;'.
 1275:              &Apache::edit::select_arg('y-axis visible:','yaxisvisible',
 1276:                                   ['yes','no'],$token).'<br />'.
 1277:              &Apache::edit::select_arg('Grid visible:','gridvisible',
 1278:                                   ['yes','no'],$token).'<br />'.
 1279:              &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,...):',
 1280:                                          'answerdisplay',$token,'50').
 1281:              &Apache::edit::end_row().&Apache::edit::start_spanning_row();
 1282:   } elsif ($target eq 'modified') {
 1283:     my $constructtag=&Apache::edit::get_new_args($token,$parstack,
 1284:                                                  $safeeval,'width','height','xlabel','xmin','xmax','ylabel','ymin','ymax',
 1285:                                                            'xaxisvisible','yaxisvisible','gridvisible','answerdisplay');
 1286:     if ($constructtag) { $result = &Apache::edit::rebuild_tag($token); }
 1287: 
 1288:   } elsif ($target eq 'meta') {
 1289:        $result=&Apache::response::meta_package_write('functionplotresponse');
 1290:   } elsif (($target eq 'answer') &&
 1291:             ($env{'form.answer_output_mode'} ne 'tex') &&
 1292:             ($Apache::lonhomework::viewgrades == 'F')) {
 1293:       my (undef,undef,$udom,$uname)=&Apache::lonnet::whichuser();
 1294:       $uname =~s/\W//g;
 1295:       $udom  =~s/\W//g;
 1296:       my $function_name =
 1297:                 join('_','LONCAPA_scriptvars',$uname,$udom,
 1298:                      $env{'form.counter'},$Apache::lonxml::curdepth);
 1299:       &Apache::lonxml::add_script_result(
 1300:           &Apache::loncommon::modal_adhoc_window($function_name,700,500,
 1301:              '<pre>'.$Apache::functionplotresponse::ruleslog.'</pre>',
 1302:               &mt('Rules Log'))."<br />");
 1303:   }
 1304:   return $result;
 1305: }
 1306: 
 1307: sub compare_rel {
 1308:    my ($relationship,$value,$realval,$tol)=@_;
 1309: # is the real value undefined?
 1310:    unless (defined($realval)) {
 1311: # the real value is not defined
 1312:       if ($relationship eq 'eq') {
 1313:          if ($value eq 'undef') {
 1314:             return 1;
 1315:          } else {
 1316:             return 0;
 1317:          }
 1318:       } elsif ($relationship eq 'ne') {
 1319:          if ($value eq 'undef') {
 1320:             return 0;
 1321:          } else {
 1322:             return 1;
 1323:          }
 1324:       } else {
 1325:          return 0;
 1326:       }
 1327:    }
 1328: 
 1329: # is the expected value undefined?
 1330:    if ($value eq 'undef') {
 1331: # but by now we know that the real value is defined
 1332:       return 0;
 1333:    }
 1334: 
 1335: # both are defined.
 1336:    if ($relationship eq 'gt') {
 1337:       return ($realval>$value);
 1338:    } elsif ($relationship eq 'ge') {
 1339:       return ($realval>$value-$tol);
 1340:    } elsif ($relationship eq 'lt') {
 1341:       return ($realval<$value);
 1342:    } elsif ($relationship eq 'le') {
 1343:       return ($realval<$value+$tol);
 1344:    } elsif ($relationship eq 'ne') {
 1345:       return (abs($value-$realval)>$tol);
 1346:    } else {
 1347:       return (abs($value-$realval)<$tol);
 1348:    }
 1349:    return 0;
 1350: }
 1351: 
 1352: sub addlog {
 1353:    my ($text)=@_;
 1354:    $text=~s/\'/\\\'/g;
 1355:    $Apache::functionplotresponse::ruleslog.=$text.'<br />';
 1356: }
 1357: 
 1358: sub actualval {
 1359:    my ($i,$xmin,$xmax)=@_;
 1360:    return $xmin+$i/400.*($xmax-$xmin);
 1361: }
 1362: 
 1363: sub fpr_val {
 1364:    my ($arg)=@_;
 1365:    return &actualval($Apache::functionplotresponse::functionplotrulelabels{$arg},
 1366:                      $Apache::functionplotresponse::fpr_xmin,
 1367:                      $Apache::functionplotresponse::fpr_xmax);
 1368: }
 1369: 
 1370: sub fpr_f {
 1371:    my ($arg)=@_;
 1372:    return $Apache::functionplotresponse::func[&array_index($Apache::functionplotresponse::fpr_xmin,
 1373:                                                            $Apache::functionplotresponse::fpr_xmax,
 1374:                                                            $arg)];
 1375: }
 1376: 
 1377: sub fpr_dfdx {
 1378:    my ($arg)=@_;
 1379:    return $Apache::functionplotresponse::dfuncdx[&array_index($Apache::functionplotresponse::fpr_xmin,
 1380:                                                               $Apache::functionplotresponse::fpr_xmax,
 1381:                                                               $arg)];
 1382: }
 1383: 
 1384: sub fpr_d2fdx2 {
 1385:    my ($arg)=@_;
 1386:    return $Apache::functionplotresponse::d2funcdx2[&array_index($Apache::functionplotresponse::fpr_xmin,
 1387:                                                                 $Apache::functionplotresponse::fpr_xmax,
 1388:                                                                 $arg)];
 1389: }
 1390: 
 1391: sub fpr_vectorcoords {
 1392:    my ($arg)=@_;
 1393:    $arg=~s/\W//gs;
 1394:    $arg=ucfirst($arg);
 1395:    my $id=$Apache::inputtags::response[-1];
 1396:    my $partid=$Apache::inputtags::part;
 1397:    my $internalid = $partid.'_'.$id;
 1398:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_x'},
 1399:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_x'},
 1400:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'Start_y'},
 1401:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'End_y'});
 1402: }
 1403: 
 1404: sub fpr_objectcoords {
 1405:    my ($arg)=@_;
 1406:    $arg=~s/\W//gs;
 1407:    $arg=ucfirst($arg);
 1408:    my $id=$Apache::inputtags::response[-1];
 1409:    my $partid=$Apache::inputtags::part;
 1410:    my $internalid = $partid.'_'.$id;
 1411:    return ($env{'form.HWVAL_'.$internalid.'_'.$arg.'_x'},
 1412:            $env{'form.HWVAL_'.$internalid.'_'.$arg.'_y'});
 1413: }
 1414: 
 1415: sub fpr_vectorlength {
 1416:    my ($arg)=@_;
 1417:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
 1418:    return sqrt(($xe-$xs)*($xe-$xs)+($ye-$ys)*($ye-$ys));
 1419: }
 1420: 
 1421: sub fpr_vectorangle {
 1422:    my ($arg)=@_;
 1423:    my ($xs,$xe,$ys,$ye)=&fpr_vectorcoords($arg);
 1424:    my $angle=57.2957795*atan2(($ye-$ys),($xe-$xs));
 1425:    if ($angle<0) { $angle=360+$angle; }
 1426:    return $angle;
 1427: }
 1428: 
 1429: sub vectorcoords {
 1430:    my ($id,$label)=@_;
 1431:    return ($env{'form.HWVAL_'.$id.'_'.$label.'Start_x'},
 1432:            $env{'form.HWVAL_'.$id.'_'.$label.'End_x'},
 1433:            $env{'form.HWVAL_'.$id.'_'.$label.'Start_y'},
 1434:            $env{'form.HWVAL_'.$id.'_'.$label.'End_y'});
 1435: }
 1436: 
 1437: sub objectcoords {
 1438:    my ($id,$label)=@_;
 1439:    return ($env{'form.HWVAL_'.$id.'_'.$label.'_x'},
 1440:            $env{'form.HWVAL_'.$id.'_'.$label.'_y'});
 1441: }
 1442: 
 1443: sub attached {
 1444:    my ($id,$vector,$objects,$xmin,$xmax,$ymin,$ymax)=@_;
 1445:    my ($xs,$xe,$ys,$ye)=&vectorcoords($id,$vector);
 1446:    my $tolx=($xmax-$xmin)/100.;
 1447:    my $toly=($ymax-$ymin)/100.;
 1448:    my $tail=0;
 1449:    my $tip=0;
 1450:    foreach my $obj (split(/\s*\,\s*/,$objects)) {
 1451:       $obj=~s/\W//g;
 1452:       unless ($obj) { next; }
 1453:       $obj=ucfirst($obj);
 1454:       my ($xo,$yo)=&objectcoords($id,$obj);
 1455:       &addlog("Proximity $vector ($xs,$ys)-($xe,$ye) to $obj ($xo,$yo)");
 1456:       if ((abs($xs-$xo)<$tolx) && (abs($ys-$yo)<$toly)) {
 1457:          $tail=1;
 1458:          &addlog("Attached tail: $obj"); 
 1459:       }
 1460:       if ((abs($xe-$xo)<$tolx) && (abs($ye-$yo)<$toly)) { 
 1461:          $tip=1;
 1462:          &addlog("Attached tip: $obj"); 
 1463:       }
 1464:    }
 1465:    &addlog("Result tail:$tail tip:$tip");
 1466:    return($tail,$tip);
 1467: }
 1468: 
 1469:  
 1470: sub vectorangle {
 1471:    my ($x,$y)=@_;
 1472:    my $angle=57.2957795*atan2($y,$x);
 1473:    if ($angle<0) { $angle=360+$angle; }
 1474:    return $angle;
 1475: }
 1476: 
 1477: sub vectorlength {
 1478:    my ($x,$y)=@_;
 1479:    return sqrt($x*$x+$y*$y);
 1480: }
 1481: 
 1482: sub relvector {
 1483:    my ($xs,$xe,$ys,$ye)=@_;
 1484:    return ($xe-$xs,$ye-$ys);
 1485: }
 1486: 
 1487: sub plotvectorlength {
 1488:    return &vectorlength(&relvector(&vectorcoords(@_)));
 1489: }
 1490: 
 1491: sub plotvectorangle {
 1492:    return &vectorangle(&relvector(&vectorcoords(@_)));
 1493: }
 1494: 
 1495: 
 1496: #
 1497: # Evaluate a functionplotvectorrule
 1498: #
 1499: 
 1500: sub functionplotvectorrulecheck {
 1501:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1502:    &addlog("=================");
 1503:    my ($label,$type)=split(/\:/,$rule);
 1504:    if ($type eq 'vector') {
 1505:       return &vectorcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
 1506:    } elsif ($type eq 'sum') {
 1507:       return &sumcheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval);
 1508:    } elsif ($type eq 'custom') {
 1509:       return &customcheck($rule,$safeeval);
 1510:    }
 1511: }
 1512: 
 1513: sub vectorcheck {
 1514:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1515:    my ($label,$type,$id,$vector,
 1516:        $attachpoint,$notattachpoint,
 1517:        $tailpoint,$tippoint,$nottailpoint,$nottippoint,
 1518:        $length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
 1519:    &addlog("Vector Rule $label for vector ".$vector);
 1520:    if ($length ne '') {
 1521:       &addlog("Checking for length $length with error $lengtherror");
 1522:       $length=&Apache::run::run($length,$safeeval);
 1523:       &addlog("Length evaluated to $length");
 1524:       my $thislength=&plotvectorlength($id,$vector);
 1525:       &addlog("Found length $thislength");
 1526:       if (abs($thislength-$length)>$lengtherror) {
 1527:          &setfailed($label);
 1528:          return 0;
 1529:       }
 1530:    }
 1531:    if ($angle ne '') {
 1532:       &addlog("Checking for angle $angle with error $angleerror");
 1533:       $angle=&Apache::run::run($angle,$safeeval);
 1534:       &addlog("Angle evaluated to $angle");
 1535:       my $thisangle=&plotvectorangle($id,$vector);
 1536:       &addlog("Found angle $thisangle");
 1537:       my $anglediff=abs($thisangle-$angle);
 1538:       &addlog("Angle difference: $anglediff");
 1539:       if ($anglediff>360.-$anglediff) {
 1540:          $anglediff=360.-$anglediff;
 1541:       }
 1542:       &addlog("Smallest angle difference: $anglediff");
 1543:       if ($anglediff>$angleerror) {
 1544:          &setfailed($label);
 1545:          return 0;
 1546:       }
 1547:    }
 1548:    if ($attachpoint ne '') {
 1549:       &addlog("Checking attached: ".$attachpoint);
 1550:       my ($tail,$tip)=&attached($id,$vector,$attachpoint,$xmin,$xmax,$ymin,$ymax);
 1551:       unless ($tail || $tip) {
 1552:          &setfailed($label);
 1553:          return 0;
 1554:       }
 1555:    }
 1556:    if ($notattachpoint ne '') {
 1557:       &addlog("Checking not attached: ".$notattachpoint);
 1558:       my ($tail,$tip)=&attached($id,$vector,$notattachpoint,$xmin,$xmax,$ymin,$ymax);
 1559:       if ($tail || $tip) {
 1560:          &setfailed($label);
 1561:          return 0;
 1562:       }
 1563:    }
 1564:    if ($tailpoint ne '') {
 1565:       &addlog("Checking tail: ".$tailpoint);
 1566:       my ($tail,$tip)=&attached($id,$vector,$tailpoint,$xmin,$xmax,$ymin,$ymax);
 1567:       unless ($tail) {
 1568:          &setfailed($label);
 1569:          return 0;
 1570:       }
 1571:    }
 1572:    if ($nottailpoint ne '') {
 1573:       &addlog("Checking not tail: ".$nottailpoint);
 1574:       my ($tail,$tip)=&attached($id,$vector,$nottailpoint,$xmin,$xmax,$ymin,$ymax);
 1575:       if ($tail) {
 1576:          &setfailed($label);
 1577:          return 0;
 1578:       }
 1579:    }
 1580:    if ($tippoint ne '') {
 1581:       &addlog("Checking tip: ".$tippoint);
 1582:       my ($tail,$tip)=&attached($id,$vector,$tippoint,$xmin,$xmax,$ymin,$ymax);
 1583:       unless ($tip) {
 1584:          &setfailed($label);
 1585:          return 0;
 1586:       }
 1587:    }
 1588:    if ($nottippoint ne '') {
 1589:       &addlog("Checking not tip: ".$nottippoint);
 1590:       my ($tail,$tip)=&attached($id,$vector,$nottippoint,$xmin,$xmax,$ymin,$ymax);
 1591:       if ($tip) {
 1592:          &setfailed($label);
 1593:          return 0;
 1594:       }
 1595:    }
 1596: 
 1597:    &addlog("Rule $label passed.");
 1598:    return 1;
 1599: }
 1600: 
 1601: sub sumcheck {
 1602:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1603:    my ($label,$type,$id,$vectors,$length,$angle,$lengtherror,$angleerror)=split(/\:/,$rule);
 1604:    &addlog("Vector Sum Rule $label for vectors ".$vectors);
 1605:    my $sumx=0;
 1606:    my $sumy=0;
 1607:    foreach my $sv (split(/\s*\,\s*/,$vectors)) {
 1608:       my ($rx,$ry)=&relvector(&vectorcoords($id,$sv));
 1609:       $sumx+=$rx;
 1610:       $sumy+=$ry;
 1611:    }
 1612:    &addlog("Sum vector ($sumx,$sumy)");
 1613:    if ($length ne '') {
 1614:       &addlog("Checking length $length with error $lengtherror");
 1615:       $length=&Apache::run::run($length,$safeeval);
 1616:       &addlog("Evaluated to $length");
 1617:       my $thislength=&vectorlength($sumx,$sumy);
 1618:       &addlog("Actual length $thislength");
 1619:       if (abs($length-$thislength)>$lengtherror) {
 1620:                   &setfailed($label);
 1621:          return 0;
 1622:       }
 1623:    }
 1624:    if ($angle ne '') {
 1625:       &addlog("Checking angle $angle with error $angleerror");
 1626:       $angle=&Apache::run::run($angle,$safeeval);
 1627:       &addlog("Evaluated to $angle");
 1628:       my $thisangle=&vectorangle($sumx,$sumy);
 1629:       &addlog("Actual angle $thisangle");
 1630:       my $anglediff=abs($thisangle-$angle);
 1631:       &addlog("Angle difference: $anglediff");
 1632:       if ($anglediff>360.-$anglediff) {
 1633:          $anglediff=360.-$anglediff;
 1634:       }
 1635:       &addlog("Smallest angle difference: $anglediff");
 1636:       if ($anglediff>$angleerror) {
 1637:          &setfailed($label);
 1638:          return 0;
 1639:       }
 1640:    }
 1641:    &addlog("Rule $label passed.");
 1642:    return 1;
 1643: }
 1644: 
 1645: sub customcheck {
 1646:    my ($rule,$safeeval)=@_;
 1647:    my ($label,$type,$prg)=split(/\:/,$rule);
 1648:    &addlog("Custom Rule ".$label);
 1649:    my $result=&Apache::run::run(&unescape($prg),$safeeval);
 1650:    &addlog("Algorithm returned $result");
 1651:    unless ($result) {
 1652:       &setfailed($label);
 1653:       return 0;
 1654:    }
 1655:    &addlog("Rule $label passed.");
 1656:    return 1;
 1657: }
 1658: 
 1659: #
 1660: # Evaluate a functionplotrule
 1661: #
 1662:  
 1663: sub functionplotrulecheck {
 1664:    my ($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)=@_;
 1665: 
 1666:    my ($label,$derivative,$xinitial,$xinitiallabel,$xfinal,$xfinallabel,$minimumlength,$maximumlength,$relationship,$value,$percent)
 1667:       =split(/\:/,$rule);
 1668:    $percent=($percent>0?$percent:5);
 1669:    &addlog("=================");
 1670:    &addlog("Rule $label for ".($derivative<0?'integral':('function itself','first derivative','second derivative')[$derivative])." $relationship $value");
 1671: #
 1672: # Evaluate the value
 1673: #
 1674:    if (($value=~/\D/) && ($value ne 'undef')) {
 1675:       $Apache::functionplotresponse::fpr_xmin=$xmin;
 1676:       $Apache::functionplotresponse::fpr_xmax=$xmax;
 1677:       $value=&Apache::run::run($value,$safeeval);
 1678:       &addlog("Value evaluated to $value");
 1679:    }
 1680: 
 1681: #
 1682: # Minimum and maximum lengths of the interval
 1683: #
 1684:    if ((defined($minimumlength)) || (defined($maximumlength))) {
 1685:       &addlog("Minimumlength $minimumlength Maximumlength $maximumlength");
 1686:    }
 1687:    my $li=0;
 1688:    my $lh=400;
 1689: 
 1690: # Special case: the upper boundary was not defined
 1691: # and needs to be set to the value where
 1692: # the condition is not true anymore => set flag
 1693: 
 1694:    my $findupper=0;
 1695:    if (($xfinal eq '')
 1696:     && (!defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}))
 1697:     && ($xfinallabel)) {
 1698:        $findupper=1;
 1699:    }
 1700: 
 1701: # if a hard value is set for the boundaries, it overrides the label
 1702:    if (($xinitial ne '') && ($xinitiallabel ne '') && ($xinitiallabel ne 'start')) {
 1703:       $li=&array_index($xmin,$xmax,$xinitial);
 1704:       $Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel}=$li;
 1705:    }
 1706:    if (($xfinal ne '') && ($xfinallabel ne '') && ($xfinallabel ne 'end')) {
 1707:       $lh=&array_index($xmin,$xmax,$xfinal);
 1708:       $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$lh;
 1709:    }
 1710: # if the label is defined, use it
 1711:    if (defined($Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel})) {
 1712:       &addlog("Using lower label $xinitiallabel");
 1713:       $li=$Apache::functionplotresponse::functionplotrulelabels{$xinitiallabel};
 1714:    } else {
 1715:       $li=&array_index($xmin,$xmax,$xinitial);
 1716:    }
 1717:    unless ($findupper) {
 1718:       if (defined($Apache::functionplotresponse::functionplotrulelabels{$xfinallabel})) {
 1719:          &addlog("Using upper label $xfinallabel");
 1720:          $lh=$Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}-1;
 1721:       } else {
 1722:          $lh=&array_index($xmin,$xmax,$xfinal);
 1723:       }
 1724:    }
 1725: # Basic sanity checks
 1726:    if ($li<0) { $li=0; }
 1727:    if ($lh>400) { $lh=400; }
 1728:    if (($li>$lh) || (!defined($lh))) {
 1729:        $lh=$li;
 1730:    }
 1731: 
 1732:    &addlog("Boundaries: x=".&actualval($li,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$li]."; index $li)) to x=".
 1733:                             &actualval($lh,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$lh]."; index $lh))");
 1734:    if ($findupper) {
 1735:       &addlog("Looking for label $xfinallabel");
 1736:    }
 1737:    my $tol=$percent*($ymax-$ymin)/100;
 1738:    if ($xmax>$xmin) {
 1739:       if ($derivative==2) {
 1740:          $tol=4.*$tol/($xmax-$xmin);
 1741:       } elsif ($derivative==1) {
 1742:          $tol=2.*$tol/($xmax-$xmin);
 1743:       } elsif ($derivative==-1) {
 1744:          $tol=$tol*($xmax-$xmin)/2.;
 1745:       }
 1746:    }
 1747:    my $integral=0;
 1748:    my $binwidth=($xmax-$xmin)/400.;
 1749:    if (($derivative<0) && (!$findupper)) {
 1750: # definite integral, calculate over whole length
 1751:      &addlog("Calculating definite integral");
 1752:      for (my $i=$li; $i<=$lh; $i++) {
 1753:         $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1754:      }
 1755:      unless (&compare_rel($relationship,$value,$integral,$tol)) {
 1756:         &addlog("Actual integral ".(defined($integral)?$integral:'undef').", expected $value, tolerance $tol");
 1757:         &addlog("Rule $label failed.");
 1758:         &setfailed($label);
 1759:         return 0;
 1760:      } 
 1761:    } else {
 1762:      for (my $i=$li; $i<=$lh; $i++) {
 1763:         my $val;
 1764:         if ($derivative==2) {
 1765:            $val=$Apache::functionplotresponse::d2funcdx2[$i];
 1766:         } elsif ($derivative==1) {
 1767:            $val=$Apache::functionplotresponse::dfuncdx[$i];
 1768:         } elsif ($derivative==-1) {
 1769:            $integral+=$Apache::functionplotresponse::func[$i]*$binwidth;
 1770:            $val=$integral;      
 1771:         } else {
 1772:            $val=$Apache::functionplotresponse::func[$i];
 1773:         }
 1774:         unless (&compare_rel($relationship,$value,$val,$tol)) { 
 1775:            &addlog("Actual value ".(defined($val)?$val:'undef').", expected $value, tolerance $tol");
 1776:            &addlog("Condition not fulfilled at x=".&actualval($i,$xmin,$xmax)." (".$Apache::functionplotresponse::actualxval[$i]."; index $i)");
 1777:            if (($findupper) && ($i>$li)) {
 1778: # Check lengths
 1779:               unless (&checklength($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1780: # Successfully found a new label, set it
 1781:               $Apache::functionplotresponse::functionplotrulelabels{$xfinallabel}=$i;
 1782:               &addlog("Rule $label passed, setting label $xfinallabel");
 1783:               return 1;
 1784:            } else {
 1785:               &addlog("Rule $label failed.");
 1786:               &setfailed($label);
 1787:               return 0; 
 1788:            }
 1789:         }
 1790:      }
 1791:    }
 1792: # Corner case where this makes sense: using start or stop as defined labels
 1793:    unless (&checklength($lh,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)) { return 0; }
 1794:    &addlog("Rule $label passed.");
 1795:    return 1;
 1796: }
 1797: 
 1798: #
 1799: # check for minimum and maximum lengths
 1800: #
 1801: 
 1802: sub checklength {
 1803:     my ($i,$li,$minimumlength,$maximumlength,$xmin,$xmax,$label)=@_;
 1804:     unless (($minimumlength) || ($maximumlength)) { return 1; }
 1805:     my $length=&actualval($i,$xmin,$xmax)-&actualval($li,$xmin,$xmax);
 1806:     if ($minimumlength) {
 1807:        if ($length<$minimumlength) {
 1808:           &addlog("Rule $label failed, actual length $length, minimum length $minimumlength");
 1809:           &setfailed($label);
 1810:           return 0;
 1811:        }
 1812:     }
 1813:     if ($maximumlength) {
 1814:        if ($length>$maximumlength) {
 1815:           &addlog("Rule $label failed, actual length $length, maximum length $maximumlength");
 1816:           &setfailed($label);
 1817:           return 0;
 1818:        }
 1819:     }
 1820:     return 1;
 1821: }
 1822: 
 1823: sub setfailed {
 1824:    my ($hintlabel)=@_;
 1825:    $hintlabel=~s/^R//;
 1826:    push(@Apache::functionplotresponse::failedrules,$hintlabel);
 1827:    &addlog("Set hint condition $hintlabel");
 1828: }
 1829: 
 1830: sub start_functionplotruleset {
 1831:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1832:    if ($target eq 'edit') {
 1833:       return &Apache::edit::start_table($token).
 1834:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Rule Set').'</span></td>'
 1835:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 1836:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 1837:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 1838:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Rule_Set','Function Plot Rules')
 1839:        .'</span></td>'
 1840:        ."<td>&nbsp;"
 1841:        .&Apache::edit::end_row()
 1842:        .&Apache::edit::start_spanning_row()
 1843:        ."\n";
 1844:    }
 1845: }
 1846: 
 1847: sub end_functionplotruleset {
 1848:     my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1849:     my $id=$Apache::inputtags::response[-1];
 1850:     my $partid=$Apache::inputtags::part;
 1851:     my $internalid = $partid.'_'.$id;
 1852: 
 1853:     if ($target eq 'edit' ) {
 1854:         return &Apache::edit::end_table();
 1855:     }  elsif ($target eq 'grade'
 1856:          && &Apache::response::submitted()
 1857:          && $Apache::lonhomework::type ne 'exam') {
 1858: #
 1859: # Actually grade
 1860: #
 1861:     my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1862: 
 1863:         my $ad='';
 1864:         undef  %Apache::functionplotresponse::functionplotrulelabels;
 1865:         $Apache::functionplotresponse::ruleslog='';
 1866:         $Apache::functionplotresponse::functionplotrulelabels{'start'}=400;
 1867:         $Apache::functionplotresponse::functionplotrulelabels{'end'}=0;
 1868:         if (&populate_arrays($internalid,$xmin,$xmax,$ymin,$ymax) eq 'no_func') {
 1869:            $ad='NOT_FUNCTION';
 1870:         } else {
 1871:            &addlog("Start of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'start'},$xmin,$xmax)." (index ".
 1872:                                         $Apache::functionplotresponse::functionplotrulelabels{'start'}.")");
 1873:            &addlog("End of function ".&actualval($Apache::functionplotresponse::functionplotrulelabels{'end'},$xmin,$xmax)." (index ".
 1874:                                         $Apache::functionplotresponse::functionplotrulelabels{'end'}.")");
 1875: 
 1876: # We have a function that we can actually grade, go through the spline rules.
 1877:            foreach my $rule (@Apache::functionplotresponse::functionplotrules) {
 1878:               unless (&functionplotrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
 1879:                  $ad='INCORRECT';
 1880:                  last;
 1881:               }
 1882:            }
 1883: # And now go through the vector rules
 1884:            foreach my $rule (@Apache::functionplotresponse::functionplotvectorrules) {
 1885:               unless (&functionplotvectorrulecheck($rule,$xmin,$xmax,$ymin,$ymax,$safeeval)) {
 1886:                  $ad='INCORRECT';
 1887:                  last;
 1888:               }
 1889:            }
 1890: # If it's not wrong, it's correct 
 1891:            unless ($ad) { $ad='EXACT_ANS' };
 1892:         }
 1893:         &addlog("Set hint conditions: ".join(",",@Apache::functionplotresponse::failedrules));
 1894:         &addlog("Assigned award detail: $ad");
 1895: # Store for later to be assigned at end_functionplotresponse
 1896:         $Apache::functionplotresponse::awarddetail=$ad;
 1897:      }
 1898: }
 1899: 
 1900: 
 1901: sub end_functionplotresponse {
 1902:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 1903:   &Apache::response::end_response;
 1904: 
 1905:   my $result;
 1906:   my $id=$Apache::inputtags::response[-1];
 1907:   my $partid=$Apache::inputtags::part;
 1908:   my $internalid = $partid.'_'.$id;
 1909: 
 1910:     if ($target eq 'edit') { $result=&Apache::edit::end_table(); }
 1911:     if ($target eq 'grade'
 1912:          && &Apache::response::submitted()
 1913:          && $Apache::lonhomework::type eq 'exam') {
 1914: 
 1915:         &Apache::response::scored_response($partid,$id);
 1916: 
 1917:     } elsif ($target eq 'grade'
 1918:          && &Apache::response::submitted()
 1919:          && $Apache::lonhomework::type ne 'exam') {
 1920:         my ($response,%coords)=&get_answer_from_form_fields($internalid);
 1921:         $Apache::lonhomework::results{"resource.$partid.$id.submission"}=$response;
 1922:         my %previous=&Apache::response::check_for_previous($response,$partid,$id);
 1923: #
 1924: # Assign grade
 1925: #
 1926:         my $ad=$Apache::functionplotresponse::awarddetail;
 1927: #
 1928: # Store grading info
 1929: #
 1930:         $Apache::lonhomework::results{"resource.$partid.$id.awarddetail"}=$ad;
 1931:         &Apache::response::handle_previous(\%previous,$ad);
 1932:    } elsif ($target eq 'web') {
 1933:         undef @Apache::functionplotresponse::failedrules;
 1934:    }
 1935:    return $result;
 1936: }
 1937: 
 1938: sub end_functionplotelements {
 1939:   my ($target,$token,$tagstack,$parstack,$parser,$safeeval)=@_;
 1940:   my $result='';
 1941:   my $id=$Apache::inputtags::response[-1];
 1942:   my $partid=$Apache::inputtags::part;
 1943:   my $internalid = $partid.'_'.$id;
 1944:   if ($target eq 'edit' ) {
 1945:      $result=&Apache::edit::end_table();
 1946:   } elsif ($target eq 'web') {
 1947:      my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 1948: 
 1949: # Are we in show answer mode?
 1950:      my $showanswer=&Apache::response::show_answer();
 1951:      if ($showanswer) {
 1952: # Render answerdisplay
 1953:         my $answerdisplay=&Apache::lonxml::get_param('answerdisplay',$parstack,$safeeval,-2);
 1954:         if ($answerdisplay=~/\S/s) {
 1955:            foreach my $plot (split(/\s*\,\s*/,$answerdisplay)) {
 1956:               my @components=split(/\s*\:\s*/,$plot);
 1957:               if ($#components<3) {
 1958: # Just a simple plot
 1959:                  my ($func,$xl,$xh)=@components;
 1960:                  if ((!defined($xl)) || ($xl eq '')) { $xl=$xmin; }
 1961:                  if ((!defined($xh)) || ($xh eq '')) { $xh=$xmax; }
 1962:                  $result.=&plot_script($internalid,$func,1,'','00aa00',$xl,$xh,6);
 1963:               } else {
 1964: # This is a spline
 1965:                  $result.=&answer_spline_script($internalid,@components);
 1966:               }
 1967:            }
 1968:         }
 1969:      }
 1970:      my $fixed=0;
 1971:      if (($showanswer) || (&Apache::response::check_status()>=2)) { $fixed=1; }
 1972: # Now is the time to render all of the stored splines
 1973:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1974:         $result.=&generate_spline($internalid,$label,$xmin,$xmax,$ymin,$ymax,$fixed);
 1975:      }
 1976: # close the init script
 1977:      $result.=&end_init_script();
 1978: # register all splines in this response 
 1979:      $result.='<input type="hidden" name="HWVAL_AllSplines_'.$internalid.'" value="'.
 1980:                  join(',',keys(%Apache::functionplotresponse::splineorder)).'" />'."\n";
 1981:      foreach my $label (keys(%Apache::functionplotresponse::splineorder)) {
 1982:         $result.='<input type="hidden" name="HWVAL_SplineOrder_'.$internalid.'_'.$label.'" value="'.
 1983:                  $Apache::functionplotresponse::splineorder{$label}.'" />'."\n";
 1984:      }
 1985: # generate the input fields
 1986:      $result.=$Apache::functionplotresponse::inputfields;
 1987: # actually start the <applet>-tag
 1988:      $result.=&geogebra_startcode($internalid,
 1989:                                   &Apache::lonxml::get_param('width',$parstack,$safeeval,-2),
 1990:                                   &Apache::lonxml::get_param('height',$parstack,$safeeval,-2));
 1991: # load the spline bytecode
 1992:      $result.=&geogebra_spline_program();
 1993: # set default parameters
 1994:      $result.=&geogebra_default_parameters($internalid);
 1995: # close the <applet>-tag
 1996:      $result.=&geogebra_endcode();
 1997:   }
 1998:   return $result;
 1999: }
 2000: 
 2001: sub boundaries {
 2002:    my ($parstack,$safeeval,$level)=@_;
 2003:    my $xmin=&Apache::lonxml::get_param('xmin',$parstack,$safeeval,$level);
 2004:    $xmin=(defined($xmin)?$xmin:-10);
 2005:    my $xmax=&Apache::lonxml::get_param('xmax',$parstack,$safeeval,$level);
 2006:    $xmax=(defined($xmax)?$xmax:10);
 2007:    my $ymin=&Apache::lonxml::get_param('ymin',$parstack,$safeeval,$level);
 2008:    $ymin=(defined($ymin)?$ymin:-10);
 2009:    my $ymax=&Apache::lonxml::get_param('ymax',$parstack,$safeeval,$level);
 2010:    $ymax=(defined($ymax)?$ymax:10);
 2011:    if ($xmax<=$xmin) {
 2012:       $xmax=$xmin+20;
 2013:    }
 2014:    if ($ymax<=$ymin) {
 2015:       $ymax=$ymin+20;
 2016:    }
 2017:    return ($xmin,$xmax,$ymin,$ymax);
 2018: }
 2019: 
 2020: sub start_functionplotelements {
 2021:    my ($target,$token,$tagstack,$parstack,$parser,$safeeval,$style)=@_;
 2022:    my $result='';
 2023:    my $id=$Apache::inputtags::response[-1];
 2024:    my $partid=$Apache::inputtags::part;
 2025:    my $internalid = $partid.'_'.$id;
 2026: 
 2027:    if ($target eq 'edit') {
 2028:       return &Apache::edit::start_table($token).
 2029:         '<tr><td><span class="LC_nobreak">'.&mt('Function Plot Elements').'</span></td>'
 2030:        .'<td><span class="LC_nobreak">'.&mt('Delete?').' '
 2031:        .&Apache::edit::deletelist($target,$token).'&nbsp;&nbsp;&nbsp;'.
 2032:         &Apache::edit::insertlist($target,$token).'&nbsp;&nbsp;&nbsp;'
 2033:        .&Apache::loncommon::help_open_topic('Function_Plot_Response_Elements','Function Plot Elements')
 2034:        .'</span></td>'
 2035:        ."<td>&nbsp;"
 2036:        .&Apache::edit::end_row()
 2037:        .&Apache::edit::start_spanning_row()
 2038:        ."\n";
 2039:    } elsif ($target eq 'web') {
 2040:       my ($xmin,$xmax,$ymin,$ymax)=&boundaries($parstack,$safeeval,-2);
 2041:       my $xaxisvisible=(&Apache::lonxml::get_param('xaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2042:       my $yaxisvisible=(&Apache::lonxml::get_param('yaxisvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2043:       my $gridvisible=(&Apache::lonxml::get_param('gridvisible',$parstack,$safeeval,-2)=~/on|true|yes|1/i?'true':'false');
 2044:       my $xlabel=&Apache::lonxml::get_param('xlabel',$parstack,$safeeval,-2);
 2045:       my $ylabel=&Apache::lonxml::get_param('ylabel',$parstack,$safeeval,-2);
 2046: 
 2047: 
 2048: # paste in the update routine to receive stuff back from the applet
 2049:      $result.=&update_script($internalid);
 2050: # start the initscript for this applet
 2051:      $result.=&start_init_script($internalid);
 2052: # put the axis commands inside
 2053:      $result.=&axes_script($internalid,$xmin,$xmax,$ymin,$ymax,$xaxisvisible,$yaxisvisible,$gridvisible);
 2054:      $result.=&axes_label($internalid,$xmin,$xmax,$ymin,$ymax,$xlabel,$ylabel);
 2055: # init script is left open
 2056:   }
 2057:   return $result;
 2058: }
 2059: 
 2060: 1;
 2061: 
 2062: __END__
 2063:  
 2064: =head1 NAME
 2065: 
 2066: Apache::functionplotresponse.pm;
 2067: 
 2068: =head1 SYNOPSIS
 2069: 
 2070: Handles tags associated with accepting function plots.
 2071: 
 2072: This is part of the LearningOnline Network with CAPA project
 2073: described at http://www.lon-capa.org.
 2074: 
 2075: =head1 HANDLER SUBROUTINE
 2076: 
 2077: start_functionplotresponse()
 2078: 
 2079: =head1 OTHER SUBROUTINES
 2080: 
 2081: =over
 2082: 
 2083: =item end_functionplotresponse()
 2084: 
 2085: =back
 2086: 
 2087: =cut

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