File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.97: download - view: text, annotated - select for diffs
Thu Aug 16 23:03:01 2012 UTC (11 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
Further work on HTML5.

TODO: Need to replace "_" in applet-ID, as JavaScript implementation ignores it.

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

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