File:  [LON-CAPA] / loncom / homework / functionplotresponse.pm
Revision 1.112: download - view: text, annotated - select for diffs
Thu Jun 6 15:55:19 2024 UTC (3 weeks, 1 day ago) by raeburn
Branches: MAIN
CVS tags: version_2_12_X, HEAD
- Modify changes in rev 1.111 so GeoGebra 5.0.426 and later display works
  well with LON-CAPA Authoring Space menus for all supported web browsers.

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

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