TweetFollow Us on Twitter

Regions 2
Volume Number:4
Issue Number:9
Column Tag:Pascal Procedures

Fun With Regions, Part II

By Stephen Dubin, V.M.D., Ph.D.,, Thomas W. Moore, PH.D., Drexel University, Sheel Kishore, MS

In our previous paper (Fun with Regions Part I: High Level Language Implementation), we showed how it was possible to estimate the area of an arbitrarily drawn region from high level languages such as Pascal and C using repeated application of the ROM subroutine, PtInRgn. Although this approach is simple and intuitive, execution time is excessive for large or complex regions. Whenever part of a high level language routine consumes an inconveniently long execution time, the possibility of using assembly language to achieve better efficiency should be considered. Two fundamental approaches may be applied. A study of the code generated by the compiler may reveal unnecessary looping, inefficient use of registers or other complexities which can be streamlined. If savings can be made within loops executed many times, the resulting speedup can be significant. The second approach applies when the task at hand is relatively simple and straightforward. In this case, determination of a specific efficient algorithm is the key, with translation to assembly code following directly. In dealing with the area computation part of our regions manipulation, we have explored both of these approaches and found the latter approach to be clearly superior.

In the first article, we provided the C Language code for the area calculation program at the end of the article with major subroutines interpolated into the text as implemented in Pascal. In this installment, the “tables are turned”; the interpolated routines are implemented for the Megamax C development system and the Consulair (MDS) assembly language system [This is included in the source code due to space considerations-ED]. At the end of the article, a program using the most useful of the assembly language optimizations is shown for Turbo Pascal with explanation of minor changes needed for the TML Pascal Development system. We recognize that our program may not be the most elegant or efficient approach to the problems; but even where an attempt at optimization yielded poor or marginal results, an interesting and - hopefully - useful technique is explored.

Figure 1.

Several authors ( Morton, M.: Reduce Your Time in the Traps! MacTutor October 1986 pp 21-24. and Knaster, S.: “How to Write Macintosh Software.” Hayden, Hasbrouck Heights NJ, 1986, p 368 ) have advocated bypassing the trap dispatcher as a means of speeding routines in which ROM calls are made repeatedly. Certainly our CountPix routine, since it calls PtInRgn for every point within the region bounding box, is a candidate for this type of optimization. Mike Morton presents the underlying mechanism for this strategy, points out some cautions and pitfalls and shows how to do this task in Pascal using INLINE calls. Briefly, any call to the ROM must go through an intermediate step of finding the “true” address of the call in the particular version of the ROM in your machine before it can be invoked. When a ROM call is to be used many times, this address may be determined one time by means of the GetTrapAddress function early in the program; then you may employ some means of jumping to this address directly whenever the particular ROM call is to be used. In C language, the address might be acquired as follows:

trap = gettrapaddress(0xa8e8);   /*  trap is a global long integer */
 /* A8E8 is the trap # for ptinrgn */

In order to see how the jump might be made, consider the following “glue” routine which is used for ptinrgn by the Megamax system:

boolean ptinrgn(pt, rgn)  /* as copied from qd13.c  */
point *pt;
rgnhandle rgn;
{
    asm {
 subq #2,A7 /* make room on the stack for the result */
 move.l pt(A6),A0/*  address of point into A0 */
 move.l (A0),-(A7) /*  dereference and put onto stack*/
 move.l rgn(A6),-(A7)/* region handle onto stack */
 dc.w 0xa8e8/* call the ROM for ptinrgn */
 move.b (A7)+,D0 /* result into D0 where C expects to find the answer 
*/
 ext.w D0 /* sign extend the result */
    }
}

Note that with Megamax inline assembly, the compiler takes care of setting up (and tearing down) the stack frame. Automatic (local) variables are accessed using the name of the variable as a displacement from A6. Global variables are treated similarly as offsets from A4. Thus if we have safely installed the true ROM address of ptinrgn in “trap”, we can write a “new improved” version of the glue routine as follows:

boolean zptinrgn(pt, rgn) /* same as ptinrgn except */
point *pt;/*  bypasses the trap dispatcher */
rgnhandle rgn;
{
    asm {
 subq #2,A7 /* make room on the stack for the result */
 move.l pt(A6),A0/* address of point into A0*/
 move.l (A0),-(A7) /* dereference and put onto stack */
 move.l rgn(A6),-(A7)/* region handle onto stack */
 move.l trap(A4),A2/* address of “true address” of ptinrgn into A2 */ 

 jsr  (A2)  /* dereference once and jump there */
 move.b (A7)+,D0 /* result into D0 where C expects to find the answer 
*/
 ext.w D0 /* sign extend the result */
    }
}

When this version was used in place of ptinrgn, the time needed to estimate the area of a region was decreased by 15% for small simple regions and about 9% for larger and more complex ones. Although this would ordinarily be considered a significant improvement, it is little comfort to know that a five minute computation can now be completed in only four and a quarter minutes.

Upon examination of the disassembled code for counbtpix(), we noticed that the most often used variables were the points delimiting the region bounding box as well as the “exploring” point on which we called ptinrgn. Following classical optimization strategy, the next step was to set up these data structures on registers rather than to fetch them every time the coordinates of the exploring point were incremented. The code for this implementation of the countpix function is shown below:

{1}
bcountpix(theregion) /* sets up test point on registers  */
rgnhandle theregion;
{

 
 asm{
 
 move.l trap(A4),A2; address of ptinregn
 move.w #0xA8E8,D0 ; trap number for ptinrgn
 dc.w   0xA146   ; call the trap, address is in A0
 move.l A0,A2    ; put it into A2
 
 move.l theregion(A6),A3  ; regionhandle 
 move.l (A3),A1  ; dereference once
 move.l 2(A1),D4 ; topleft of rgnbox
 move.l 6(A1),D5 ; botright of rgnbox
 move.l D4,D6    ; copy of TL as VH current point
 
hortest:
 cmp.w  D5,D6    ; compare horizontal
 blt.s  vertest  ; go on
 swap D4  ; D4 is now HV
 addq.w #1,D4    ; down 1 row
 swap D4; now D4 is back to HV
 move.l D4,D6    ; make this the current test point
 
vertest:
 swap D6; now is HV
 swap D5; now is RB
 cmp.w  D5,D6    ; compare vertical
 blt.s  pointest ; go on
 bra.s  done; 
 
pointest:
 swap D5; back to BR
 swap D6; back to VH
 subq #2,A7 ; make room for result
 move.l D6,-(A7) ; point onto stack
 move.l theregion(A6),-(A7) ; rgnhandle onto stack
 jsr  (A2); go to ROM
 move.b (A7)+,D0 ; result onto stack
 tst.b  D0; was it true?
 beq  skip; not this time  
 addq.l #1,numpix(A4); yes, increment the counter
skip:
 addq.w #1,D6    ; over 1 column
 bra.s  hortest  ; back for another point
 
done: 
 } 
}

As with the previous attempt at optimization, the speed increase with this approach was marginal at best. Our final attempt in this direction was to examine the code for ptinregn in the ROM in order to transpose (plagiarize?) it directly into the above routine. The result was surprising as well as disappointing. Although there was a measurable but tiny improvement for small simple regions, ones for which optimization was not needed anyway, the time needed to calculate the area of large, complex or disjoint regions increased significantly!! Our theory as to why this happens is based on the way in which the 68000 accesses ROM and RAM. Accesses to RAM (where the program resides) are shared with the video display, sound generator and disk speed controller. This leads to a RAM access rate of approximately six megahertz. The ROM has a “direct line” and is accessed at 7.83 MHz (Inside Macintosh. III-18, Addison-Wesley, Reading MA, 1985).

All of this preoccupation with ptinregn led to an understanding of why the area computation takes so long for large or complex regions. A flow chart of how ptinregn works is shown in figure 1. Unless the region under examination is rectangular, it may be necessary to examine all of the region data, one word at a time, before deciding whether the point is indeed in the region. This is particularly true as the exploring point moves toward increasing values in the vertical (y) component. Clearly, our original countpix procedure, which calls ptinregn on every point in the bounding box, covers the same ground many times. Based on a conviction that the region information should be adequate to permit estimation of the area with one pass, we resolved to implement a specific algorithm “from the ground up.”

As mentioned in the first installment of this article, region information is stored in memory in a way designed to require minimal space. A clear understanding of this method of encoding region boundaries is necessary in order to design our area calculating algorithm. To illustrate this process, consider the simple region plotted in Figure 2. The numbers on the plot are the coordinates of the “corners” of the outlined region. A memory dump of the data representing this region is shown below the graph. In order to design an algorithm for area calculation, we must understand the method of encoding the region in memory. As explained in our previous paper, the first five words of this data list are the data size in bytes (44) followed by the “upper left” and “lower right” coordinates of the rectangular boundary of the region - the regnbbox (100,100,220,200). Following these five words we find the information needed to compute area. Only horizontal boundary information is stored. The region being defined consists of the (rectangular) area under a given boundary line, extending down to the next horizontal boundary line encountered. Horizontal boundary lines are indicated by a y coordinate word, followed by start and stop x values (more than one pair if the line has multiple segments). The flag word, #7FFF, marks the end of the boundary segments at a particular y value. Therefore, the sixth word of data (100) is the y coordinate of the top boundary line of the region. It is followed by x values 100 (start of line) and 200 (end of line). Then we get a flag indicating that no more boundary segments exist at this level. The next horizontal boundary is the line from (125,150) to (180,150). Therefore we find 150 (y value) and 125,180 (x start and stop values) to be the next three words of the data. In this manner, the remaining data can be seen to define the region of figure 2. The double flag indicates the end of the data table.

The question now is how to use this table to calculate the area of the region thus defined. The arrangement of the data suggests dividing the area into rectangular pieces and adding their areas. We might start by subtracting the first x value (100) from the second (200) to get the width of the top of the first rectangle (marked “A”). The y value of this line could be put aside to be subtracted from the next y value (170) yielding the height of the rectangle. The product of these dimensions is one component of the final area

The x values following the 150 are endpoints of a new horizontal boundary line. Since this line falls under the previous boundary, it represents the bottom of a rectangular piece rather than the top of a new one. From here (y = 150 ) our region will now grow downward in two rectangular pieces, B and C. To calculate the areas of these pieces, we must make use of the two new x values found in the data table (125,180). If we arrange all x values found so far in order of magnitude (100, 125, 180, 200), the appropriate widths can be found by pairing the values and subtracting the first from the second in each pair. This is a rule we can use in our algorithm: maintain an ordered list of all encountered x values, pair them and subtract the first of each pair from the second. The sum of these differences will be the total width at the top of each of the rectangular regions. The y coordinate at the top of B and C is subtracted from the next y coordinate found (170-150) to determine the height of these rectangles. Height times width is then added to the accumulating total area.

One problem remains: how to end the process? Following y value 170, we find x values of 100 and 125 in the data. One leg of our descending area ends here so we would like our x table to list just 180, 200 (the top of D) from here on. Therefore, the final rule we need for our area algorithm is to remove entries from the x value ordered list whenever they are matched by a newly encountered x value. At the final y value (220), we subtract the remaining x pair (200-180), and multiply by the last y difference (220-170), giving the area of the last piece, D.

A flowchart of this process is given in figure 3. The routine as implemented to provide a linkable object file using the MDS (now Consulair) 68000 assembly system is shown below. Using the TTAA (Tom Terrific Area Algorithm), even the largest and most complex region that could be drawn on the Macintosh screen could have its area estimated in less than 20 seconds. Such regions take as long as ten minutes using the old CountPix.

This is the code for use with the MDS assembler to produce the file ACountPix.REL. This can then be linked to a Pascal or other “main” program.

{2}
;
;ACountPix.asm
;Pascal Usage: Function ACountPix( theRegion:RgnHandle) : LongInt;
;This function emulates CountPix
;  Written by Thomas W. Moore, Ph.D. and Stephen Dubin, V.M.D., Ph.D.
;Copyright © 1987
 
 XDEF  ACountPix
 XREF  myBUF
; The buffer is allocated in the calling program even though it might 
be
; more elegant to allocate it here with a DS statement; however Turbo
; Pascal V1.0 seems intolerant of this. ( p 335 of the Turbo Pascal manual)
;-------------------------------- INCLUDES ------------------------

Include Traps.D  ; Use System and ToolBox traps
Include ToolEqu.D; Use ToolBox equates



ACountPix:
 link A6,#0 ; set up frame pointer
 movem.lA0-A3/D0-D7,-(A7) ; save the world
 clr.l  -(A7)  ; make room on stack for result
 movea.l8(A6),A0 ; region handle into A0
 movea.l(A0),A0  ; dereference => pointer in A0
 clr.l  D7; set area to zero
 lea  myBUF(A5),A1 ; lowest address of x list
 
rectcheck:; see whether it is a rect and if so - do  the job here
 cmpi.w #10,(A0) ; is this a single rectangle
 bne.s  morework ; if not do the big job
 move.w 4(A0),D1 ; left
 move.w 8(A0),D2 ; right
 move.w 2(A0),D3 ; top
 move.w 6(A0),D4 ; bottom
 sub.w  D1,D2  ; width
 sub.w  D3,D4  ; height
 mulu.w D2,D4  ; area in D4
 move.w D4,D7  ; lower word into D7
 bra  done

morework: ; get ready for some serious work
 lea  10(A0),A0  ; beginning of region info
 clr.l  D4;
 clr.l  D2;
 move.l #512,D3  ; size of buffer to hold ordered list of x values
 adda.l D3,A1  ; highest address in buffer
 movea.lA1,A2  ; copy in A2
 movea.lA1,A3  ; another in A3
 move.w #-1,(A1) ; -1 in highest x address so that 1st x entry will be 
greater

gety:   ; read in y coordinate of next horizontalboundary       
 
 move.w (A0)+, D3; latest y value
 jsr  calc
 
getx:
 move.w (A0)+,D1 ; new x value
 cmpi.w #$7fff,D1; flag indicates no more x values at this y
 bne  storex; if no flag, it is a new x
 move.w (A0),D1  ; next word of region info
 cmpi.w #$7fff,D1; all done?
 beq  done; yes go home
 bra  gety; no, get next y

storex: ; place new x value in proper place in ordered list
 movea.lA3,A1  ; A3 points to highest x value in ordered list
 cmp.w  (A1),D1  ; compare new x value to largest entry
 bne  s1; if not equal, it must be added to list
 addq #2,A3 ; if match, remove from list
 bra  getx; next x
 
s1:
 lea  -2(A3),A3  ; add a space at high end of list for new x
 bgt.s  insert ; if new x value is greatest, put it on top
 
mkroom: ; new x is not greatest so we must   move list values up to make 
room
 move.w (A1)+,-4(A1) ; move data  up (1 word net distance)
 cmp.w  (A1),D1  ; compare next list entry
 beq.s  remove ; if it matches, remove it
 bcc.s  insert ; it is greater, so put it above
 cmpa.l A1,A2  ; are we at bottom?
 bne  mkroom; no, move another one up
 
insert: ; insert new x value in ordered place in list
 move.w D1,-(A1) ; insert above present location
 bra  getx;
 
remove: ; erases an entry from the list
 subq #2,A1 ; point to next higher
 
r1:
 cmpa.l A1,A3  ; is it the top?
 beq  shrink; yes so exit
 move.w -(A1),4(A1); move greater x values down to replace
 bra  r1; value removed
 
shrink:
 addq #4,A3 ; if a match occurred, list shrinks by 2 words
 bra  getx; one that we didn’t insert and one that we erased
 
calc:   ; determine new Height
 sub.w   D3,D4 ; Y old - Y new
 neg.w  D4; Height of the rectangle(s)
 
newW:   ; prepare for Width calculation
 clr.l  D2; Will receive width
 clr.l  D1; work reg
 movea.lA2,A1  ; reset A1 to point to least x value in list
 
dx:; check to see if all x pairs have been used. 
 ; multiply H x W and add to area
 cmpa.l A1,A3  ; A3 points to greatest x value in  list
 bne  morex ; if not equal, not all x’s have been  used
 mulu   D4,D2  ; H x W
 add.l  D2,D7  ; add to accumulating area
 move.w D3,D4  ; for next time
 rts
 
morex:  ; subtracts x values in pairs adding differences to accumulating 
W
 move.w -(A1),D1 ; Xi (lower x value of a pair)
 sub.w  -(A1),D1 ; Xi - Xi+1 (length of a horizontal boundary segment)
 neg.w  D1; Xi+1 - Xi (correct sign)
 add.w  D1,D2  ; W (add to accumulating width)
 bra  dx;
 
done:
 move.l D7,12(A6); store result “under” the last parameter
 movem.l(A7)+,A0-A3/D0-D7 ; restore registers
 unlk A6; restore original stack
 move.l (A7)+,A0 ; get return address
 addq.l #4,A7  ; remove parameters
 jmp  (A0); return this way
 
 end  

The same algorithm can be used with the very convenient inline assembly facility of the Megamax and other C development systems. Because these compilers take care of “tending the stack” for you, the entry and exit procedures are significantly simplified. For the Megamax systems, they are as follows:

{3}
acountpix(theregion)
rgnhandle theregion;
{
intbuf[1000];  
 asm{
 
 move.l theregion(A6),A0  ; regionhandle  note: local variables are 
 referred off A6
 move.l (A0),A0  ; dereference once => region pointer
 clr.l  D7; set area to zero
 lea  buf(A6),A1 ; lowest address of x list

 rectcheck:

/*  Everything in between is the same as in ACountPix.Asm above */ 
 
done:
 move.l D7,numpix(A4);report the answer note: global variables 
 are referred offA4 
 
 } 
}

This is the code for our main calling program as implemented in Turbo Pascal:

{4}
{PasArea.Pas }
{Copyright 1987 by Stephen Dubin, V.M.D.and Thomas W. Moore,Ph.D. }
{Prepared with Turbo Pascal V1.0                                  }
{ Users of other Pascal systems should particularly check the “preamble”}
{ portion of their program (Linking directives, “uses”, “includes”, etc.}
{ also check usage of type “point” - TML doesn’t like use of pt.h and}
{ pt.v as control elements in a for statement.                       
}

program PasArea; 

{$R-}               { Turn off range checking               }
{$I-}               { Turn off I/O error checking           }
{$R PasArea.rsrc}   { Identify resource file                }
{$U-}               { Turn off auto link to runtime units   }
{$L ACountPix.Rel } { Link in Assembly Language Segment}
{$D+}               { Embed Procedure Labels                }

uses  Memtypes,QuickDraw,OSIntf,ToolIntf,PackIntf;

const
  FileMenuID = 1;{ the File menu}
  OptionMenuID = 2;{ the option menu}
  WindResID = 1; { the resource id of my window}
 
type
  BUF   = array[1..512] of Integer; { Make it bigger if you are really 
paranoid}
  
var
  myMenus : Array[FileMenuId..OptionMenuID] of MenuHandle; 
  Done : Boolean;
  MyWindow : WindowPtr;   
  TotalRegion   :   RgnHandle;
  Numpix        :   Longint;
  myBUF         : BUF;
    
function ACountPix( theRegion:RgnHandle) : LongInt; external;

function CountPix(theRegion : RgnHandle): LongInt;       
var
 pt : Point;
 rgn    :   Region;
 temp   :   LongInt;
 x      :   Integer;
 y      :   Integer;
  
begin
   temp   :=  0;
   rgn  :=  theRegion^^;
   for  x  := rgn.rgnBBox.left  to  rgn.rgnBBox.right do 
        begin
     pt.h := x;
            for y := rgn.rgnBBox.top to rgn.rgnBBox.bottom do
      begin
 pt.v := y;
                if  PtInRgn( pt, TheRegion) then  temp := temp + 1;
 end;
        end;
        CountPix := temp;
end;
{ Turbo seems to accept pt.h and pt.v as control elements but TML does}
{ not. Some format checkers agree with TML}

procedure Wipe;  
var
    r   :   Rect;
      
begin
    SetRect(r,0,0,504,300);
    EraseRect(r);
  
end;

procedure Data;  
var
    rgn         :   Region;
    rgnpntr     :   Ptr;
    size        :   Integer;
    thebuf      :   BUF;
    bfpntr      :   Ptr;
    myString    :   Str255;
    i           :   Integer;
    x           :   Integer;
    y           :   Integer;
 
 begin
    Wipe;
    TextSize(9);
    TextFont(Monaco);
    rgn  :=  totalRegion^^;
    rgnpntr := ptr(totalRegion^); 
    size := rgn.rgnSize;
    if size > 800 then size:= 800;
    bfpntr := ptr(@thebuf);
    BlockMove(rgnpntr,bfpntr,size);
    MoveTo(10,10);
    DrawString(‘Here are the first 400 words of the region data. (FLAG 
= 32767)’);
    x := 10;
    y := 20;
    for i  := 1  to  (size div 2) do 
        begin
        MoveTo(x,y);
        NumToString(theBuf[i],myString);
        if theBuf[i] < 32766 then 
            begin
                if theBuf[i] <10  then DrawString(‘ ‘);
                if theBuf[i] <100 then DrawString(‘ ‘);
                if theBuf[i] < 1000 then DrawString(‘ ‘);
                if theBuf[i] < 10000 then DrawString(‘ ‘);
                DrawString(MyString);
            end;
        if theBuf[i] > 32766 then DrawString(‘ FLAG’);
        x := x + 30;
        if (i mod 16) = 0 then
            begin
            x := 10;
            y := y+10;
            end; 
        end;   
end;

procedure OvalRegion;
var
    RectA : Rect;
      
begin
   Wipe;   
   TotalRegion := NewRgn;
   SetRect(RectA, 170,175,195,200);
   OpenRgn;
   ShowPen;
   FrameOval(RectA);
   HidePen;
   CloseRgn(TotalRegion);   
end;

procedure Contour; 
var
    p1  :   Point;
    p2  :   Point;
    OldTick :  Longint;
    
begin
  Wipe;
  TotalRegion := NewRgn;
  OldTick := TickCount;
  Repeat
    GetMouse(p1);
    MoveTo(p1.h,p1.v);
    p2 := p1;  
  Until Button = True;  
  OpenRgn;
  ShowPen;
  PenMode(patXor);  
  Repeat
    GetMouse(p2);
    Repeat Until (OldTick <> TickCount);
    LineTo(p2.h,p2.v);
  Until Button <> True;  
  Repeat Until (OldTick <> TickCount);
  LineTo(p1.h,p1.v);
  PenNormal;
  HidePen;
  CloseRgn(TotalRegion);
  InvertRgn(TotalRegion);
end;

procedure Example; 
  
begin
    Wipe;
    OpenRgn;
    TotalRegion := NewRgn;
    ShowPen;
    MoveTo(100,100);
    LineTo(200,100);
    LineTo(200,220);
    LineTo(180,220);
    LineTo(180,150);
    LineTo(125,150);
    LineTo(125,170);
    LineTo(125,170);
    LineTo(100,170);
    LineTo(100,100);
    HidePen;
    CloseRgn(TotalRegion);
end;

procedure FreeBox; 
var
    p1  :   Point;
    p2  :   Point;
    p3  :   Point;
    OldTick :  Longint;
    MyRect  :  Rect;
      
begin
    Wipe;
    TotalRegion := NewRgn;
    OldTick := TickCount;
    PenPat(gray);
    PenMode(patXor);    
    Repeat
    GetMouse(p1);
    p2 := p1;  
    Until Button = True;   
    OpenRgn;
    ShowPen;
    PenMode(patXor);    
    Repeat
    Pt2Rect(p1,p2,MyRect);
    Repeat Until (OldTick <> TickCount);
    FrameRect(MyRect);   
        Repeat
            GetMouse(p3);
        Until  EqualPt(p2,p3) <> True;   
   Repeat Until (OldTick <> TickCount);
   FrameRect(MyRect);
   p2 := p3;   
   Until Button <> True;
   Pennormal;
   HidePen;
   PenPat(black);
   FrameRect(MyRect);
   CloseRgn(TotalRegion);
   InvertRgn(TotalRegion);  
end;

procedure Area;  
var
    NumTix  :   LongInt;
    MoreTix :   LongInt;
    TicString   :   Str255;
    PixString   :   Str255;  
  
begin   
   TextFont(Monaco);
   TextSize(9);
   TextMode(0);
   MoveTo(10,20); DrawString(‘ Using Pascal ‘); 
   NumTix := TickCount;
   NumPix :=  CountPix( TotalRegion ); 
   MoreTix := TickCount - NumTix;
   NumToString(MoreTix,TicString);
   NumToString(NumPix,PixString);
   MoveTo(10,30); DrawString(‘ Tickcount = ‘);
   MoveTo(120,30); DrawString(TicString);
   MoveTo(10,40); DrawString(‘ Pixel Number = ‘);
   MoveTo(120,40); DrawString(PixString);    
   MoveTo(10,50); DrawString(‘ Using Tom Terrific ‘); 
   NumTix := TickCount;
   NumPix :=  ACountPix( TotalRegion ); 
   MoreTix := TickCount - NumTix;
   NumToString(MoreTix,TicString);
   NumToString(NumPix,PixString);
   MoveTo(10,60); DrawString(‘ Tickcount = ‘);
   MoveTo(120,60); DrawString(TicString);
   MoveTo(10,70); DrawString(‘ Pixel Number = ‘);
   MoveTo(120,70); DrawString(PixString);  
end;

procedure ProcessMenu(codeWord : Longint);   
var
  menuNum : Integer;
  itemNum : Integer;
 
begin
  if codeWord <> 0 then 
    begin
      menuNum := HiWord(codeWord);
      itemNum := LoWord(codeWord);
      case menuNum of 
        FileMenuID :Done := true; 
        OptionMenuID :
            begin
                case ItemNum of
                    1:Contour;      {Contour}
                    2:FreeBox;      {Freebox}
                    3:OvalRegion;   {Oval}
                    4:Example;      {Example}
                    5: Area;        {Area}
                    6:Data;         {Region Data}
                end; { of ItemNum case}               
       end;{ of MenuNum case}
    end;
  HiliteMenu(0); 
 end;
end;

procedure DealWithMouseDowns(theEvent: EventRecord);
var
  location : Integer;
  windowPointedTo : WindowPtr;
  mouseLoc : point;
  windowLoc : integer;
  VandH : Longint;
  Height : Integer;
  Width : Integer;
  
 begin
  mouseLoc := theEvent.where;
  windowLoc := FindWindow(mouseLoc,windowPointedTo);
  case windowLoc of
    inMenuBar : 
      begin
        ProcessMenu(MenuSelect(mouseLoc));
      end;
    
  end;
end;

procedure MainEventLoop;
var
  Event : EventRecord;
  theItem : integer;
  
begin
  repeat
    SystemTask;
    if GetNextEvent(everyEvent, Event) then
     begin  
      case Event.what of
       mouseDown : DealWithMouseDowns(Event);
      end;
     end;
  until Done;
end;

procedure MakeMenus; 
var
  index : Integer;
begin
  for index := FileMenuId to OptionMenuID do
    begin
      myMenus[index] := GetMenu(index);
      InsertMenu(myMenus[index],0);
    end;
  DrawMenuBar;
end;

{  Main Program   }
begin
  Done := false;   FlushEvents(everyEvent,0);        InitGraf(@thePort);
   InitFonts;    InitWindows;   InitMenus;     InitDialogs(nil);
  InitCursor;  
  MoreMasters;
  MoreMasters;
  MakeMenus;
  MyWindow := GetNewWindow(WindResID,nil,Pointer(-1)); 
  SetPort(MyWindow); 
  TotalRegion := NewRgn;   {Lazy way to avoid bomb if your select “Area” 
first}  
  MainEventLoop; 
end.

Here is the resource file for use with the above program (Turbo Pascal):

*
*   Resource listing from file: “PasArea.R”.
*

PasArea.rsrc

Type AREA = STR 
,0
PasArea, by Stephen Dubin and Thomas W. Moore Copyright © 1987 

Type WIND
,1
Fun with Regions II
40 5 330 505
Visible NoGoAway
0
0

Type MENU
,1
File
Quit

,2
Option
Contour
Freebox
Oval
Example
Compute Area
Region Data

In order to compile the same program with TML Pascal V2.0, a few minor adjustments were needed. The preamble was changed to:

{5}
program TMPasArea;

{$T APPL AREA} { set the type and creator}
{$B+} { set the bundle bit}
{$L TMPasAreaRes}{ link the resource file too...}

uses MacIntf;

{ Constant, Type and Variable declarations as above are the same as in 
PasArea.Pas above}

{Declare the Assembly Language routine as external }
function ACountPix( theRegion:RgnHandle) : LongInt; external;
{$U ACountPix  } 
{ This directive will not appear in the .link file unless it follows 
the declaration of the }
{ relocatable object file as external}

The only change needed in the body of the program was in the high level CountPix function. A form that compiled with TML is:


{6}
function CountPix(theRegion : RgnHandle): LongInt;
var
 pt : Point;
 rgn    :   Region;
 temp   :   LongInt;
 x :   Integer;
 y :   Integer;
  
begin
   temp   :=  0;
   rgn  :=  theRegion^^;
   for  x  := rgn.rgnBBox.left  to  rgn.rgnBBox.right do 
        begin
            pt.h := x;
            for y := rgn.rgnBBox.top to rgn.rgnBBox.bottom do
                begin
                   pt.v := y;
                   if  PtInRgn( pt, TheRegion) then  temp := temp + 1;
                end;
        end;
        CountPix := temp;
end;

TML does not seem to like having pt.h and pt.v as control elements. PasMat, a Pascal formatting and syntax checking program, agrees with TML on this point. In keeping with our local traditions, the first non-comment line of our TML resource file was “TMPasAreaRes”. Although it probably is of little interest in these days of monstrous memories, the TML version of the program requires 3,305 bytes of memory; whereas the Turbo program weighs in at a hefty 10,855 bytes.

Some final zingers for the reader - Although it was certainly necessary for us to use assembler to plumb the depths of the ROM and to work out the algorithm for making our area measurement lightning fast; one might consider whether the same algorithm might now be implemented entirely from C, Pascal or possibly Basic. Would the speed be degraded to any appreciable extent? Will a new call AreaRgn be found in the 512K Roms on the Mack III’s?

 
AAPL
$111.78
Apple Inc.
-0.87
MSFT
$47.66
Microsoft Corpora
+0.14
GOOG
$516.35
Google Inc.
+5.25

MacTech Search:
Community Search:

Software Updates via MacUpdate

calibre 2.13 - Complete e-library manage...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital librarian... Read more
Mellel 3.3.7 - Powerful word processor w...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
ScreenFlow 5.0.1 - Create screen recordi...
Save 10% with the exclusive MacUpdate coupon code: AFMacUpdate10 Buy now! ScreenFlow is powerful, easy-to-use screencasting software for the Mac. With ScreenFlow you can record the contents of your... Read more
Simon 4.0 - Monitor changes and crashes...
Simon monitors websites and alerts you of crashes and changes. Select pages to monitor, choose your alert options, and customize your settings. Simon does the rest. Keep a watchful eye on your... Read more
BBEdit 11.0.2 - Powerful text and HTML e...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
ExpanDrive 4.2.1 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Adobe After Effects CC 2014 13.2 - Creat...
After Effects CC 2014 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). After Effects CS6 is still available... Read more
Evernote 6.0.5 - Create searchable notes...
Evernote allows you to easily capture information in any environment using whatever device or platform you find most convenient, and makes this information accessible and searchable at anytime, from... Read more
Command-C 1.1.7 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Tidy Up 4.0.2 - Find duplicate files and...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more

Latest Forum Discussions

See All

Make your own Tribez Figures (and More)...
Make your own Tribez Figures (and More) with Toyze Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
So Many Holiday iOS Sales Oh My Goodness...
The holiday season is in full-swing, which means a whole lot of iOS apps and games are going on sale. A bunch already have, in fact. Naturally this means we’re putting together a hand-picked list of the best discounts and sales we can find in order... | Read more »
It’s Bird vs. Bird in the New PvP Mode f...
It’s Bird vs. Bird in the New PvP Mode for Angry Birds Epic Posted by Jessica Fisher on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »
Telltale Games and Mojang Announce Minec...
Telltale Games and Mojang Announce Minecraft: Story Mode – A Telltale Games Series Posted by Jessica Fisher on December 19th, 2014 [ permalink ] | Read more »
WarChest and Splash Damage Annouce Their...
WarChest and Splash Damage Annouce Their New Game: Tempo Posted by Jessica Fisher on December 19th, 2014 [ permalink ] WarChest Ltd and Splash Damage Ltd are teaming up again to work | Read more »
BulkyPix Celebrates its 6th Anniversary...
BulkyPix Celebrates its 6th Anniversary with a Bunch of Free Games Posted by Jessica Fisher on December 19th, 2014 [ permalink ] BulkyPix has | Read more »
Indulge in Japanese cuisine in Cooking F...
Indulge in Japanese cuisine in Cooking Fever’s new sushi-themed update Posted by Simon Reed on December 19th, 2014 [ permalink ] Lithuanian developer Nordcurrent has yet again updated its restaurant simulat | Read more »
Badland Daydream Level Pack Arrives to C...
Badland Daydream Level Pack Arrives to Celebrate 20 Million Downloads Posted by Ellis Spice on December 19th, 2014 [ permalink ] | Read more »
Far Cry 4, Assassin’s Creed Unity, Desti...
Far Cry 4, Assassin’s Creed Unity, Destiny, and Beyond – AppSpy Takes a Look at AAA Companion Apps Posted by Rob Rich on December 19th, 2014 [ permalink ] These day | Read more »
A Bunch of Halfbrick Games Are Going Fre...
A Bunch of Halfbrick Games Are Going Free for the Holidays Posted by Ellis Spice on December 19th, 2014 [ permalink ] Universal App - Designed for iPhone and iPad | Read more »

Price Scanner via MacPrices.net

The Apple Store offering free next-day shippi...
The Apple Store is now offering free next-day shipping on all in stock items if ordered before 12/23/14 at 10:00am PT. Local store pickup is also available within an hour of ordering for any in stock... Read more
It’s 1992 Again At Sony Pictures, Except For...
Techcrunch’s John Biggs interviewed a Sony Pictures Entertainment (SPE) employee, who quite understandably wished to remain anonymous, regarding post-hack conditions in SPE’s L.A office, explaining “... Read more
Holiday sales this weekend: MacBook Pros for...
 B&H Photo has new MacBook Pros on sale for up to $300 off MSRP as part of their Holiday pricing. Shipping is free, and B&H charges NY sales tax only: - 15″ 2.2GHz Retina MacBook Pro: $1699... Read more
Holiday sales this weekend: MacBook Airs for...
B&H Photo has 2014 MacBook Airs on sale for up to $120 off MSRP, for a limited time, for the Thanksgiving/Christmas Holiday shopping season. Shipping is free, and B&H charges NY sales tax... Read more
Holiday sales this weekend: iMacs for up to $...
B&H Photo has 21″ and 27″ iMacs on sale for up to $200 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 1.4GHz... Read more
Holiday sales this weekend: Mac minis availab...
B&H Photo has new 2014 Mac minis on sale for up to $80 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 1.4GHz Mac mini: $459 $40 off MSRP - 2.6GHz Mac mini: $629 $70 off MSRP... Read more
Holiday sales this weekend: Mac Pros for up t...
B&H Photo has Mac Pros on sale for up to $500 off MSRP. Shipping is free, and B&H charges sales tax in NY only: - 3.7GHz 4-core Mac Pro: $2599, $400 off MSRP - 3.5GHz 6-core Mac Pro: $3499, $... Read more
Save up to $400 on MacBooks with Apple Certif...
The Apple Store has Apple Certified Refurbished 2014 MacBook Pros and MacBook Airs available for up to $400 off the cost of new models. An Apple one-year warranty is included with each model, and... Read more
Save up to $300 on Macs, $30 on iPads with Ap...
Purchase a new Mac or iPad at The Apple Store for Education and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free,... Read more
iOS and Android OS Targeted by Man-in-the-Mid...
Cloud services security provider Akamai Technologies, Inc. has released, through the company’s Prolexic Security Engineering & Research Team (PLXsert), a new cybersecurity threat advisory. The... Read more

Jobs Board

*Apple* Store Leader Program (US) - Apple, I...
…Summary Learn and grow as you explore the art of leadership at the Apple Store. You'll master our retail business inside and out through training, hands-on experience, Read more
Project Manager, *Apple* Financial Services...
**Job Summary** Apple Financial Services (AFS) offers consumers, businesses and educational institutions ways to finance Apple purchases. We work with national and Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.