Archive

Archive for May, 2012

A new designer, a new office

May 25, 2012 Comments off
Get ready for some serious action, spartan style!

Get ready for some serious action, spartan style!

Ok. This is has been a very exciting week, but also a very strange week. I feel a bit like the guy in “a hitchhiker’s guide to the galaxy”, that was just going down to the pub to grab a few pints – only to find himself in an alien landscape where things go topsy-turvy.

First, I got so sick of my basement office that I decided to give it to the kids – which are now painting it in all possible colors and filling it up with lego. My new home office is in a room upstairs which is much bigger and has actual sunlight. So the days when i’m working from home, i dont have to feel like i’m working on cracking the enigma machine in a british bunker somewhere near france.

Secondly, I’ve drunk far too much coca-cola, so i have to seriously get my ass back into the gym!

And third, and perhaps more important: I hate the designer in smart mobile. I never got to spend enough time on it, and having written a couple of apps with it — i lay myself down flat: it really sucks. But thankfully the Delphi community is a proverbial shangrila of cool people, so i contacted Greatis Software and they were kind enough to mail me a full version of their latest form designer. So far the tests look good (they previously hooked the window messages without any filter, so several instances of a designer in one app crashes)! Everything seems to work – and I will now test it with frames to make sure we can use it in Smart.

And yes, we are busy adding the “missing bits” to the editor as well. Things like mouse-over hints, ctrl + click lookup and the lines will hopefully (i cant promise anything) make it into the hotfix before the holiday.

But that’s not all the news, oh no — while i’m busy strangling the python at delphi – eric, primoz and andre is kicking persian butt with awesome stuff.. that I cant talk about. Since you already know about webGL support I can mention that, but if you think we’re backing down now — think again 😉

Let’s give em hell

Comparing smart to other alternatives

May 20, 2012 Comments off

If you look at smart mobile from the context of Delphi, comparing it directly with Delphi or expecting it to be a re-engineered version of a product that (let’s be honest) has 15 years head start with countless senior architects working on it, then smart will naturally never live up to your expectations.

You have to look at it in context to web development and the tools common to JavaScript developers, and also similar tools available for other programming languages (like visual basic for android). The tools we set out to “beat” in terms of code were:

A fair comparison

First, none of these products (with the exception of monkeycoder) can offer you classes, inheritance, interfaces, virtual and abstract methods or anything even close to such functionality. You have to make do with java script, prototype chaining and a lot of manual labour to create an iPhone app.

Secondly, of these products only dreamweaver and sencha have designers that can render the html “live” (the preview function in smart is actually quite similar to what you find in dreamweaver, except that we don’t open the preview in a separate page).

Monkeycoder

Monkeycoder which is a new version of blitzbasic, have no design features at all. The IDE is basically notepad with a few adaptations. Yet it enjoys quite a large following due to the quality of the code it generates. But the system is very small and is best compared to old turbo pascal in terms of what you get out of the box.

Apple Dashcode

Apple dashcode is an excellent system, both in terms of design, events via the designer and editor functions. But it’s still a mess to work with and JavaScript only. It will be utterly alien to anycome comming purely from Delphi and also boxes you into apple standards forever.

Adobe Dreamweaver

Dreamweaver is a multi million dollar application with at least 10 years of constant development behind it. It is at present being touted as a “mobile web studio”, but that statement is cosmetic and carries little substance behind it. This is for designers more than it is programmers (and it is by far the best designer out there in my view).

Aptana studio

Aptana web studio is source-code only and more or less an html editor with syntax highlighting (but with a very cool plugin system) and auto correction.

Sencha designer

Sencha designer is a bit like Delphi, but the system is pure javascript and have no classes or wrappers except for the visual elements.

Taking a closer look

When you start to compare what these systems deliver, I think most developers will agree that what we have done with smart mobile studio is quite an achievement. We might not have all the “bling” down yet, but we are more interested in rock solid classes than we are superficial pixels. We could have cut development time by 50% had we deviated from the first principle of “Delphi only” components. But part of the motivation was to prove that Delphi still have some life in it and can be used to knock out unique and powerful solutions.

With smart mobile you can knock out a pretty complex web app in hours rather than days, and days rather than weeks. It does require you to write your own event handlers (just like you would under JavaScript, c# monotouch, freepascal and c++) and looking at the RTL units to familiarize with the new HTML5 based component library is a primer. But I’ll set smart mobile against the wast majority of HTML5 “web app makers” out there – any day of the week.

IE9, not as bad as i thought

May 19, 2012 Comments off
One size fits all is a dangerous game

One size fits all is a dangerous game

Im playing around with the IE9 driver for Smart Mobile Studio right now. Like most people I’ve sort of dreaded this task, since IE have so many peculiarities associated with it – but you know what? It’s actually not as bad as I thought it would be. I know IE has a bad rap around the world for being the worst browser ever, but starting with IE 8 things have improved considerably.

I actually got most smart apps and demos running on IE9 now (having changed very little). The driver system got a new function, “getEffectCaps” which returns a bitmask for the current browser capabilities, which means that things like the “form sliding” will just be skipped if the driver finds that these effects are not supported.

What IE9 (or indeed, any browser) support boils down to – is basically:

  • CSS pre and post fixing
  • The use of special effects

Our javascript is universal to begin with and will run on pretty much everything (I even tested it on Playstation, works like a charm). So the challenge is pushed into the outer rim of the VJL, the classes and methods that use CSS transformations and “special effects”, rather than the core of the product itself.

The dark side of special effects

Effects is sort of a double-edged sword. You want to use it to show off the product and what it can do, but the more you use it – the more you bind the RTL to these effects, which means larger and more time-consuming updates for very little gain (for the end-user). I think it’s important that the VJL provides a solid foundation for the user – but effects should not come at the expense of the customer. Instead of drowning the customer with effects that, when it really count, wont make the customer’s code any better (it will just look better but make things more complex), I like to do things the old fashion way. By old fashion I mean steady and robust. I would rather have a system that can take a punch than a “Barbie doll” that looks good but is useless in real-world scenarios.

So, in short: I will make sure the foundation classes for special effects are up to date, but I wont add everything under the sun just to please a small group of people. Instead, I’m more interested in making the VJL as lightweight as possible and to make each visual control as feature rich as it can be.

I can hardly wait until I can add the delegate system. It’s going to be the frosting on the cake 🙂

Exhausted, but happy

May 18, 2012 Comments off

Man what a week! You know how things build up when you have a deadline – and just at the very end things you forgotten about come back to bite you in the ass? Well this was no different. But after 20+ hours straight I got it sorted. We have had good sales with smart mobile already, without any advertising except word of mouth – so I am extremely happy. If we keep this up we can get another guy working on it and double the amount of units and updates the customers get within the calculated timeframe. And it’s going to be awesome. With any luck, we will be the first to implement metro style apps on a large-scale outside of native languages, bringing the onslaught of the VJL 1.1 with us – absorbing all the fancy new API stuff that microsoft have to offer.

And since metro allows you to call native functions .. you can link to your delphi code as well. You can use smart as a ramp, or blend the two (where smart is the online version, and the delphi dll’s are used offline). Microsoft and metro is growing on me, I must admit. After 2 years with Apple I am homesick for Windows perhaps?

Use the force luke

The ancient religion of object pascal

The ancient religion of object pascal

Which has gotten me thinking. If I by some strange accident grow 4 hands, I’ll re-implement phonegap as a C# project, and kill two birds (android and iphone native) with one stone. Perhaps even 3 since C# is the prefered language for metro apps.

I know.. I know, the fact that I actually enjoy C# side by side with object pascal these days makes me a pervert, but Miguel de Icaza did it so well. And he is a really cool guy (don’t worry, I’m an object pascal fundamentalist to the bitter end). I’ve only chatted with him once but he really is a nice dude and his work is outstanding. I’m allergic to microsoft’s vision of C# and the CLR but Miguel brings the “magic” of the open-source hacker scene into the equation – and that resonates with me. You either have that creative, intense energy or you don’t. There is no point trying to explain it in rational terms because there is nothing rational about it. You must create. It’s a part of you.

Commander of the northern legions

Also, I’ve started on the command line compiler for Smart Mobile. I have had a prototype running for a while now, which (drumroll) also works fine on the mac. It’s going to be even cooler when I isolate the RTL files in a single zip. This really is a feature delphi should have had years ago. By housing the RTL in a zip, we can have many different RTL’s without much fuzz. For instance the metro system will require a fair bit of re-design in the forms department – but the user wont have to worry about it. And in the future, should an old project surface — just pick the right RTL zip to compile with, and your are home free. Also a lot easier to use the compiler anywhere when it’s just 2 files. A zip for the RTL and the command line compiler. On the mac it’s even simpler – because I stuffed the RTL into the app folder – so it’s just a single file.

I’m also very impressed by Andre Mussche’s work. He took on smart mobile from the get-go and did things few people imagined it could do. Huge fan of this guy. I’m so looking forward to checking out his remobjects to smart mapper. I love remobjects remoting system and use it as much as possible. Connecting remobjects to smart is the perfect match. Unprecedented server control meets equally limitless client control. It’s gonna make the native javascript solutions look like lego in comparison.

Well, better fire up the grill. We have finally finished the 17 of may celebrations (liberation day), with parades for the children and an unholy amount of sugar. So I’m looking forward to kick back with a good steak, an ice-cold Guinness and my wonderful wife and children. I can hardly remember the last time I had a day off so this is going to be great (apart from the slight cold I got yesterday).

Oh and I finally reached level 36 in Battlefield (yeej!). I find that games is an excellent way to exercise the problem solving muscles of the brain. It might look primitive but it’s great fun and requires some intuition. When you face 8 level 50 gamers by yourself – you really have to use every trick in the book to survive. You either evolve some interesting improvisations (if you have the patience to succeed) or you give up. I never give up, and always win in the end. Good game and good fun!

RC4 encryption revisited

May 15, 2012 Comments off

RC4 is my favorite cipher routine. It’s fast, extremely reliable and nearly unbreakable. I do not remember how many thousands of computers were used to crack it, but it was many. So for normal use by us mere mortals, RC4 is one of the easiest ways to add some very good protection.
 
Here is a nice class I made which simplifies the whole process:

  unit jlrc4enc;

  interface

  uses sysutils, classes;

  type

  TJLRC4EncodingTable = Packed Record
    etShr: Packed Array[0..255] of Byte;
    etMod: Packed Array[0..255] of Byte;
  End;

  TJLRC4Encoder = Class(TObject)
  Private
    FTable:   TJLRC4EncodingTable;
    FReady:   Boolean;
  Public
    Procedure ResetRCTable;
    Function  BuildRCTable(Const Key;Const KeyLen:Integer):Boolean;overload;
    Function  BuildRCTable(Stream:TStream):Boolean;overload;
    Function  BuildRCTable(aKey:AnsiString):Boolean;overload;
    Function  BuildRCTable(aKey:WideString):Boolean;overload;

    Function  EncStream(Source,Target:TStream):Boolean;overload;
    Function  EncBuffer(Const Source;Const Target;
              aLen:Integer):Boolean;overload;

    function  EncStream(Const aStream:TStream):TStream;overload;

  Public
    Property  Ready:Boolean read FReady;
  End;

  implementation

  type
  TRCByteArray = Packed Array[0..4095] of Byte;
  PRCByteArray = ^TRCByteArray;

  Procedure TJLRC4Encoder.ResetRCTable;
  Begin
    FReady:=False;
    Fillchar(FTable,SizeOf(FTable),#0);
  end;

  Function TJLRC4Encoder.BuildRCTable(Stream:TStream):Boolean;
  var
    FLen:   Integer;
    FData:  Pointer;
  Begin
    result:=(Stream<>NIL) and (Stream.size>=256);
    If result then
    Begin
      Stream.Position:=0;
      FData:=AllocMem(256);
      try
        fillchar(FData^,256,#0);
        FLen:=Stream.Read(FData^,256);
        result:=FLen>0;
        If result then
        result:=BuildRCTable(FData^,FLen);
      finally
        FreeMem(FData);
      end;
    end;

    if not result then
    Begin
      (* reset key data *)
      FReady:=False;
      Fillchar(FTable,SizeOf(FTable),#0);
    end;

  end;
  
  Function TJLRC4Encoder.BuildRCTable(Const Key;
           Const KeyLen:Integer):Boolean;
  var
    i,j:    Integer;
    temp:   Byte;
    FData:  PRCByteArray;
  Begin
    (* reset key data *)
    FReady:=False;
    Fillchar(FTable,SizeOf(FTable),#0);

    FData:=@Key;

    result:=(FData<>NIL) and (KeyLen>0);
    If result then
    Begin
      J:=0;

      { Generate internal shift table based on key }
      {.$R-}
      for I:=0 to 255 do
      begin
        FTable.etShr[i]:=i;
        If J=KeyLen then
        j:=1 else inc(J);
        FTable.etMod[i]:=FData[j-1];
      end;
      {.$R+}

      { Modulate shift table }
      J:=0;
      For i:=0 to 255 do
      begin
        j:=(j+FTable.etShr[i] + FTable.etMod[i]) mod 256;
        temp:=FTable.etShr[i];
        FTable.etShr[i]:=FTable.etShr[j];
        FTable.etShr[j]:=Temp;
      end;

      FReady:=True;
    end;
  end;

  Function TJLRC4Encoder.BuildRCTable(aKey:WideString):Boolean;
  var
    FLen: Integer;
  Begin
    aKey:=trim(aKey);
    FLen:=Length(aKey);
    Result:=FLen>0;
    If result then
    result:=BuildRCTable(aKey[1],FLen);
  end;
  
  Function TJLRC4Encoder.BuildRCTable(aKey:AnsiString):Boolean;
  var
    FLen: Integer;
  Begin
    aKey:=trim(aKey);
    FLen:=Length(aKey);
    Result:=FLen>0;
    If result then
    result:=BuildRCTable(aKey[1],FLen);
  end;

  Function TJLRC4Encoder.EncBuffer(Const Source;Const Target;
           aLen:Integer):Boolean;
  var
    i,j,t:  Integer;
    Temp,y:   Byte;
    FSpare:   TJLRC4EncodingTable;
    FSource:  PByte;
    FTarget:  PByte;
  Begin
    FSource:=@Source;
    FTarget:=@Target;
    Result:=FReady
    and (FSource<>NIL)
    and (FTarget<>NIL)
    and (aLen>0);

    If result then
    Begin
      (* duplicate table *)
      FSpare:=FTable;

      try

        i:=0; j:=0;
        while 1>0 do
        Begin
          i:=(i+1) mod 256;
          j:=(j+FSpare.etShr[i]) mod 256;
          temp:=FSpare.etShr[i];
          FSpare.etShr[i]:=FSpare.etShr[j];
          FSpare.etShr[j]:=temp;
          t:=(FSpare.etShr[i] + (FSpare.etShr[j] mod 256)) mod 256;
          y:=FSpare.etShr[t];

          FTarget^:=Byte( FSource^ xor y );
          inc(FTarget);
          inc(FSource);
        end;
      except
        on exception do
        Result:=False;
      end;
    end;
  end;

  function TJLRC4Encoder.EncStream(Const aStream:TStream):TStream;
  Begin
    result:=NIL;
    if aStream<>NIl then
    begin
      result:=TMemoryStream.Create;
      if not EncStream(aStream,result) then
      freeAndNil(result);
    end;
  end;

  Function TJLRC4Encoder.EncStream(Source,Target:TStream):Boolean;
  var
    i,j,t:  Integer;
    Temp,y:   Byte;
    FSpare:   TJLRC4EncodingTable;
    FDat:     Byte;
  Begin
    result:=(Source<>NIL)
    and (Source.size>0)
    and (Target<>NIL)
    and FReady;

    If result then
    Begin

      FSpare:=FTable;

      try
        Source.Position:=0;
        i:=0; j:=0;
        while 1>0 do
        Begin
          i:=(i+1) mod 256;
          j:=(j+FSpare.etShr[i]) mod 256;
          temp:=FSpare.etShr[i];
          FSpare.etShr[i]:=FSpare.etShr[j];
          FSpare.etShr[j]:=temp;
          t:=(FSpare.etShr[i] + (FSpare.etShr[j] mod 256)) mod 256;
          y:=FSpare.etShr[t];

          if source.Read(FDat,1)=1 then
          Begin
            FDat:=FDat xor y;
            if Target.Write(FDat,1)<1 then
            Begin
              result:=False;
              Break;
            end;
          end else
          Break;
        end;
      except
        on exception do
        Result:=False;
      end;
    end;
  end;


  end.

Finally, it is done

May 14, 2012 Comments off
Submission.. now that's gonna be a problem

Submission.. now that’s gonna be a problem

Let me paint a mental picture for you: working from you wake up until you fall asleep, for 12 months straight. Driven completely by the will to reach a goal. That has been my life for the past year.

Think big brother is rough? Try working from home during a Norwegian winter. It takes a fair bit of discipline and stubbornness to actually poll through.

Today we finally finished version 1.0 of smart mobile studio, and I can (after a year in exile, or so it feels) dismantle my home office and return to normal hours. I never thought I would see the day when I was looking forward to spending time in the office, but after a whole year working from home, with only random status meetings, it’s going to feel so good getting up in the morning, working out – and then heading for work. Right now my sleep cycle is in sync with australia I think (in other words: topsy turvy). That my wife havent killed me in my sleep during this period of time is beyond me, the woman is a saint.

But one thing you can bet your life on  – I keep my promises. I promised it could be done if we decided on a goal – and I have done it. Not by myself, not because I am special, but because the Delphi community have all the resources it needs to rock the world right under it’s very nose.

Now I’m going to sleep for 4 days

Is the world of google any better?

May 10, 2012 Leave a comment

Lately I have been pondering if the online apps of google really has made the world any better. Dont get me wrong, google is by far the #1 driving force behind moving from native, local applications – to global, browser-based applications. But while their ideas and concepts are brilliant – their minimalistic vision of user interface design leaves a lot to be desired. As does their lack of respect for people’s privacy and how they make their money by boxing people in.

Let’s take the design problem first: which is probably best expressed under Gmail. Where good old outlook express displayed your messages in a listview (express) or tree node (office) structure, making it very easy to see the exact chain of correspondence. This simple interaction between the reader and the content Gmail turns into a complete flurry of text. I often find myself replying not to the latest email, but to an older message by mistake, because it’s not easy to tell the header from the preview line. And yes, I know you can change themes but the palette they have used are either high contrast (which gives me a spiking headache after some hours) or soft crayons (which is just as evil).

After 8 hours and hundreds of emails, this GUI will seem like a paradise compared to gmail

After 8 hours and hundreds of emails, this GUI will seem like a paradise compared to Gmail

When Google and Apple started to take a bite out of the world-wide web I was initially very optimistic. Microsoft had ruled that gig for so long that it was about time that someone new and fresh got into the game – but now I’m starting to question the development of the past 8 years. Is really GMail better than outlook? I mean the news reader in outlook was fantastic and so was the email layout. And also, is really my super-hyped, juiced up mac any better than Windows 7? Was it worth the money? Or is my iPhone really any better to call with than my old Nokia? Have you ever had your iPhone with you while jogging? If your hands are sweaty and someone calls, you can’t even unlock it – because the touchscreen doesn’t register your fingers due to moisture. And at home I can hardly get any reception in my basement office. With my old Nokia I could get a crystal clear reception in the caves of moria if I so desired.

Facts of life vs. bling

Gøtes color theorem

Gøtes color theorem

When Microsoft created Windows XP, they spent millions of dollars doing design research. They took into account every factor, things like color theorem (which colors complement each other, and what effect they have on the viewer’s mind), proportional layout – and they also took into account how a user interface would appear to people who are color blind, have poor eyesight and so on. But the most important factor was the long-term effect of working with the user interface. How well does the interface work after 8 hours? If the colors are slightly off, you can get anything from a headache to fatigue.

What google have done is to take all these factors and thrown them out of the window. But they have forgotten that these design rules were not invented by Microsoft. They are the laws of nature. The reason we have a color theorem is because, well, that’s how colors affect us from a scientific point of view. The reason a clear-cut border will cause less eye strain after 8+ hours is because the receptors in our eyes pick up clear borders easier than round, pastel colored drab.

Why do I put Apple and Google in the same basket? Because Apple is doing the exact same thing. If you have ever worked with the disabled or people with handicaps, you will know that mac’s are rarely their favorite machines. The combination of graphical effects and contrasts that hardly show up on the colorblind’s radar makes it a torturous adventure.

Cost effective

For me personally, both Google and Apple are awesome companies – but there comes a time when throwing ideas around has run its course. A time when you have to go back to what “works”. Hopefully google is done experimenting with design, privacy and data roaming. And hopefully apple is done bloating the universe with senseless features and denying you access to your own bloody hardware.

Møvenpic hotel outside of luxor, my favorite

Møvenpic hotel outside of Luxor, my favorite

And next time, I’m getting a real phone. One with buttons on it. My old Nokia cost me 500 NKR (less than $100) and I called for roughly 400 NKR a month. So give or take: a new Nokia phone + 1 year subscription cost me 5300 NKR a year (around $1000 in total). My iPhone alone cost me 8.500 NKR with a monthly call rate of around 500 NKR. So that’s 8500 + 6000 = 14500 NKR for one phone for a year. And I bought 2 of them (one for my wife as well).

The sub total equals 4 weeks vacation in a 5 star hotel in Sharm El Sheik, Egypt. Which sure as hell would have done a lot more for my headaches than Gmail.

When you sum up the expenses and added factors technology have gained for the past 8 years – from design problems to outright bloat – and weigh them against what is sensible, what works and what you really need to do your job – I find it hard to lobby for further innovation on Google and Apple’s part. There are always things to fix in the world of software, but there is a fine line between perfecting a product and exhausting it. A distinction that is clearly visible between Delphi 7 and Delphi XE2. Delphi 7 was the old Delphi perfected, and we had to wait until Delphi XE2 to find a product of equal quality. Between these versions were ideas that quite frankly exhausted both the technology and the user’s patience.

Turning your life into a product

And where the hell does google get off uploading pictures from my iPhone without asking? My kids were at a birthday party – and I really got pissed to see that my google app had automatically uploaded the pictures to my G+ account. What the hell! You don’t set a function like that to ON by default. As a result I have removed G+ and Facebook from my iPhone and iPad. And I’m seriously considering dropping my google account all together – and going back to Hotmail instead. Kidnapping data, selling your queries to advertising companies, data roaming — This is bordering on the insane. And to think they refused Microsoft to ship Windows with Internet Explorer. They should have blocked the google street view car as a threat to national security. It is by definition espionage on an international scale.

External references

Pictures as a medium for binary data

May 7, 2012 Comments off

At work I am currently adding the final touches to Smart Mobile Studio (with some excellent help from Primoz Gabrijelcic and Eric Grange. If you havent seen what these guys do then you are in for a treat!). For people moving their code from object pascal to HTMLr5 however, one of the biggest problems is the fact that JavaScript doesn’t allow you to access files directly, only indirectly. In fact large parts of JavaScript is like that so it can be very frustrating for us native Spartans! Some desktop browsers have reader and writer objects to access files – but again they differ in that every operation is async. So your “stream.read()” may call back in 80 seconds if your network is dizzed. And dont get me started on the mobile scene (the javascript frameworks on sale out there “huff and puff” but they are for the most part re-hashing bad news. Delphi users on the other hand, are in the business of creating good news, so we skip that part *smile*).

Pondering how we could solve the mysterious case of alien data (i.e when you got a binary file that you dont want to hand-punch as an array), I realized that we could use pictures as a medium. It wont help loading files from the device (unless you compile to phonegap), but it will help with converting files from Delphi to HTML5. While I can only speculate on the maximum size we can get and the differences between mobile and stationary webkit  (behind Apple’s “bling” it’s all unix after all), –under winAPI a DIB (device independent bitmap) has a max size of 4096 x 4096 x 32 bits – which yields a total of 67108864 bytes of storage space. I think you can go higher if you throw in a memory mapped file handle – but it’s been a while since I hacked around the winAPI to be honest. I got sick of the whole limitation and coded my own system (see “uni-surface” under pixelrage).

So, right now im adding a new wizard to Smart Mobile which allows you to embed a binary file as a picture. Instead of RGBA pixel data, we write the bytes from the file – and you can read them out via a normal TW3ImageData object.

Thanks to Kostas for the head’s up!

Spirit of Delphi

On a second note, my main man Dorin is ever pushing limits to the max and have released an awesome example of source code mini maps for synEdit. With some of the killer stuff Dorin is knocking out these days — he will probably take over the world in 10 years time. Head over to the spirit of Delphi and check out his top-notch stuff!

Scale a polygon?

May 3, 2012 1 comment

Following up on fun “bare-bones” retro coding, here is how you scale a polygon. While I can’t think of a single use for this in a real life application, I can paradoxically also think of a million uses for it. For instance, if you are making a paint program which uses polygon based brushes – you could use this to scale the same shape up and down. Well, I’ll leave the creativity up to you — it’s retro time!

Note: The example below is just one way of doing things. As a friend of mine pointed out, it would be considerably faster to use a matrix / linear approach.

Once again, this is written in Smart Mobile Studio‘s version of object pascal, but it should be easy to get it running on vanilla Delphi 🙂

type
TPointArray = array of TPoint;

Function ScalePolygon(factor:Float;InPoints:TPointArray;
         Const centerX,centerY:Float):TPointArray;
var
  i:   integer;
  r,p: float;
begin
  result.SetLength(inPoints.length);
  if inPoints.Length>0 then
  begin
    for i := 0 to inPoints.high do
    begin
      r:= factor * sqrt(sqr(InPoints[i].X - centerX) + sqr(InPoints[i].Y - centerY));
      p:= arcTan2(InPoints[i].Y - centerY, InPoints[i].X - centerX);
      Result[i].X := Round(centerX + r * cos(p));
      Result[i].Y := Round(centerY + r * sin(p));
    end;
  end;
end;

Incidentaly, here is Spaceballs – the Amiga polygon demo par excellence:

Old school but still cool

Old school but still cool

Rotate a polygon

May 3, 2012 Leave a comment

One of the benefits of writing an RTL from scratch is that you get the chance to wake up old gems from the past. For instance, how do you rotate a polygon (array of TPoints) around a variable axis? While my work at the office is extremely serious, I must admit that playing around with these routines is very entertaining.

Note: The example below is just one way of doing things. As a friend of mine pointed out, it would be considerably faster to use a matrix / linear approach.

While this example is for Smart Mobile Studio‘s flavour of object pascal, it should be fairly easy to get it running under vanilla Delphi or freepascal. Enjoy the retro feeling 🙂

type
TPointArray = array of TPoint;

function Rotate(const angle:Float;
         const aValues:TPointArray;
         const centerX,centerY:Float):TPointArray;
var
  i:    integer;
  r,p:  Float;
begin
  if aValues.Length>0 then
  Begin
    result.SetLength(aValues.Length);
    for i := 0 to aValues.length-1 do
    begin
      r:=sqrt(sqr(aValues[i].X - centerX) + sqr(aValues[i].Y - centerY));
      p := angle + arcTan2(aValues[i].Y - centerY, aValues[i].X - centerX);
      Result[i].X := Round(centerX + r * cos(p));
      Result[i].Y := Round(centerY + r * sin(p));
    end;
  end;
end;

Here is one way of using it:

  (* setup our array of points *)
  mItems.SetLength(0);
  mItems.add(Tpoint.Create(10,10));
  mItems.add(TPoint.Create(100,10));
  mItems.add(TPoint.create(100,100));
  mItems.add(TPoint.create(10,100));

  (* do the mambo *)
  mItems:=rotate(fbValue,mItems,gameview.width div 2,gameview.height div 2);

  (* Paint on our HTML5 canvas *)
  Canvas.MoveToF(mItems[0].x,mItems[0].y);
  for i:=1 to mItems.high do
  canvas.linetoF(mItems[i].x,mItems[i].y);
  canvas.linetoF(mItems[0].x,mItems[0].y);

And the end result (the cube rotates around the screen):

A static image hardly does it justice

A static image hardly does it justice

Here is a buffer we prepared earlier, using the numbers of life:

Archimedes spiral

Archimedes spiral + extra rotation

Pixelrage C# version?

May 2, 2012 Leave a comment

Please let me underline that when i write “C#” I do not refer to the Microsoft version of that system. It is wholeheartedly mono, the full creation of Miguel de Icaza. In fact I find the Microsoft limitations (like not being able to compile to a single .exe binary) bordering on the offensive. Miguel did the work of porting it, promoting it and making it a reality – so he deserves the credit for it.

Et tu brutus?

But yes, it is true. I did spend a week or two converting the foundation of pixelrage to C# (codename sharpdraw). It’s naturally not a full implementation, but we only needed to blit graphics around on the iPhone. So all in all just a DIB (device independant bitmap) and the pixel writers. Porting the rest is a piece of cake.

C# is a toy compared to Delphi

C# is a toy compared to Delphi

The sourcecode has been moved to the pixelrage repository on google: http://code.google.com/p/pixelrage/