File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.98: download - view: text, annotated - select for diffs
Fri Aug 17 13:08:11 2012 UTC (11 years, 9 months ago) by www
Branches: MAIN
CVS tags: HEAD
HTML5/JavaScript does not understand underscores in applet IDs

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

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