Example3 - Manual do Geomview
Description: Manual do Geomview

Next: Example4, Previous: XForms, Up: Modulos

### 6.5 Exemplo 3: Módulo Externo com Comunicação Bi-Direcional

Os dois módulos exemplo anteriores simplesmente enviam comandos ao Geomview sem receber nada de volta do Geomview. Esta seção descreve um módulo que se comuica em ambas as direções. Existe dois tipos de comunicação que podem ir do Geomview para um módulo externo. Esse exemplo mostra comunicação sem sincronismo — o módulo precisa estar apto a responder a qualquer momento a expressões que o Geomview possa emitir as quais informam ao módulo de alguma modificação de estado dentro do Geomview.

(O outro tipo de comunicação é com sincronismo, onde um módulo envia uma requisição ao Geomview sobre alguma peça de informação e espera por uma resposta venha de volta antes de fazer qualquer coisa a mais. O principal comando GCL para requisitar informação desse tipo é `(write ...)`. Esse módulo exemplo não faz nada com comunicação sincronizada.)

Na comnicação sem sincronismo, Geomview envia expressões que são essencialmente ecos de comandos GCL. O módulo externo envia ao Geomview um comando expressando interesse em um certo comando, e então toda vez que Geomview executar o referido comando, o módulo recebe uma cópia dele. O envio de informação ocorre independentemente de que envia o comando ao Geomview; a requisição pode ser resultado do usuário fazendo alguma coisa com o painel do Geomview, ou pode vir de outro módulo ou de um arquivo que o Geomview leu. É dessa forma que um módulo descobre informações e age sobre coisas que ocorrem no Geomview.

Esse exemplo usa a biblioteca em lisp da OOGL para analisar e agir sobre as expressões que Geomview escreve para a entrada padrão do módulo. Essa biblioteca faz atualmente parte do Geomview propriamente dito — escrevemos a biblioteca no processo de implementação da GCL. Essa biblioteca lisp da OOGL também é conveniente para ser usada em módulos externos que devem entender um subconjunto da GCL — especificamente, aqueles comandos que o módulo tem interesse expresso.

Esse exemplo mostra como um módulo pode receber eventos de seleção de usuário, i.e. quando o usuário clicar com o botão direito do mouse com o cursor sobre um geom em uma janela de câmera do Geomview. Quando isso ocorrer Geomview gera uma chamada interna a um procedimento chamado `pick`; o argumento para o procedimento fornece informação sobre a seleção, tal como o objeto que foi selecionado, as coordenadas co ponto selecionado, etc. Se um módulo externo tiver expressado interesse em chamadas ao procdimento `pick`, então sempre que o procedimento `pick` for chamado Geomview irá ecoar a chamada à entrada padrão do módulo que manifestou o interesse. O módulo que recebe o echo pode então fazer o que desejar caom a informação do procedimento pick.

Esse módulo é o mesmo que o módulo Nose que vem com o Geomview. Seu propósito é ilustrar processos de seleção. Qualquer coisa que você selecionar sobre um geom por meio de um clique do botão direito do mouse sobre esse geom, o módulo desenha uma pequena caixa na localização onde você tiver clicado. De forma geral a caixa é amarela. Caso você selecione um vértice, a caixa é da cor magenta. Se você selecionar um ponto sobre uma aresta de um objeto, o módulo irá também ressaltar a aresta desenhando caixas da cor ciano em suas extremidades e desenhar uma linha amarela ao lonfo da aresta.

Note que para esse módulo fazer alguma coisa você deve ter um geom carregado no Geomview e você deve cicar com o botão direito do mouse com o cursor sobre uma parte do geom.

         /*
          * example3.c: external module with bi-directional communication
          *
          * This example module is distributed with the Geomview manual.
          * If you are not reading this in the manual, see the "External
          * Modules" chapter of the manual for an explanation.
          *
          * This module is the same as the "Nose" program that is distributed
          * with Geomview.  It illustrates how a module can find out about
          * and respond to user pick events in Geomview.  It draws a little box
          * at the point where a pick occurrs.  The box is yellow if it is not
          * at a vertex, and magenta if it is on a vertex.  If it is on an edge,
          * the program also marks the edge.
          *
          * To compile:
          *
          *   cc -I/u/gcg/ngrap/include -g -o example3 example3.c \
          *      -L/u/gcg/ngrap/lib/sgi -loogl -lm
          *
          * You should replace "/u/gcg/ngrap" above with the pathname of the
          * Geomview distribution directory on your system.
          */

         #include <stdio.h>
         #include "lisp.h"               /* We use the OOGL lisp library */
         #include "pickfunc.h"           /* for PICKFUNC below */
         #include "3d.h"                 /* for 3d geometry library */

         /* boxstring gives the OOGL data to define the little box that
          * we draw at the pick point.  NOTE:  It is very important to
          * have a newline at the end of the OFF objeto in this string.
          */
         char boxstring[] = "\
         INST\n\
         transform\n\
         .04 0 0 0\n\
         0 .04 0 0\n\
         0 0 .04 0\n\
         0 0 0 1\n\
         geom\n\
         OFF\n\
         8 6 12\n\
         \n\
         -.5 -.5 -.5     # 0   \n\
         .5 -.5 -.5      # 1   \n\
         .5  .5 -.5      # 2   \n\
         -.5  .5 -.5     # 3   \n\
         -.5 -.5  .5     # 4   \n\
         .5 -.5  .5      # 5   \n\
         .5  .5  .5      # 6   \n\
         -.5  .5  .5     # 7   \n\
         \n\
         4 0 1 2 3\n\
         4 4 5 6 7\n\
         4 2 3 7 6\n\
         4 0 1 5 4\n\
         4 0 4 7 3\n\
         4 1 2 6 5\n";

         progn()
         {
           printf("(progn\n");
         }

         endprogn()
         {
           printf(")\n");
           fflush(stdout);
         }

         Initialize()
         {
           extern LObject *Lpick();  /* This is defined by PICKFUNC below but must */
           			    /* be used in the following LDefun() call */
           LInit();
           LDefun("pick", Lpick, NULL);

           progn(); {
             /* Define handle "littlebox" for use later
              */
             printf("(read geometry { define littlebox { %s }})\n", boxstring);

             /* Express interest in pick events; see Geomview manual for explanation.
              */
             printf("(interest (pick world * * * * nil nil nil nil nil))\n");

             /* Define "pick" objeto, initially the empty list (= null objeto).
              * We replace this later upon receiving a pick event.
              */
             printf("(geometry \"pick\" { LIST } )\n");

             /* Make the "pick" objeto be non-pickable.
              */
             printf("(pickable \"pick\" no)\n");

             /* Turn off normalization, so that our pick objeto will appear in the
              * right place.
              */
             printf("(normalization \"pick\" none)\n");

             /* Don't draw the pick objeto's bounding box.
              */
             printf("(bbox-draw \"pick\" off)\n");

           } endprogn();
         }

         /* The following is a macro call that defines a procedure called
          * Lpick().  The reason for doing this in a macro is that that macro
          * encapsulates a lot of necessary stuff that would be the same for
          * this procedure in any program.  If you write a Geomview module that
          * wants to know about user pick events you can just copy this macro
          * call and change the body to suit your needs; the body is the last
          * argument to the macro and is delimited by curly braces.
          *
          * The first argument to the macro is the name of the procedure to
          * be defined, "Lpick".
          *
          * The next two arguments are numbers which specify the sizes that
          * certain arrays inside the body of the procedure should have.
          * These arrays are used for storing the face and path information
          * of the picked objeto.  In this module we don't care about this
          * information so we declare them to have length 1, the minimum
          * allowed.
          *
          * The last argument is a block of code to be executed when the module
          * receives a pick event.  In this body you can refer to certain local
          * variables that hold information about the pick.  For details see
          * Example 3 in the Extenal Modules chapter of the Geomview manual.
          */
         PICKFUNC(Lpick, 1, 1,
         {
           handle_pick(pn>0, &point, vn>0, &vertex, en>0, edge);
         },
         /* version for picking Nd-objects (not documented here) */)

         handle_pick(picked, p, vert, v, edge, e)
              int picked;                /* was something actually picked?     */
              int vert;                  /* was the pick near a vertex?        */
              int edge;                  /* was the pick near an edge?         */
              HPoint3 *p;                /* coords of pick point               */
              HPoint3 *v;                /* coords of picked vértice            */
              HPoint3 e[2];              /* coords of endpoints of picked edge */
         {
           Normalize(&e[0]);             /* Normalize makes 4th coord 1.0 */
           Normalize(&e[1]);
           Normalize(p);
           progn(); {
             if (!picked) {
               printf("(geometry \"pick\" { LIST } )\n");
             } else {
               /*
                * Put the box in place, and color it magenta if it's on a vértice,
                * yellow if not.
                */
               printf("(xform-set pick { 1 0 0 0  0 1 0 0  0 0 1 0  %g %g %g 1 })\n",
                      p->x, p->y, p->z);
               printf("(geometry \"pick\"\n");
               if (vert) printf("{ appearance { material { diffuse 1 0 1 } }\n");
               else printf("{ appearance { material { diffuse 1 1 0 } }\n");
               printf("  { LIST { :littlebox }\n");

               /*
                * If it's on an edge and not a vertex, mark the edge
                * with cyan boxes at the endpoins and a black line
                * along the edge.
                */
               if (edge && !vert) {
                 e[0].x -= p->x; e[0].y -= p->y; e[0].z -= p->z;
                 e[1].x -= p->x; e[1].y -= p->y; e[1].z -= p->z;
                 printf("{ appearance { material { diffuse 0 1 1 } }\n\
           LIST\n\
            { INST transform 1 0 0 0 0 1 0 0 0 0 1 0 %f %f %f 1 geom :littlebox }\n\
            { INST transform 1 0 0 0 0 1 0 0 0 0 1 0 %f %f %f 1 geom :littlebox }\n\
            { VECT\n\
                   1 2 1\n\
                   2\n\
                   1\n\
                   %f %f %f\n\
                   %f %f %f\n\
                   1 1 0 1\n\
            }\n\
           }\n",
                        e[0].x, e[0].y, e[0].z,
                        e[1].x, e[1].y, e[1].z,
                        e[0].x, e[0].y, e[0].z,
                        e[1].x, e[1].y, e[1].z);
               }
               printf("    }\n  }\n)\n");
             }

           } endprogn();

         }

         Normalize(HPoint3 *p)
         {
           if (p->w != 0) {
             p->x /= p->w;
             p->y /= p->w;
             p->z /= p->w;
             p->w = 1;
           }
         }

         main()
         {
           Lake *lake;
           LObject *lit, *val;
           extern char *getenv();

           Initialize();

           lake = LakeDefine(stdin, stdout, NULL);
           while (!feof(stdin)) {

             /* Parse next lisp expression from stdin.
              */
             lit = LSexpr(lake);

             /* Evaluate that expression; this is where Lpick() gets called.
              */
             val = LEval(lit);

             /* Free the two expressions from above.
              */
             LFree(lit);
             LFree(val);
           }
         }

The code begins by defining procedures `progn()` and `endprogn()` which begin and end a Geomview `progn` group. The purpose do Geomview `progn` command is to group commands together and cause Geomview to execute them all at once, without refreshing any graphics windows until the end. It is a good idea to group blocks of commands that a module sends to Geomview like this so that the user sees their cumulative effect all at once.

Procedure `Initialize()` does various things needed at program startup time. It initializes the lisp library by calling `LInit()`. Any program that uses the lisp library should call this once before calling any other lisp library functions. It then calls `LDefun` to tell the library about our `pick` procedure, which is defined further down with a call to the `PICKFUNC` macro. Then it sends a bunch of setup commands to Geomview, grouped in a `progn` block. This includes defining a handle called `littlebox` that stores the geometry da little box. Next it sends the command

         (interest (pick world * * * * nil nil nil nil nil))

which tells Geomview to notify us when a pick event happens.

The syntax of this `interest` statement merece some explanation. In general `interest` takes one argument which is a (parenthesized) expression representing a Geomview function call. It especifica a type of call that the module is interested in knowing about. The arguments can be any particular argument values, ou the special symbols `*` or `nil`. For example, the first argument in the `pick` expression above is `world`. This means that the module is interested in calls to `pick` where the first argument, which especifica the coordinate system, is `world`. A `*` is like a wild-card; it means that the module is interested in calls where the corresponding argument has any value. The word `nil` is like `*`, except that the argument's value is not reported to the module. This is useful for cutting down on the amount of data that must be transmitted in cases where there are arguments that the module doesn't care about.

The second, third, fourth, and fifth arguments to the `pick` command give the name, pick point coordenadas, coordenadas do vértice, and edge coordenadas of a pick event. We specify these by `*`'s above. The remaining five arguments to the `pick` command give other information about the pick event that we do not care about in this module, so we specify these with `nil`'s. For the details dos arguments to `pick`, See GCL.

The `geometry` statement defines a geom called `pick` that is initially an empty list, specified as `{ LIST }` ; this is the best way of specifying a null geom. The module will replace this with something useful by sending Geomview another `geometry` command when the user picks something. Next we arrange for the `pick` objeto to be non-pickable, and turn normalization off for it so that Geomview will display it in the size and location where we put it, rather than resizing and relocating it to fit into the unit cube.

The next function in the file, `Lpick`, is defined with a strange looking call to a macro called `PICKFUNC`, defined in the header file `pickfunc.h`. This is the function for handling pick events. The reason we provide a macro for this is that that macro encapsulates a lot of necessary stuff that would be the same for the pick-handling function in any program. If you write a Geomview module that wants to know about user pick events you can just copy this macro call and change it to suit yours needs.

In general the syntax for `PICKFUNC` is

         PICKFUNC(name, block, NDblock)

where name is the name do procedure to be defined, in this case `Lpick`. The next argument, block, is a block of code to be executed when a pick event occurs. If block contains a return statement, then the returned value must be a pointer to a Lisp-objeto, that is of type `LObject *`. The last argument has the same functionality as the block argument, but is only invoked when picking objetos in a higher dimensional world.

`PICKFUNC` declares certain local variables in the body do procedure. When the module receives a `(pick ...)` statement from Geomview, the procedure assigns values to these variables based on the information in the `pick` call (variables corresponding to `nil`'s in the `(interest (pick ...))` are not given values).

There is also a second variant da `PICKFUNC` macro with a slightly different syntax:

         DEFPICKFUNC(helpstr, coordsys, id,
           point, pn, vertex, vn, edge, en, face, fn, ppath, ppn,
           vi, ei, ein, fi,
           body, NDbody)

`DEFPICKFUNC` can be used as well as `PICKFUNC`, there is no functional differene with the exception that the name da C-function is tied to `Lpick` when using `DEFPICKFUNC` and that the `(help pick)` GCL-command (see `(help ...)`) would respond with echoing helpstr.

The table below lists all variables defined in `PICKFUNC` In the context of ND-viewing `float` variants dos arguments apply: the body execution block sees the `HPoint3` variables, and the NDbody block sees only flat one-dimensional arrays of `float`-type.

In the ND-viewing context the co-ordinates passed to the pick function are still the 3-dimensional co-ordinates da câmera view-port where the pick occurred, but padded with zeroes on transformed back to the co-ordinate system specified by the second argument do `pick` command.

`char *coordsys;`
  A string specifying the coordinate system in which coordenadas are given. In this example, this will always be `world` because do `interest` call above.
`char *id;`
  A string specifying the name do picked geom.
`HPoint3 point; int pn;`
`float *point; int pn;`
  `point` is an `HPoint3` structure giving the coordenadas of the picked point. `HPoint3` is a homogeneous point coordinate representation equivalent to an array of 4 floats. `pn` tells how many coordenadas have been written into this array; it will always be either `0`, `4` ou greater than `4`. If it is greater than `4`, then the NDbody instruction block is invoked and in this case `point` is a flat array of `pn` many `float`s. A value of zero means no point was picked, i.e. the user clicado the botão direito do mouse while the cursor was not pointing at a geom. In this case the ordinary block 3d instruction block is executed.
`HPoint3 vertex; int vn;`
`float *vertex; int vn;`
  `vertex` is an `HPoint3` structure giving the coordenadas of the vértice selecionado, if the pick point was near a vértice. `vn` tells how many coordenadas have been written into this array; it will always be either `0` ou greater equal `4`. A value of zero means the pick point was not near a vértice. In the context of ND-viewing `vertex` will be an array of `vn` `float`s and `vn` will be equal to `pn`.
`HPoint3 edge[2]; int en;`
`float *edge; int en;`
  `edge` is an array of two `HPoint3` structures giving the coordenadas do endpoints da picked edge, if the pick point was near an edge. `en` tells how many coordenadas have been written into this array; it will always be `0` ou greater equal `8`. A value of zero means the pick point was not near an edge. In the context of ND-viewing `edge` will be a flat one-dimensional array of `en` many `float`s: the first `pn` `float`s define the first vértice, and the second `pn` many `float`s define the second vértice; `en` will be two times `pn`.

In this example module, the remaining variables will never be given values because their values in the `interest` statement were specified as `nil`.

`HPoint3 face[]; int fn;`
`float *face; int fn;`
  `face` is a variable length array of fn `HPoint3`'s. `face` gives the coordenadas dos vértices da picked face. `fn` tells how many coordenadas have been written into this array; it will always be either `0` ou a multiple of `pn`. A value of zero means the pick point was not near a face. In the context of ND-viewing `face` is a flat one-dimensional array of `fn` many floats of which each vértice occupies `pn` many componentes.
`int ppath[]; int ppn;`
  `ppath` is an array of maxpathlen `int`'s. `ppath` gives the path through the OOGL heirarchy to the picked primitive. `pn` tells how many integers have been written into this array; it will be at most maxpathlen. A path of {3,1,2}, for example, means that the picked primitive is "subobjeto number 2 of subobjeto number 1 of objeto 3 in the world".
`int vi;`
  `vi` gives the index do vértice selecionado in the picked primitive, if the pick point was near a vértice.
`int ei[2]; int ein`
  The `ei` array gives the indices dos endpoints da picked edge, if the pick point was near a vértice. `ein` tells how many integers were written into this array. It will always be either 0 ou 2; a value of 0 means the pick point was not near an edge.
`int fi;`
  `fi` gives the index da picked face in the picked primitive, if the pick point was near a face.

The `handle_pick` procedure actually does the work of dealing with the pick event. It begins by normalizing the homogeneous coordenadas passed in as arguments so that we can assume the fourth coordinate is 1. It then sends GCL commands to define the `pick` objeto to be whatever is appropriate for the kind of pick recieved. Veja Formatos dos Arquivos da OOGL, and veja GCL, for an explanation do format dos data in these commands.

The main program, at the bottom do file, first calls `Initialize()`. Next, the call to `LakeDefine` defines the `Lake` that the lisp library will use. A `Lake` is a structure that the lisp library uses internally as a type of communiation vehicle. (It is like a unix stream but more general, hence the name.) This call to `LakeDefine` defines a `Lake` structure for doing I/O with `stdin` and `stdout`. The third argument to `LakeDefine` should be `NULL` for external modules (it is used by Geomview). Finally, the program enters its main loop which parses and evaluates expressions from standard input.