File: gamemap.pas

package info (click to toggle)
castle-game-engine 6.4%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 194,520 kB
  • sloc: pascal: 364,585; ansic: 8,606; java: 2,851; objc: 2,601; cpp: 1,412; xml: 851; makefile: 725; sh: 563; php: 26
file content (321 lines) | stat: -rw-r--r-- 8,715 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
{
  Copyright 2011-2017 Michalis Kamburelis.

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  ----------------------------------------------------------------------------
}

{ Map composed from tiles. }
unit GameMap;

interface

uses Classes, CastleVectors, CastleImages, CastleGLUtils, CastleGLImages;

type
  TTile = class
  public
    GLImage: TGLImage;
    { Relative URL vs tiles directory.
      This is read and written from/to a map file. }
    RelativeURL: string;
    { This is an absolute URL constructed from RelativeURL. }
    function FullURL: string;
  public
    CharCode: char;
    procedure LoadFromFile; virtual; abstract;
    destructor Destroy; override;
  end;

  { Base ground tile. When loading from file, this will always be resized to
    BaseWidth x BaseHeight.

    It must have alpha channel set properly,
    so that corners are not drawn. If the image doesn't have alpha channel,
    alpha channel will be added and colors equal to lower-left corner
    will be set transparent. It's @link(Image) is always TRGBAlphaImage. }
  TBaseTile = class(TTile)
    procedure LoadFromFile; override;
  end;

  TBonusTile = class(TTile)
    procedure LoadFromFile; override;
  end;

  TMapTile = class
    { Base ground tile. }
    BaseTile: TBaseTile;
    { Object drawn on top of base. Usually has alpha such that
      base is visible beside it. May be large, covering other tiles.
      May be nil to indicate no object. }
    BonusTile: TBonusTile;
  end;

  TMap = class
  private
    procedure CommonCreate;
    { Call this after Width and Height are set, this will initialize Items. }
    procedure CreateItems;
  public
    BaseTiles: array[char] of TBaseTile;
    BonusTiles: array[char] of TBonusTile;
    BaseTilesList: TList;
    BonusTilesList: TList;
    Items: array of array of TMapTile;
    { Must be > 0 always }
    Width, Height: Cardinal;
    PlayerStartX, PlayerStartY: Cardinal;
    constructor Create(AWidth, AHeight: Cardinal);
    constructor CreateFromFile(const AURL: string);
    destructor Destroy; override;
    procedure SaveToFile(const AURL: string);
  end;

implementation

uses SysUtils,
  CastleFilesUtils, CastleUtils, CastleStringUtils,
  CastleClassUtils, CastleDownload,
  GameWindow;

{ TTile ---------------------------------------------------------------------- }

destructor TTile.Destroy;
begin
  FreeAndNil(GLImage);
  inherited;
end;

function TTile.FullURL: string;
begin
  Result := ApplicationData('tiles/' + RelativeURL);
end;

{ TBaseTile ------------------------------------------------------------------ }

procedure TBaseTile.LoadFromFile;
var
  Image: TCastleImage;
  NewImage: TRGBAlphaImage;
begin
  Image := LoadImage(FullURL, [TRGBImage, TRGBAlphaImage], BaseWidth, BaseHeight);
  if not (Image is TRGBAlphaImage) then
  begin
    NewImage := (Image as TRGBImage).ToRGBAlphaImage;
    NewImage.AlphaDecide(
      Vector3Byte(
        TRGBAlphaImage(Image).Pixels[0][0],
        TRGBAlphaImage(Image).Pixels[1][0],
        TRGBAlphaImage(Image).Pixels[2][0]),
      0, 0, 255);
    Writeln('Alpha added to "', RelativeURL, '" while loading');
    FreeAndNil(Image);
    Image := NewImage;
    { This will automatically fix such images, assuming that URL
      extension is PNG.
    SaveImage(Image, FullURL); }
  end;

  GLImage := TGLImage.Create(Image, false, true);
end;

{ TBonusTile ----------------------------------------------------------------- }

procedure TBonusTile.LoadFromFile;
var
  Image: TCastleImage;
begin
  Image := LoadImage(FullURL, PixelsImageClasses);
  GLImage := TGLImage.Create(Image, false, true);
end;

{ TMap ----------------------------------------------------------------------- }

procedure TMap.CommonCreate;
begin
  inherited Create;
  BaseTilesList := TList.Create;
  BonusTilesList := TList.Create;
end;

constructor TMap.Create(AWidth, AHeight: Cardinal);
begin
  CommonCreate;
  Width := AWidth;
  Height := AHeight;
  CreateItems;
end;

constructor TMap.CreateFromFile(const AURL: string);

  procedure ReadlnTileLine(const F: TTextReader;
    var C: char; var RelativeURL: string);
  var
    CStr: string;
  begin
    CStr := F.Read;
    if Length(CStr) <> 1 then
      raise Exception.Create('Not a single 1st character');
    C := CStr[1];

    RelativeURL := F.Read;
    if RelativeURL = '' then
      raise Exception.CreateFmt('Empty URL after character "%s"', [C]);

    F.Readln;
  end;

var
  F: TTextReader;
  BaseTilesCount, BonusTilesCount: Cardinal;
  C: char;
  S: string;
  I: Integer;
  X, Y: Cardinal;
begin
  CommonCreate;

  F := TTextReader.Create(AURL);
  try
    Width := F.ReadInteger;
    Height := F.ReadInteger;
    PlayerStartX := F.ReadInteger;
    PlayerStartY := F.ReadInteger;
    BaseTilesCount := F.ReadInteger;
    BonusTilesCount := F.ReadInteger;

    if (Width = 0) or (Height = 0) then
      raise Exception.Create('Map width and height must be > 0');

    for I := 0 to Integer(BaseTilesCount) - 1 do
    begin
      ReadlnTileLine(F, C, S);
      BaseTiles[C] := TBaseTile.Create;
      BaseTiles[C].CharCode := C;
      BaseTiles[C].RelativeURL := S;
      BaseTiles[C].LoadFromFile;
      BaseTilesList.Add(BaseTiles[C]);
    end;

    for I := 0 to Integer(BonusTilesCount) - 1 do
    begin
      ReadlnTileLine(F, C, S);
      if C = '_' then
        raise Exception.Create('Bonus tile character cannot be "_"');
      BonusTiles[C] := TBonusTile.Create;
      BonusTiles[C].CharCode := C;
      BonusTiles[C].RelativeURL := S;
      BonusTiles[C].LoadFromFile;
      BonusTilesList.Add(BonusTiles[C]);
    end;

    CreateItems;

    for Y := Height - 1 downto 0 do
    begin
      S := F.Readln;
      if Cardinal(Length(S)) <> Width * 2  then
        raise Exception.CreateFmt('Map line %d has wrong length (%d instead of %d)',
          [Y, Cardinal(Length(S)), Width * 2]);
      for X := 0 to Width - 1 do
      begin
        C := S[X*2 + 1];
        Items[X, Y].BaseTile := BaseTiles[C];
        if Items[X, Y].BaseTile = nil then
          raise Exception.CreateFmt('Base tile character "%s" not initialized, ' +
            'but used on map position (%d, %d)', [C, X, Y]);
        C := S[X*2 + 2];
        if C <> '_' then
        begin
          Items[X, Y].BonusTile := BonusTiles[C];
          if Items[X, Y].BonusTile = nil then
            raise Exception.CreateFmt('Bonus tile character "%s" not initialized, ' +
              'but used on map position (%d, %d)', [C, X, Y]);
        end else
          Items[X, Y].BonusTile := nil;
      end;
    end;
  finally FreeAndNil(F) end;
end;

procedure TMap.CreateItems;
var
  X, Y: Cardinal;
begin
  SetLength(Items, Width, Height);
  for X := 0 to Width - 1 do
    for Y := 0 to Height - 1 do
      Items[X, Y] := TMapTile.Create;
end;

destructor TMap.Destroy;
var
  X, Y: Integer;
  C: char;
begin
  { We can't assume that Width and Height are > 0 here,
    they are possibly not initialized. That's why X, Y must be Integer,
    not Cardinal. }
  for X := 0 to Length(Items) - 1 do
    for Y := 0 to Length(Items[X]) - 1 do
      FreeAndNil(Items[X, Y]);

  for C := Low(C) to High(C) do
  begin
    FreeAndNil(BaseTiles[C]);
    FreeAndNil(BonusTiles[C]);
  end;

  FreeAndNil(BaseTilesList);
  FreeAndNil(BonusTilesList);

  inherited;
end;

procedure TMap.SaveToFile(const AURL: string);
var
  F: TStream;
  S: string;
  I: Integer;
  X, Y: Cardinal;
begin
  F := URLSaveStream(AURL);
  try
    WritelnStr(F, Format('%d %d', [Width, Height]));
    WritelnStr(F, Format('%d %d', [PlayerStartX, PlayerStartY]));
    WritelnStr(F, Format('%d %d', [BaseTilesList.Count, BonusTilesList.Count]));

    for I := 0 to BaseTilesList.Count - 1 do
      WritelnStr(F, Format('%s %s', [
        TBaseTile(BaseTilesList[I]).CharCode,
        TBaseTile(BaseTilesList[I]).RelativeURL]));

    for I := 0 to BonusTilesList.Count - 1 do
      WritelnStr(F, Format('%s %s', [
        TBonusTile(BonusTilesList[I]).CharCode,
        TBonusTile(BonusTilesList[I]).RelativeURL]));

    for Y := Height - 1 downto 0 do
    begin
      SetLength(S, Width * 2);
      for X := 0 to Width - 1 do
      begin
        S[X*2 + 1] := Items[X, Y].BaseTile.CharCode;
        if Items[X, Y].BonusTile <> nil then
          S[X*2 + 2] := Items[X, Y].BonusTile.CharCode else
          S[X*2 + 2] := '_';
      end;
      WritelnStr(F, S);
    end;
  finally FreeAndNil(F) end;
end;

end.