/* Next available MSG number is  33 */

/***************************************************************************
   Module Name:  grvecs.c

   Copyright (C) 1992, 1993, 1994 by Autodesk, Inc.
 
   Permission to use, copy, modify, and distribute this software in 
   object code form for any purpose and without fee is hereby granted, 
   provided that the above copyright notice appears in all copies and 
   that both that copyright notice and the limited warranty and 
   restricted rights notice below appear in all supporting 
   documentation.
 
   AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.  
   AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF 
   MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE.  AUTODESK, INC.
   DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE 
   UNINTERRUPTED OR ERROR FREE.
 
   Use, duplication, or disclosure by the U.S. Government is subject to 
   restrictions set forth in FAR 52.227-19 (Commercial Computer 
   Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) 
   (Rights in Technical Data and Computer Software), as applicable.
    
   .

   Description:ADS version of the AutLISP program sprial.lsp

   Author     :
                 Autodesk, Inc.
                 2320 Marinship Way
                 Sausalito, CA. 94965
                 (415)332-2344

  **************************************************************************

    Function Entry Points:
        void
        main(argc, argv)
        int    argc;              [Number of argument passed in cmd line]
        char   *argv[];           [Array of pointers to arguments]

    Exported ADS Functions
        TESTGRVECS                [Test the ADS_GRVECS function]

    Modification History:
        Feb 28 1992 - bcm - original creation

    Notes and restrictions on use:


***************************************************************************/

/**************************************************************************/
/*  MODULE NAME  */
/**************************************************************************/
#define    GRVECS

/****************************************************************************/
/*  DEFINES  */
/****************************************************************************/
#define ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
#define SPOINT(p, x, y, z) p[X] = (x); p[Y] = (y); p[Z] = (z)
#define CPOINT(dst, src) dst[X] = src[X]; dst[Y] = src[Y]; dst[Z] = src[Z]
/**************************************************************************/
/*  TYPEDEFS  */
/**************************************************************************/
/* ADS Function Table */
typedef struct {
    char    *name;
    int     (*fptr)();
} ftblent;

typedef struct resbuf rbtype;
/**************************************************************************/
/*  INCLUDES  */
/**************************************************************************/

#include <stdio.h>
#include <math.h>
#ifndef __WATCOMC__
#include <memory.h>
#endif
#include "adslib.h"
/****************************************************************************/
/*  LOCAL FUNCTION FORWARD DECLARATIONS  */
/****************************************************************************/
int grspiral   _((int ntimes, ads_point bpoint, ads_real cfac, int lppass));
int testgrvecs _((void));

/**************************************************************************/
/*  GLOBAL VARIABLES  */
/**************************************************************************/
/* Table of ADS functions */
ftblent exfun[] = {
            {/*MSG0*/"C:TESTGRVECS", testgrvecs},
        };

/**************************************************************************/
/*  EXTERNAL FUNCTION DECLARATIONS  */
/**************************************************************************/

/**************************************************************************/
/*  EXTERNAL VARIABLE DECLARATIONS  */
/**************************************************************************/

/****************************************************************************/
/*  LOCAL FUNCTION DECLARATIONS  */
/****************************************************************************/
int funcload   _((void));
int funcunload _((void));
int dofun      _((void));

/******************************************************************************/
/*.doc geterrno(internal) */
/*+
    This function is called to obtain the value of the AutoCAD system
    variable ERRNO and return it as a result.
-*/
/******************************************************************************/
int
/*FCN*/geterrno()
{
    rbtype errval;

    ads_getvar(/*MSG0*/"ERRNO", &errval);

    return errval.resval.rint;
}

/******************************************************************************/
/*.doc funcload(internal) */
/*+
    This function is called to define all function names in the ADS
    function table.  Each named function will be callable from lisp or
    invokable from another ADS application.
-*/
/******************************************************************************/
int
/*FCN*/funcload()
{
    int i;

    for (i = 0; i < ELEMENTS(exfun); i++) {
        if (!ads_defun(exfun[i].name, i))
            return RTERROR;
    }

    return RTNORM;
}

/******************************************************************************/
/*.doc funclunoad(internal) */
/*+
    This function is called to undefine all function names in the ADS
    function table.  Each named function will be removed from the
    AutoLISP hash table.
-*/
/******************************************************************************/
int
/*FCN*/funcunload()
{
    int i;

    /* Undefine each function we defined */

    for (i = 0; i < ELEMENTS(exfun); i++) {
        ads_undef(exfun[i].name,i);
    }

    return RTNORM;
}
/******************************************************************************/
/*.doc dofun(internal) */
/*+
    This function is called to invoke the function which has the
    registerd function code that is obtained from  ads_getfuncode.  The
    function will return RTERROR if the function code is invalid, or
    RSERR if the invoked function fails to return RTNORM.  The value
    RSRSLT will be returned if the function code is valid and the
    invoked subroutine returns RTNORM.
-*/
/******************************************************************************/
int
/*FCN*/dofun()
{
    int    val;
    int    rc;

    ads_retvoid();
 
    if ((val = ads_getfuncode()) < 0 || val > ELEMENTS(exfun))
        return RTERROR;
 
    rc = (*exfun[val].fptr)();
 
    return ((rc == RTNORM) ? RSRSLT:RSERR);
}

/******************************************************************************/
/*.doc main(internal) */
/*+
    This is the main entry point for the ADS application.  All ADS
    requests will be dispatched from this function.  This is your
    standard ADS dispatch loop.
-*/
/******************************************************************************/
void
/*FCN*/main(argc,argv)
int argc;
char *argv[];
{
    short scode = RSRSLT;          /* Normal result code (default) */
    int   stat;
    char errmsg[80];

    ads_init(argc, argv);          /* Initiate communication with AutoLISP */

    for ( ;; ) {                   /* Request/Result loop */

        if ((stat = ads_link(scode)) < 0) {
            sprintf(errmsg,
                    /*MSG1*/"GRVECS: bad status from ads_link() = %d\n",
                    stat);
#ifdef Macintosh
            macalert(errmsg);
#else
            puts(errmsg);
            fflush(stdout);
#endif /* Macintosh */
            exit(1);
        }

        scode = RSRSLT;           /* Reset result code */

        switch (stat) {

        case RQXLOAD:             /* Load & define functions */
            scode = funcload() ? -RSRSLT : -RSERR;
            break;

        case RQXUNLD:             /* Unload functions */
            scode = funcunload() ? -RSRSLT : -RSERR;
            ads_printf(/*MSG2*/"Unloading.\n");
            break;

        case RQSUBR:             /* Handle request for external function */
            dofun();
            break;

        default:
            break;
        }
    }
}

/******************************************************************************/
/*.doc grspiral(internal) */
/*+
    This function is a C translation of the grspiral.lsp program
    designed to exersise the AutoLISP function grvecs.  The function
    takes the arguments: number of spiral rotations, the center point
    for the spiral, the rate of growth per rotation, and the number of
    points per rotation.

    The vectors for the spiral will be generated in the form of a
    linked list of three dimentional point nodes, and color short
    nodes.  The resulting list will be passed to the ads_grvecs
    function which will perform the actual graphical output.  Each
    vector in the list will include a color value which is obtained by
    cycling thru the range of colors specified by the values of minclr,
    and maxclr.

    This function always returns RTNORM.
-*/
/******************************************************************************/
int
/*FCN*/grspiral(ntimes, bpoint, cfac, lppass)
int       ntimes;
ads_point bpoint;
ads_real  cfac;
int       lppass;
{
    ads_real     circle;
    ads_real     ainc;
    ads_real     dinc;
    ads_real     ang;
    ads_real     dist;
    ads_real     zdir;
    ads_point    lpoint;
    ads_point    tp;
    rbtype       *plist;
    rbtype       *tplist;
    int          minclr;
    int          maxclr;
    int          color;
    int          n;
    int          l;
    int          sindex;
    ads_matrix   mat;

    extern ads_matrix ads_identmat;
    memcpy(mat, ads_identmat, sizeof(ads_matrix));
    CPOINT(lpoint, bpoint);
    circle = 3.141496235 * 2;
    ainc = circle / lppass;
    dinc = cfac / lppass;
    ang = 0.0;
    dist = 0.0;
    minclr = 1;
    maxclr = 200;
    color = minclr;
    zdir = 0.0;

    ads_retnil();
    tplist = plist = ads_buildlist(RTSHORT, color, NULL);

    for (n = ntimes; n > 0 && tplist != NULL; n--) {
        for (l = lppass; l > 0 && tplist != NULL; l--) {
            ang = ang + ainc;
            dist = dist + dinc;
            ads_polar(bpoint, ang, dist, tp);

            /* adjust z coordinate to this point */
            tp[Z] = zdir;

            /* append last point and new point to end of grvecs list */
            tplist = tplist->rbnext = ads_buildlist(RT3DPOINT, lpoint, NULL);
            if (tplist == NULL)
                continue;
            tplist = tplist->rbnext = ads_buildlist(RT3DPOINT, tp, NULL);
            if (tplist == NULL)
                continue;

            /* increment color */
            color++;

            /* if color is == max color then reset it to one and
               loop thru them again */
            if (color == maxclr)
                color = minclr;

            /* append new color number to end of grvecs list */
            tplist = tplist->rbnext = ads_buildlist(RTSHORT, color, NULL);
            if (tplist == NULL)
                continue;

            /* save new point as last point */
            CPOINT(lpoint, tp);

            /* adjust the z coord for the next point */
            zdir = zdir + cfac;
        }
    }
    if (plist != NULL && tplist != NULL)
        ads_grvecs(plist, NULL);
        for (sindex = 0; sindex < 100; sindex ++) {
            mat[X][X] = mat[Y][Y] = mat[Z][Z] += .05;
            ads_grvecs(plist, mat);
        }
    if (plist != NULL)
        ads_relrb(plist);
    return RTNORM;
}


/******************************************************************************/
/*.doc testgrvecs(internal) */
/*+
    This function is called from dofun function as a result of RQSUBR
    request being sent to the main dispatch loop.

    It prompts the user for the Center point of a spiral, the number of
    rotations in the spiral, the amount of growth per rotation, and the
    number of points in each rotation.   The function can be canceled
    by the user by pressing the Control-C keys.

    This function does not perfrom an error checking.  The return value
    for this function is the last value in rc.
-*/
/******************************************************************************/
int
/*FCN*/testgrvecs()
{
    rbtype      *args;
    int         rc;
    ads_point   bp;
    int         nt;
    ads_real    cf;
    int         lp;

    args = ads_getargs();
    ads_printf(/*MSG3*/"\nPerforming ads_grvecs test\n");
    if (args != NULL) {
        ads_printf(/*MSG4*/"No arguments please.\n");
    }
    rc = ads_getpoint(NULL, /*MSG5*/"\nCenter point: ", bp);
    if (rc == RTCAN) return RTNORM;
    rc = ads_getint(/*MSG6*/"\nNumber of rotations: ", &nt);
    if (rc == RTCAN) return RTNORM;
    rc = ads_getreal(/*MSG7*/"\nGrowth per rotation: ", &cf);
    if (rc == RTCAN) return RTNORM;
    lp = 30;
    ads_initget(0, NULL);
    rc = ads_getint(/*MSG8*/"\nPoints per rotation <30>: ", &lp);
    if (rc == RTCAN) return RTNORM;

    rc = grspiral(nt, bp, cf, lp);

    return rc;
}

